difftreelog
Merge pull request #691 from UniqueNetwork/feature/pallet-scheduler-v2
in: master
Feature/pallet scheduler v2
32 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5389,7 +5389,7 @@
"pallet-transaction-payment-rpc-runtime-api",
"pallet-treasury",
"pallet-unique",
- "pallet-unique-scheduler",
+ "pallet-unique-scheduler-v2",
"pallet-xcm",
"parachain-info",
"parity-scale-codec 3.2.1",
@@ -6725,9 +6725,10 @@
dependencies = [
"frame-support",
"frame-system",
- "pallet-unique-scheduler",
+ "pallet-unique-scheduler-v2",
"parity-scale-codec 3.2.1",
"scale-info",
+ "sp-std",
]
[[package]]
@@ -6851,22 +6852,21 @@
]
[[package]]
-name = "pallet-unique-scheduler"
-version = "0.1.1"
+name = "pallet-unique-scheduler-v2"
+version = "0.1.0"
dependencies = [
"frame-benchmarking",
"frame-support",
"frame-system",
"log",
+ "pallet-preimage",
"parity-scale-codec 3.2.1",
"scale-info",
- "serde",
"sp-core",
"sp-io",
"sp-runtime",
"sp-std",
"substrate-test-utils",
- "up-sponsorship",
]
[[package]]
@@ -8861,7 +8861,6 @@
"pallet-transaction-payment-rpc-runtime-api",
"pallet-treasury",
"pallet-unique",
- "pallet-unique-scheduler",
"pallet-xcm",
"parachain-info",
"parity-scale-codec 3.2.1",
@@ -12992,7 +12991,6 @@
"pallet-transaction-payment-rpc-runtime-api",
"pallet-treasury",
"pallet-unique",
- "pallet-unique-scheduler",
"pallet-xcm",
"parachain-info",
"parity-scale-codec 3.2.1",
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -118,7 +118,7 @@
.PHONY: bench-scheduler
bench-scheduler:
- make _bench PALLET=unique-scheduler PALLET_DIR=scheduler
+ make _bench PALLET=unique-scheduler-v2 PALLET_DIR=scheduler-v2
.PHONY: bench-rmrk-core
bench-rmrk-core:
pallets/scheduler-v2/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/pallets/scheduler-v2/Cargo.toml
@@ -0,0 +1,48 @@
+[package]
+name = "pallet-unique-scheduler-v2"
+version = "0.1.0"
+authors = ["Unique Network <support@uniquenetwork.io>"]
+edition = "2021"
+license = "GPLv3"
+homepage = "https://unique.network"
+repository = "https://github.com/UniqueNetwork/unique-chain"
+description = "Unique Scheduler pallet"
+readme = "README.md"
+
+[dependencies]
+codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
+log = { version = "0.4.17", default-features = false }
+scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
+frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+sp-io = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+sp-runtime = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+sp-std = { version = "4.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+sp-core = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+
+[dev-dependencies]
+pallet-preimage = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+sp-core = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+substrate-test-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+
+[features]
+default = ["std"]
+runtime-benchmarks = [
+ "frame-benchmarking",
+ "frame-support/runtime-benchmarks",
+ "frame-system/runtime-benchmarks",
+]
+std = [
+ "codec/std",
+ "frame-benchmarking?/std",
+ "frame-support/std",
+ "frame-system/std",
+ "log/std",
+ "scale-info/std",
+ "sp-io/std",
+ "sp-runtime/std",
+ "sp-std/std",
+ "sp-core/std",
+]
+try-runtime = ["frame-support/try-runtime"]
pallets/scheduler-v2/src/benchmarking.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/scheduler-v2/src/benchmarking.rs
@@ -0,0 +1,374 @@
+// 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-2022 Parity Technologies (UK) Ltd.
+// SPDX-License-Identifier: Apache-2.0
+
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Scheduler pallet benchmarking.
+
+use super::*;
+use frame_benchmarking::{account, benchmarks};
+use frame_support::{
+ ensure,
+ traits::{schedule::Priority, PreimageRecipient},
+};
+use frame_system::RawOrigin;
+use sp_std::{prelude::*, vec};
+use sp_io::hashing::blake2_256;
+
+use crate::{Pallet as Scheduler, ScheduledCall, EncodedCall};
+use frame_system::Call as SystemCall;
+
+const SEED: u32 = 0;
+
+const BLOCK_NUMBER: u32 = 2;
+
+/// Add `n` items to the schedule.
+///
+/// For `resolved`:
+/// - `
+/// - `None`: aborted (hash without preimage)
+/// - `Some(true)`: hash resolves into call if possible, plain call otherwise
+/// - `Some(false)`: plain call
+fn fill_schedule<T: Config>(when: T::BlockNumber, n: u32) -> Result<(), &'static str> {
+ let t = DispatchTime::At(when);
+ let origin: <T as Config>::PalletsOrigin = frame_system::RawOrigin::Root.into();
+ for i in 0..n {
+ let call = make_call::<T>(None);
+ let period = Some(((i + 100).into(), 100));
+ let name = u32_to_name(i);
+ Scheduler::<T>::do_schedule_named(name, t, period, 0, origin.clone(), call)?;
+ }
+ ensure!(
+ Agenda::<T>::get(when).agenda.len() == n as usize,
+ "didn't fill schedule"
+ );
+ Ok(())
+}
+
+/// Generate a name for a scheduled task from an unsigned integer.
+fn u32_to_name(i: u32) -> TaskName {
+ i.using_encoded(blake2_256)
+}
+
+/// A utility for creating simple scheduled tasks.
+///
+/// # Arguments
+/// * `periodic` - makes the task periodic.
+/// Sets the task's period and repetition count to `100`.
+/// * `named` - gives a name to the task: `u32_to_name(0)`.
+/// * `signed` - determines the origin of the task.
+/// If true, it will have the Signed origin. Otherwise it will have the Root origin.
+/// See [`make_origin`] for details.
+/// * maybe_lookup_len - sets optional lookup length. It is used to benchmark task fetching from the `Preimages` store.
+/// * priority - the task's priority.
+fn make_task<T: Config>(
+ periodic: bool,
+ named: bool,
+ signed: bool,
+ maybe_lookup_len: Option<u32>,
+ priority: Priority,
+) -> ScheduledOf<T> {
+ let call = make_call::<T>(maybe_lookup_len);
+ let maybe_periodic = match periodic {
+ true => Some((100u32.into(), 100)),
+ false => None,
+ };
+ let maybe_id = match named {
+ true => Some(u32_to_name(0)),
+ false => None,
+ };
+ let origin = make_origin::<T>(signed);
+ Scheduled {
+ maybe_id,
+ priority,
+ call,
+ maybe_periodic,
+ origin,
+ _phantom: PhantomData,
+ }
+}
+
+/// Creates a `SystemCall::remark` scheduled call with a given `len` in bytes.
+/// Returns `None` if the call is too large to encode.
+fn bounded<T: Config>(len: u32) -> Option<ScheduledCall<T>> {
+ let call = <<T as Config>::RuntimeCall>::from(SystemCall::remark {
+ remark: vec![0; len as usize],
+ });
+ ScheduledCall::new(call).ok()
+}
+
+/// Creates a scheduled call and maximizes its size.
+///
+/// If the `maybe_lookup_len` is not supplied, the task will create the maximal `Inline` scheduled call.
+///
+/// Otherwise, the function will take the length value from the `maybe_lookup_len`
+/// and find a minimal length value that ensures that the scheduled call will require a Preimage lookup.
+fn make_call<T: Config>(maybe_lookup_len: Option<u32>) -> ScheduledCall<T> {
+ let bound = EncodedCall::bound() as u32;
+ let mut len = match maybe_lookup_len {
+ Some(len) => {
+ len.min(<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get() - 2)
+ .max(bound) - 3
+ }
+ None => bound.saturating_sub(4),
+ };
+
+ loop {
+ let c = match bounded::<T>(len) {
+ Some(x) => x,
+ None => {
+ len -= 1;
+ continue;
+ }
+ };
+ if c.lookup_needed() == maybe_lookup_len.is_some() {
+ break c;
+ }
+ if maybe_lookup_len.is_some() {
+ len += 1;
+ } else {
+ if len > 0 {
+ len -= 1;
+ } else {
+ break c;
+ }
+ }
+ }
+}
+
+/// Creates an origin for a scheduled call.
+///
+/// If `signed` is true, it creates the Signed origin from a default account `account("origin", 0, SEED)`.
+/// Otherwise, it creates the Root origin.
+fn make_origin<T: Config>(signed: bool) -> <T as Config>::PalletsOrigin {
+ match signed {
+ true => frame_system::RawOrigin::Signed(account("origin", 0, SEED)).into(),
+ false => frame_system::RawOrigin::Root.into(),
+ }
+}
+
+/// Creates a dummy `WeightCounter` with the maximum possible weight limit.
+fn dummy_counter() -> WeightCounter {
+ WeightCounter {
+ used: Weight::zero(),
+ limit: Weight::MAX,
+ }
+}
+
+benchmarks! {
+ // `service_agendas` when no work is done.
+ // (multiple agendas - scheduled tasks in several blocks)
+ service_agendas_base {
+ let now = T::BlockNumber::from(BLOCK_NUMBER);
+ IncompleteSince::<T>::put(now - One::one());
+ }: {
+ Scheduler::<T>::service_agendas(&mut dummy_counter(), now, 0);
+ } verify {
+ assert_eq!(IncompleteSince::<T>::get(), Some(now - One::one()));
+ }
+
+ // `service_agenda` when no work is done.
+ // (only one agenda - scheduled tasks in a single block)
+ service_agenda_base {
+ let now = BLOCK_NUMBER.into();
+ let s in 0 .. T::MaxScheduledPerBlock::get();
+ fill_schedule::<T>(now, s)?;
+ let mut executed = 0;
+ }: {
+ Scheduler::<T>::service_agenda(&mut dummy_counter(), &mut executed, now, now, 0);
+ } verify {
+ assert_eq!(executed, 0);
+ }
+
+ // `service_task` when the task is a non-periodic, non-named, non-fetched call which is not
+ // dispatched (e.g. due to being overweight).
+ service_task_base {
+ let now = BLOCK_NUMBER.into();
+ let task = make_task::<T>(false, false, false, None, 0);
+ // prevent any tasks from actually being executed as we only want the surrounding weight.
+ let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
+ }: {
+ let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
+ } verify {
+ //assert_eq!(result, Ok(()));
+ }
+
+ // TODO uncomment if we will use the Preimages
+ // // `service_task` when the task is a non-periodic, non-named, fetched call (with a known
+ // // preimage length) and which is not dispatched (e.g. due to being overweight).
+ // service_task_fetched {
+ // let s in (EncodedCall::bound() as u32) .. (<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get());
+ // let now = BLOCK_NUMBER.into();
+ // let task = make_task::<T>(false, false, false, Some(s), 0);
+ // // prevent any tasks from actually being executed as we only want the surrounding weight.
+ // let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
+ // }: {
+ // let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
+ // } verify {
+ // }
+
+ // `service_task` when the task is a non-periodic, named, non-fetched call which is not
+ // dispatched (e.g. due to being overweight).
+ service_task_named {
+ let now = BLOCK_NUMBER.into();
+ let task = make_task::<T>(false, true, false, None, 0);
+ // prevent any tasks from actually being executed as we only want the surrounding weight.
+ let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
+ }: {
+ let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
+ } verify {
+ }
+
+ // `service_task` when the task is a periodic, non-named, non-fetched call which is not
+ // dispatched (e.g. due to being overweight).
+ service_task_periodic {
+ let now = BLOCK_NUMBER.into();
+ let task = make_task::<T>(true, false, false, None, 0);
+ // prevent any tasks from actually being executed as we only want the surrounding weight.
+ let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
+ }: {
+ let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
+ } verify {
+ }
+
+ // `execute_dispatch` when the origin is `Signed`, not counting the dispatable's weight.
+ execute_dispatch_signed {
+ let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };
+ let origin = make_origin::<T>(true);
+ let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;
+ }: {
+ assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());
+ }
+ verify {
+ }
+
+ // `execute_dispatch` when the origin is not `Signed`, not counting the dispatable's weight.
+ execute_dispatch_unsigned {
+ let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };
+ let origin = make_origin::<T>(false);
+ let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;
+ }: {
+ assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());
+ }
+ verify {
+ }
+
+ schedule {
+ let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);
+ let when = BLOCK_NUMBER.into();
+ let periodic = Some((T::BlockNumber::one(), 100));
+ let priority = Some(0);
+ // Essentially a no-op call.
+ let call = Box::new(SystemCall::set_storage { items: vec![] }.into());
+
+ fill_schedule::<T>(when, s)?;
+ }: _(RawOrigin::Root, when, periodic, priority, call)
+ verify {
+ ensure!(
+ Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,
+ "didn't add to schedule"
+ );
+ }
+
+ cancel {
+ let s in 1 .. T::MaxScheduledPerBlock::get();
+ let when = BLOCK_NUMBER.into();
+
+ fill_schedule::<T>(when, s)?;
+ assert_eq!(Agenda::<T>::get(when).agenda.len(), s as usize);
+ }: _(RawOrigin::Root, when, 0)
+ verify {
+ ensure!(
+ Lookup::<T>::get(u32_to_name(0)).is_none(),
+ "didn't remove from lookup"
+ );
+ // Removed schedule is NONE
+ ensure!(
+ Agenda::<T>::get(when).agenda[0].is_none(),
+ "didn't remove from schedule"
+ );
+ }
+
+ schedule_named {
+ let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);
+ let id = u32_to_name(s);
+ let when = BLOCK_NUMBER.into();
+ let periodic = Some((T::BlockNumber::one(), 100));
+ let priority = Some(0);
+ // Essentially a no-op call.
+ let call = Box::new(SystemCall::set_storage { items: vec![] }.into());
+
+ fill_schedule::<T>(when, s)?;
+ }: _(RawOrigin::Root, id, when, periodic, priority, call)
+ verify {
+ ensure!(
+ Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,
+ "didn't add to schedule"
+ );
+ }
+
+ cancel_named {
+ let s in 1 .. T::MaxScheduledPerBlock::get();
+ let when = BLOCK_NUMBER.into();
+
+ fill_schedule::<T>(when, s)?;
+ }: _(RawOrigin::Root, u32_to_name(0))
+ verify {
+ ensure!(
+ Lookup::<T>::get(u32_to_name(0)).is_none(),
+ "didn't remove from lookup"
+ );
+ // Removed schedule is NONE
+ ensure!(
+ Agenda::<T>::get(when).agenda[0].is_none(),
+ "didn't remove from schedule"
+ );
+ }
+
+ change_named_priority {
+ let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Root;
+ let s in 1 .. T::MaxScheduledPerBlock::get();
+ let when = BLOCK_NUMBER.into();
+ let idx = s - 1;
+ let id = u32_to_name(idx);
+ let priority = 42;
+ fill_schedule::<T>(when, s)?;
+ }: _(origin, id, priority)
+ verify {
+ ensure!(
+ Agenda::<T>::get(when).agenda[idx as usize].clone().unwrap().priority == priority,
+ "didn't change the priority"
+ );
+ }
+
+ impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test);
+}
pallets/scheduler-v2/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/scheduler-v2/src/lib.rs
@@ -0,0 +1,1330 @@
+// 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-2022 Parity Technologies (UK) Ltd.
+// SPDX-License-Identifier: Apache-2.0
+
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! # Scheduler
+//! A Pallet for scheduling dispatches.
+//!
+//! - [`Config`]
+//! - [`Call`]
+//! - [`Pallet`]
+//!
+//! ## Overview
+//!
+//! 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.
+//!
+//! **NOTE:** The scheduled calls will be dispatched with the default filter
+//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin
+//! except root which will get no filter. And not the filter contained in origin
+//! use to call `fn schedule`.
+//!
+//! If a call is scheduled using proxy or whatever mecanism which adds filter,
+//! then those filter will not be used when dispatching the schedule call.
+//!
+//! ## Interface
+//!
+//! ### 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.
+//! * `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)]
+#![deny(missing_docs)]
+
+#[cfg(feature = "runtime-benchmarks")]
+mod benchmarking;
+#[cfg(test)]
+mod mock;
+#[cfg(test)]
+mod tests;
+pub mod weights;
+
+use codec::{Codec, Decode, Encode, MaxEncodedLen};
+use frame_support::{
+ dispatch::{
+ DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,
+ },
+ traits::{
+ schedule::{self, DispatchTime, LOWEST_PRIORITY},
+ EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,
+ ConstU32, UnfilteredDispatchable,
+ },
+ weights::Weight,
+ unsigned::TransactionValidityError,
+};
+
+use frame_system::{self as system};
+use scale_info::TypeInfo;
+use sp_runtime::{
+ traits::{BadOrigin, One, Saturating, Zero, Hash},
+ BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,
+};
+use sp_core::H160;
+use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*};
+pub use weights::WeightInfo;
+
+pub use pallet::*;
+
+/// 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);
+
+/// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.
+pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;
+
+#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
+#[scale_info(skip_type_params(T))]
+/// A scheduled call is stored as is or as a preimage hash to lookup.
+/// This enum represents both variants.
+pub enum ScheduledCall<T: Config> {
+ /// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.
+ Inline(EncodedCall),
+
+ /// A Blake2-256 hash of the call together with an upper limit for its size.
+ PreimageLookup {
+ /// A call hash to lookup
+ hash: T::Hash,
+
+ /// The length of the decoded call
+ unbounded_len: u32,
+ },
+}
+
+impl<T: Config> ScheduledCall<T> {
+ /// Convert an otherwise unbounded or large value into a type ready for placing in storage.
+ ///
+ /// NOTE: Once this API is used, you should use either `drop` or `realize`.
+ pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {
+ let encoded = call.encode();
+ let len = encoded.len();
+
+ match EncodedCall::try_from(encoded.clone()) {
+ Ok(bounded) => Ok(Self::Inline(bounded)),
+ Err(_) => {
+ let hash = <T as system::Config>::Hashing::hash_of(&encoded);
+ <T as Config>::Preimages::note_preimage(
+ encoded
+ .try_into()
+ .map_err(|_| <Error<T>>::TooBigScheduledCall)?,
+ );
+
+ Ok(Self::PreimageLookup {
+ hash,
+ unbounded_len: len as u32,
+ })
+ }
+ }
+ }
+
+ /// The maximum length of the lookup that is needed to peek `Self`.
+ pub fn lookup_len(&self) -> Option<u32> {
+ match self {
+ Self::Inline(..) => None,
+ Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),
+ }
+ }
+
+ /// Returns whether the image will require a lookup to be peeked.
+ pub fn lookup_needed(&self) -> bool {
+ match self {
+ Self::Inline(_) => false,
+ Self::PreimageLookup { .. } => true,
+ }
+ }
+
+ // Decodes a runtime call
+ fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {
+ <T as Config>::RuntimeCall::decode(&mut data)
+ .map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())
+ }
+}
+
+/// Weight Info for the Preimages fetches.
+pub trait SchedulerPreimagesWeightInfo<W: WeightInfo> {
+ /// Get the weight of a task fetches with a given decoded length.
+ fn service_task_fetched(call_length: u32) -> Weight;
+}
+
+impl<W: WeightInfo> SchedulerPreimagesWeightInfo<W> for () {
+ fn service_task_fetched(_call_length: u32) -> Weight {
+ W::service_task_base()
+ }
+}
+
+/// A scheduler's interface for managing preimages to hashes
+/// and looking up preimages from their hash on-chain.
+pub trait SchedulerPreimages<T: Config>:
+ PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>
+{
+ /// No longer request that the data for decoding the given `call` is available.
+ fn drop(call: &ScheduledCall<T>);
+
+ /// Convert the given `call` instance back into its original instance, also returning the
+ /// exact size of its encoded form if it needed to be looked-up from a stored preimage.
+ ///
+ /// NOTE: This does not remove any data needed for realization. If you will no longer use the
+ /// `call`, use `realize` instead or use `drop` afterwards.
+ fn peek(
+ call: &ScheduledCall<T>,
+ ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;
+
+ /// Convert the given scheduled `call` value back into its original instance. If successful,
+ /// `drop` any data backing it. This will not break the realisability of independently
+ /// created instances of `ScheduledCall` which happen to have identical data.
+ fn realize(
+ call: &ScheduledCall<T>,
+ ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;
+}
+
+impl<T: Config, PP: PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>>
+ SchedulerPreimages<T> for PP
+{
+ fn drop(call: &ScheduledCall<T>) {
+ match call {
+ ScheduledCall::Inline(_) => {}
+ ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),
+ }
+ }
+
+ fn peek(
+ call: &ScheduledCall<T>,
+ ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {
+ match call {
+ ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),
+ ScheduledCall::PreimageLookup {
+ hash,
+ unbounded_len,
+ } => {
+ let (preimage, len) = Self::get_preimage(hash)
+ .ok_or(<Error<T>>::PreimageNotFound)
+ .map(|preimage| (preimage, *unbounded_len))?;
+
+ Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))
+ }
+ }
+ }
+
+ fn realize(
+ call: &ScheduledCall<T>,
+ ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {
+ let r = Self::peek(call)?;
+ Self::drop(call);
+ Ok(r)
+ }
+}
+
+/// Scheduler's supported origins.
+pub enum ScheduledEnsureOriginSuccess<AccountId> {
+ /// A scheduled transaction has the Root origin.
+ Root,
+
+ /// A specific account has signed a scheduled transaction.
+ Signed(AccountId),
+}
+
+/// An identifier of a scheduled task.
+pub type TaskName = [u8; 32];
+
+/// Information regarding an item to be executed in the future.
+#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
+#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]
+pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {
+ /// The unique identity for this task, if there is one.
+ maybe_id: Option<Name>,
+
+ /// This task's priority.
+ priority: schedule::Priority,
+
+ /// The call to be dispatched.
+ call: Call,
+
+ /// If the call is periodic, then this points to the information concerning that.
+ maybe_periodic: Option<schedule::Period<BlockNumber>>,
+
+ /// The origin with which to dispatch the call.
+ origin: PalletsOrigin,
+ _phantom: PhantomData<AccountId>,
+}
+
+/// Information regarding an item to be executed in the future.
+pub type ScheduledOf<T> = Scheduled<
+ TaskName,
+ ScheduledCall<T>,
+ <T as frame_system::Config>::BlockNumber,
+ <T as Config>::PalletsOrigin,
+ <T as frame_system::Config>::AccountId,
+>;
+
+#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]
+#[scale_info(skip_type_params(T))]
+/// A structure for storing scheduled tasks in a block.
+/// The `BlockAgenda` tracks the available free space for a new task in a block.4
+///
+/// The agenda's maximum amount of tasks is `T::MaxScheduledPerBlock`.
+pub struct BlockAgenda<T: Config> {
+ agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,
+ free_places: u32,
+}
+
+impl<T: Config> BlockAgenda<T> {
+ /// Tries to push a new scheduled task into the block's agenda.
+ /// If there is a free place, the new task will take it,
+ /// and the `BlockAgenda` will record that the number of free places has decreased.
+ ///
+ /// An error containing the scheduled task will be returned if there are no free places.
+ ///
+ /// The complexity of the check for the *existence* of a free place is O(1).
+ /// The complexity of *finding* the free slot is O(n).
+ fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Result<u32, ScheduledOf<T>> {
+ if self.free_places == 0 {
+ return Err(scheduled);
+ }
+
+ self.free_places = self.free_places.saturating_sub(1);
+
+ if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {
+ // will always succeed due to the above check.
+ let _ = self.agenda.try_push(Some(scheduled));
+ Ok((self.agenda.len() - 1) as u32)
+ } else {
+ match self.agenda.iter().position(|i| i.is_none()) {
+ Some(hole_index) => {
+ self.agenda[hole_index] = Some(scheduled);
+ Ok(hole_index as u32)
+ }
+ None => unreachable!("free_places was greater than 0; qed"),
+ }
+ }
+ }
+
+ /// Sets a slot by the given index and the slot value.
+ ///
+ /// ### Panics
+ /// If the index is out of range, the function will panic.
+ fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {
+ self.agenda[index as usize] = slot;
+ }
+
+ /// Returns an iterator containing references to the agenda's slots.
+ fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {
+ self.agenda.iter()
+ }
+
+ /// Returns an immutable reference to a scheduled task if there is one under the given index.
+ ///
+ /// The function returns `None` if:
+ /// * The `index` is out of range
+ /// * No scheduled task occupies the agenda slot under the given index.
+ fn get(&self, index: u32) -> Option<&ScheduledOf<T>> {
+ match self.agenda.get(index as usize) {
+ Some(Some(scheduled)) => Some(scheduled),
+ _ => None,
+ }
+ }
+
+ /// Returns a mutable reference to a scheduled task if there is one under the given index.
+ ///
+ /// The function returns `None` if:
+ /// * The `index` is out of range
+ /// * No scheduled task occupies the agenda slot under the given index.
+ fn get_mut(&mut self, index: u32) -> Option<&mut ScheduledOf<T>> {
+ match self.agenda.get_mut(index as usize) {
+ Some(Some(scheduled)) => Some(scheduled),
+ _ => None,
+ }
+ }
+
+ /// Take a scheduled task by the given index.
+ ///
+ /// If there is a task under the index, the function will:
+ /// * Free the corresponding agenda slot.
+ /// * Decrease the number of free places.
+ /// * Return the scheduled task.
+ ///
+ /// The function returns `None` if there is no task under the index.
+ fn take(&mut self, index: u32) -> Option<ScheduledOf<T>> {
+ let removed = self.agenda.get_mut(index as usize)?.take();
+
+ if removed.is_some() {
+ self.free_places = self.free_places.saturating_add(1);
+ }
+
+ removed
+ }
+}
+
+impl<T: Config> Default for BlockAgenda<T> {
+ fn default() -> Self {
+ let agenda = Default::default();
+ let free_places = T::MaxScheduledPerBlock::get();
+
+ Self {
+ agenda,
+ free_places,
+ }
+ }
+}
+/// A structure for tracking the used weight
+/// and checking if it does not exceed the weight limit.
+struct WeightCounter {
+ used: Weight,
+ limit: Weight,
+}
+
+impl WeightCounter {
+ /// Checks if the weight `w` can be accommodated by the counter.
+ ///
+ /// If there is room for the additional weight `w`,
+ /// the function will update the used weight and return true.
+ fn check_accrue(&mut self, w: Weight) -> bool {
+ let test = self.used.saturating_add(w);
+ if test.any_gt(self.limit) {
+ false
+ } else {
+ self.used = test;
+ true
+ }
+ }
+
+ /// Checks if the weight `w` can be accommodated by the counter.
+ fn can_accrue(&mut self, w: Weight) -> bool {
+ self.used.saturating_add(w).all_lte(self.limit)
+ }
+}
+
+pub(crate) struct MarginalWeightInfo<T: Config>(sp_std::marker::PhantomData<T>);
+
+impl<T: Config> MarginalWeightInfo<T> {
+ /// Return the weight of servicing a single task.
+ fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {
+ let base = T::WeightInfo::service_task_base();
+ let mut total = match maybe_lookup_len {
+ None => base,
+ Some(l) => T::Preimages::service_task_fetched(l as u32),
+ };
+ if named {
+ total.saturating_accrue(T::WeightInfo::service_task_named().saturating_sub(base));
+ }
+ if periodic {
+ total.saturating_accrue(T::WeightInfo::service_task_periodic().saturating_sub(base));
+ }
+ total
+ }
+}
+
+#[frame_support::pallet]
+pub mod pallet {
+ use super::*;
+ use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};
+ use system::pallet_prelude::*;
+
+ /// The current storage version.
+ const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
+
+ #[pallet::pallet]
+ #[pallet::generate_store(pub(super) trait Store)]
+ #[pallet::storage_version(STORAGE_VERSION)]
+ pub struct Pallet<T>(_);
+
+ #[pallet::config]
+ pub trait Config: frame_system::Config {
+ /// The overarching event type.
+ type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
+
+ /// The aggregated origin which the dispatch will take.
+ type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
+ + From<Self::PalletsOrigin>
+ + IsType<<Self as system::Config>::RuntimeOrigin>
+ + Clone;
+
+ /// The caller origin, overarching type of all pallets origins.
+ type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>
+ + Codec
+ + Clone
+ + Eq
+ + TypeInfo
+ + MaxEncodedLen;
+
+ /// The aggregated call type.
+ type RuntimeCall: Parameter
+ + Dispatchable<
+ RuntimeOrigin = <Self as Config>::RuntimeOrigin,
+ PostInfo = PostDispatchInfo,
+ > + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>
+ + GetDispatchInfo
+ + From<system::Call<Self>>;
+
+ /// The maximum weight that may be scheduled per block for any dispatchables.
+ #[pallet::constant]
+ type MaximumWeight: Get<Weight>;
+
+ /// Required origin to schedule or cancel calls.
+ type ScheduleOrigin: EnsureOrigin<
+ <Self as system::Config>::RuntimeOrigin,
+ Success = ScheduledEnsureOriginSuccess<Self::AccountId>,
+ >;
+
+ /// 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.
+ ///
+ /// 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.
+ #[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 Preimages: SchedulerPreimages<Self>;
+
+ /// The helper type used for custom transaction fee logic.
+ type CallExecutor: DispatchCall<Self, H160>;
+
+ /// Required origin to set/change calls' priority.
+ type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;
+ }
+
+ /// It contains the block number from which we should service tasks.
+ /// It's used for delaying the servicing of future blocks' agendas if we had overweight tasks.
+ #[pallet::storage]
+ pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;
+
+ /// 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, BlockAgenda<T>, ValueQuery>;
+
+ /// Lookup from a name to the block number and index of the task.
+ #[pallet::storage]
+ pub(crate) type Lookup<T: Config> =
+ StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;
+
+ /// Events type.
+ #[pallet::event]
+ #[pallet::generate_deposit(pub(super) fn deposit_event)]
+ pub enum Event<T: Config> {
+ /// Scheduled some task.
+ Scheduled {
+ /// The block number in which the scheduled task should be executed.
+ when: T::BlockNumber,
+
+ /// The index of the block's agenda slot.
+ index: u32,
+ },
+ /// Canceled some task.
+ Canceled {
+ /// The block number in which the canceled task has been.
+ when: T::BlockNumber,
+
+ /// The index of the block's agenda slot that had become available.
+ index: u32,
+ },
+ /// Dispatched some task.
+ Dispatched {
+ /// The task's address - the block number and the block's agenda index.
+ task: TaskAddress<T::BlockNumber>,
+
+ /// The task's name if it is not anonymous.
+ id: Option<[u8; 32]>,
+
+ /// The task's execution result.
+ result: DispatchResult,
+ },
+ /// Scheduled task's priority has changed
+ PriorityChanged {
+ /// The task's address - the block number and the block's agenda index.
+ task: TaskAddress<T::BlockNumber>,
+
+ /// The new priority of the task.
+ priority: schedule::Priority,
+ },
+ /// The call for the provided hash was not found so the task has been aborted.
+ CallUnavailable {
+ /// The task's address - the block number and the block's agenda index.
+ task: TaskAddress<T::BlockNumber>,
+
+ /// The task's name if it is not anonymous.
+ id: Option<[u8; 32]>,
+ },
+ /// The given task can never be executed since it is overweight.
+ PermanentlyOverweight {
+ /// The task's address - the block number and the block's agenda index.
+ task: TaskAddress<T::BlockNumber>,
+
+ /// The task's name if it is not anonymous.
+ id: Option<[u8; 32]>,
+ },
+ }
+
+ #[pallet::error]
+ pub enum Error<T> {
+ /// Failed to schedule a call
+ FailedToSchedule,
+ /// There is no place for a new task in the agenda
+ AgendaIsExhausted,
+ /// Scheduled call is corrupted
+ ScheduledCallCorrupted,
+ /// Scheduled call preimage is not found
+ PreimageNotFound,
+ /// Scheduled call is too big
+ TooBigScheduledCall,
+ /// Cannot find the scheduled call.
+ NotFound,
+ /// Given target block number is in the past.
+ TargetBlockNumberInPast,
+ /// Attempt to use a non-named function on a named task.
+ Named,
+ }
+
+ #[pallet::hooks]
+ impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
+ /// Execute the scheduled calls
+ fn on_initialize(now: T::BlockNumber) -> Weight {
+ let mut weight_counter = WeightCounter {
+ used: Weight::zero(),
+ limit: T::MaximumWeight::get(),
+ };
+ Self::service_agendas(&mut weight_counter, now, u32::max_value());
+ weight_counter.used
+ }
+ }
+
+ #[pallet::call]
+ impl<T: Config> Pallet<T> {
+ /// Anonymously schedule a task.
+ ///
+ /// Only `T::ScheduleOrigin` is allowed to schedule a task.
+ /// Only `T::PrioritySetOrigin` is allowed to set the task's priority.
+ #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]
+ pub fn schedule(
+ origin: OriginFor<T>,
+ when: T::BlockNumber,
+ maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
+ priority: Option<schedule::Priority>,
+ call: Box<<T as Config>::RuntimeCall>,
+ ) -> DispatchResult {
+ T::ScheduleOrigin::ensure_origin(origin.clone())?;
+
+ if priority.is_some() {
+ T::PrioritySetOrigin::ensure_origin(origin.clone())?;
+ }
+
+ let origin = <T as Config>::RuntimeOrigin::from(origin);
+ Self::do_schedule(
+ DispatchTime::At(when),
+ maybe_periodic,
+ priority.unwrap_or(LOWEST_PRIORITY),
+ origin.caller().clone(),
+ <ScheduledCall<T>>::new(*call)?,
+ )?;
+ Ok(())
+ }
+
+ /// Cancel an anonymously scheduled task.
+ ///
+ /// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.
+ #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]
+ pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {
+ T::ScheduleOrigin::ensure_origin(origin.clone())?;
+ let origin = <T as Config>::RuntimeOrigin::from(origin);
+ Self::do_cancel(Some(origin.caller().clone()), (when, index))?;
+ Ok(())
+ }
+
+ /// Schedule a named task.
+ ///
+ /// Only `T::ScheduleOrigin` is allowed to schedule a task.
+ /// Only `T::PrioritySetOrigin` is allowed to set the task's priority.
+ #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
+ pub fn schedule_named(
+ origin: OriginFor<T>,
+ id: TaskName,
+ when: T::BlockNumber,
+ maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
+ priority: Option<schedule::Priority>,
+ call: Box<<T as Config>::RuntimeCall>,
+ ) -> DispatchResult {
+ T::ScheduleOrigin::ensure_origin(origin.clone())?;
+
+ if priority.is_some() {
+ T::PrioritySetOrigin::ensure_origin(origin.clone())?;
+ }
+
+ let origin = <T as Config>::RuntimeOrigin::from(origin);
+ Self::do_schedule_named(
+ id,
+ DispatchTime::At(when),
+ maybe_periodic,
+ priority.unwrap_or(LOWEST_PRIORITY),
+ origin.caller().clone(),
+ <ScheduledCall<T>>::new(*call)?,
+ )?;
+ Ok(())
+ }
+
+ /// Cancel a named scheduled task.
+ ///
+ /// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.
+ #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]
+ pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {
+ T::ScheduleOrigin::ensure_origin(origin.clone())?;
+ let origin = <T as Config>::RuntimeOrigin::from(origin);
+ Self::do_cancel_named(Some(origin.caller().clone()), id)?;
+ Ok(())
+ }
+
+ /// Anonymously schedule a task after a delay.
+ ///
+ /// # <weight>
+ /// Same as [`schedule`].
+ /// # </weight>
+ #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]
+ pub fn schedule_after(
+ origin: OriginFor<T>,
+ after: T::BlockNumber,
+ maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
+ priority: Option<schedule::Priority>,
+ call: Box<<T as Config>::RuntimeCall>,
+ ) -> DispatchResult {
+ T::ScheduleOrigin::ensure_origin(origin.clone())?;
+
+ if priority.is_some() {
+ T::PrioritySetOrigin::ensure_origin(origin.clone())?;
+ }
+
+ let origin = <T as Config>::RuntimeOrigin::from(origin);
+ Self::do_schedule(
+ DispatchTime::After(after),
+ maybe_periodic,
+ priority.unwrap_or(LOWEST_PRIORITY),
+ origin.caller().clone(),
+ <ScheduledCall<T>>::new(*call)?,
+ )?;
+ Ok(())
+ }
+
+ /// Schedule a named task after a delay.
+ ///
+ /// Only `T::ScheduleOrigin` is allowed to schedule a task.
+ /// Only `T::PrioritySetOrigin` is allowed to set the task's priority.
+ ///
+ /// # <weight>
+ /// Same as [`schedule_named`](Self::schedule_named).
+ /// # </weight>
+ #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
+ pub fn schedule_named_after(
+ origin: OriginFor<T>,
+ id: TaskName,
+ after: T::BlockNumber,
+ maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
+ priority: Option<schedule::Priority>,
+ call: Box<<T as Config>::RuntimeCall>,
+ ) -> DispatchResult {
+ T::ScheduleOrigin::ensure_origin(origin.clone())?;
+
+ if priority.is_some() {
+ T::PrioritySetOrigin::ensure_origin(origin.clone())?;
+ }
+
+ let origin = <T as Config>::RuntimeOrigin::from(origin);
+ Self::do_schedule_named(
+ id,
+ DispatchTime::After(after),
+ maybe_periodic,
+ priority.unwrap_or(LOWEST_PRIORITY),
+ origin.caller().clone(),
+ <ScheduledCall<T>>::new(*call)?,
+ )?;
+ Ok(())
+ }
+
+ /// Change a named task's priority.
+ ///
+ /// Only the `T::PrioritySetOrigin` is allowed to change the task's priority.
+ #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]
+ pub fn change_named_priority(
+ origin: OriginFor<T>,
+ id: TaskName,
+ priority: schedule::Priority,
+ ) -> DispatchResult {
+ T::PrioritySetOrigin::ensure_origin(origin.clone())?;
+ let origin = <T as Config>::RuntimeOrigin::from(origin);
+ Self::do_change_named_priority(origin.caller().clone(), id, priority)
+ }
+ }
+}
+
+impl<T: Config> Pallet<T> {
+ /// Converts the `DispatchTime` to the `BlockNumber`.
+ ///
+ /// Returns an error if the block number is in the past.
+ fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {
+ let now = frame_system::Pallet::<T>::block_number();
+
+ let when = match when {
+ DispatchTime::At(x) => x,
+ // The current block has already completed it's scheduled tasks, so
+ // Schedule the task at lest one block after this current block.
+ DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),
+ };
+
+ if when <= now {
+ return Err(Error::<T>::TargetBlockNumberInPast.into());
+ }
+
+ Ok(when)
+ }
+
+ /// Places the mandatory task.
+ ///
+ /// It will try to place the task into the block pointed by the `when` parameter.
+ ///
+ /// If the block has no room for a task,
+ /// the function will search for a future block that can accommodate the task.
+ fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {
+ Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");
+ }
+
+ /// Tries to place a task `what` into the given block `when`.
+ ///
+ /// Returns an error if the block has no room for the task.
+ fn try_place_task(
+ when: T::BlockNumber,
+ what: ScheduledOf<T>,
+ ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
+ Self::place_task(when, what, false)
+ }
+
+ /// If `is_mandatory` is true, the function behaves like [`mandatory_place_task`](Self::mandatory_place_task);
+ /// otherwise it acts like [`try_place_task`](Self::try_place_task).
+ ///
+ /// The function also updates the `Lookup` storage.
+ fn place_task(
+ mut when: T::BlockNumber,
+ what: ScheduledOf<T>,
+ is_mandatory: bool,
+ ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
+ let maybe_name = what.maybe_id;
+ let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;
+ let address = (when, index);
+ if let Some(name) = maybe_name {
+ Lookup::<T>::insert(name, address)
+ }
+ Self::deposit_event(Event::Scheduled {
+ when: address.0,
+ index: address.1,
+ });
+ Ok(address)
+ }
+
+ /// Pushes the scheduled task into the block's agenda.
+ ///
+ /// If `is_mandatory` is true, it searches for a block with a free slot for the given task.
+ ///
+ /// If `is_mandatory` is false and there is no free slot, the function returns an error.
+ fn push_to_agenda(
+ when: &mut T::BlockNumber,
+ mut what: ScheduledOf<T>,
+ is_mandatory: bool,
+ ) -> Result<u32, DispatchError> {
+ let mut agenda;
+
+ let index = loop {
+ agenda = Agenda::<T>::get(*when);
+
+ match agenda.try_push(what) {
+ Ok(index) => break index,
+ Err(returned_what) if is_mandatory => {
+ what = returned_what;
+ when.saturating_inc();
+ }
+ Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),
+ }
+ };
+
+ Agenda::<T>::insert(when, agenda);
+ Ok(index)
+ }
+
+ fn do_schedule(
+ when: DispatchTime<T::BlockNumber>,
+ maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
+ priority: schedule::Priority,
+ origin: T::PalletsOrigin,
+ call: ScheduledCall<T>,
+ ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
+ let when = Self::resolve_time(when)?;
+
+ // sanitize maybe_periodic
+ let maybe_periodic = maybe_periodic
+ .filter(|p| p.1 > 1 && !p.0.is_zero())
+ // Remove one from the number of repetitions since we will schedule one now.
+ .map(|(p, c)| (p, c - 1));
+ let task = Scheduled {
+ maybe_id: None,
+ priority,
+ call,
+ maybe_periodic,
+ origin,
+ _phantom: PhantomData,
+ };
+ Self::try_place_task(when, task)
+ }
+
+ fn do_cancel(
+ origin: Option<T::PalletsOrigin>,
+ (when, index): TaskAddress<T::BlockNumber>,
+ ) -> Result<(), DispatchError> {
+ let scheduled = Agenda::<T>::try_mutate(
+ when,
+ |agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {
+ let scheduled = match agenda.get(index) {
+ Some(scheduled) => scheduled,
+ None => return Ok(None),
+ };
+
+ if let Some(ref o) = origin {
+ if matches!(
+ T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),
+ Some(Ordering::Less) | None
+ ) {
+ return Err(BadOrigin.into());
+ }
+ }
+
+ Ok(agenda.take(index))
+ },
+ )?;
+ if let Some(s) = scheduled {
+ T::Preimages::drop(&s.call);
+
+ if let Some(id) = s.maybe_id {
+ Lookup::<T>::remove(id);
+ }
+ Self::deposit_event(Event::Canceled { when, index });
+ Ok(())
+ } else {
+ Err(Error::<T>::NotFound.into())
+ }
+ }
+
+ fn do_schedule_named(
+ id: TaskName,
+ when: DispatchTime<T::BlockNumber>,
+ maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
+ priority: schedule::Priority,
+ origin: T::PalletsOrigin,
+ call: ScheduledCall<T>,
+ ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
+ // ensure id it is unique
+ if Lookup::<T>::contains_key(&id) {
+ return Err(Error::<T>::FailedToSchedule.into());
+ }
+
+ let when = Self::resolve_time(when)?;
+
+ // sanitize maybe_periodic
+ let maybe_periodic = maybe_periodic
+ .filter(|p| p.1 > 1 && !p.0.is_zero())
+ // Remove one from the number of repetitions since we will schedule one now.
+ .map(|(p, c)| (p, c - 1));
+
+ let task = Scheduled {
+ maybe_id: Some(id),
+ priority,
+ call,
+ maybe_periodic,
+ origin,
+ _phantom: Default::default(),
+ };
+ Self::try_place_task(when, task)
+ }
+
+ fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {
+ Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {
+ if let Some((when, index)) = lookup.take() {
+ Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {
+ let scheduled = match agenda.get(index) {
+ Some(scheduled) => scheduled,
+ None => return Ok(()),
+ };
+
+ if let Some(ref o) = origin {
+ if matches!(
+ T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),
+ Some(Ordering::Less) | None
+ ) {
+ return Err(BadOrigin.into());
+ }
+ T::Preimages::drop(&scheduled.call);
+ }
+
+ agenda.take(index);
+
+ Ok(())
+ })?;
+ Self::deposit_event(Event::Canceled { when, index });
+ Ok(())
+ } else {
+ Err(Error::<T>::NotFound.into())
+ }
+ })
+ }
+
+ fn do_change_named_priority(
+ origin: T::PalletsOrigin,
+ id: TaskName,
+ priority: schedule::Priority,
+ ) -> DispatchResult {
+ match Lookup::<T>::get(id) {
+ Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {
+ let scheduled = match agenda.get_mut(index) {
+ Some(scheduled) => scheduled,
+ None => return Ok(()),
+ };
+
+ if matches!(
+ T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),
+ Some(Ordering::Less) | None
+ ) {
+ return Err(BadOrigin.into());
+ }
+
+ scheduled.priority = priority;
+ Self::deposit_event(Event::PriorityChanged {
+ task: (when, index),
+ priority,
+ });
+
+ Ok(())
+ }),
+ None => Err(Error::<T>::NotFound.into()),
+ }
+ }
+}
+
+enum ServiceTaskError {
+ /// Could not be executed due to missing preimage.
+ Unavailable,
+ /// Could not be executed due to weight limitations.
+ Overweight,
+}
+use ServiceTaskError::*;
+
+/// A Scheduler-Runtime interface for finer payment handling.
+pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {
+ /// Resolve the call dispatch, including any post-dispatch operations.
+ fn dispatch_call(
+ signer: Option<T::AccountId>,
+ function: <T as Config>::RuntimeCall,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ >;
+}
+
+impl<T: Config> Pallet<T> {
+ /// Service up to `max` agendas queue starting from earliest incompletely executed agenda.
+ fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {
+ if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {
+ return;
+ }
+
+ let mut incomplete_since = now + One::one();
+ let mut when = IncompleteSince::<T>::take().unwrap_or(now);
+ let mut executed = 0;
+
+ let max_items = T::MaxScheduledPerBlock::get();
+ let mut count_down = max;
+ let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);
+ while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {
+ if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {
+ incomplete_since = incomplete_since.min(when);
+ }
+ when.saturating_inc();
+ count_down.saturating_dec();
+ }
+ incomplete_since = incomplete_since.min(when);
+ if incomplete_since <= now {
+ IncompleteSince::<T>::put(incomplete_since);
+ }
+ }
+
+ /// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a
+ /// later block.
+ fn service_agenda(
+ weight: &mut WeightCounter,
+ executed: &mut u32,
+ now: T::BlockNumber,
+ when: T::BlockNumber,
+ max: u32,
+ ) -> bool {
+ let mut agenda = Agenda::<T>::get(when);
+ let mut ordered = agenda
+ .iter()
+ .enumerate()
+ .filter_map(|(index, maybe_item)| {
+ maybe_item
+ .as_ref()
+ .map(|item| (index as u32, item.priority))
+ })
+ .collect::<Vec<_>>();
+ ordered.sort_by_key(|k| k.1);
+ let within_limit =
+ weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));
+ debug_assert!(
+ within_limit,
+ "weight limit should have been checked in advance"
+ );
+
+ // Items which we know can be executed and have postponed for execution in a later block.
+ let mut postponed = (ordered.len() as u32).saturating_sub(max);
+ // Items which we don't know can ever be executed.
+ let mut dropped = 0;
+
+ for (agenda_index, _) in ordered.into_iter().take(max as usize) {
+ let task = match agenda.take(agenda_index).take() {
+ None => continue,
+ Some(t) => t,
+ };
+ let base_weight = MarginalWeightInfo::<T>::service_task(
+ task.call.lookup_len().map(|x| x as usize),
+ task.maybe_id.is_some(),
+ task.maybe_periodic.is_some(),
+ );
+ if !weight.can_accrue(base_weight) {
+ postponed += 1;
+ break;
+ }
+ let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);
+ match result {
+ Err((Unavailable, slot)) => {
+ dropped += 1;
+ agenda.set_slot(agenda_index, slot);
+ }
+ Err((Overweight, slot)) => {
+ postponed += 1;
+ agenda.set_slot(agenda_index, slot);
+ }
+ Ok(()) => {
+ *executed += 1;
+ }
+ };
+ }
+ if postponed > 0 || dropped > 0 {
+ Agenda::<T>::insert(when, agenda);
+ } else {
+ Agenda::<T>::remove(when);
+ }
+ postponed == 0
+ }
+
+ /// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.
+ ///
+ /// This involves:
+ /// - removing and potentially replacing the `Lookup` entry for the task.
+ /// - realizing the task's call which can include a preimage lookup.
+ /// - Rescheduling the task for execution in a later agenda if periodic.
+ fn service_task(
+ weight: &mut WeightCounter,
+ now: T::BlockNumber,
+ when: T::BlockNumber,
+ agenda_index: u32,
+ is_first: bool,
+ mut task: ScheduledOf<T>,
+ ) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {
+ let (call, lookup_len) = match T::Preimages::peek(&task.call) {
+ Ok(c) => c,
+ Err(_) => {
+ if let Some(ref id) = task.maybe_id {
+ Lookup::<T>::remove(id);
+ }
+
+ return Err((Unavailable, Some(task)));
+ }
+ };
+
+ weight.check_accrue(MarginalWeightInfo::<T>::service_task(
+ lookup_len.map(|x| x as usize),
+ task.maybe_id.is_some(),
+ task.maybe_periodic.is_some(),
+ ));
+
+ match Self::execute_dispatch(weight, task.origin.clone(), call) {
+ Err(Unavailable) => {
+ debug_assert!(false, "Checked to exist with `peek`");
+
+ if let Some(ref id) = task.maybe_id {
+ Lookup::<T>::remove(id);
+ }
+
+ Self::deposit_event(Event::CallUnavailable {
+ task: (when, agenda_index),
+ id: task.maybe_id,
+ });
+ Err((Unavailable, Some(task)))
+ }
+ Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {
+ T::Preimages::drop(&task.call);
+
+ if let Some(ref id) = task.maybe_id {
+ Lookup::<T>::remove(id);
+ }
+
+ Self::deposit_event(Event::PermanentlyOverweight {
+ task: (when, agenda_index),
+ id: task.maybe_id,
+ });
+ Err((Unavailable, Some(task)))
+ }
+ Err(Overweight) => {
+ // Preserve Lookup -- the task will be postponed.
+ Err((Overweight, Some(task)))
+ }
+ Ok(result) => {
+ Self::deposit_event(Event::Dispatched {
+ task: (when, agenda_index),
+ id: task.maybe_id,
+ result,
+ });
+
+ let is_canceled = task
+ .maybe_id
+ .as_ref()
+ .map(|id| !Lookup::<T>::contains_key(id))
+ .unwrap_or(false);
+
+ match &task.maybe_periodic {
+ &Some((period, count)) if !is_canceled => {
+ if count > 1 {
+ task.maybe_periodic = Some((period, count - 1));
+ } else {
+ task.maybe_periodic = None;
+ }
+ let wake = now.saturating_add(period);
+ Self::mandatory_place_task(wake, task);
+ }
+ _ => {
+ if let Some(ref id) = task.maybe_id {
+ Lookup::<T>::remove(id);
+ }
+
+ T::Preimages::drop(&task.call)
+ }
+ }
+ Ok(())
+ }
+ }
+ }
+
+ fn is_runtime_upgraded() -> bool {
+ let last = system::LastRuntimeUpgrade::<T>::get();
+ let current = T::Version::get();
+
+ last.map(|v| v.was_upgraded(¤t)).unwrap_or(true)
+ }
+
+ /// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`
+ /// counter does not exceed its limit and that it is counted accurately (e.g. accounted using
+ /// post info if available).
+ ///
+ /// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the
+ /// call itself).
+ fn execute_dispatch(
+ weight: &mut WeightCounter,
+ origin: T::PalletsOrigin,
+ call: <T as Config>::RuntimeCall,
+ ) -> Result<DispatchResult, ServiceTaskError> {
+ let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();
+ let base_weight = match dispatch_origin.clone().as_signed() {
+ Some(_) => T::WeightInfo::execute_dispatch_signed(),
+ _ => T::WeightInfo::execute_dispatch_unsigned(),
+ };
+ let call_weight = call.get_dispatch_info().weight;
+ // We only allow a scheduled call if it cannot push the weight past the limit.
+ let max_weight = base_weight.saturating_add(call_weight);
+
+ if !weight.can_accrue(max_weight) {
+ return Err(Overweight);
+ }
+
+ let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());
+
+ let r = match ensured_origin {
+ Ok(ScheduledEnsureOriginSuccess::Root) => {
+ Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))
+ }
+ Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {
+ // Execute transaction via chain default pipeline
+ // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken
+ T::CallExecutor::dispatch_call(Some(sender), call)
+ }
+ Err(e) => Ok(Err(e.into())),
+ };
+
+ let (maybe_actual_call_weight, result) = match r {
+ Ok(result) => match result {
+ Ok(post_info) => (post_info.actual_weight, Ok(())),
+ Err(error_and_info) => (
+ error_and_info.post_info.actual_weight,
+ Err(error_and_info.error),
+ ),
+ },
+ Err(_) => {
+ log::error!(
+ target: "runtime::scheduler",
+ "Warning: Scheduler has failed to execute a post-dispatch transaction. \
+ This block might have become invalid.");
+ (None, Err(DispatchError::CannotLookup))
+ }
+ };
+ let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);
+ weight.check_accrue(base_weight);
+ weight.check_accrue(call_weight);
+ Ok(result)
+ }
+}
pallets/scheduler-v2/src/mock.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/scheduler-v2/src/mock.rs
@@ -0,0 +1,287 @@
+// 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-2022 Parity Technologies (UK) Ltd.
+// SPDX-License-Identifier: Apache-2.0
+
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! # Scheduler test environment.
+
+use super::*;
+
+use crate as scheduler;
+use frame_support::{
+ ord_parameter_types, parameter_types,
+ traits::{ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnFinalize, OnInitialize},
+ weights::constants::RocksDbWeight,
+};
+use frame_system::{EnsureRoot, RawOrigin};
+use sp_core::H256;
+use sp_runtime::{
+ testing::Header,
+ traits::{BlakeTwo256, IdentityLookup},
+ Perbill,
+};
+
+// Logger module to track execution.
+#[frame_support::pallet]
+pub mod logger {
+ use super::{OriginCaller, OriginTrait};
+ use frame_support::{pallet_prelude::*, parameter_types};
+ use frame_system::pallet_prelude::*;
+
+ parameter_types! {
+ static Log: Vec<(OriginCaller, u32)> = Vec::new();
+ }
+ pub fn log() -> Vec<(OriginCaller, u32)> {
+ Log::get().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 RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
+ }
+
+ #[pallet::event]
+ #[pallet::generate_deposit(pub(super) fn deposit_event)]
+ pub enum Event<T: Config> {
+ Logged(u32, Weight),
+ }
+
+ #[pallet::call]
+ impl<T: Config> Pallet<T>
+ where
+ <T as frame_system::Config>::RuntimeOrigin: 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::mutate(|log| {
+ log.push((origin.caller().clone(), i));
+ });
+ Ok(())
+ }
+
+ #[pallet::weight(*weight)]
+ pub fn log_without_filter(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {
+ Self::deposit_event(Event::Logged(i, weight));
+ Log::mutate(|log| {
+ log.push((origin.caller().clone(), i));
+ });
+ Ok(())
+ }
+ }
+}
+
+type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
+type Block = frame_system::mocking::MockBlock<Test>;
+
+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>},
+ }
+);
+
+// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.
+pub struct BaseFilter;
+impl Contains<RuntimeCall> for BaseFilter {
+ fn contains(call: &RuntimeCall) -> bool {
+ !matches!(call, RuntimeCall::Logger(LoggerCall::log { .. }))
+ }
+}
+
+parameter_types! {
+ pub BlockWeights: frame_system::limits::BlockWeights =
+ frame_system::limits::BlockWeights::simple_max(
+ Weight::from_ref_time(2_000_000_000_000)
+ // .set_proof_size(u64::MAX),
+ );
+}
+impl system::Config for Test {
+ type BaseCallFilter = BaseFilter;
+ type BlockWeights = BlockWeights;
+ type BlockLength = ();
+ type DbWeight = RocksDbWeight;
+ type RuntimeOrigin = RuntimeOrigin;
+ type RuntimeCall = RuntimeCall;
+ type Index = u64;
+ type BlockNumber = u64;
+ type Hash = H256;
+ type Hashing = BlakeTwo256;
+ type AccountId = u64;
+ type Lookup = IdentityLookup<Self::AccountId>;
+ type Header = Header;
+ type RuntimeEvent = RuntimeEvent;
+ type BlockHashCount = ConstU64<250>;
+ 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 RuntimeEvent = RuntimeEvent;
+}
+ord_parameter_types! {
+ pub const One: u64 = 1;
+}
+
+pub struct TestWeightInfo;
+impl WeightInfo for TestWeightInfo {
+ fn service_agendas_base() -> Weight {
+ Weight::from_ref_time(0b0000_0001)
+ }
+ fn service_agenda_base(i: u32) -> Weight {
+ Weight::from_ref_time((i << 8) as u64 + 0b0000_0010)
+ }
+ fn service_task_base() -> Weight {
+ Weight::from_ref_time(0b0000_0100)
+ }
+ fn service_task_periodic() -> Weight {
+ Weight::from_ref_time(0b0000_1100)
+ }
+ fn service_task_named() -> Weight {
+ Weight::from_ref_time(0b0001_0100)
+ }
+ // fn service_task_fetched(s: u32) -> Weight {
+ // Weight::from_ref_time((s << 8) as u64 + 0b0010_0100)
+ // }
+ fn execute_dispatch_signed() -> Weight {
+ Weight::from_ref_time(0b0100_0000)
+ }
+ fn execute_dispatch_unsigned() -> Weight {
+ Weight::from_ref_time(0b1000_0000)
+ }
+ fn schedule(_s: u32) -> Weight {
+ Weight::from_ref_time(50)
+ }
+ fn cancel(_s: u32) -> Weight {
+ Weight::from_ref_time(50)
+ }
+ fn schedule_named(_s: u32) -> Weight {
+ Weight::from_ref_time(50)
+ }
+ fn cancel_named(_s: u32) -> Weight {
+ Weight::from_ref_time(50)
+ }
+ fn change_named_priority(_s: u32) -> Weight {
+ Weight::from_ref_time(50)
+ }
+}
+parameter_types! {
+ pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
+ BlockWeights::get().max_block;
+}
+
+pub struct EnsureSignedOneOrRoot;
+impl<O: Into<Result<RawOrigin<u64>, O>> + From<RawOrigin<u64>>> EnsureOrigin<O>
+ for EnsureSignedOneOrRoot
+{
+ type Success = ScheduledEnsureOriginSuccess<u64>;
+ fn try_origin(o: O) -> Result<Self::Success, O> {
+ o.into().and_then(|o| match o {
+ RawOrigin::Root => Ok(ScheduledEnsureOriginSuccess::Root),
+ RawOrigin::Signed(1) => Ok(ScheduledEnsureOriginSuccess::Signed(1)),
+ r => Err(O::from(r)),
+ })
+ }
+}
+
+pub struct Executor;
+impl DispatchCall<Test, sp_core::H160> for Executor {
+ fn dispatch_call(
+ signer: Option<u64>,
+ function: RuntimeCall,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ > {
+ let origin = match signer {
+ Some(who) => RuntimeOrigin::signed(who),
+ None => RuntimeOrigin::none(),
+ };
+ Ok(function.dispatch(origin))
+ }
+}
+
+impl Config for Test {
+ type RuntimeEvent = RuntimeEvent;
+ type RuntimeOrigin = RuntimeOrigin;
+ type PalletsOrigin = OriginCaller;
+ type RuntimeCall = RuntimeCall;
+ type MaximumWeight = MaximumSchedulerWeight;
+ type ScheduleOrigin = EnsureSignedOneOrRoot;
+ type MaxScheduledPerBlock = ConstU32<10>;
+ type WeightInfo = TestWeightInfo;
+ type OriginPrivilegeCmp = EqualPrivilegeOnly;
+ type Preimages = ();
+ type PrioritySetOrigin = EnsureRoot<u64>;
+ type CallExecutor = Executor;
+}
+
+pub type LoggerCall = logger::Call<Test>;
+
+pub type SystemCall = frame_system::Call<Test>;
+
+pub fn new_test_ext() -> sp_io::TestExternalities {
+ let t = system::GenesisConfig::default()
+ .build_storage::<Test>()
+ .unwrap();
+ t.into()
+}
+
+pub fn run_to_block(n: u64) {
+ while System::block_number() < n {
+ Scheduler::on_finalize(System::block_number());
+ System::set_block_number(System::block_number() + 1);
+ Scheduler::on_initialize(System::block_number());
+ }
+}
+
+pub fn root() -> OriginCaller {
+ system::RawOrigin::Root.into()
+}
pallets/scheduler-v2/src/tests.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/scheduler-v2/src/tests.rs
@@ -0,0 +1,900 @@
+// 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-2022 Parity Technologies (UK) Ltd.
+// SPDX-License-Identifier: Apache-2.0
+
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! # Scheduler tests.
+
+use super::*;
+use crate::mock::{
+ logger, new_test_ext, root, run_to_block, LoggerCall, RuntimeCall, Scheduler, Test, *,
+};
+use frame_support::{
+ assert_noop, assert_ok,
+ traits::{Contains, OnInitialize},
+ assert_err,
+};
+
+#[test]
+fn basic_scheduling_works() {
+ new_test_ext().execute_with(|| {
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
+ assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
+ &call
+ ));
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ run_to_block(3);
+ assert!(logger::log().is_empty());
+ run_to_block(4);
+ assert_eq!(logger::log(), vec![(root(), 42u32)]);
+ run_to_block(100);
+ assert_eq!(logger::log(), vec![(root(), 42u32)]);
+ });
+}
+
+#[test]
+fn schedule_after_works() {
+ new_test_ext().execute_with(|| {
+ run_to_block(2);
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
+ assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
+ &call
+ ));
+ // This will schedule the call 3 blocks after the next block... so block 3 + 3 = 6
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::After(3),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ run_to_block(5);
+ assert!(logger::log().is_empty());
+ run_to_block(6);
+ assert_eq!(logger::log(), vec![(root(), 42u32)]);
+ run_to_block(100);
+ assert_eq!(logger::log(), vec![(root(), 42u32)]);
+ });
+}
+
+#[test]
+fn schedule_after_zero_works() {
+ new_test_ext().execute_with(|| {
+ run_to_block(2);
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
+ assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
+ &call
+ ));
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::After(0),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ // Will trigger on the next block.
+ run_to_block(3);
+ assert_eq!(logger::log(), vec![(root(), 42u32)]);
+ run_to_block(100);
+ assert_eq!(logger::log(), vec![(root(), 42u32)]);
+ });
+}
+
+#[test]
+fn periodic_scheduling_works() {
+ new_test_ext().execute_with(|| {
+ // at #4, every 3 blocks, 3 times.
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ Some((3, 3)),
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(RuntimeCall::Logger(logger::Call::log {
+ i: 42,
+ weight: Weight::from_ref_time(10)
+ }))
+ .unwrap()
+ ));
+ run_to_block(3);
+ assert!(logger::log().is_empty());
+ run_to_block(4);
+ assert_eq!(logger::log(), vec![(root(), 42u32)]);
+ run_to_block(6);
+ assert_eq!(logger::log(), vec![(root(), 42u32)]);
+ run_to_block(7);
+ assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
+ run_to_block(9);
+ assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
+ run_to_block(10);
+ assert_eq!(
+ logger::log(),
+ vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
+ );
+ run_to_block(100);
+ assert_eq!(
+ logger::log(),
+ vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
+ );
+ });
+}
+
+#[test]
+fn cancel_named_scheduling_works_with_normal_cancel() {
+ new_test_ext().execute_with(|| {
+ // at #4.
+ Scheduler::do_schedule_named(
+ [1u8; 32],
+ DispatchTime::At(4),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: Weight::from_ref_time(10),
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ let i = Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ run_to_block(3);
+ assert!(logger::log().is_empty());
+ assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));
+ assert_ok!(Scheduler::do_cancel(None, i));
+ run_to_block(100);
+ assert!(logger::log().is_empty());
+ });
+}
+
+#[test]
+fn cancel_named_periodic_scheduling_works() {
+ new_test_ext().execute_with(|| {
+ // at #4, every 3 blocks, 3 times.
+ Scheduler::do_schedule_named(
+ [1u8; 32],
+ DispatchTime::At(4),
+ Some((3, 3)),
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ // same id results in error.
+ assert!(Scheduler::do_schedule_named(
+ [1u8; 32],
+ DispatchTime::At(4),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: Weight::from_ref_time(10)
+ }))
+ .unwrap(),
+ )
+ .is_err());
+ // different id is ok.
+ Scheduler::do_schedule_named(
+ [2u8; 32],
+ DispatchTime::At(8),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: Weight::from_ref_time(10),
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ run_to_block(3);
+ assert!(logger::log().is_empty());
+ run_to_block(4);
+ assert_eq!(logger::log(), vec![(root(), 42u32)]);
+ run_to_block(6);
+ assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));
+ run_to_block(100);
+ assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
+ });
+}
+
+#[test]
+fn scheduler_respects_weight_limits() {
+ let max_weight: Weight = <Test as Config>::MaximumWeight::get();
+ new_test_ext().execute_with(|| {
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: max_weight / 3 * 2,
+ });
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: max_weight / 3 * 2,
+ });
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ // 69 and 42 do not fit together
+ run_to_block(4);
+ assert_eq!(logger::log(), vec![(root(), 42u32)]);
+ run_to_block(5);
+ assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
+ });
+}
+
+/// Permanently overweight calls are not deleted but also not executed.
+#[test]
+fn scheduler_does_not_delete_permanently_overweight_call() {
+ let max_weight: Weight = <Test as Config>::MaximumWeight::get();
+ new_test_ext().execute_with(|| {
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: max_weight,
+ });
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ // Never executes.
+ run_to_block(100);
+ assert_eq!(logger::log(), vec![]);
+
+ // Assert the `PermanentlyOverweight` event.
+ assert_eq!(
+ System::events().last().unwrap().event,
+ crate::Event::PermanentlyOverweight {
+ task: (4, 0),
+ id: None
+ }
+ .into(),
+ );
+ // The call is still in the agenda.
+ assert!(Agenda::<Test>::get(4).agenda[0].is_some());
+ });
+}
+
+#[test]
+fn scheduler_periodic_tasks_always_find_place() {
+ let max_weight: Weight = <Test as Config>::MaximumWeight::get();
+ let max_per_block = <Test as Config>::MaxScheduledPerBlock::get();
+
+ new_test_ext().execute_with(|| {
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: (max_weight / 3) * 2,
+ });
+ let call = <ScheduledCall<Test>>::new(call).unwrap();
+
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ Some((4, u32::MAX)),
+ 127,
+ root(),
+ call.clone(),
+ ));
+ // Executes 5 times till block 20.
+ run_to_block(20);
+ assert_eq!(logger::log().len(), 5);
+
+ // Block 28 will already be full.
+ for _ in 0..max_per_block {
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(28),
+ None,
+ 120,
+ root(),
+ call.clone(),
+ ));
+ }
+
+ run_to_block(24);
+ assert_eq!(logger::log().len(), 6);
+
+ // The periodic task should be postponed
+ assert_eq!(<Agenda<Test>>::get(29).agenda.len(), 1);
+
+ run_to_block(27); // will call on_initialize(28)
+ assert_eq!(logger::log().len(), 6);
+
+ run_to_block(28); // will call on_initialize(29)
+ assert_eq!(logger::log().len(), 7);
+ });
+}
+
+#[test]
+fn scheduler_respects_priority_ordering() {
+ let max_weight: Weight = <Test as Config>::MaximumWeight::get();
+ new_test_ext().execute_with(|| {
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: max_weight / 3,
+ });
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 1,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: max_weight / 3,
+ });
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 0,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ run_to_block(4);
+ assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);
+ });
+}
+
+#[test]
+fn scheduler_respects_priority_ordering_with_soft_deadlines() {
+ new_test_ext().execute_with(|| {
+ let max_weight: Weight = <Test as Config>::MaximumWeight::get();
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: max_weight / 5 * 2,
+ });
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 255,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: max_weight / 5 * 2,
+ });
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 2600,
+ weight: max_weight / 5 * 4,
+ });
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 126,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+
+ // 2600 does not fit with 69 or 42, but has higher priority, so will go through
+ run_to_block(4);
+ assert_eq!(logger::log(), vec![(root(), 2600u32)]);
+ // 69 and 42 fit together
+ run_to_block(5);
+ assert_eq!(
+ logger::log(),
+ vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
+ );
+ });
+}
+
+#[test]
+fn on_initialize_weight_is_correct() {
+ new_test_ext().execute_with(|| {
+ let call_weight = Weight::from_ref_time(25);
+
+ // Named
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 3,
+ weight: call_weight + Weight::from_ref_time(1),
+ });
+ assert_ok!(Scheduler::do_schedule_named(
+ [1u8; 32],
+ DispatchTime::At(3),
+ None,
+ 255,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: call_weight + Weight::from_ref_time(2),
+ });
+ // Anon Periodic
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(2),
+ Some((1000, 3)),
+ 128,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: call_weight + Weight::from_ref_time(3),
+ });
+ // Anon
+ assert_ok!(Scheduler::do_schedule(
+ DispatchTime::At(2),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+ // Named Periodic
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 2600,
+ weight: call_weight + Weight::from_ref_time(4),
+ });
+ assert_ok!(Scheduler::do_schedule_named(
+ [2u8; 32],
+ DispatchTime::At(1),
+ Some((1000, 3)),
+ 126,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ ));
+
+ // Will include the named periodic only
+ assert_eq!(
+ Scheduler::on_initialize(1),
+ TestWeightInfo::service_agendas_base()
+ + TestWeightInfo::service_agenda_base(1)
+ + <MarginalWeightInfo<Test>>::service_task(None, true, true)
+ + TestWeightInfo::execute_dispatch_unsigned()
+ + call_weight + Weight::from_ref_time(4)
+ );
+ assert_eq!(IncompleteSince::<Test>::get(), None);
+ assert_eq!(logger::log(), vec![(root(), 2600u32)]);
+
+ // Will include anon and anon periodic
+ assert_eq!(
+ Scheduler::on_initialize(2),
+ TestWeightInfo::service_agendas_base()
+ + TestWeightInfo::service_agenda_base(2)
+ + <MarginalWeightInfo<Test>>::service_task(None, false, true)
+ + TestWeightInfo::execute_dispatch_unsigned()
+ + call_weight + Weight::from_ref_time(3)
+ + <MarginalWeightInfo<Test>>::service_task(None, false, false)
+ + TestWeightInfo::execute_dispatch_unsigned()
+ + call_weight + Weight::from_ref_time(2)
+ );
+ assert_eq!(IncompleteSince::<Test>::get(), None);
+ assert_eq!(
+ logger::log(),
+ vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
+ );
+
+ // Will include named only
+ assert_eq!(
+ Scheduler::on_initialize(3),
+ TestWeightInfo::service_agendas_base()
+ + TestWeightInfo::service_agenda_base(1)
+ + <MarginalWeightInfo<Test>>::service_task(None, true, false)
+ + TestWeightInfo::execute_dispatch_unsigned()
+ + call_weight + Weight::from_ref_time(1)
+ );
+ assert_eq!(IncompleteSince::<Test>::get(), None);
+ assert_eq!(
+ logger::log(),
+ vec![
+ (root(), 2600u32),
+ (root(), 69u32),
+ (root(), 42u32),
+ (root(), 3u32)
+ ]
+ );
+
+ // Will contain none
+ let actual_weight = Scheduler::on_initialize(4);
+ assert_eq!(
+ actual_weight,
+ TestWeightInfo::service_agendas_base() + TestWeightInfo::service_agenda_base(0)
+ );
+ });
+}
+
+#[test]
+fn root_calls_works() {
+ new_test_ext().execute_with(|| {
+ let call = Box::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: Weight::from_ref_time(10),
+ }));
+ let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ }));
+ assert_ok!(Scheduler::schedule_named(
+ RuntimeOrigin::root(),
+ [1u8; 32],
+ 4,
+ None,
+ Some(127),
+ call,
+ ));
+ assert_ok!(Scheduler::schedule(
+ RuntimeOrigin::root(),
+ 4,
+ None,
+ Some(127),
+ call2
+ ));
+ run_to_block(3);
+ // Scheduled calls are in the agenda.
+ assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);
+ assert!(logger::log().is_empty());
+ assert_ok!(Scheduler::cancel_named(RuntimeOrigin::root(), [1u8; 32]));
+ assert_ok!(Scheduler::cancel(RuntimeOrigin::root(), 4, 1));
+ // Scheduled calls are made NONE, so should not effect state
+ run_to_block(100);
+ assert!(logger::log().is_empty());
+ });
+}
+
+#[test]
+fn fails_to_schedule_task_in_the_past() {
+ new_test_ext().execute_with(|| {
+ run_to_block(3);
+
+ let call1 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: Weight::from_ref_time(10),
+ }));
+ let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ }));
+ let call3 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ }));
+
+ assert_noop!(
+ Scheduler::schedule_named(RuntimeOrigin::root(), [1u8; 32], 2, None, Some(127), call1),
+ Error::<Test>::TargetBlockNumberInPast,
+ );
+
+ assert_noop!(
+ Scheduler::schedule(RuntimeOrigin::root(), 2, None, Some(127), call2),
+ Error::<Test>::TargetBlockNumberInPast,
+ );
+
+ assert_noop!(
+ Scheduler::schedule(RuntimeOrigin::root(), 3, None, Some(127), call3),
+ Error::<Test>::TargetBlockNumberInPast,
+ );
+ });
+}
+
+#[test]
+fn should_use_origin() {
+ new_test_ext().execute_with(|| {
+ let call = Box::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: Weight::from_ref_time(10),
+ }));
+ let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ }));
+ assert_ok!(Scheduler::schedule_named(
+ system::RawOrigin::Signed(1).into(),
+ [1u8; 32],
+ 4,
+ None,
+ None,
+ call,
+ ));
+ assert_ok!(Scheduler::schedule(
+ system::RawOrigin::Signed(1).into(),
+ 4,
+ None,
+ None,
+ call2,
+ ));
+ run_to_block(3);
+ // Scheduled calls are in the agenda.
+ assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);
+ assert!(logger::log().is_empty());
+ assert_ok!(Scheduler::cancel_named(
+ system::RawOrigin::Signed(1).into(),
+ [1u8; 32]
+ ));
+ assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));
+ // Scheduled calls are made NONE, so should not effect state
+ run_to_block(100);
+ assert!(logger::log().is_empty());
+ });
+}
+
+#[test]
+fn should_check_origin() {
+ new_test_ext().execute_with(|| {
+ let call = Box::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: Weight::from_ref_time(10),
+ }));
+ let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ }));
+ assert_noop!(
+ Scheduler::schedule_named(
+ system::RawOrigin::Signed(2).into(),
+ [1u8; 32],
+ 4,
+ None,
+ None,
+ call
+ ),
+ BadOrigin
+ );
+ assert_noop!(
+ Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, None, call2),
+ BadOrigin
+ );
+ });
+}
+
+#[test]
+fn should_check_origin_for_cancel() {
+ new_test_ext().execute_with(|| {
+ let call = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {
+ i: 69,
+ weight: Weight::from_ref_time(10),
+ }));
+ let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ }));
+ assert_ok!(Scheduler::schedule_named(
+ system::RawOrigin::Signed(1).into(),
+ [1u8; 32],
+ 4,
+ None,
+ None,
+ call,
+ ));
+ assert_ok!(Scheduler::schedule(
+ system::RawOrigin::Signed(1).into(),
+ 4,
+ None,
+ None,
+ call2,
+ ));
+ run_to_block(3);
+ // Scheduled calls are in the agenda.
+ assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);
+ assert!(logger::log().is_empty());
+ assert_noop!(
+ Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), [1u8; 32]),
+ BadOrigin
+ );
+ assert_noop!(
+ Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1),
+ BadOrigin
+ );
+ assert_noop!(
+ Scheduler::cancel_named(system::RawOrigin::Root.into(), [1u8; 32]),
+ BadOrigin
+ );
+ assert_noop!(
+ Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1),
+ BadOrigin
+ );
+ run_to_block(5);
+ assert_eq!(
+ logger::log(),
+ vec![
+ (system::RawOrigin::Signed(1).into(), 69u32),
+ (system::RawOrigin::Signed(1).into(), 42u32)
+ ]
+ );
+ });
+}
+
+/// Cancelling a call and then scheduling a second call for the same
+/// block results in different addresses.
+#[test]
+fn schedule_does_not_resuse_addr() {
+ new_test_ext().execute_with(|| {
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
+
+ // Schedule both calls.
+ let addr_1 = Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(call.clone()).unwrap(),
+ )
+ .unwrap();
+ // Cancel the call.
+ assert_ok!(Scheduler::do_cancel(None, addr_1));
+ let addr_2 = Scheduler::do_schedule(
+ DispatchTime::At(4),
+ None,
+ 127,
+ root(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
+ )
+ .unwrap();
+
+ // Should not re-use the address.
+ assert!(addr_1 != addr_2);
+ });
+}
+
+#[test]
+fn schedule_agenda_overflows() {
+ let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();
+
+ new_test_ext().execute_with(|| {
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
+ let call = <ScheduledCall<Test>>::new(call).unwrap();
+
+ // Schedule the maximal number allowed per block.
+ for _ in 0..max {
+ Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone()).unwrap();
+ }
+
+ // One more time and it errors.
+ assert_noop!(
+ Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call,),
+ <Error<Test>>::AgendaIsExhausted,
+ );
+
+ run_to_block(4);
+ // All scheduled calls are executed.
+ assert_eq!(logger::log().len() as u32, max);
+ });
+}
+
+/// Cancelling and scheduling does not overflow the agenda but fills holes.
+#[test]
+fn cancel_and_schedule_fills_holes() {
+ let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();
+ assert!(
+ max > 3,
+ "This test only makes sense for MaxScheduledPerBlock > 3"
+ );
+
+ new_test_ext().execute_with(|| {
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
+ let call = <ScheduledCall<Test>>::new(call).unwrap();
+ let mut addrs = Vec::<_>::default();
+
+ // Schedule the maximal number allowed per block.
+ for _ in 0..max {
+ addrs.push(
+ Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())
+ .unwrap(),
+ );
+ }
+ // Cancel three of them.
+ for addr in addrs.into_iter().take(3) {
+ Scheduler::do_cancel(None, addr).unwrap();
+ }
+ // Schedule three new ones.
+ for i in 0..3 {
+ let (_block, index) =
+ Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())
+ .unwrap();
+ assert_eq!(i, index);
+ }
+
+ run_to_block(4);
+ // Maximum number of calls are executed.
+ assert_eq!(logger::log().len() as u32, max);
+ });
+}
+
+#[test]
+fn cannot_schedule_too_big_tasks() {
+ new_test_ext().execute_with(|| {
+ let call = Box::new(<<Test as Config>::RuntimeCall>::from(SystemCall::remark {
+ remark: vec![0; EncodedCall::bound() - 4],
+ }));
+
+ assert_ok!(Scheduler::schedule(
+ RuntimeOrigin::root(),
+ 4,
+ None,
+ Some(127),
+ call
+ ));
+
+ let call = Box::new(<<Test as Config>::RuntimeCall>::from(SystemCall::remark {
+ remark: vec![0; EncodedCall::bound() - 3],
+ }));
+
+ assert_err!(
+ Scheduler::schedule(RuntimeOrigin::root(), 4, None, Some(127), call),
+ <Error<Test>>::TooBigScheduledCall
+ );
+ });
+}
pallets/scheduler-v2/src/weights.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/scheduler-v2/src/weights.rs
@@ -0,0 +1,234 @@
+// Template adopted from https://github.com/paritytech/substrate/blob/master/.maintain/frame-weight-template.hbs
+
+//! Autogenerated weights for pallet_unique_scheduler_v2
+//!
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2022-10-28, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
+
+// Executed Command:
+// target/release/unique-collator
+// benchmark
+// pallet
+// --pallet
+// pallet-unique-scheduler-v2
+// --wasm-execution
+// compiled
+// --extrinsic
+// *
+// --template
+// .maintain/frame-weight-template.hbs
+// --steps=50
+// --repeat=80
+// --heap-pages=4096
+// --output=./pallets/scheduler-v2/src/weights.rs
+
+#![cfg_attr(rustfmt, rustfmt_skip)]
+#![allow(unused_parens)]
+#![allow(unused_imports)]
+#![allow(missing_docs)]
+#![allow(clippy::unnecessary_cast)]
+
+use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
+use sp_std::marker::PhantomData;
+
+/// Weight functions needed for pallet_unique_scheduler_v2.
+pub trait WeightInfo {
+ fn service_agendas_base() -> Weight;
+ fn service_agenda_base(s: u32, ) -> Weight;
+ fn service_task_base() -> Weight;
+ fn service_task_named() -> Weight;
+ fn service_task_periodic() -> Weight;
+ fn execute_dispatch_signed() -> Weight;
+ fn execute_dispatch_unsigned() -> Weight;
+ fn schedule(s: u32, ) -> Weight;
+ fn cancel(s: u32, ) -> Weight;
+ fn schedule_named(s: u32, ) -> Weight;
+ fn cancel_named(s: u32, ) -> Weight;
+ fn change_named_priority(s: u32, ) -> Weight;
+}
+
+/// Weights for pallet_unique_scheduler_v2 using the Substrate node and recommended hardware.
+pub struct SubstrateWeight<T>(PhantomData<T>);
+impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
+ // Storage: Scheduler IncompleteSince (r:1 w:1)
+ fn service_agendas_base() -> Weight {
+ Weight::from_ref_time(5_253_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn service_agenda_base(s: u32, ) -> Weight {
+ Weight::from_ref_time(3_858_000 as u64)
+ // Standard Error: 2_617
+ .saturating_add(Weight::from_ref_time(579_704 as u64).saturating_mul(s as u64))
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
+ // Storage: System LastRuntimeUpgrade (r:1 w:0)
+ fn service_task_base() -> Weight {
+ Weight::from_ref_time(10_536_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ }
+ // Storage: System LastRuntimeUpgrade (r:1 w:0)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn service_task_named() -> Weight {
+ Weight::from_ref_time(12_018_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
+ // Storage: System LastRuntimeUpgrade (r:1 w:0)
+ fn service_task_periodic() -> Weight {
+ Weight::from_ref_time(10_669_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ }
+ // Storage: System Account (r:1 w:1)
+ // Storage: System AllExtrinsicsLen (r:1 w:1)
+ // Storage: System BlockWeight (r:1 w:1)
+ // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
+ // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
+ fn execute_dispatch_signed() -> Weight {
+ Weight::from_ref_time(36_083_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(5 as u64))
+ .saturating_add(T::DbWeight::get().writes(3 as u64))
+ }
+ fn execute_dispatch_unsigned() -> Weight {
+ Weight::from_ref_time(4_386_000 as u64)
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule(s: u32, ) -> Weight {
+ Weight::from_ref_time(17_257_000 as u64)
+ // Standard Error: 2_791
+ .saturating_add(Weight::from_ref_time(574_832 as u64).saturating_mul(s as u64))
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn cancel(s: u32, ) -> Weight {
+ Weight::from_ref_time(19_803_000 as u64)
+ // Standard Error: 1_177
+ .saturating_add(Weight::from_ref_time(475_027 as u64).saturating_mul(s as u64))
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(2 as u64))
+ }
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule_named(s: u32, ) -> Weight {
+ Weight::from_ref_time(18_746_000 as u64)
+ // Standard Error: 2_997
+ .saturating_add(Weight::from_ref_time(635_697 as u64).saturating_mul(s as u64))
+ .saturating_add(T::DbWeight::get().reads(2 as u64))
+ .saturating_add(T::DbWeight::get().writes(2 as u64))
+ }
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn cancel_named(s: u32, ) -> Weight {
+ Weight::from_ref_time(20_983_000 as u64)
+ // Standard Error: 1_850
+ .saturating_add(Weight::from_ref_time(518_812 as u64).saturating_mul(s as u64))
+ .saturating_add(T::DbWeight::get().reads(2 as u64))
+ .saturating_add(T::DbWeight::get().writes(2 as u64))
+ }
+ // Storage: Scheduler Lookup (r:1 w:0)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn change_named_priority(s: u32, ) -> Weight {
+ Weight::from_ref_time(21_591_000 as u64)
+ // Standard Error: 4_187
+ .saturating_add(Weight::from_ref_time(531_231 as u64).saturating_mul(s as u64))
+ .saturating_add(T::DbWeight::get().reads(2 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
+}
+
+// For backwards compatibility and tests
+impl WeightInfo for () {
+ // Storage: Scheduler IncompleteSince (r:1 w:1)
+ fn service_agendas_base() -> Weight {
+ Weight::from_ref_time(5_253_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn service_agenda_base(s: u32, ) -> Weight {
+ Weight::from_ref_time(3_858_000 as u64)
+ // Standard Error: 2_617
+ .saturating_add(Weight::from_ref_time(579_704 as u64).saturating_mul(s as u64))
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
+ // Storage: System LastRuntimeUpgrade (r:1 w:0)
+ fn service_task_base() -> Weight {
+ Weight::from_ref_time(10_536_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ }
+ // Storage: System LastRuntimeUpgrade (r:1 w:0)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn service_task_named() -> Weight {
+ Weight::from_ref_time(12_018_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
+ // Storage: System LastRuntimeUpgrade (r:1 w:0)
+ fn service_task_periodic() -> Weight {
+ Weight::from_ref_time(10_669_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ }
+ // Storage: System Account (r:1 w:1)
+ // Storage: System AllExtrinsicsLen (r:1 w:1)
+ // Storage: System BlockWeight (r:1 w:1)
+ // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
+ // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
+ fn execute_dispatch_signed() -> Weight {
+ Weight::from_ref_time(36_083_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(5 as u64))
+ .saturating_add(RocksDbWeight::get().writes(3 as u64))
+ }
+ fn execute_dispatch_unsigned() -> Weight {
+ Weight::from_ref_time(4_386_000 as u64)
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule(s: u32, ) -> Weight {
+ Weight::from_ref_time(17_257_000 as u64)
+ // Standard Error: 2_791
+ .saturating_add(Weight::from_ref_time(574_832 as u64).saturating_mul(s as u64))
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn cancel(s: u32, ) -> Weight {
+ Weight::from_ref_time(19_803_000 as u64)
+ // Standard Error: 1_177
+ .saturating_add(Weight::from_ref_time(475_027 as u64).saturating_mul(s as u64))
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(2 as u64))
+ }
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule_named(s: u32, ) -> Weight {
+ Weight::from_ref_time(18_746_000 as u64)
+ // Standard Error: 2_997
+ .saturating_add(Weight::from_ref_time(635_697 as u64).saturating_mul(s as u64))
+ .saturating_add(RocksDbWeight::get().reads(2 as u64))
+ .saturating_add(RocksDbWeight::get().writes(2 as u64))
+ }
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn cancel_named(s: u32, ) -> Weight {
+ Weight::from_ref_time(20_983_000 as u64)
+ // Standard Error: 1_850
+ .saturating_add(Weight::from_ref_time(518_812 as u64).saturating_mul(s as u64))
+ .saturating_add(RocksDbWeight::get().reads(2 as u64))
+ .saturating_add(RocksDbWeight::get().writes(2 as u64))
+ }
+ // Storage: Scheduler Lookup (r:1 w:0)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn change_named_priority(s: u32, ) -> Weight {
+ Weight::from_ref_time(21_591_000 as u64)
+ // Standard Error: 4_187
+ .saturating_add(Weight::from_ref_time(531_231 as u64).saturating_mul(s as u64))
+ .saturating_add(RocksDbWeight::get().reads(2 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
+}
pallets/scheduler/CHANGELOG.mddiffbeforeafterboth--- a/pallets/scheduler/CHANGELOG.md
+++ /dev/null
@@ -1,10 +0,0 @@
-<!-- bureaucrate goes here -->
-## [v0.1.1] 2022-08-16
-
-### Other changes
-
-- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
-
-- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
-
-- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
\ No newline at end of file
pallets/scheduler/Cargo.tomldiffbeforeafterboth--- a/pallets/scheduler/Cargo.toml
+++ /dev/null
@@ -1,53 +0,0 @@
-[package]
-name = "pallet-unique-scheduler"
-version = "0.1.1"
-authors = ["Unique Network <support@uniquenetwork.io>"]
-edition = "2021"
-license = "GPLv3"
-homepage = "https://unique.network"
-repository = "https://github.com/UniqueNetwork/unique-chain"
-description = "Unique Scheduler pallet"
-readme = "README.md"
-
-[dependencies]
-serde = { version = "1.0.130", default-features = false }
-codec = { package = "parity-scale-codec", version = "3.1.2", default-features = false }
-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.30" }
-frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.30' }
-frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-
-up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.30" }
-log = { version = "0.4.16", default-features = false }
-
-[dev-dependencies]
-sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-substrate-test-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-
-[features]
-default = ["std"]
-std = [
- "codec/std",
- "sp-runtime/std",
- "frame-benchmarking/std",
- "frame-support/std",
- "frame-system/std",
- "up-sponsorship/std",
- "sp-io/std",
- "sp-std/std",
- "sp-core/std",
- "log/std",
-]
-runtime-benchmarks = [
- "frame-benchmarking",
- "frame-support/runtime-benchmarks",
- "frame-system/runtime-benchmarks",
-]
-try-runtime = ["frame-support/try-runtime"]
pallets/scheduler/README.mddiffbeforeafterboth--- a/pallets/scheduler/README.md
+++ /dev/null
@@ -1,34 +0,0 @@
-# Scheduler
-A module for scheduling dispatches.
-
-- [`scheduler::Trait`](https://docs.rs/pallet-scheduler/latest/pallet_scheduler/trait.Trait.html)
-- [`Call`](https://docs.rs/pallet-scheduler/latest/pallet_scheduler/enum.Call.html)
-- [`Module`](https://docs.rs/pallet-scheduler/latest/pallet_scheduler/struct.Module.html)
-
-## Overview
-
-This module 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.
-
-**NOTE:** The scheduled calls will be dispatched with the default filter
-for the origin: namely `frame_system::Config::BaseCallFilter` for all origin
-except root which will get no filter. And not the filter contained in origin
-use to call `fn schedule`.
-
-If a call is scheduled using proxy or whatever mecanism which adds filter,
-then those filter will not be used when dispatching the schedule call.
-
-## Interface
-
-### 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.
-* `cancel_named` - the named complement to the cancel function.
-
-License: Unlicense
pallets/scheduler/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/scheduler/src/benchmarking.rs
+++ /dev/null
@@ -1,260 +0,0 @@
-// 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.
-// SPDX-License-Identifier: Apache-2.0
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! Scheduler pallet benchmarking.
-
-use super::*;
-use frame_benchmarking::{benchmarks, account};
-use frame_support::{
- ensure,
- traits::{OnInitialize},
-};
-use frame_system::RawOrigin;
-use sp_runtime::traits::Hash;
-use sp_std::{prelude::*, vec};
-
-use crate::Pallet as Scheduler;
-use frame_system::Pallet as System;
-use frame_support::traits::Currency;
-
-const BLOCK_NUMBER: u32 = 2;
-
-fn make_scheduled_id(src: u32) -> ScheduledId {
- let slice_id: [u8; 4] = src.encode().try_into().unwrap();
- let mut id: [u8; 16] = [0; 16];
- id[..4].clone_from_slice(&slice_id);
- id
-}
-
-/// Add `n` named items to the schedule.
-///
-/// For `resolved`:
-/// - `None`: aborted (hash without preimage)
-/// - `Some(true)`: hash resolves into call if possible, plain call otherwise
-/// - `Some(false)`: plain call
-fn fill_schedule<T: Config>(
- when: T::BlockNumber,
- n: u32,
- periodic: bool,
- resolved: Option<bool>,
-) -> Result<(), &'static str> {
- let t = DispatchTime::At(when);
- let caller = account("user", 0, 1);
-
- // Give the sender account max funds for transfer (their account will never reasonably be killed).
- T::Currency::make_free_balance_be(&caller, T::Currency::minimum_balance());
-
- for i in 0..n {
- let (call, hash) = call_and_hash::<T>(i);
- let call_or_hash = match resolved {
- Some(_) => call.into(),
- None => CallOrHashOf::<T>::Hash(hash),
- };
- let period = match periodic {
- true => Some(((i + 100).into(), 100)),
- false => None,
- };
-
- let id = make_scheduled_id(i);
- let origin = frame_system::RawOrigin::Signed(caller.clone()).into();
- Scheduler::<T>::do_schedule_named(id, t, period, 0, origin, call_or_hash)?;
- }
- ensure!(
- Agenda::<T>::get(when).len() == n as usize,
- "didn't fill schedule"
- );
- Ok(())
-}
-
-fn call_and_hash<T: Config>(i: u32) -> (<T as Config>::RuntimeCall, T::Hash) {
- // Essentially a no-op call.
- let call: <T as Config>::RuntimeCall = frame_system::Call::remark { remark: i.encode() }.into();
- let hash = T::Hashing::hash_of(&call);
- (call, hash)
-}
-
-benchmarks! {
- on_initialize_periodic_named_resolved {
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- fill_schedule::<T>(when, s, true, Some(true))?;
- }: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
- verify {
- assert_eq!(System::<T>::event_count(), s);
- for i in 0..s {
- assert_eq!(Agenda::<T>::get(when + (i + 100).into()).len(), 1 as usize);
- }
- }
-
- on_initialize_named_resolved {
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- fill_schedule::<T>(when, s, false, Some(true))?;
- }: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
- verify {
- assert_eq!(System::<T>::event_count(), s);
- assert!(Agenda::<T>::iter().count() == 0);
- }
-
- on_initialize_periodic {
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- fill_schedule::<T>(when, s, true, Some(false))?;
- }: { Scheduler::<T>::on_initialize(when); }
- verify {
- assert_eq!(System::<T>::event_count(), s);
- for i in 0..s {
- assert_eq!(Agenda::<T>::get(when + (i + 100).into()).len(), 1 as usize);
- }
- }
-
- on_initialize_periodic_resolved {
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- fill_schedule::<T>(when, s, true, Some(true))?;
- }: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
- verify {
- assert_eq!(System::<T>::event_count(), s );
- for i in 0..s {
- assert_eq!(Agenda::<T>::get(when + (i + 100).into()).len(), 1 as usize);
- }
- }
-
- on_initialize_aborted {
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- fill_schedule::<T>(when, s, false, None)?;
- }: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
- verify {
- assert_eq!(System::<T>::event_count(), 0);
- }
-
- on_initialize_named_aborted {
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- fill_schedule::<T>(when, s, false, Some(false))?;
- }: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
- verify {
- }
-
- on_initialize_named {
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- fill_schedule::<T>(when, s, false, None)?;
- }: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
- verify {
- assert_eq!(System::<T>::event_count(), 0);
- }
-
- on_initialize {
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- fill_schedule::<T>(when, s, false, Some(false))?;
- }: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
- verify {
- assert_eq!(System::<T>::event_count(), s);
- assert!(Agenda::<T>::iter().count() == 0);
- }
-
- on_initialize_resolved {
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- fill_schedule::<T>(when, s, false, Some(true))?;
- }: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
- verify {
- assert_eq!(System::<T>::event_count(), s);
- assert!(Agenda::<T>::iter().count() == 0);
- }
-
- schedule_named {
- let caller: T::AccountId = account("user", 0, 1);
- let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Signed(caller.clone());
- let s in 0 .. T::MaxScheduledPerBlock::get();
- let slice_id: [u8; 4] = s.encode().try_into().unwrap();
- let mut id: [u8; 16] = [0; 16];
- id[..4].clone_from_slice(&slice_id);
- let when = BLOCK_NUMBER.into();
- let periodic = Some((T::BlockNumber::one(), 100));
- let priority = None;
- // Essentially a no-op call.
- let inner_call = frame_system::Call::set_storage { items: vec![] }.into();
- let call = Box::new(CallOrHashOf::<T>::Value(inner_call));
- fill_schedule::<T>(when, s, true, Some(false))?;
- }: _(origin, id, when, periodic, priority, call)
- verify {
- ensure!(
- Agenda::<T>::get(when).len() == (s + 1) as usize,
- "didn't add to schedule"
- );
- }
-
- cancel_named {
- let caller: T::AccountId = account("user", 0, 1);
- let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Signed(caller.clone());
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- let idx = s - 1;
- let id = make_scheduled_id(idx);
- fill_schedule::<T>(when, s, true, Some(false))?;
- }: _(origin, id)
- verify {
- ensure!(
- Lookup::<T>::get(id).is_none(),
- "didn't remove from lookup"
- );
- // Removed schedule is NONE
- ensure!(
- Agenda::<T>::get(when)[idx as usize].is_none(),
- "didn't remove from schedule"
- );
- }
-
- change_named_priority {
- let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Root;
- let s in 1 .. T::MaxScheduledPerBlock::get();
- let when = BLOCK_NUMBER.into();
- let idx = s - 1;
- let id = make_scheduled_id(idx);
- let priority = 42;
- fill_schedule::<T>(when, s, true, Some(false))?;
- }: _(origin, id, priority)
- verify {
- ensure!(
- Agenda::<T>::get(when)[idx as usize].clone().unwrap().priority == priority,
- "didn't change the priority"
- );
- }
-
- impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test);
-}
pallets/scheduler/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler/src/lib.rs
+++ /dev/null
@@ -1,802 +0,0 @@
-// 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-2022 Parity Technologies (UK) Ltd.
-// SPDX-License-Identifier: Apache-2.0
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// <http://www.apache.org/licenses/LICENSE-2.0>
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! # Unique scheduler
-//! A Pallet for scheduling dispatches.
-//!
-//! - [`Config`]
-//! - [`Call`]
-//! - [`Pallet`]
-//!
-//! ## Overview
-//!
-//! This Pallet exposes capabilities for scheduling dispatches to occur at a
-//! specified block number or at a specified period. These scheduled dispatches
-//! should be named and may be canceled.
-//!
-//! **NOTE:** The unique scheduler is designed for deferred transaction calls by block number.
-//! Any user can book a call of a certain transaction to a specific block number.
-//! Also possible to book a call with a certain frequency.
-//!
-//! Key differences from the original pallet:
-//! <https://crates.io/crates/pallet-scheduler>
-//! Schedule Id restricted by 16 bytes. Identificator for booked call.
-//! Priority limited by HARD DEADLINE (<= 63). Calls over maximum weight don't include to block.
-//! The maximum weight that may be scheduled per block for any dispatchables of less priority than `schedule::HARD_DEADLINE`.
-//! Maybe_periodic limit is 100 calls. Reserved for future sponsored transaction support.
-//! At 100 calls reserved amount is not so much and this is avoid potential problems with balance locks.
-//! Any account allowed to schedule any calls. Account withdraw implemented through default transaction logic.
-//!
-//! ## Interface
-//!
-//! ### Dispatchable Functions
-//!
-//! * `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)]
-
-#[cfg(feature = "runtime-benchmarks")]
-mod benchmarking;
-
-pub mod weights;
-
-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::{
- traits::{BadOrigin, One, Saturating, Zero},
- RuntimeDebug, DispatchErrorWithPostInfo,
-};
-use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};
-
-use frame_support::{
- dispatch::{
- DispatchError, DispatchResult, Dispatchable, UnfilteredDispatchable, Parameter,
- GetDispatchInfo,
- },
- traits::{
- schedule::{self, DispatchTime, MaybeHashed},
- NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,
- StorageVersion,
- },
- weights::{Weight},
-};
-
-pub use weights::WeightInfo;
-
-/// 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;
-
-pub type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];
-pub type CallOrHashOf<T> =
- MaybeHashed<<T as Config>::RuntimeCall, <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 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {
- /// The unique identity for this task, if there is one.
- maybe_id: Option<ScheduledId>,
- /// This task's priority.
- priority: schedule::Priority,
- /// The call to be dispatched.
- call: Call,
- /// If the call is periodic, then this points to the information concerning that.
- maybe_periodic: Option<schedule::Period<BlockNumber>>,
- /// The origin to dispatch the call.
- origin: PalletsOrigin,
- _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> =
- ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;
-
-pub enum ScheduledEnsureOriginSuccess<AccountId> {
- Root,
- Signed(AccountId),
-}
-
-#[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 {}
-}
-
-#[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 {}
-}
-
-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_resolved(2)
- - Self::on_initialize_periodic_named_resolved(1)
- }
- (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(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 {}
-
-#[frame_support::pallet]
-pub mod pallet {
- use super::*;
- use frame_support::{
- dispatch::PostDispatchInfo,
- pallet_prelude::*,
- traits::{
- schedule::{LookupError, LOWEST_PRIORITY},
- 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 RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
-
- /// The aggregated origin which the dispatch will take.
- type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
- + From<Self::PalletsOrigin>
- + IsType<<Self as system::Config>::RuntimeOrigin>;
-
- /// 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 RuntimeCall: Parameter
- + Dispatchable<
- RuntimeOrigin = <Self as Config>::RuntimeOrigin,
- PostInfo = PostDispatchInfo,
- > + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>
- + GetDispatchInfo
- + From<system::Call<Self>>;
-
- /// 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>;
-
- /// Required origin to schedule or cancel calls.
- type ScheduleOrigin: EnsureOrigin<
- <Self as system::Config>::RuntimeOrigin,
- Success = ScheduledEnsureOriginSuccess<Self::AccountId>,
- >;
-
- /// Required origin to set/change calls' priority.
- type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;
-
- /// 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.
- ///
- /// 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>;
- }
-
- /// A Scheduler-Runtime interface for finer payment handling.
- pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {
- /// Reserve (lock) the maximum spendings on a call, calculated from its weight and the repetition count.
- fn reserve_balance(
- id: ScheduledId,
- sponsor: <T as frame_system::Config>::AccountId,
- call: <T as Config>::RuntimeCall,
- count: u32,
- ) -> Result<(), DispatchError>;
-
- /// Unreserve (unlock) a certain amount from the payer's reserved funds, returning the change.
- fn pay_for_call(
- id: ScheduledId,
- sponsor: <T as frame_system::Config>::AccountId,
- call: <T as Config>::RuntimeCall,
- ) -> Result<u128, DispatchError>;
-
- /// Resolve the call dispatch, including any post-dispatch operations.
- fn dispatch_call(
- signer: Option<T::AccountId>,
- function: <T as Config>::RuntimeCall,
- ) -> Result<
- Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
- TransactionValidityError,
- >;
-
- /// Release unspent reserved funds in case of a schedule cancel.
- fn cancel_reserve(
- id: ScheduledId,
- sponsor: <T as frame_system::Config>::AccountId,
- ) -> Result<u128, DispatchError>;
- }
-
- /// 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 },
- /// Scheduled task's priority has changed
- PriorityChanged {
- when: T::BlockNumber,
- index: u32,
- priority: schedule::Priority,
- },
- /// 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.
- NotFound,
- /// Given target block number is in the past.
- TargetBlockNumberInPast,
- /// Reschedule failed because it does not change scheduled time.
- RescheduleNoChange,
- }
-
- #[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<_>>();
-
- 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 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 = s.maybe_id.is_some();
-
- 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));
- } else if let Some(ref id) = s.maybe_id {
- Lookup::<T>::remove(id);
- }
- 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>::RuntimeOrigin 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.all_gt(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 scheduled_origin =
- <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(
- s.origin.clone(),
- );
- let ensured_origin = T::ScheduleOrigin::ensure_origin(scheduled_origin.into());
-
- let r = match ensured_origin {
- Ok(ScheduledEnsureOriginSuccess::Root) => {
- Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))
- }
- Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {
- // Execute transaction via chain default pipeline
- // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken
- T::CallExecutor::dispatch_call(Some(sender), call.clone())
- }
- Err(e) => Ok(Err(e.into())),
- };
-
- 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;
- let is_canceled;
-
- // If scheduled is named, place its information in `Lookup`
- if let Some(ref id) = s.maybe_id {
- is_canceled = Lookup::<T>::get(id).is_none();
- let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);
-
- if !is_canceled {
- Lookup::<T>::insert(id, (wake, wake_index as u32));
- }
- } else {
- is_canceled = false;
- }
-
- if !is_canceled {
- Agenda::<T>::append(wake, Some(s));
- }
- } else if let Some(ref id) = s.maybe_id {
- Lookup::<T>::remove(id);
- }
- }
- total_weight
- }
- }
-
- #[pallet::call]
- impl<T: Config> Pallet<T> {
- /// Schedule a named task.
- #[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: Option<schedule::Priority>,
- call: Box<CallOrHashOf<T>>,
- ) -> DispatchResult {
- T::ScheduleOrigin::ensure_origin(origin.clone())?;
-
- if priority.is_some() {
- T::PrioritySetOrigin::ensure_origin(origin.clone())?;
- }
-
- let origin = <T as Config>::RuntimeOrigin::from(origin);
- Self::do_schedule_named(
- id,
- DispatchTime::At(when),
- maybe_periodic,
- priority.unwrap_or(LOWEST_PRIORITY),
- origin.caller().clone(),
- *call,
- )?;
- Ok(())
- }
-
- /// Cancel a named scheduled task.
- #[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>::RuntimeOrigin::from(origin);
- Self::do_cancel_named(Some(origin.caller().clone()), id)?;
- Ok(())
- }
-
- /// Schedule a named task after a delay.
- ///
- /// # <weight>
- /// Same as [`schedule_named`](Self::schedule_named).
- /// # </weight>
- #[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: Option<schedule::Priority>,
- call: Box<CallOrHashOf<T>>,
- ) -> DispatchResult {
- T::ScheduleOrigin::ensure_origin(origin.clone())?;
-
- if priority.is_some() {
- T::PrioritySetOrigin::ensure_origin(origin.clone())?;
- }
-
- let origin = <T as Config>::RuntimeOrigin::from(origin);
- Self::do_schedule_named(
- id,
- DispatchTime::After(after),
- maybe_periodic,
- priority.unwrap_or(LOWEST_PRIORITY),
- origin.caller().clone(),
- *call,
- )?;
- Ok(())
- }
-
- #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]
- pub fn change_named_priority(
- origin: OriginFor<T>,
- id: ScheduledId,
- priority: schedule::Priority,
- ) -> DispatchResult {
- T::PrioritySetOrigin::ensure_origin(origin.clone())?;
- let origin = <T as Config>::RuntimeOrigin::from(origin);
- Self::do_change_named_priority(origin.caller().clone(), id, priority)
- }
- }
-}
-
-impl<T: Config> Pallet<T> {
- #[cfg(feature = "try-runtime")]
- pub fn pre_migrate_to_v3() -> Result<(), &'static str> {
- Ok(())
- }
-
- #[cfg(feature = "try-runtime")]
- pub fn post_migrate_to_v3() -> Result<(), &'static str> {
- use frame_support::dispatch::GetStorageVersion;
-
- 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<_>>(),
- )
- });
- }
-
- fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {
- let now = frame_system::Pallet::<T>::block_number();
-
- let when = match when {
- DispatchTime::At(x) => x,
- // The current block has already completed it's scheduled tasks, so
- // Schedule the task at lest one block after this current block.
- DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),
- };
-
- if when <= now {
- return Err(Error::<T>::TargetBlockNumberInPast.into());
- }
-
- Ok(when)
- }
-
- fn do_schedule_named(
- id: ScheduledId,
- when: DispatchTime<T::BlockNumber>,
- maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
- priority: schedule::Priority,
- origin: T::PalletsOrigin,
- call: CallOrHashOf<T>,
- ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
- // ensure id it is unique
- if Lookup::<T>::contains_key(&id) {
- 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())
- // Remove one from the number of repetitions since we will schedule one now.
- .map(|(p, c)| (p, c - 1));
-
- let s = Scheduled {
- maybe_id: Some(id.clone()),
- priority,
- call: call.clone(),
- maybe_periodic,
- 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;
- let address = (when, index);
- Lookup::<T>::insert(&id, &address);
- Self::deposit_event(Event::Scheduled { when, index });
-
- Ok(address)
- }
-
- 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.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(Event::Canceled { when, index });
- Ok(())
- } else {
- Err(Error::<T>::NotFound)?
- }
- })
- }
-
- fn do_change_named_priority(
- origin: T::PalletsOrigin,
- id: ScheduledId,
- priority: schedule::Priority,
- ) -> DispatchResult {
- match Lookup::<T>::get(id) {
- Some((when, index)) => {
- let i = index as usize;
- Agenda::<T>::try_mutate(when, |agenda| {
- if let Some(Some(s)) = agenda.get_mut(i) {
- if matches!(
- T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),
- Some(Ordering::Less) | None
- ) {
- return Err(BadOrigin.into());
- }
-
- s.priority = priority;
- Self::deposit_event(Event::PriorityChanged {
- when,
- index,
- priority,
- });
- }
- Ok(())
- })
- }
- None => Err(Error::<T>::NotFound.into()),
- }
- }
-}
pallets/scheduler/src/weights.rsdiffbeforeafterboth--- a/pallets/scheduler/src/weights.rs
+++ /dev/null
@@ -1,369 +0,0 @@
-// Template adopted from https://github.com/paritytech/substrate/blob/master/.maintain/frame-weight-template.hbs
-
-//! Autogenerated weights for pallet_unique_scheduler
-//!
-//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-09-14, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
-//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
-
-// Executed Command:
-// target/release/unique-collator
-// benchmark
-// pallet
-// --pallet
-// pallet-unique-scheduler
-// --wasm-execution
-// compiled
-// --extrinsic
-// *
-// --template
-// .maintain/frame-weight-template.hbs
-// --steps=50
-// --repeat=80
-// --heap-pages=4096
-// --output=./pallets/scheduler/src/weights.rs
-
-#![cfg_attr(rustfmt, rustfmt_skip)]
-#![allow(unused_parens)]
-#![allow(unused_imports)]
-#![allow(missing_docs)]
-#![allow(clippy::unnecessary_cast)]
-
-use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
-use sp_std::marker::PhantomData;
-
-/// Weight functions needed for pallet_unique_scheduler.
-pub trait WeightInfo {
- fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight;
- fn on_initialize_named_resolved(s: u32, ) -> Weight;
- fn on_initialize_periodic(s: u32, ) -> Weight;
- fn on_initialize_periodic_resolved(s: u32, ) -> Weight;
- fn on_initialize_aborted(s: u32, ) -> Weight;
- fn on_initialize_named_aborted(s: u32, ) -> Weight;
- fn on_initialize_named(s: u32, ) -> Weight;
- fn on_initialize(s: u32, ) -> Weight;
- fn on_initialize_resolved(s: u32, ) -> Weight;
- fn schedule_named(s: u32, ) -> Weight;
- fn cancel_named(s: u32, ) -> Weight;
- fn change_named_priority(s: u32, ) -> Weight;
-}
-
-/// Weights for pallet_unique_scheduler using the Substrate node and recommended hardware.
-pub struct SubstrateWeight<T>(PhantomData<T>);
-impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
- // Storage: Scheduler Agenda (r:2 w:2)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:1 w:1)
- fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
- Weight::from_ref_time(26_641_000)
- // Standard Error: 9_000
- .saturating_add(Weight::from_ref_time(8_547_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(4 as u64))
- .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
- .saturating_add(T::DbWeight::get().writes(4 as u64))
- .saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:1 w:1)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize_named_resolved(s: u32, ) -> Weight {
- Weight::from_ref_time(23_941_000)
- // Standard Error: 17_000
- .saturating_add(Weight::from_ref_time(5_282_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(4 as u64))
- .saturating_add(T::DbWeight::get().writes(4 as u64))
- .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:2 w:2)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:1 w:1)
- fn on_initialize_periodic(s: u32, ) -> Weight {
- Weight::from_ref_time(24_858_000)
- // Standard Error: 7_000
- .saturating_add(Weight::from_ref_time(8_657_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(4 as u64))
- .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
- .saturating_add(T::DbWeight::get().writes(4 as u64))
- .saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:2 w:2)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:1 w:1)
- fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
- Weight::from_ref_time(25_515_000)
- // Standard Error: 14_000
- .saturating_add(Weight::from_ref_time(8_656_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(4 as u64))
- .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
- .saturating_add(T::DbWeight::get().writes(4 as u64))
- .saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:2 w:2)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize_aborted(s: u32, ) -> Weight {
- Weight::from_ref_time(7_584_000)
- // Standard Error: 1_000
- .saturating_add(Weight::from_ref_time(2_065_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(2 as u64))
- .saturating_add(T::DbWeight::get().writes(2 as u64))
- .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:1 w:1)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize_named_aborted(s: u32, ) -> Weight {
- Weight::from_ref_time(25_552_000)
- // Standard Error: 4_000
- .saturating_add(Weight::from_ref_time(5_187_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(4 as u64))
- .saturating_add(T::DbWeight::get().writes(4 as u64))
- .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:2 w:2)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize_named(s: u32, ) -> Weight {
- Weight::from_ref_time(8_980_000)
- // Standard Error: 12_000
- .saturating_add(Weight::from_ref_time(2_050_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(2 as u64))
- .saturating_add(T::DbWeight::get().writes(2 as u64))
- .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:1 w:1)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize(s: u32, ) -> Weight {
- Weight::from_ref_time(24_482_000)
- // Standard Error: 4_000
- .saturating_add(Weight::from_ref_time(5_249_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(4 as u64))
- .saturating_add(T::DbWeight::get().writes(4 as u64))
- .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:1 w:1)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize_resolved(s: u32, ) -> Weight {
- Weight::from_ref_time(25_187_000)
- // Standard Error: 4_000
- .saturating_add(Weight::from_ref_time(5_216_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(4 as u64))
- .saturating_add(T::DbWeight::get().writes(4 as u64))
- .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Lookup (r:1 w:1)
- // Storage: Scheduler Agenda (r:1 w:1)
- fn schedule_named(s: u32, ) -> Weight {
- Weight::from_ref_time(17_316_000)
- // Standard Error: 3_000
- .saturating_add(Weight::from_ref_time(82_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(2 as u64))
- .saturating_add(T::DbWeight::get().writes(2 as u64))
- }
- // Storage: Scheduler Lookup (r:1 w:1)
- // Storage: Scheduler Agenda (r:1 w:1)
- fn cancel_named(s: u32, ) -> Weight {
- Weight::from_ref_time(15_652_000)
- // Standard Error: 1_000
- .saturating_add(Weight::from_ref_time(436_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(2 as u64))
- .saturating_add(T::DbWeight::get().writes(2 as u64))
- }
- // Storage: Scheduler Lookup (r:1 w:1)
- // Storage: Scheduler Agenda (r:1 w:1)
- fn change_named_priority(s: u32, ) -> Weight {
- Weight::from_ref_time(8_642_000)
- // Standard Error: 0
- .saturating_add(Weight::from_ref_time(431_000).saturating_mul(s as u64))
- .saturating_add(T::DbWeight::get().reads(2 as u64))
- .saturating_add(T::DbWeight::get().writes(2 as u64))
- }
-}
-
-// For backwards compatibility and tests
-impl WeightInfo for () {
- // Storage: Scheduler Agenda (r:2 w:2)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:1 w:1)
- fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
- Weight::from_ref_time(26_641_000)
- // Standard Error: 9_000
- .saturating_add(Weight::from_ref_time(8_547_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(4 as u64))
- .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
- .saturating_add(RocksDbWeight::get().writes(4 as u64))
- .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:1 w:1)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize_named_resolved(s: u32, ) -> Weight {
- Weight::from_ref_time(23_941_000)
- // Standard Error: 17_000
- .saturating_add(Weight::from_ref_time(5_282_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(4 as u64))
- .saturating_add(RocksDbWeight::get().writes(4 as u64))
- .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:2 w:2)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:1 w:1)
- fn on_initialize_periodic(s: u32, ) -> Weight {
- Weight::from_ref_time(24_858_000)
- // Standard Error: 7_000
- .saturating_add(Weight::from_ref_time(8_657_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(4 as u64))
- .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
- .saturating_add(RocksDbWeight::get().writes(4 as u64))
- .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:2 w:2)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:1 w:1)
- fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
- Weight::from_ref_time(25_515_000)
- // Standard Error: 14_000
- .saturating_add(Weight::from_ref_time(8_656_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(4 as u64))
- .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
- .saturating_add(RocksDbWeight::get().writes(4 as u64))
- .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:2 w:2)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize_aborted(s: u32, ) -> Weight {
- Weight::from_ref_time(7_584_000)
- // Standard Error: 1_000
- .saturating_add(Weight::from_ref_time(2_065_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(2 as u64))
- .saturating_add(RocksDbWeight::get().writes(2 as u64))
- .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:1 w:1)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize_named_aborted(s: u32, ) -> Weight {
- Weight::from_ref_time(25_552_000)
- // Standard Error: 4_000
- .saturating_add(Weight::from_ref_time(5_187_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(4 as u64))
- .saturating_add(RocksDbWeight::get().writes(4 as u64))
- .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:2 w:2)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize_named(s: u32, ) -> Weight {
- Weight::from_ref_time(8_980_000)
- // Standard Error: 12_000
- .saturating_add(Weight::from_ref_time(2_050_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(2 as u64))
- .saturating_add(RocksDbWeight::get().writes(2 as u64))
- .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:1 w:1)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize(s: u32, ) -> Weight {
- Weight::from_ref_time(24_482_000)
- // Standard Error: 4_000
- .saturating_add(Weight::from_ref_time(5_249_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(4 as u64))
- .saturating_add(RocksDbWeight::get().writes(4 as u64))
- .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Agenda (r:1 w:1)
- // Storage: System Account (r:1 w:1)
- // Storage: System AllExtrinsicsLen (r:1 w:1)
- // Storage: System BlockWeight (r:1 w:1)
- // Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
- // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
- // Storage: Scheduler Lookup (r:0 w:1)
- fn on_initialize_resolved(s: u32, ) -> Weight {
- Weight::from_ref_time(25_187_000)
- // Standard Error: 4_000
- .saturating_add(Weight::from_ref_time(5_216_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(4 as u64))
- .saturating_add(RocksDbWeight::get().writes(4 as u64))
- .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
- }
- // Storage: Scheduler Lookup (r:1 w:1)
- // Storage: Scheduler Agenda (r:1 w:1)
- fn schedule_named(s: u32, ) -> Weight {
- Weight::from_ref_time(17_316_000)
- // Standard Error: 3_000
- .saturating_add(Weight::from_ref_time(82_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(2 as u64))
- .saturating_add(RocksDbWeight::get().writes(2 as u64))
- }
- // Storage: Scheduler Lookup (r:1 w:1)
- // Storage: Scheduler Agenda (r:1 w:1)
- fn cancel_named(s: u32, ) -> Weight {
- Weight::from_ref_time(15_652_000)
- // Standard Error: 1_000
- .saturating_add(Weight::from_ref_time(436_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(2 as u64))
- .saturating_add(RocksDbWeight::get().writes(2 as u64))
- }
-
- // Storage: Scheduler Lookup (r:1 w:1)
- // Storage: Scheduler Agenda (r:1 w:1)
- fn change_named_priority(s: u32, ) -> Weight {
- Weight::from_ref_time(8_642_000)
- // Standard Error: 0
- .saturating_add(Weight::from_ref_time(431_000).saturating_mul(s as u64))
- .saturating_add(RocksDbWeight::get().reads(2 as u64))
- .saturating_add(RocksDbWeight::get().writes(2 as u64))
- }
-}
runtime/common/config/pallets/scheduler.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/scheduler.rs
+++ b/runtime/common/config/pallets/scheduler.rs
@@ -25,9 +25,9 @@
use codec::Decode;
use crate::{
runtime_common::{scheduler::SchedulerPaymentExecutor, config::substrate::RuntimeBlockWeights},
- Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, OriginCaller, Balances,
+ Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, OriginCaller,
};
-use pallet_unique_scheduler::ScheduledEnsureOriginSuccess;
+use pallet_unique_scheduler_v2::ScheduledEnsureOriginSuccess;
use up_common::types::AccountId;
parameter_types! {
@@ -70,19 +70,17 @@
}
}
-impl pallet_unique_scheduler::Config for Runtime {
+impl pallet_unique_scheduler_v2::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
- type Currency = Balances;
type PalletsOrigin = OriginCaller;
type RuntimeCall = RuntimeCall;
type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureSignedOrRoot<AccountId>;
- type PrioritySetOrigin = EnsureRoot<AccountId>;
+ type OriginPrivilegeCmp = EqualOrRootOnly;
type MaxScheduledPerBlock = MaxScheduledPerBlock;
type WeightInfo = ();
+ type Preimages = ();
type CallExecutor = SchedulerPaymentExecutor;
- type OriginPrivilegeCmp = EqualOrRootOnly;
- type PreimageProvider = ();
- type NoPreimagePostponement = NoPreimagePostponement;
+ type PrioritySetOrigin = EnsureRoot<AccountId>;
}
runtime/common/config/test_pallets.rsdiffbeforeafterboth--- a/runtime/common/config/test_pallets.rs
+++ b/runtime/common/config/test_pallets.rs
@@ -14,8 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use crate::{Runtime, RuntimeEvent};
+use crate::{Runtime, RuntimeEvent, RuntimeCall};
impl pallet_test_utils::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
+ type RuntimeCall = RuntimeCall;
}
runtime/common/construct_runtime/mod.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -58,7 +58,7 @@
Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
#[runtimes(opal)]
- Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+ Scheduler: pallet_unique_scheduler_v2::{Pallet, Call, Storage, Event<T>} = 62,
Configuration: pallet_configuration::{Pallet, Call, Storage} = 63,
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -683,8 +683,8 @@
#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
list_benchmark!(list, extra, pallet_refungible, Refungible);
- // #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
- // list_benchmark!(list, extra, pallet_unique_scheduler, Scheduler);
+ #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
+ list_benchmark!(list, extra, pallet_unique_scheduler_v2, Scheduler);
#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
list_benchmark!(list, extra, pallet_proxy_rmrk_core, RmrkCore);
@@ -743,8 +743,8 @@
#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
add_benchmark!(params, batches, pallet_refungible, Refungible);
- // #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
- // add_benchmark!(params, batches, pallet_unique_scheduler, Scheduler);
+ #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
+ add_benchmark!(params, batches, pallet_unique_scheduler_v2, Scheduler);
#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
add_benchmark!(params, batches, pallet_proxy_rmrk_core, RmrkCore);
runtime/common/scheduler.rsdiffbeforeafterboth--- a/runtime/common/scheduler.rs
+++ b/runtime/common/scheduler.rs
@@ -15,44 +15,29 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use frame_support::{
- traits::NamedReservableCurrency,
dispatch::{GetDispatchInfo, PostDispatchInfo, DispatchInfo},
};
use sp_runtime::{
traits::{Dispatchable, Applyable, Member},
- generic::Era,
transaction_validity::TransactionValidityError,
- DispatchErrorWithPostInfo, DispatchError,
+ DispatchErrorWithPostInfo,
};
use codec::Encode;
-use crate::{Runtime, RuntimeCall, RuntimeOrigin, Balances, maintenance};
-use up_common::types::{AccountId, Balance};
+use crate::{Runtime, RuntimeCall, RuntimeOrigin, maintenance};
+use up_common::types::AccountId;
use fp_self_contained::SelfContainedCall;
-use pallet_unique_scheduler::DispatchCall;
+use pallet_unique_scheduler_v2::DispatchCall;
use pallet_transaction_payment::ChargeTransactionPayment;
-type SponsorshipChargeTransactionPayment =
- pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
-
/// The SignedExtension to the basic transaction logic.
pub type SignedExtraScheduler = (
- frame_system::CheckSpecVersion<Runtime>,
- frame_system::CheckGenesis<Runtime>,
- frame_system::CheckEra<Runtime>,
- frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
maintenance::CheckMaintenance,
ChargeTransactionPayment<Runtime>,
);
-fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
+fn get_signed_extras() -> 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(),
maintenance::CheckMaintenance,
ChargeTransactionPayment::<Runtime>::from(0),
@@ -61,7 +46,7 @@
pub struct SchedulerPaymentExecutor;
-impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
+impl<T: frame_system::Config + pallet_unique_scheduler_v2::Config, SelfContainedSignedInfo>
DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
where
<T as frame_system::Config>::RuntimeCall: Member
@@ -71,13 +56,13 @@
+ From<frame_system::Call<Runtime>>,
SelfContainedSignedInfo: Send + Sync + 'static,
RuntimeCall: From<<T as frame_system::Config>::RuntimeCall>
- + From<<T as pallet_unique_scheduler::Config>::RuntimeCall>
+ + From<<T as pallet_unique_scheduler_v2::Config>::RuntimeCall>
+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
{
fn dispatch_call(
signer: Option<<T as frame_system::Config>::AccountId>,
- call: <T as pallet_unique_scheduler::Config>::RuntimeCall,
+ call: <T as pallet_unique_scheduler_v2::Config>::RuntimeCall,
) -> Result<
Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
TransactionValidityError,
@@ -88,7 +73,7 @@
let signed = match signer {
Some(signer) => fp_self_contained::CheckedSignature::Signed(
signer.clone().into(),
- get_signed_extras(signer.into()),
+ get_signed_extras(),
),
None => fp_self_contained::CheckedSignature::Unsigned,
};
@@ -104,53 +89,5 @@
};
extrinsic.apply::<Runtime>(&dispatch_info, len)
- }
-
- fn reserve_balance(
- id: [u8; 16],
- sponsor: <T as frame_system::Config>::AccountId,
- call: <T as pallet_unique_scheduler::Config>::RuntimeCall,
- count: u32,
- ) -> Result<(), DispatchError> {
- let dispatch_info = call.get_dispatch_info();
- let weight: Balance =
- SponsorshipChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
- .saturating_mul(count.into());
-
- <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
- &id,
- &(sponsor.into()),
- weight,
- )
- }
-
- fn pay_for_call(
- id: [u8; 16],
- sponsor: <T as frame_system::Config>::AccountId,
- call: <T as pallet_unique_scheduler::Config>::RuntimeCall,
- ) -> Result<u128, DispatchError> {
- let dispatch_info = call.get_dispatch_info();
- let weight: Balance =
- SponsorshipChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
- Ok(
- <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
- &id,
- &(sponsor.into()),
- weight,
- ),
- )
- }
-
- fn cancel_reserve(
- id: [u8; 16],
- sponsor: <T as frame_system::Config>::AccountId,
- ) -> Result<u128, DispatchError> {
- Ok(
- <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
- &id,
- &(sponsor.into()),
- u128::MAX,
- ),
- )
}
}
runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -41,7 +41,7 @@
'pallet-unique/runtime-benchmarks',
'pallet-inflation/runtime-benchmarks',
'pallet-app-promotion/runtime-benchmarks',
- 'pallet-unique-scheduler/runtime-benchmarks',
+ 'pallet-unique-scheduler-v2/runtime-benchmarks',
'pallet-xcm/runtime-benchmarks',
'sp-runtime/runtime-benchmarks',
'xcm-builder/runtime-benchmarks',
@@ -71,7 +71,6 @@
'cumulus-pallet-dmp-queue/try-runtime',
'pallet-inflation/try-runtime',
'pallet-unique/try-runtime',
- 'pallet-unique-scheduler/try-runtime',
'pallet-configuration/try-runtime',
'pallet-charge-transaction/try-runtime',
'pallet-common/try-runtime',
@@ -142,7 +141,7 @@
'pallet-proxy-rmrk-core/std',
'pallet-proxy-rmrk-equip/std',
'pallet-unique/std',
- 'pallet-unique-scheduler/std',
+ 'pallet-unique-scheduler-v2/std',
'pallet-charge-transaction/std',
'up-data-structs/std',
'sp-api/std',
@@ -474,8 +473,8 @@
pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
pallet-proxy-rmrk-equip = { default-features = false, path = "../../pallets/proxy-rmrk-equip", package = "pallet-rmrk-equip" }
-pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.30", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
+pallet-unique-scheduler-v2 = { path = '../../pallets/scheduler-v2', default-features = false }
pallet-evm-migration = { path = '../../pallets/evm-migration', default-features = false }
pallet-evm-contract-helpers = { path = '../../pallets/evm-contract-helpers', default-features = false }
pallet-evm-transaction-payment = { path = '../../pallets/evm-transaction-payment', default-features = false }
runtime/quartz/Cargo.tomldiffbeforeafterboth--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -40,7 +40,6 @@
'pallet-unique/runtime-benchmarks',
'pallet-foreign-assets/runtime-benchmarks',
'pallet-inflation/runtime-benchmarks',
- 'pallet-unique-scheduler/runtime-benchmarks',
'pallet-xcm/runtime-benchmarks',
'sp-runtime/runtime-benchmarks',
'xcm-builder/runtime-benchmarks',
@@ -70,7 +69,6 @@
'cumulus-pallet-dmp-queue/try-runtime',
'pallet-inflation/try-runtime',
'pallet-unique/try-runtime',
- 'pallet-unique-scheduler/try-runtime',
'pallet-configuration/try-runtime',
'pallet-charge-transaction/try-runtime',
'pallet-common/try-runtime',
@@ -139,7 +137,6 @@
'pallet-proxy-rmrk-core/std',
'pallet-proxy-rmrk-equip/std',
'pallet-unique/std',
- 'pallet-unique-scheduler/std',
'pallet-charge-transaction/std',
'up-data-structs/std',
'sp-api/std',
@@ -475,7 +472,6 @@
pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
pallet-proxy-rmrk-equip = { default-features = false, path = "../../pallets/proxy-rmrk-equip", package = "pallet-rmrk-equip" }
-pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
# pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.30", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
pallet-evm-migration = { path = '../../pallets/evm-migration', default-features = false }
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -40,7 +40,6 @@
'pallet-unique/runtime-benchmarks',
'pallet-foreign-assets/runtime-benchmarks',
'pallet-inflation/runtime-benchmarks',
- 'pallet-unique-scheduler/runtime-benchmarks',
'pallet-xcm/runtime-benchmarks',
'sp-runtime/runtime-benchmarks',
'xcm-builder/runtime-benchmarks',
@@ -71,7 +70,6 @@
'cumulus-pallet-dmp-queue/try-runtime',
'pallet-inflation/try-runtime',
'pallet-unique/try-runtime',
- 'pallet-unique-scheduler/try-runtime',
'pallet-configuration/try-runtime',
'pallet-charge-transaction/try-runtime',
'pallet-common/try-runtime',
@@ -140,7 +138,6 @@
'pallet-proxy-rmrk-core/std',
'pallet-proxy-rmrk-equip/std',
'pallet-unique/std',
- 'pallet-unique-scheduler/std',
'pallet-charge-transaction/std',
'up-data-structs/std',
'sp-api/std',
@@ -469,7 +466,6 @@
pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
pallet-proxy-rmrk-equip = { default-features = false, path = "../../pallets/proxy-rmrk-equip", package = "pallet-rmrk-equip" }
-pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
# pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.30", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
pallet-evm-migration = { path = '../../pallets/evm-migration', default-features = false }
test-pallets/utils/Cargo.tomldiffbeforeafterboth--- a/test-pallets/utils/Cargo.toml
+++ b/test-pallets/utils/Cargo.toml
@@ -10,7 +10,9 @@
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
+# pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
+pallet-unique-scheduler-v2 = { path = '../../pallets/scheduler-v2', default-features = false }
+sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
[features]
default = ["std"]
@@ -19,6 +21,7 @@
"scale-info/std",
"frame-support/std",
"frame-system/std",
- "pallet-unique-scheduler/std",
+ "pallet-unique-scheduler-v2/std",
+ "sp-std/std",
]
-try-runtime = ["frame-support/try-runtime", "pallet-unique-scheduler/try-runtime"]
+try-runtime = ["frame-support/try-runtime", "pallet-unique-scheduler-v2/try-runtime"]
test-pallets/utils/src/lib.rsdiffbeforeafterboth--- a/test-pallets/utils/src/lib.rs
+++ b/test-pallets/utils/src/lib.rs
@@ -22,13 +22,29 @@
#[frame_support::pallet]
pub mod pallet {
- use frame_support::pallet_prelude::*;
+ use frame_support::{
+ pallet_prelude::*,
+ dispatch::{Dispatchable, GetDispatchInfo, PostDispatchInfo},
+ traits::{UnfilteredDispatchable, IsSubType, OriginTrait},
+ };
use frame_system::pallet_prelude::*;
- use pallet_unique_scheduler::{ScheduledId, Pallet as SchedulerPallet};
+ use sp_std::vec::Vec;
+ use pallet_unique_scheduler_v2::{TaskName, Pallet as SchedulerPallet};
#[pallet::config]
- pub trait Config: frame_system::Config + pallet_unique_scheduler::Config {
+ pub trait Config: frame_system::Config + pallet_unique_scheduler_v2::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
+
+ /// The overarching call type.
+ type RuntimeCall: Parameter
+ + Dispatchable<
+ RuntimeOrigin = <Self as frame_system::Config>::RuntimeOrigin,
+ PostInfo = PostDispatchInfo,
+ > + GetDispatchInfo
+ + From<frame_system::Call<Self>>
+ + UnfilteredDispatchable<RuntimeOrigin = <Self as frame_system::Config>::RuntimeOrigin>
+ + IsSubType<Call<Self>>
+ + IsType<<Self as frame_system::Config>::RuntimeCall>;
}
#[pallet::event]
@@ -36,6 +52,7 @@
pub enum Event<T: Config> {
ValueIsSet,
ShouldRollback,
+ BatchCompleted,
}
#[pallet::pallet]
@@ -94,14 +111,13 @@
#[pallet::weight(10_000)]
pub fn self_canceling_inc(
origin: OriginFor<T>,
- id: ScheduledId,
+ id: TaskName,
max_test_value: u32,
) -> DispatchResult {
Self::ensure_origin_and_enabled(origin.clone())?;
+ Self::inc_test_value(origin.clone())?;
- if <TestValue<T>>::get() < max_test_value {
- Self::inc_test_value(origin)?;
- } else {
+ if <TestValue<T>>::get() == max_test_value {
SchedulerPallet::<T>::cancel_named(origin, id)?;
}
@@ -113,6 +129,35 @@
Self::ensure_origin_and_enabled(origin)?;
Ok(())
}
+
+ #[pallet::weight(10_000)]
+ pub fn batch_all(
+ origin: OriginFor<T>,
+ calls: Vec<<T as Config>::RuntimeCall>,
+ ) -> DispatchResultWithPostInfo {
+ Self::ensure_origin_and_enabled(origin.clone())?;
+
+ let is_root = ensure_root(origin.clone()).is_ok();
+
+ for call in calls {
+ if is_root {
+ call.dispatch_bypass_filter(origin.clone())?;
+ } else {
+ let mut filtered_origin = origin.clone();
+ // Don't allow users to nest `batch_all` calls.
+ filtered_origin.add_filter(
+ move |c: &<T as frame_system::Config>::RuntimeCall| {
+ let c = <T as Config>::RuntimeCall::from_ref(c);
+ !matches!(c.is_sub_type(), Some(Call::batch_all { .. }))
+ },
+ );
+ call.dispatch(filtered_origin)?;
+ }
+ }
+
+ Self::deposit_event(Event::BatchCompleted);
+ Ok(None::<Weight>.into())
+ }
}
}
tests/src/eth/scheduling.test.tsdiffbeforeafterboth--- a/tests/src/eth/scheduling.test.ts
+++ b/tests/src/eth/scheduling.test.ts
@@ -15,7 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {expect} from 'chai';
-import {EthUniqueHelper, itEth} from './util';
+import {EthUniqueHelper, itSchedEth} from './util';
import {Pallets, usingPlaygrounds} from '../util';
describe('Scheduing EVM smart contracts', () => {
@@ -26,11 +26,11 @@
});
});
- itEth.ifWithPallets('Successfully schedules and periodically executes an EVM contract', [Pallets.Scheduler], async ({helper, privateKey}) => {
+ itSchedEth.ifWithPallets('Successfully schedules and periodically executes an EVM contract', [Pallets.Scheduler], async (scheduleKind, {helper, privateKey}) => {
const donor = await privateKey({filename: __filename});
const [alice] = await helper.arrange.createAccounts([1000n], donor);
- const scheduledId = await helper.arrange.makeScheduledId();
+ const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
const deployer = await helper.eth.createAccountWithBalance(alice);
const flipper = await helper.eth.deployFlipper(deployer);
@@ -44,7 +44,7 @@
repetitions: 2,
};
- await helper.scheduler.scheduleAfter<EthUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+ await helper.scheduler.scheduleAfter<EthUniqueHelper>(waitForBlocks, {scheduledId, periodic})
.eth.sendEVM(
alice,
flipper.options.address,
tests/src/eth/util/index.tsdiffbeforeafterboth--- a/tests/src/eth/util/index.ts
+++ b/tests/src/eth/util/index.ts
@@ -8,6 +8,7 @@
import {EthUniqueHelper} from './playgrounds/unique.dev';
import {SilentLogger, SilentConsole} from '../../util/playgrounds/unique.dev';
+import {SchedKind} from '../../util';
export {EthUniqueHelper} from './playgrounds/unique.dev';
@@ -81,3 +82,19 @@
itEthIfWithPallet.only = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itEthIfWithPallet(name, required, cb, {only: true});
itEthIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itEthIfWithPallet(name, required, cb, {skip: true});
itEth.ifWithPallets = itEthIfWithPallet;
+
+export function itSchedEth(
+ name: string,
+ cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any,
+ opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {},
+) {
+ itEth(name + ' (anonymous scheduling)', (apis) => cb('anon', apis), opts);
+ itEth(name + ' (named scheduling)', (apis) => cb('named', apis), opts);
+}
+itSchedEth.only = (name: string, cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itSchedEth(name, cb, {only: true});
+itSchedEth.skip = (name: string, cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itSchedEth(name, cb, {skip: true});
+itSchedEth.ifWithPallets = itSchedIfWithPallets;
+
+function itSchedIfWithPallets(name: string, required: string[], cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
+ return itSchedEth(name, cb, {requiredPallets: required, ...opts});
+}
tests/src/maintenanceMode.seqtest.tsdiffbeforeafterboth--- a/tests/src/maintenanceMode.seqtest.ts
+++ b/tests/src/maintenanceMode.seqtest.ts
@@ -16,7 +16,7 @@
import {IKeyringPair} from '@polkadot/types/types';
import {ApiPromise} from '@polkadot/api';
-import {expect, itSub, Pallets, usingPlaygrounds} from './util';
+import {expect, itSched, itSub, Pallets, usingPlaygrounds} from './util';
import {itEth} from './eth/util';
async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {
@@ -162,34 +162,38 @@
await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;
});
- itSub.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.Scheduler], async ({helper}) => {
+ itSched.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.Scheduler], async (scheduleKind, {helper}) => {
const collection = await helper.nft.mintCollection(bob);
const nftBeforeMM = await collection.mintToken(bob);
const nftDuringMM = await collection.mintToken(bob);
const nftAfterMM = await collection.mintToken(bob);
- const scheduledIdBeforeMM = '0x' + '0'.repeat(31) + '0';
- const scheduledIdDuringMM = '0x' + '0'.repeat(31) + '1';
- const scheduledIdBunkerThroughMM = '0x' + '0'.repeat(31) + '2';
- const scheduledIdAttemptDuringMM = '0x' + '0'.repeat(31) + '3';
- const scheduledIdAfterMM = '0x' + '0'.repeat(31) + '4';
+ const [
+ scheduledIdBeforeMM,
+ scheduledIdDuringMM,
+ scheduledIdBunkerThroughMM,
+ scheduledIdAttemptDuringMM,
+ scheduledIdAfterMM,
+ ] = scheduleKind == 'named'
+ ? helper.arrange.makeScheduledIds(5)
+ : new Array(5);
const blocksToWait = 6;
// Scheduling works before the maintenance
- await nftBeforeMM.scheduleAfter(scheduledIdBeforeMM, blocksToWait)
+ await nftBeforeMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdBeforeMM})
.transfer(bob, {Substrate: superuser.address});
await helper.wait.newBlocks(blocksToWait + 1);
expect(await nftBeforeMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});
// Schedule a transaction that should occur *during* the maintenance
- await nftDuringMM.scheduleAfter(scheduledIdDuringMM, blocksToWait)
+ await nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdDuringMM})
.transfer(bob, {Substrate: superuser.address});
// Schedule a transaction that should occur *after* the maintenance
- await nftDuringMM.scheduleAfter(scheduledIdBunkerThroughMM, blocksToWait * 2)
+ await nftDuringMM.scheduleAfter(blocksToWait * 2, {scheduledId: scheduledIdBunkerThroughMM})
.transfer(bob, {Substrate: superuser.address});
await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);
@@ -200,7 +204,7 @@
expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: bob.address});
// Any attempts to schedule a tx during the MM should be rejected
- await expect(nftDuringMM.scheduleAfter(scheduledIdAttemptDuringMM, blocksToWait)
+ await expect(nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAttemptDuringMM})
.transfer(bob, {Substrate: superuser.address}))
.to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);
@@ -208,7 +212,7 @@
expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;
// Scheduling works after the maintenance
- await nftAfterMM.scheduleAfter(scheduledIdAfterMM, blocksToWait)
+ await nftAfterMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAfterMM})
.transfer(bob, {Substrate: superuser.address});
await helper.wait.newBlocks(blocksToWait + 1);
tests/src/scheduler.seqtest.tsdiffbeforeafterboth--- a/tests/src/scheduler.seqtest.ts
+++ b/tests/src/scheduler.seqtest.ts
@@ -14,43 +14,53 @@
// 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, itSub, Pallets, usingPlaygrounds} from './util';
+import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';
import {IKeyringPair} from '@polkadot/types/types';
import {DevUniqueHelper} from './util/playgrounds/unique.dev';
describe('Scheduling token and balance transfers', () => {
+ let superuser: IKeyringPair;
let alice: IKeyringPair;
let bob: IKeyringPair;
let charlie: IKeyringPair;
- before(async () => {
- await usingPlaygrounds(async (helper, privateKeyWrapper) => {
- alice = await privateKeyWrapper('//Alice');
- bob = await privateKeyWrapper('//Bob');
- charlie = await privateKeyWrapper('//Charlie');
+ before(async function() {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.Scheduler]);
+ superuser = await privateKey('//Alice');
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+
await helper.testUtils.enable();
});
});
- itSub.ifWithPallets('Can delay a transfer of an owned token', [Pallets.Scheduler], async ({helper}) => {
+ beforeEach(async () => {
+ await usingPlaygrounds(async (helper) => {
+ await helper.wait.noScheduledTasks();
+ });
+ });
+
+ itSched('Can delay a transfer of an owned token', async (scheduleKind, {helper}) => {
const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
const token = await collection.mintToken(alice);
- const schedulerId = await helper.arrange.makeScheduledId();
+ const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
const blocksBeforeExecution = 4;
-
- await token.scheduleAfter(schedulerId, blocksBeforeExecution)
+
+ await token.scheduleAfter(blocksBeforeExecution, {scheduledId})
.transfer(alice, {Substrate: bob.address});
+ const executionBlock = await helper.chain.getLatestBlockNumber() + blocksBeforeExecution + 1;
expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
- await helper.wait.newBlocks(blocksBeforeExecution + 1);
+ await helper.wait.forParachainBlockNumber(executionBlock);
expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
});
- itSub.ifWithPallets('Can transfer funds periodically', [Pallets.Scheduler], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
+ itSched('Can transfer funds periodically', async (scheduleKind, {helper}) => {
+ const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
const waitForBlocks = 1;
const amount = 1n * helper.balance.getOneTokenNominal();
@@ -61,10 +71,11 @@
const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
- await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})
+ await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId, periodic})
.balance.transferToSubstrate(alice, bob.address, amount);
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
- await helper.wait.newBlocks(waitForBlocks + 1);
+ await helper.wait.forParachainBlockNumber(executionBlock);
const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);
expect(bobsBalanceAfterFirst)
@@ -73,7 +84,7 @@
'#1 Balance of the recipient should be increased by 1 * amount',
);
- await helper.wait.newBlocks(periodic.period);
+ await helper.wait.forParachainBlockNumber(executionBlock + periodic.period);
const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);
expect(bobsBalanceAfterSecond)
@@ -83,42 +94,44 @@
);
});
- itSub.ifWithPallets('Can cancel a scheduled operation which has not yet taken effect', [Pallets.Scheduler], async ({helper}) => {
+ itSub('Can cancel a scheduled operation which has not yet taken effect', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
const token = await collection.mintToken(alice);
- const scheduledId = await helper.arrange.makeScheduledId();
+ const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 4;
expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
- await token.scheduleAfter(scheduledId, waitForBlocks)
+ await token.scheduleAfter(waitForBlocks, {scheduledId})
.transfer(alice, {Substrate: bob.address});
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
await helper.scheduler.cancelScheduled(alice, scheduledId);
- await helper.wait.newBlocks(waitForBlocks + 1);
+ await helper.wait.forParachainBlockNumber(executionBlock);
expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
- itSub.ifWithPallets('Can cancel a periodic operation (transfer of funds)', [Pallets.Scheduler], async ({helper}) => {
+ itSub('Can cancel a periodic operation (transfer of funds)', async ({helper}) => {
const waitForBlocks = 1;
const periodic = {
period: 3,
repetitions: 2,
};
- const scheduledId = await helper.arrange.makeScheduledId();
+ const scheduledId = helper.arrange.makeScheduledId();
const amount = 1n * helper.balance.getOneTokenNominal();
const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
- await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})
+ await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId, periodic})
.balance.transferToSubstrate(alice, bob.address, amount);
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
- await helper.wait.newBlocks(waitForBlocks + 1);
+ await helper.wait.forParachainBlockNumber(executionBlock);
const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);
@@ -129,7 +142,7 @@
);
await helper.scheduler.cancelScheduled(alice, scheduledId);
- await helper.wait.newBlocks(periodic.period);
+ await helper.wait.forParachainBlockNumber(executionBlock + periodic.period);
const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);
expect(bobsBalanceAfterSecond)
@@ -139,8 +152,54 @@
);
});
- itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
+ itSched('scheduler will not insert more tasks than allowed', async (scheduleKind, {helper}) => {
+ const maxScheduledPerBlock = 50;
+ let fillScheduledIds = new Array(maxScheduledPerBlock);
+ let extraScheduledId = undefined;
+
+ if (scheduleKind == 'named') {
+ const scheduledIds = helper.arrange.makeScheduledIds(maxScheduledPerBlock + 1);
+ fillScheduledIds = scheduledIds.slice(0, maxScheduledPerBlock);
+ extraScheduledId = scheduledIds[maxScheduledPerBlock];
+ }
+
+ // Since the dev node has Instant Seal,
+ // we need a larger gap between the current block and the target one.
+ //
+ // We will schedule `maxScheduledPerBlock` transaction into the target block,
+ // so we need at least `maxScheduledPerBlock`-wide gap.
+ // We add some additional blocks to this gap to mitigate possible PolkadotJS delays.
+ const waitForBlocks = await helper.arrange.isDevNode() ? maxScheduledPerBlock + 5 : 5;
+
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks;
+
+ const amount = 1n * helper.balance.getOneTokenNominal();
+
+ const balanceBefore = await helper.balance.getSubstrate(bob.address);
+
+ // Fill the target block
+ for (let i = 0; i < maxScheduledPerBlock; i++) {
+ await helper.scheduler.scheduleAt(executionBlock, {scheduledId: fillScheduledIds[i]})
+ .balance.transferToSubstrate(superuser, bob.address, amount);
+ }
+
+ // Try to schedule a task into a full block
+ await expect(helper.scheduler.scheduleAt(executionBlock, {scheduledId: extraScheduledId})
+ .balance.transferToSubstrate(superuser, bob.address, amount))
+ .to.be.rejectedWith(/scheduler\.AgendaIsExhausted/);
+
+ await helper.wait.forParachainBlockNumber(executionBlock);
+
+ const balanceAfter = await helper.balance.getSubstrate(bob.address);
+
+ expect(balanceAfter > balanceBefore).to.be.true;
+
+ const diff = balanceAfter - balanceBefore;
+ expect(diff).to.be.equal(amount * BigInt(maxScheduledPerBlock));
+ });
+
+ itSched.ifWithPallets('Scheduled tasks are transactional', [Pallets.TestUtils], async (scheduleKind, {helper}) => {
+ const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
const waitForBlocks = 4;
const initTestVal = 42;
@@ -148,18 +207,19 @@
await helper.testUtils.setTestValue(alice, initTestVal);
- await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks)
+ await helper.scheduler.scheduleAfter<DevUniqueHelper>(waitForBlocks, {scheduledId})
.testUtils.setTestValueAndRollback(alice, changedTestVal);
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
- await helper.wait.newBlocks(waitForBlocks + 1);
+ await helper.wait.forParachainBlockNumber(executionBlock);
const testVal = await helper.testUtils.testValue();
expect(testVal, 'The test value should NOT be commited')
.to.be.equal(initTestVal);
});
- itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.Scheduler, Pallets.TestUtils], async function({helper}) {
- const scheduledId = await helper.arrange.makeScheduledId();
+ itSched.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.TestUtils], async function(scheduleKind, {helper}) {
+ const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
const waitForBlocks = 4;
const periodic = {
period: 2,
@@ -172,15 +232,14 @@
const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))
.partialFee.toBigInt();
- await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+ await helper.scheduler.scheduleAfter<DevUniqueHelper>(waitForBlocks, {scheduledId, periodic})
.testUtils.justTakeFee(alice);
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
- await helper.wait.newBlocks(1);
-
const aliceInitBalance = await helper.balance.getSubstrate(alice.address);
let diff;
- await helper.wait.newBlocks(waitForBlocks);
+ await helper.wait.forParachainBlockNumber(executionBlock);
const aliceBalanceAfterFirst = await helper.balance.getSubstrate(alice.address);
expect(
@@ -194,7 +253,7 @@
'Scheduled task should take the right amount of fees',
);
- await helper.wait.newBlocks(periodic.period);
+ await helper.wait.forParachainBlockNumber(executionBlock + periodic.period);
const aliceBalanceAfterSecond = await helper.balance.getSubstrate(alice.address);
expect(
@@ -211,7 +270,7 @@
// Check if we can cancel a scheduled periodic operation
// in the same block in which it is running
- itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
+ itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.TestUtils], async ({helper}) => {
const currentBlockNumber = await helper.chain.getLatestBlockNumber();
const blocksBeforeExecution = 10;
const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;
@@ -219,7 +278,7 @@
const [
scheduledId,
scheduledCancelId,
- ] = await helper.arrange.makeScheduledIds(2);
+ ] = helper.arrange.makeScheduledIds(2);
const periodic = {
period: 5,
@@ -232,14 +291,14 @@
await helper.testUtils.setTestValue(alice, initTestVal);
- await helper.scheduler.scheduleAt<DevUniqueHelper>(scheduledId, firstExecutionBlockNumber, {periodic})
+ await helper.scheduler.scheduleAt<DevUniqueHelper>(firstExecutionBlockNumber, {scheduledId, periodic})
.testUtils.incTestValue(alice);
// Cancel the inc tx after 2 executions
// *in the same block* in which the second execution is scheduled
await helper.scheduler.scheduleAt(
- scheduledCancelId,
firstExecutionBlockNumber + periodic.period,
+ {scheduledId: scheduledCancelId},
).scheduler.cancelScheduled(alice, scheduledId);
await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber);
@@ -261,8 +320,8 @@
}
});
- itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
+ itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.TestUtils], async ({helper}) => {
+ const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 4;
const periodic = {
period: 2,
@@ -274,47 +333,49 @@
await helper.testUtils.setTestValue(alice, initTestVal);
- await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+ await helper.scheduler.scheduleAfter<DevUniqueHelper>(waitForBlocks, {scheduledId, periodic})
.testUtils.selfCancelingInc(alice, scheduledId, maxTestVal);
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
- await helper.wait.newBlocks(waitForBlocks + 1);
+ await helper.wait.forParachainBlockNumber(executionBlock);
// execution #0
expect(await helper.testUtils.testValue())
.to.be.equal(initTestVal + 1);
- await helper.wait.newBlocks(periodic.period);
+ await helper.wait.forParachainBlockNumber(executionBlock + periodic.period);
// execution #1
expect(await helper.testUtils.testValue())
.to.be.equal(initTestVal + 2);
- await helper.wait.newBlocks(periodic.period);
+ await helper.wait.forParachainBlockNumber(executionBlock + 2 * periodic.period);
// <canceled>
expect(await helper.testUtils.testValue())
.to.be.equal(initTestVal + 2);
});
- itSub.ifWithPallets('Root can cancel any scheduled operation', [Pallets.Scheduler], async ({helper}) => {
+ itSub('Root can cancel any scheduled operation', async ({helper}) => {
const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
const token = await collection.mintToken(bob);
- const scheduledId = await helper.arrange.makeScheduledId();
+ const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 4;
- await token.scheduleAfter(scheduledId, waitForBlocks)
+ await token.scheduleAfter(waitForBlocks, {scheduledId})
.transfer(bob, {Substrate: alice.address});
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
- await helper.getSudo().scheduler.cancelScheduled(alice, scheduledId);
+ await helper.getSudo().scheduler.cancelScheduled(superuser, scheduledId);
- await helper.wait.newBlocks(waitForBlocks + 1);
+ await helper.wait.forParachainBlockNumber(executionBlock);
expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
});
- itSub.ifWithPallets('Root can set prioritized scheduled operation', [Pallets.Scheduler], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
+ itSched('Root can set prioritized scheduled operation', async (scheduleKind, {helper}) => {
+ const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
const waitForBlocks = 4;
const amount = 42n * helper.balance.getOneTokenNominal();
@@ -322,10 +383,11 @@
const balanceBefore = await helper.balance.getSubstrate(charlie.address);
await helper.getSudo()
- .scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42})
- .balance.forceTransferToSubstrate(alice, bob.address, charlie.address, amount);
+ .scheduler.scheduleAfter(waitForBlocks, {scheduledId, priority: 42})
+ .balance.forceTransferToSubstrate(superuser, bob.address, charlie.address, amount);
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
- await helper.wait.newBlocks(waitForBlocks + 1);
+ await helper.wait.forParachainBlockNumber(executionBlock);
const balanceAfter = await helper.balance.getSubstrate(charlie.address);
@@ -335,18 +397,19 @@
expect(diff).to.be.equal(amount);
});
- itSub.ifWithPallets("Root can change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {
+ itSub("Root can change scheduled operation's priority", async ({helper}) => {
const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
const token = await collection.mintToken(bob);
- const scheduledId = await helper.arrange.makeScheduledId();
+ const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 6;
- await token.scheduleAfter(scheduledId, waitForBlocks)
+ await token.scheduleAfter(waitForBlocks, {scheduledId})
.transfer(bob, {Substrate: alice.address});
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
const priority = 112;
- await helper.getSudo().scheduler.changePriority(alice, scheduledId, priority);
+ await helper.getSudo().scheduler.changePriority(superuser, scheduledId, priority);
const priorityChanged = await helper.wait.event(
waitForBlocks,
@@ -355,14 +418,19 @@
);
expect(priorityChanged !== null).to.be.true;
- expect(priorityChanged!.event.data[2].toString()).to.be.equal(priority.toString());
+
+ const [blockNumber, index] = priorityChanged!.event.data[0].toJSON() as any[];
+ expect(blockNumber).to.be.equal(executionBlock);
+ expect(index).to.be.equal(0);
+
+ expect(priorityChanged!.event.data[1].toString()).to.be.equal(priority.toString());
});
- itSub.ifWithPallets('Prioritized operations executes in valid order', [Pallets.Scheduler], async ({helper}) => {
+ itSub('Prioritized operations execute in valid order', async ({helper}) => {
const [
scheduledFirstId,
scheduledSecondId,
- ] = await helper.arrange.makeScheduledIds(2);
+ ] = helper.arrange.makeScheduledIds(2);
const currentBlockNumber = await helper.chain.getLatestBlockNumber();
const blocksBeforeExecution = 6;
@@ -379,19 +447,25 @@
const amount = 1n * helper.balance.getOneTokenNominal();
// Scheduler a task with a lower priority first, then with a higher priority
- await helper.getSudo().scheduler.scheduleAt(scheduledFirstId, firstExecutionBlockNumber, {priority: prioLow, periodic})
- .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);
+ await helper.getSudo().scheduler.scheduleAt(firstExecutionBlockNumber, {
+ scheduledId: scheduledFirstId,
+ priority: prioLow,
+ periodic,
+ }).balance.forceTransferToSubstrate(superuser, alice.address, bob.address, amount);
- await helper.getSudo().scheduler.scheduleAt(scheduledSecondId, firstExecutionBlockNumber, {priority: prioHigh, periodic})
- .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);
+ await helper.getSudo().scheduler.scheduleAt(firstExecutionBlockNumber, {
+ scheduledId: scheduledSecondId,
+ priority: prioHigh,
+ periodic,
+ }).balance.forceTransferToSubstrate(superuser, alice.address, bob.address, amount);
const capture = await helper.arrange.captureEvents('scheduler', 'Dispatched');
await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber);
// Flip priorities
- await helper.getSudo().scheduler.changePriority(alice, scheduledFirstId, prioHigh);
- await helper.getSudo().scheduler.changePriority(alice, scheduledSecondId, prioLow);
+ await helper.getSudo().scheduler.changePriority(superuser, scheduledFirstId, prioHigh);
+ await helper.getSudo().scheduler.changePriority(superuser, scheduledSecondId, prioLow);
await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber + periodic.period);
@@ -409,38 +483,123 @@
expect(secondExecuctionIds[0]).to.be.equal(scheduledFirstId);
expect(secondExecuctionIds[1]).to.be.equal(scheduledSecondId);
});
+
+ itSched('Periodic operations always can be rescheduled', async (scheduleKind, {helper}) => {
+ const maxScheduledPerBlock = 50;
+ const numFilledBlocks = 3;
+ const ids = helper.arrange.makeScheduledIds(numFilledBlocks * maxScheduledPerBlock + 1);
+ const periodicId = scheduleKind == 'named' ? ids[0] : undefined;
+ const fillIds = ids.slice(1);
+
+ const fillScheduleFn = scheduleKind == 'named' ? 'scheduleNamed' : 'schedule';
+
+ const initTestVal = 0;
+ const firstExecTestVal = 1;
+ const secondExecTestVal = 2;
+ await helper.testUtils.setTestValue(alice, initTestVal);
+
+ const currentBlockNumber = await helper.chain.getLatestBlockNumber();
+ const blocksBeforeExecution = 8;
+ const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;
+
+ const period = 5;
+
+ const periodic = {
+ period,
+ repetitions: 2,
+ };
+
+ // Fill `numFilledBlocks` blocks beginning from the block in which the second execution should occur
+ const txs = [];
+ for (let offset = 0; offset < numFilledBlocks; offset ++) {
+ for (let i = 0; i < maxScheduledPerBlock; i++) {
+
+ const scheduledTx = helper.constructApiCall('api.tx.balances.transfer', [bob.address, 1n]);
+
+ const when = firstExecutionBlockNumber + period + offset;
+ const mandatoryArgs = [when, null, null, scheduledTx];
+ const scheduleArgs = scheduleKind == 'named'
+ ? [fillIds[i + offset * maxScheduledPerBlock], ...mandatoryArgs]
+ : mandatoryArgs;
+
+ const tx = helper.constructApiCall(`api.tx.scheduler.${fillScheduleFn}`, scheduleArgs);
+
+ txs.push(tx);
+ }
+ }
+ await helper.executeExtrinsic(alice, 'api.tx.testUtils.batchAll', [txs], true);
+
+ await helper.scheduler.scheduleAt<DevUniqueHelper>(firstExecutionBlockNumber, {
+ scheduledId: periodicId,
+ periodic,
+ }).testUtils.incTestValue(alice);
+
+ await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber);
+ expect(await helper.testUtils.testValue()).to.be.equal(firstExecTestVal);
+
+ await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber + period + numFilledBlocks);
+
+ // The periodic operation should be postponed by `numFilledBlocks`
+ for (let i = 0; i < numFilledBlocks; i++) {
+ expect(await helper.testUtils.testValue(firstExecutionBlockNumber + period + i)).to.be.equal(firstExecTestVal);
+ }
+
+ // After the `numFilledBlocks` the periodic operation will eventually be executed
+ expect(await helper.testUtils.testValue()).to.be.equal(secondExecTestVal);
+ });
+
+ itSched('scheduled operations does not change nonce', async (scheduleKind, {helper}) => {
+ const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
+ const blocksBeforeExecution = 4;
+
+ await helper.scheduler
+ .scheduleAfter<DevUniqueHelper>(blocksBeforeExecution, {scheduledId})
+ .balance.transferToSubstrate(alice, bob.address, 1n);
+ const executionBlock = await helper.chain.getLatestBlockNumber() + blocksBeforeExecution + 1;
+
+ const initNonce = await helper.chain.getNonce(alice.address);
+
+ await helper.wait.forParachainBlockNumber(executionBlock);
+
+ const finalNonce = await helper.chain.getNonce(alice.address);
+
+ expect(initNonce).to.be.equal(finalNonce);
+ });
});
describe('Negative Test: Scheduling', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
- before(async () => {
- await usingPlaygrounds(async (helper, privateKeyWrapper) => {
- alice = await privateKeyWrapper('//Alice');
- bob = await privateKeyWrapper('//Bob');
+ before(async function() {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.Scheduler]);
+
+ const donor = await privateKey({filename: __filename});
+ [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
await helper.testUtils.enable();
});
});
- itSub.ifWithPallets("Can't overwrite a scheduled ID", [Pallets.Scheduler], async ({helper}) => {
+ itSub("Can't overwrite a scheduled ID", async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
const token = await collection.mintToken(alice);
- const scheduledId = await helper.arrange.makeScheduledId();
+ const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 4;
- await token.scheduleAfter(scheduledId, waitForBlocks)
+ await token.scheduleAfter(waitForBlocks, {scheduledId})
.transfer(alice, {Substrate: bob.address});
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
- const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks);
+ const scheduled = helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId});
await expect(scheduled.balance.transferToSubstrate(alice, bob.address, 1n * helper.balance.getOneTokenNominal()))
.to.be.rejectedWith(/scheduler\.FailedToSchedule/);
const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
- await helper.wait.newBlocks(waitForBlocks + 1);
+ await helper.wait.forParachainBlockNumber(executionBlock);
const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);
@@ -448,58 +607,61 @@
expect(bobsBalanceBefore).to.be.equal(bobsBalanceAfter);
});
- itSub.ifWithPallets("Can't cancel an operation which is not scheduled", [Pallets.Scheduler], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
+ itSub("Can't cancel an operation which is not scheduled", async ({helper}) => {
+ const scheduledId = helper.arrange.makeScheduledId();
await expect(helper.scheduler.cancelScheduled(alice, scheduledId))
.to.be.rejectedWith(/scheduler\.NotFound/);
});
- itSub.ifWithPallets("Can't cancel a non-owned scheduled operation", [Pallets.Scheduler], async ({helper}) => {
+ itSub("Can't cancel a non-owned scheduled operation", async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
const token = await collection.mintToken(alice);
- const scheduledId = await helper.arrange.makeScheduledId();
+ const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 4;
- await token.scheduleAfter(scheduledId, waitForBlocks)
+ await token.scheduleAfter(waitForBlocks, {scheduledId})
.transfer(alice, {Substrate: bob.address});
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
await expect(helper.scheduler.cancelScheduled(bob, scheduledId))
.to.be.rejectedWith(/BadOrigin/);
- await helper.wait.newBlocks(waitForBlocks + 1);
+ await helper.wait.forParachainBlockNumber(executionBlock);
expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
});
- itSub.ifWithPallets("Regular user can't set prioritized scheduled operation", [Pallets.Scheduler], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
+ itSched("Regular user can't set prioritized scheduled operation", async (scheduleKind, {helper}) => {
+ const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
const waitForBlocks = 4;
const amount = 42n * helper.balance.getOneTokenNominal();
const balanceBefore = await helper.balance.getSubstrate(bob.address);
- const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42});
+ const scheduled = helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId, priority: 42});
await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))
.to.be.rejectedWith(/BadOrigin/);
- await helper.wait.newBlocks(waitForBlocks + 1);
+ const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
+
+ await helper.wait.forParachainBlockNumber(executionBlock);
const balanceAfter = await helper.balance.getSubstrate(bob.address);
expect(balanceAfter).to.be.equal(balanceBefore);
});
- itSub.ifWithPallets("Regular user can't change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {
+ itSub("Regular user can't change scheduled operation's priority", async ({helper}) => {
const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
const token = await collection.mintToken(bob);
- const scheduledId = await helper.arrange.makeScheduledId();
+ const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 4;
- await token.scheduleAfter(scheduledId, waitForBlocks)
+ await token.scheduleAfter(waitForBlocks, {scheduledId})
.transfer(bob, {Substrate: alice.address});
const priority = 112;
@@ -522,9 +684,9 @@
// let bob: IKeyringPair;
// before(async() => {
- // await usingApi(async (_, privateKeyWrapper) => {
- // alice = privateKeyWrapper('//Alice');
- // bob = privateKeyWrapper('//Bob');
+ // await usingApi(async (_, privateKey) => {
+ // alice = privateKey('//Alice');
+ // bob = privateKey('//Bob');
// });
// });
@@ -550,9 +712,9 @@
});
it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
- // await usingApi(async (api, privateKeyWrapper) => {
+ // await usingApi(async (api, privateKey) => {
// // Find an empty, unused account
- // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+ // const zeroBalance = await findUnusedAddress(api, privateKey);
// const collectionId = await createCollectionExpectSuccess();
@@ -591,8 +753,8 @@
it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
// const collectionId = await createCollectionExpectSuccess();
- // await usingApi(async (api, privateKeyWrapper) => {
- // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+ // await usingApi(async (api, privateKey) => {
+ // const zeroBalance = await findUnusedAddress(api, privateKey);
// const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
// await submitTransactionAsync(alice, balanceTx);
@@ -622,8 +784,8 @@
// await setCollectionSponsorExpectSuccess(collectionId, bob.address);
// await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
- // await usingApi(async (api, privateKeyWrapper) => {
- // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+ // await usingApi(async (api, privateKey) => {
+ // const zeroBalance = await findUnusedAddress(api, privateKey);
// await enablePublicMintingExpectSuccess(alice, collectionId);
// await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
tests/src/util/index.tsdiffbeforeafterboth--- a/tests/src/util/index.ts
+++ b/tests/src/util/index.ts
@@ -130,6 +130,24 @@
itSubIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {skip: true});
itSub.ifWithPallets = itSubIfWithPallet;
+export type SchedKind = 'anon' | 'named';
+
+export function itSched(
+ name: string,
+ cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any,
+ opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {},
+) {
+ itSub(name + ' (anonymous scheduling)', (apis) => cb('anon', apis), opts);
+ itSub(name + ' (named scheduling)', (apis) => cb('named', apis), opts);
+}
+itSched.only = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {only: true});
+itSched.skip = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {skip: true});
+itSched.ifWithPallets = itSchedIfWithPallets;
+
+function itSchedIfWithPallets(name: string, required: string[], cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
+ return itSched(name, cb, {requiredPallets: required, ...opts});
+}
+
export function describeXCM(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {
(process.env.RUN_XCM_TESTS && !opts.skip
? describe
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -172,6 +172,7 @@
}
export interface ISchedulerOptions {
+ scheduledId?: string,
priority?: number,
periodic?: {
period: number,
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -308,11 +308,9 @@
return encodeAddress(address);
}
- async makeScheduledIds(num: number): Promise<string[]> {
- await this.helper.wait.noScheduledTasks();
-
+ makeScheduledIds(num: number): string[] {
function makeId(slider: number) {
- const scheduledIdSize = 32;
+ const scheduledIdSize = 64;
const hexId = slider.toString(16);
const prefixSize = scheduledIdSize - hexId.length;
@@ -330,8 +328,8 @@
return ids;
}
- async makeScheduledId(): Promise<string> {
- return (await this.makeScheduledIds(1))[0];
+ makeScheduledId(): string {
+ return (this.makeScheduledIds(1))[0];
}
async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {
@@ -537,8 +535,12 @@
await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);
}
- async testValue() {
- return (await this.helper.callRpc('api.query.testUtils.testValue', [])).toNumber();
+ async testValue(blockIdx?: number) {
+ const api = blockIdx
+ ? await this.helper.getApi().at(await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockIdx]))
+ : this.helper.getApi();
+
+ return (await api.query.testUtils.testValue()).toJSON();
}
async justTakeFee(signer: TSigner) {
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';4647export class CrossAccountId implements ICrossAccountId {48 Substrate?: TSubstrateAccount;49 Ethereum?: TEthereumAccount;5051 constructor(account: ICrossAccountId) {52 if (account.Substrate) this.Substrate = account.Substrate;53 if (account.Ethereum) this.Ethereum = account.Ethereum;54 }5556 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {57 switch (domain) {58 case 'Substrate': return new CrossAccountId({Substrate: account.address});59 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();60 }61 }6263 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {64 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});65 }6667 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {68 return encodeAddress(decodeAddress(address), ss58Format);69 }7071 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {72 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});73 }7475 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {76 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);77 return this;78 }7980 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {81 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));82 }8384 toEthereum(): CrossAccountId {85 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});86 return this;87 }8889 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {90 return evmToAddress(address, ss58Format);91 }9293 toSubstrate(ss58Format?: number): CrossAccountId {94 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});95 return this;96 }9798 toLowerCase(): CrossAccountId {99 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();100 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();101 return this;102 }103}104105const nesting = {106 toChecksumAddress(address: string): string {107 if (typeof address === 'undefined') return '';108109 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);110111 address = address.toLowerCase().replace(/^0x/i,'');112 const addressHash = keccakAsHex(address).replace(/^0x/i,'');113 const checksumAddress = ['0x'];114115 for (let i = 0; i < address.length; i++) {116 // If ith character is 8 to f then make it uppercase117 if (parseInt(addressHash[i], 16) > 7) {118 checksumAddress.push(address[i].toUpperCase());119 } else {120 checksumAddress.push(address[i]);121 }122 }123 return checksumAddress.join('');124 },125 tokenIdToAddress(collectionId: number, tokenId: number) {126 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);127 },128};129130class UniqueUtil {131 static transactionStatus = {132 NOT_READY: 'NotReady',133 FAIL: 'Fail',134 SUCCESS: 'Success',135 };136137 static chainLogType = {138 EXTRINSIC: 'extrinsic',139 RPC: 'rpc',140 };141142 static getTokenAccount(token: IToken): CrossAccountId {143 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});144 }145146 static getTokenAddress(token: IToken): string {147 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);148 }149150 static getDefaultLogger(): ILogger {151 return {152 log(msg: any, level = 'INFO') {153 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));154 },155 level: {156 ERROR: 'ERROR',157 WARNING: 'WARNING',158 INFO: 'INFO',159 },160 };161 }162163 static vec2str(arr: string[] | number[]) {164 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');165 }166167 static str2vec(string: string) {168 if (typeof string !== 'string') return string;169 return Array.from(string).map(x => x.charCodeAt(0));170 }171172 static fromSeed(seed: string, ss58Format = 42) {173 const keyring = new Keyring({type: 'sr25519', ss58Format});174 return keyring.addFromUri(seed);175 }176177 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {178 if (creationResult.status !== this.transactionStatus.SUCCESS) {179 throw Error('Unable to create collection!');180 }181182 let collectionId = null;183 creationResult.result.events.forEach(({event: {data, method, section}}) => {184 if ((section === 'common') && (method === 'CollectionCreated')) {185 collectionId = parseInt(data[0].toString(), 10);186 }187 });188189 if (collectionId === null) {190 throw Error('No CollectionCreated event was found!');191 }192193 return collectionId;194 }195196 static extractTokensFromCreationResult(creationResult: ITransactionResult): {197 success: boolean,198 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],199 } {200 if (creationResult.status !== this.transactionStatus.SUCCESS) {201 throw Error('Unable to create tokens!');202 }203 let success = false;204 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];205 creationResult.result.events.forEach(({event: {data, method, section}}) => {206 if (method === 'ExtrinsicSuccess') {207 success = true;208 } else if ((section === 'common') && (method === 'ItemCreated')) {209 tokens.push({210 collectionId: parseInt(data[0].toString(), 10),211 tokenId: parseInt(data[1].toString(), 10),212 owner: data[2].toHuman(),213 amount: data[3].toBigInt(),214 });215 }216 });217 return {success, tokens};218 }219220 static extractTokensFromBurnResult(burnResult: ITransactionResult): {221 success: boolean,222 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],223 } {224 if (burnResult.status !== this.transactionStatus.SUCCESS) {225 throw Error('Unable to burn tokens!');226 }227 let success = false;228 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];229 burnResult.result.events.forEach(({event: {data, method, section}}) => {230 if (method === 'ExtrinsicSuccess') {231 success = true;232 } else if ((section === 'common') && (method === 'ItemDestroyed')) {233 tokens.push({234 collectionId: parseInt(data[0].toString(), 10),235 tokenId: parseInt(data[1].toString(), 10),236 owner: data[2].toHuman(),237 amount: data[3].toBigInt(),238 });239 }240 });241 return {success, tokens};242 }243244 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {245 let eventId = null;246 events.forEach(({event: {data, method, section}}) => {247 if ((section === expectedSection) && (method === expectedMethod)) {248 eventId = parseInt(data[0].toString(), 10);249 }250 });251252 if (eventId === null) {253 throw Error(`No ${expectedMethod} event was found!`);254 }255 return eventId === collectionId;256 }257258 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {259 const normalizeAddress = (address: string | ICrossAccountId) => {260 if(typeof address === 'string') return address;261 const obj = {} as any;262 Object.keys(address).forEach(k => {263 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];264 });265 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);266 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();267 return address;268 };269 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;270 events.forEach(({event: {data, method, section}}) => {271 if ((section === 'common') && (method === 'Transfer')) {272 const hData = (data as any).toJSON();273 transfer = {274 collectionId: hData[0],275 tokenId: hData[1],276 from: normalizeAddress(hData[2]),277 to: normalizeAddress(hData[3]),278 amount: BigInt(hData[4]),279 };280 }281 });282 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;283 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);284 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);285 isSuccess = isSuccess && amount === transfer.amount;286 return isSuccess;287 }288289 static bigIntToDecimals(number: bigint, decimals = 18) {290 const numberStr = number.toString();291 const dotPos = numberStr.length - decimals;292293 if (dotPos <= 0) {294 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;295 } else {296 const intPart = numberStr.substring(0, dotPos);297 const fractPart = numberStr.substring(dotPos);298 return intPart + '.' + fractPart;299 }300 }301}302303class UniqueEventHelper {304 private static extractIndex(index: any): [number, number] | string {305 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];306 return index.toJSON();307 }308309 private static extractSub(data: any, subTypes: any): {[key: string]: any} {310 let obj: any = {};311 let index = 0;312313 if (data.entries) {314 for(const [key, value] of data.entries()) {315 obj[key] = this.extractData(value, subTypes[index]);316 index++;317 }318 } else obj = data.toJSON();319320 return obj;321 }322323 private static extractData(data: any, type: any): any {324 if(!type) return data.toHuman();325 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();326 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();327 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);328 return data.toHuman();329 }330331 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {332 const parsedEvents: IEvent[] = [];333334 events.forEach((record) => {335 const {event, phase} = record;336 const types = event.typeDef;337338 const eventData: IEvent = {339 section: event.section.toString(),340 method: event.method.toString(),341 index: this.extractIndex(event.index),342 data: [],343 phase: phase.toJSON(),344 };345346 event.data.forEach((val: any, index: number) => {347 eventData.data.push(this.extractData(val, types[index]));348 });349350 parsedEvents.push(eventData);351 });352353 return parsedEvents;354 }355}356357export class ChainHelperBase {358 helperBase: any;359360 transactionStatus = UniqueUtil.transactionStatus;361 chainLogType = UniqueUtil.chainLogType;362 util: typeof UniqueUtil;363 eventHelper: typeof UniqueEventHelper;364 logger: ILogger;365 api: ApiPromise | null;366 forcedNetwork: TNetworks | null;367 network: TNetworks | null;368 chainLog: IUniqueHelperLog[];369 children: ChainHelperBase[];370 address: AddressGroup;371 chain: ChainGroup;372373 constructor(logger?: ILogger, helperBase?: any) {374 this.helperBase = helperBase;375376 this.util = UniqueUtil;377 this.eventHelper = UniqueEventHelper;378 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();379 this.logger = logger;380 this.api = null;381 this.forcedNetwork = null;382 this.network = null;383 this.chainLog = [];384 this.children = [];385 this.address = new AddressGroup(this);386 this.chain = new ChainGroup(this);387 }388389 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {390 Object.setPrototypeOf(helperCls.prototype, this);391 const newHelper = new helperCls(this.logger, options);392393 newHelper.api = this.api;394 newHelper.network = this.network;395 newHelper.forceNetwork = this.forceNetwork;396397 this.children.push(newHelper);398399 return newHelper;400 }401402 getApi(): ApiPromise {403 if(this.api === null) throw Error('API not initialized');404 return this.api;405 }406407 clearChainLog(): void {408 this.chainLog = [];409 }410411 forceNetwork(value: TNetworks): void {412 this.forcedNetwork = value;413 }414415 async connect(wsEndpoint: string, listeners?: IApiListeners) {416 if (this.api !== null) throw Error('Already connected');417 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);418 this.api = api;419 this.network = network;420 }421422 async disconnect() {423 for (const child of this.children) {424 child.clearApi();425 }426427 if (this.api === null) return;428 await this.api.disconnect();429 this.clearApi();430 }431432 clearApi() {433 this.api = null;434 this.network = null;435 }436437 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {438 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;439 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];440441 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;442443 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;444 return 'opal';445 }446447 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {448 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});449 await api.isReady;450451 const network = await this.detectNetwork(api);452453 await api.disconnect();454455 return network;456 }457458 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{459 api: ApiPromise;460 network: TNetworks;461 }> {462 if(typeof network === 'undefined' || network === null) network = 'opal';463 const supportedRPC = {464 opal: {465 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,466 },467 quartz: {468 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,469 },470 unique: {471 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,472 },473 rococo: {},474 westend: {},475 moonbeam: {},476 moonriver: {},477 acala: {},478 karura: {},479 westmint: {},480 };481 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);482 const rpc = supportedRPC[network];483484 // TODO: investigate how to replace rpc in runtime485 // api._rpcCore.addUserInterfaces(rpc);486487 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});488489 await api.isReadyOrError;490491 if (typeof listeners === 'undefined') listeners = {};492 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {493 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;494 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);495 }496497 return {api, network};498 }499500 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {501 const {events, status} = data;502 if (status.isReady) {503 return this.transactionStatus.NOT_READY;504 }505 if (status.isBroadcast) {506 return this.transactionStatus.NOT_READY;507 }508 if (status.isInBlock || status.isFinalized) {509 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');510 if (errors.length > 0) {511 return this.transactionStatus.FAIL;512 }513 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {514 return this.transactionStatus.SUCCESS;515 }516 }517518 return this.transactionStatus.FAIL;519 }520521 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {522 const sign = (callback: any) => {523 if(options !== null) return transaction.signAndSend(sender, options, callback);524 return transaction.signAndSend(sender, callback);525 };526 // eslint-disable-next-line no-async-promise-executor527 return new Promise(async (resolve, reject) => {528 try {529 const unsub = await sign((result: any) => {530 const status = this.getTransactionStatus(result);531532 if (status === this.transactionStatus.SUCCESS) {533 this.logger.log(`${label} successful`);534 unsub();535 resolve({result, status});536 } else if (status === this.transactionStatus.FAIL) {537 let moduleError = null;538539 if (result.hasOwnProperty('dispatchError')) {540 const dispatchError = result['dispatchError'];541542 if (dispatchError) {543 if (dispatchError.isModule) {544 const modErr = dispatchError.asModule;545 const errorMeta = dispatchError.registry.findMetaError(modErr);546547 moduleError = `${errorMeta.section}.${errorMeta.name}`;548 } else {549 moduleError = dispatchError.toHuman();550 }551 } else {552 this.logger.log(result, this.logger.level.ERROR);553 }554 }555556 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);557 unsub();558 reject({status, moduleError, result});559 }560 });561 } catch (e) {562 this.logger.log(e, this.logger.level.ERROR);563 reject(e);564 }565 });566 }567568 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {569 const api = this.getApi();570 const signingInfo = await api.derive.tx.signingInfo(signer.address);571572 // We need to sign the tx because573 // unsigned transactions does not have an inclusion fee574 tx.sign(signer, {575 blockHash: api.genesisHash,576 genesisHash: api.genesisHash,577 runtimeVersion: api.runtimeVersion,578 nonce: signingInfo.nonce,579 });580581 if (len === null) {582 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;583 } else {584 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;585 }586 }587588 constructApiCall(apiCall: string, params: any[]) {589 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);590 let call = this.getApi() as any;591 for(const part of apiCall.slice(4).split('.')) {592 call = call[part];593 }594 return call(...params);595 }596597 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {598 if(this.api === null) throw Error('API not initialized');599 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);600601 const startTime = (new Date()).getTime();602 let result: ITransactionResult;603 let events: IEvent[] = [];604 try {605 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;606 events = this.eventHelper.extractEvents(result.result.events);607 }608 catch(e) {609 if(!(e as object).hasOwnProperty('status')) throw e;610 result = e as ITransactionResult;611 }612613 const endTime = (new Date()).getTime();614615 const log = {616 executedAt: endTime,617 executionTime: endTime - startTime,618 type: this.chainLogType.EXTRINSIC,619 status: result.status,620 call: extrinsic,621 signer: this.getSignerAddress(sender),622 params,623 } as IUniqueHelperLog;624625 if(result.status !== this.transactionStatus.SUCCESS) {626 if (result.moduleError) log.moduleError = result.moduleError;627 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;628 }629 if(events.length > 0) log.events = events;630631 this.chainLog.push(log);632633 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {634 if (result.moduleError) throw Error(`${result.moduleError}`);635 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));636 }637 return result;638 }639640 async callRpc(rpc: string, params?: any[]) {641 if(typeof params === 'undefined') params = [];642 if(this.api === null) throw Error('API not initialized');643 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);644645 const startTime = (new Date()).getTime();646 let result;647 let error = null;648 const log = {649 type: this.chainLogType.RPC,650 call: rpc,651 params,652 } as IUniqueHelperLog;653654 try {655 result = await this.constructApiCall(rpc, params);656 }657 catch(e) {658 error = e;659 }660661 const endTime = (new Date()).getTime();662663 log.executedAt = endTime;664 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';665 log.executionTime = endTime - startTime;666667 this.chainLog.push(log);668669 if(error !== null) throw error;670671 return result;672 }673674 getSignerAddress(signer: IKeyringPair | string): string {675 if(typeof signer === 'string') return signer;676 return signer.address;677 }678679 fetchAllPalletNames(): string[] {680 if(this.api === null) throw Error('API not initialized');681 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());682 }683684 fetchMissingPalletNames(requiredPallets: string[]): string[] {685 const palletNames = this.fetchAllPalletNames();686 return requiredPallets.filter(p => !palletNames.includes(p));687 }688}689690691class HelperGroup<T extends ChainHelperBase> {692 helper: T;693694 constructor(uniqueHelper: T) {695 this.helper = uniqueHelper;696 }697}698699700class CollectionGroup extends HelperGroup<UniqueHelper> {701 /**702 * Get number of blocks when sponsored transaction is available.703 *704 * @param collectionId ID of collection705 * @param tokenId ID of token706 * @param addressObj address for which the sponsorship is checked707 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});708 * @returns number of blocks or null if sponsorship hasn't been set709 */710 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {711 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();712 }713714 /**715 * Get the number of created collections.716 *717 * @returns number of created collections718 */719 async getTotalCount(): Promise<number> {720 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();721 }722723 /**724 * Get information about the collection with additional data,725 * including the number of tokens it contains, its administrators,726 * the normalized address of the collection's owner, and decoded name and description.727 *728 * @param collectionId ID of collection729 * @example await getData(2)730 * @returns collection information object731 */732 async getData(collectionId: number): Promise<{733 id: number;734 name: string;735 description: string;736 tokensCount: number;737 admins: CrossAccountId[];738 normalizedOwner: TSubstrateAccount;739 raw: any740 } | null> {741 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);742 const humanCollection = collection.toHuman(), collectionData = {743 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],744 raw: humanCollection,745 } as any, jsonCollection = collection.toJSON();746 if (humanCollection === null) return null;747 collectionData.raw.limits = jsonCollection.limits;748 collectionData.raw.permissions = jsonCollection.permissions;749 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);750 for (const key of ['name', 'description']) {751 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);752 }753754 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))755 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)756 : 0;757 collectionData.admins = await this.getAdmins(collectionId);758759 return collectionData;760 }761762 /**763 * Get the addresses of the collection's administrators, optionally normalized.764 *765 * @param collectionId ID of collection766 * @param normalize whether to normalize the addresses to the default ss58 format767 * @example await getAdmins(1)768 * @returns array of administrators769 */770 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {771 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();772773 return normalize774 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())775 : admins;776 }777778 /**779 * Get the addresses added to the collection allow-list, optionally normalized.780 * @param collectionId ID of collection781 * @param normalize whether to normalize the addresses to the default ss58 format782 * @example await getAllowList(1)783 * @returns array of allow-listed addresses784 */785 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {786 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();787 return normalize788 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())789 : allowListed;790 }791792 /**793 * Get the effective limits of the collection instead of null for default values794 *795 * @param collectionId ID of collection796 * @example await getEffectiveLimits(2)797 * @returns object of collection limits798 */799 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {800 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();801 }802803 /**804 * Burns the collection if the signer has sufficient permissions and collection is empty.805 *806 * @param signer keyring of signer807 * @param collectionId ID of collection808 * @example await helper.collection.burn(aliceKeyring, 3);809 * @returns ```true``` if extrinsic success, otherwise ```false```810 */811 async burn(signer: TSigner, collectionId: number): Promise<boolean> {812 const result = await this.helper.executeExtrinsic(813 signer,814 'api.tx.unique.destroyCollection', [collectionId],815 true,816 );817818 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');819 }820821 /**822 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.823 *824 * @param signer keyring of signer825 * @param collectionId ID of collection826 * @param sponsorAddress Sponsor substrate address827 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")828 * @returns ```true``` if extrinsic success, otherwise ```false```829 */830 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {831 const result = await this.helper.executeExtrinsic(832 signer,833 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],834 true,835 );836837 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');838 }839840 /**841 * Confirms consent to sponsor the collection on behalf of the signer.842 *843 * @param signer keyring of signer844 * @param collectionId ID of collection845 * @example confirmSponsorship(aliceKeyring, 10)846 * @returns ```true``` if extrinsic success, otherwise ```false```847 */848 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {849 const result = await this.helper.executeExtrinsic(850 signer,851 'api.tx.unique.confirmSponsorship', [collectionId],852 true,853 );854855 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');856 }857858 /**859 * Removes the sponsor of a collection, regardless if it consented or not.860 *861 * @param signer keyring of signer862 * @param collectionId ID of collection863 * @example removeSponsor(aliceKeyring, 10)864 * @returns ```true``` if extrinsic success, otherwise ```false```865 */866 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {867 const result = await this.helper.executeExtrinsic(868 signer,869 'api.tx.unique.removeCollectionSponsor', [collectionId],870 true,871 );872873 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');874 }875876 /**877 * Sets the limits of the collection. At least one limit must be specified for a correct call.878 *879 * @param signer keyring of signer880 * @param collectionId ID of collection881 * @param limits collection limits object882 * @example883 * await setLimits(884 * aliceKeyring,885 * 10,886 * {887 * sponsorTransferTimeout: 0,888 * ownerCanDestroy: false889 * }890 * )891 * @returns ```true``` if extrinsic success, otherwise ```false```892 */893 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {894 const result = await this.helper.executeExtrinsic(895 signer,896 'api.tx.unique.setCollectionLimits', [collectionId, limits],897 true,898 );899900 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');901 }902903 /**904 * Changes the owner of the collection to the new Substrate address.905 *906 * @param signer keyring of signer907 * @param collectionId ID of collection908 * @param ownerAddress substrate address of new owner909 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")910 * @returns ```true``` if extrinsic success, otherwise ```false```911 */912 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {913 const result = await this.helper.executeExtrinsic(914 signer,915 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],916 true,917 );918919 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');920 }921922 /**923 * Adds a collection administrator.924 *925 * @param signer keyring of signer926 * @param collectionId ID of collection927 * @param adminAddressObj Administrator address (substrate or ethereum)928 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})929 * @returns ```true``` if extrinsic success, otherwise ```false```930 */931 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {932 const result = await this.helper.executeExtrinsic(933 signer,934 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],935 true,936 );937938 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');939 }940941 /**942 * Removes a collection administrator.943 *944 * @param signer keyring of signer945 * @param collectionId ID of collection946 * @param adminAddressObj Administrator address (substrate or ethereum)947 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})948 * @returns ```true``` if extrinsic success, otherwise ```false```949 */950 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {951 const result = await this.helper.executeExtrinsic(952 signer,953 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],954 true,955 );956957 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');958 }959960 /**961 * Check if user is in allow list.962 *963 * @param collectionId ID of collection964 * @param user Account to check965 * @example await getAdmins(1)966 * @returns is user in allow list967 */968 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {969 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();970 }971972 /**973 * Adds an address to allow list974 * @param signer keyring of signer975 * @param collectionId ID of collection976 * @param addressObj address to add to the allow list977 * @returns ```true``` if extrinsic success, otherwise ```false```978 */979 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {980 const result = await this.helper.executeExtrinsic(981 signer,982 'api.tx.unique.addToAllowList', [collectionId, addressObj],983 true,984 );985986 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');987 }988989 /**990 * Removes an address from allow list991 *992 * @param signer keyring of signer993 * @param collectionId ID of collection994 * @param addressObj address to remove from the allow list995 * @returns ```true``` if extrinsic success, otherwise ```false```996 */997 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {998 const result = await this.helper.executeExtrinsic(999 signer,1000 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1001 true,1002 );10031004 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');1005 }10061007 /**1008 * Sets onchain permissions for selected collection.1009 *1010 * @param signer keyring of signer1011 * @param collectionId ID of collection1012 * @param permissions collection permissions object1013 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1014 * @returns ```true``` if extrinsic success, otherwise ```false```1015 */1016 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1017 const result = await this.helper.executeExtrinsic(1018 signer,1019 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1020 true,1021 );10221023 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');1024 }10251026 /**1027 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1028 *1029 * @param signer keyring of signer1030 * @param collectionId ID of collection1031 * @param permissions nesting permissions object1032 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1033 * @returns ```true``` if extrinsic success, otherwise ```false```1034 */1035 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1036 return await this.setPermissions(signer, collectionId, {nesting: permissions});1037 }10381039 /**1040 * Disables nesting for selected collection.1041 *1042 * @param signer keyring of signer1043 * @param collectionId ID of collection1044 * @example disableNesting(aliceKeyring, 10);1045 * @returns ```true``` if extrinsic success, otherwise ```false```1046 */1047 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1048 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1049 }10501051 /**1052 * Sets onchain properties to the collection.1053 *1054 * @param signer keyring of signer1055 * @param collectionId ID of collection1056 * @param properties array of property objects1057 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1058 * @returns ```true``` if extrinsic success, otherwise ```false```1059 */1060 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1061 const result = await this.helper.executeExtrinsic(1062 signer,1063 'api.tx.unique.setCollectionProperties', [collectionId, properties],1064 true,1065 );10661067 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1068 }10691070 /**1071 * Get collection properties.1072 *1073 * @param collectionId ID of collection1074 * @param propertyKeys optionally filter the returned properties to only these keys1075 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1076 * @returns array of key-value pairs1077 */1078 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1079 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1080 }10811082 async getCollectionOptions(collectionId: number) {1083 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1084 }10851086 /**1087 * Deletes onchain properties from the collection.1088 *1089 * @param signer keyring of signer1090 * @param collectionId ID of collection1091 * @param propertyKeys array of property keys to delete1092 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1093 * @returns ```true``` if extrinsic success, otherwise ```false```1094 */1095 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1096 const result = await this.helper.executeExtrinsic(1097 signer,1098 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1099 true,1100 );11011102 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1103 }11041105 /**1106 * Changes the owner of the token.1107 *1108 * @param signer keyring of signer1109 * @param collectionId ID of collection1110 * @param tokenId ID of token1111 * @param addressObj address of a new owner1112 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1113 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1114 * @returns true if the token success, otherwise false1115 */1116 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1117 const result = await this.helper.executeExtrinsic(1118 signer,1119 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1120 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1121 );11221123 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1124 }11251126 /**1127 *1128 * Change ownership of a token(s) on behalf of the owner.1129 *1130 * @param signer keyring of signer1131 * @param collectionId ID of collection1132 * @param tokenId ID of token1133 * @param fromAddressObj address on behalf of which the token will be sent1134 * @param toAddressObj new token owner1135 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1136 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1137 * @returns true if the token success, otherwise false1138 */1139 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1140 const result = await this.helper.executeExtrinsic(1141 signer,1142 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1143 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1144 );1145 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1146 }11471148 /**1149 *1150 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1151 *1152 * @param signer keyring of signer1153 * @param collectionId ID of collection1154 * @param tokenId ID of token1155 * @param amount amount of tokens to be burned. For NFT must be set to 1n1156 * @example burnToken(aliceKeyring, 10, 5);1157 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1158 */1159 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1160 const burnResult = await this.helper.executeExtrinsic(1161 signer,1162 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1163 true, // `Unable to burn token for ${label}`,1164 );1165 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1166 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1167 return burnedTokens.success;1168 }11691170 /**1171 * Destroys a concrete instance of NFT on behalf of the owner1172 *1173 * @param signer keyring of signer1174 * @param collectionId ID of collection1175 * @param tokenId ID of token1176 * @param fromAddressObj address on behalf of which the token will be burnt1177 * @param amount amount of tokens to be burned. For NFT must be set to 1n1178 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1179 * @returns ```true``` if extrinsic success, otherwise ```false```1180 */1181 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1182 const burnResult = await this.helper.executeExtrinsic(1183 signer,1184 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1185 true, // `Unable to burn token from for ${label}`,1186 );1187 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1188 return burnedTokens.success && burnedTokens.tokens.length > 0;1189 }11901191 /**1192 * Set, change, or remove approved address to transfer the ownership of the NFT.1193 *1194 * @param signer keyring of signer1195 * @param collectionId ID of collection1196 * @param tokenId ID of token1197 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1198 * @param amount amount of token to be approved. For NFT must be set to 1n1199 * @returns ```true``` if extrinsic success, otherwise ```false```1200 */1201 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1202 const approveResult = await this.helper.executeExtrinsic(1203 signer,1204 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1205 true, // `Unable to approve token for ${label}`,1206 );12071208 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1209 }12101211 /**1212 * Get the amount of token pieces approved to transfer or burn. Normally 0.1213 *1214 * @param collectionId ID of collection1215 * @param tokenId ID of token1216 * @param toAccountObj address which is approved to use token pieces1217 * @param fromAccountObj address which may have allowed the use of its owned tokens1218 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1219 * @returns number of approved to transfer pieces1220 */1221 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1222 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1223 }12241225 /**1226 * Get the last created token ID in a collection1227 *1228 * @param collectionId ID of collection1229 * @example getLastTokenId(10);1230 * @returns id of the last created token1231 */1232 async getLastTokenId(collectionId: number): Promise<number> {1233 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1234 }12351236 /**1237 * Check if token exists1238 *1239 * @param collectionId ID of collection1240 * @param tokenId ID of token1241 * @example doesTokenExist(10, 20);1242 * @returns true if the token exists, otherwise false1243 */1244 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1245 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1246 }1247}12481249class NFTnRFT extends CollectionGroup {1250 /**1251 * Get tokens owned by account1252 *1253 * @param collectionId ID of collection1254 * @param addressObj tokens owner1255 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1256 * @returns array of token ids owned by account1257 */1258 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1259 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1260 }12611262 /**1263 * Get token data1264 *1265 * @param collectionId ID of collection1266 * @param tokenId ID of token1267 * @param propertyKeys optionally filter the token properties to only these keys1268 * @param blockHashAt optionally query the data at some block with this hash1269 * @example getToken(10, 5);1270 * @returns human readable token data1271 */1272 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1273 properties: IProperty[];1274 owner: CrossAccountId;1275 normalizedOwner: CrossAccountId;1276 }| null> {1277 let tokenData;1278 if(typeof blockHashAt === 'undefined') {1279 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1280 }1281 else {1282 if(propertyKeys.length == 0) {1283 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1284 if(!collection) return null;1285 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1286 }1287 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1288 }1289 tokenData = tokenData.toHuman();1290 if (tokenData === null || tokenData.owner === null) return null;1291 const owner = {} as any;1292 for (const key of Object.keys(tokenData.owner)) {1293 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1294 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1295 : tokenData.owner[key];1296 }1297 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1298 return tokenData;1299 }13001301 /**1302 * Set permissions to change token properties1303 *1304 * @param signer keyring of signer1305 * @param collectionId ID of collection1306 * @param permissions permissions to change a property by the collection admin or token owner1307 * @example setTokenPropertyPermissions(1308 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1309 * )1310 * @returns true if extrinsic success otherwise false1311 */1312 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1313 const result = await this.helper.executeExtrinsic(1314 signer,1315 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1316 true,1317 );13181319 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1320 }13211322 /**1323 * Get token property permissions.1324 *1325 * @param collectionId ID of collection1326 * @param propertyKeys optionally filter the returned property permissions to only these keys1327 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1328 * @returns array of key-permission pairs1329 */1330 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1331 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1332 }13331334 /**1335 * Set token properties1336 *1337 * @param signer keyring of signer1338 * @param collectionId ID of collection1339 * @param tokenId ID of token1340 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1341 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1342 * @returns ```true``` if extrinsic success, otherwise ```false```1343 */1344 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1345 const result = await this.helper.executeExtrinsic(1346 signer,1347 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1348 true,1349 );13501351 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1352 }13531354 /**1355 * Get properties, metadata assigned to a token.1356 *1357 * @param collectionId ID of collection1358 * @param tokenId ID of token1359 * @param propertyKeys optionally filter the returned properties to only these keys1360 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1361 * @returns array of key-value pairs1362 */1363 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1364 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1365 }13661367 /**1368 * Delete the provided properties of a token1369 * @param signer keyring of signer1370 * @param collectionId ID of collection1371 * @param tokenId ID of token1372 * @param propertyKeys property keys to be deleted1373 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1374 * @returns ```true``` if extrinsic success, otherwise ```false```1375 */1376 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1377 const result = await this.helper.executeExtrinsic(1378 signer,1379 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1380 true,1381 );13821383 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1384 }13851386 /**1387 * Mint new collection1388 *1389 * @param signer keyring of signer1390 * @param collectionOptions basic collection options and properties1391 * @param mode NFT or RFT type of a collection1392 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1393 * @returns object of the created collection1394 */1395 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1396 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1397 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1398 for (const key of ['name', 'description', 'tokenPrefix']) {1399 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1400 }1401 const creationResult = await this.helper.executeExtrinsic(1402 signer,1403 'api.tx.unique.createCollectionEx', [collectionOptions],1404 true, // errorLabel,1405 );1406 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1407 }14081409 getCollectionObject(_collectionId: number): any {1410 return null;1411 }14121413 getTokenObject(_collectionId: number, _tokenId: number): any {1414 return null;1415 }1416}141714181419class NFTGroup extends NFTnRFT {1420 /**1421 * Get collection object1422 * @param collectionId ID of collection1423 * @example getCollectionObject(2);1424 * @returns instance of UniqueNFTCollection1425 */1426 getCollectionObject(collectionId: number): UniqueNFTCollection {1427 return new UniqueNFTCollection(collectionId, this.helper);1428 }14291430 /**1431 * Get token object1432 * @param collectionId ID of collection1433 * @param tokenId ID of token1434 * @example getTokenObject(10, 5);1435 * @returns instance of UniqueNFTToken1436 */1437 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1438 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1439 }14401441 /**1442 * Get token's owner1443 * @param collectionId ID of collection1444 * @param tokenId ID of token1445 * @param blockHashAt optionally query the data at the block with this hash1446 * @example getTokenOwner(10, 5);1447 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1448 */1449 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1450 let owner;1451 if (typeof blockHashAt === 'undefined') {1452 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1453 } else {1454 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1455 }1456 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1457 }14581459 /**1460 * Is token approved to transfer1461 * @param collectionId ID of collection1462 * @param tokenId ID of token1463 * @param toAccountObj address to be approved1464 * @returns ```true``` if extrinsic success, otherwise ```false```1465 */1466 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1467 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1468 }14691470 /**1471 * Changes the owner of the token.1472 *1473 * @param signer keyring of signer1474 * @param collectionId ID of collection1475 * @param tokenId ID of token1476 * @param addressObj address of a new owner1477 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1478 * @returns ```true``` if extrinsic success, otherwise ```false```1479 */1480 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1481 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1482 }14831484 /**1485 *1486 * Change ownership of a NFT on behalf of the owner.1487 *1488 * @param signer keyring of signer1489 * @param collectionId ID of collection1490 * @param tokenId ID of token1491 * @param fromAddressObj address on behalf of which the token will be sent1492 * @param toAddressObj new token owner1493 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1494 * @returns ```true``` if extrinsic success, otherwise ```false```1495 */1496 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1497 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1498 }14991500 /**1501 * Recursively find the address that owns the token1502 * @param collectionId ID of collection1503 * @param tokenId ID of token1504 * @param blockHashAt1505 * @example getTokenTopmostOwner(10, 5);1506 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1507 */1508 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1509 let owner;1510 if (typeof blockHashAt === 'undefined') {1511 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1512 } else {1513 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1514 }15151516 if (owner === null) return null;15171518 return owner.toHuman();1519 }15201521 /**1522 * Get tokens nested in the provided token1523 * @param collectionId ID of collection1524 * @param tokenId ID of token1525 * @param blockHashAt optionally query the data at the block with this hash1526 * @example getTokenChildren(10, 5);1527 * @returns tokens whose depth of nesting is <= 51528 */1529 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1530 let children;1531 if(typeof blockHashAt === 'undefined') {1532 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1533 } else {1534 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1535 }15361537 return children.toJSON().map((x: any) => {1538 return {collectionId: x.collection, tokenId: x.token};1539 });1540 }15411542 /**1543 * Nest one token into another1544 * @param signer keyring of signer1545 * @param tokenObj token to be nested1546 * @param rootTokenObj token to be parent1547 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1548 * @returns ```true``` if extrinsic success, otherwise ```false```1549 */1550 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1551 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1552 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1553 if(!result) {1554 throw Error('Unable to nest token!');1555 }1556 return result;1557 }15581559 /**1560 * Remove token from nested state1561 * @param signer keyring of signer1562 * @param tokenObj token to unnest1563 * @param rootTokenObj parent of a token1564 * @param toAddressObj address of a new token owner1565 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1566 * @returns ```true``` if extrinsic success, otherwise ```false```1567 */1568 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1569 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1570 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1571 if(!result) {1572 throw Error('Unable to unnest token!');1573 }1574 return result;1575 }15761577 /**1578 * Mint new collection1579 * @param signer keyring of signer1580 * @param collectionOptions Collection options1581 * @example1582 * mintCollection(aliceKeyring, {1583 * name: 'New',1584 * description: 'New collection',1585 * tokenPrefix: 'NEW',1586 * })1587 * @returns object of the created collection1588 */1589 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1590 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1591 }15921593 /**1594 * Mint new token1595 * @param signer keyring of signer1596 * @param data token data1597 * @returns created token object1598 */1599 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1600 const creationResult = await this.helper.executeExtrinsic(1601 signer,1602 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1603 nft: {1604 properties: data.properties,1605 },1606 }],1607 true,1608 );1609 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1610 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1611 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1612 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1613 }16141615 /**1616 * Mint multiple NFT tokens1617 * @param signer keyring of signer1618 * @param collectionId ID of collection1619 * @param tokens array of tokens with owner and properties1620 * @example1621 * mintMultipleTokens(aliceKeyring, 10, [{1622 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1623 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1624 * },{1625 * owner: {Ethereum: "0x9F0583DbB855d..."},1626 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1627 * }]);1628 * @returns ```true``` if extrinsic success, otherwise ```false```1629 */1630 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1631 const creationResult = await this.helper.executeExtrinsic(1632 signer,1633 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1634 true,1635 );1636 const collection = this.getCollectionObject(collectionId);1637 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1638 }16391640 /**1641 * Mint multiple NFT tokens with one owner1642 * @param signer keyring of signer1643 * @param collectionId ID of collection1644 * @param owner tokens owner1645 * @param tokens array of tokens with owner and properties1646 * @example1647 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1648 * properties: [{1649 * key: "gender",1650 * value: "female",1651 * },{1652 * key: "age",1653 * value: "33",1654 * }],1655 * }]);1656 * @returns array of newly created tokens1657 */1658 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1659 const rawTokens = [];1660 for (const token of tokens) {1661 const raw = {NFT: {properties: token.properties}};1662 rawTokens.push(raw);1663 }1664 const creationResult = await this.helper.executeExtrinsic(1665 signer,1666 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1667 true,1668 );1669 const collection = this.getCollectionObject(collectionId);1670 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1671 }16721673 /**1674 * Set, change, or remove approved address to transfer the ownership of the NFT.1675 *1676 * @param signer keyring of signer1677 * @param collectionId ID of collection1678 * @param tokenId ID of token1679 * @param toAddressObj address to approve1680 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1681 * @returns ```true``` if extrinsic success, otherwise ```false```1682 */1683 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1684 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1685 }1686}168716881689class RFTGroup extends NFTnRFT {1690 /**1691 * Get collection object1692 * @param collectionId ID of collection1693 * @example getCollectionObject(2);1694 * @returns instance of UniqueRFTCollection1695 */1696 getCollectionObject(collectionId: number): UniqueRFTCollection {1697 return new UniqueRFTCollection(collectionId, this.helper);1698 }16991700 /**1701 * Get token object1702 * @param collectionId ID of collection1703 * @param tokenId ID of token1704 * @example getTokenObject(10, 5);1705 * @returns instance of UniqueNFTToken1706 */1707 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1708 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1709 }17101711 /**1712 * Get top 10 token owners with the largest number of pieces1713 * @param collectionId ID of collection1714 * @param tokenId ID of token1715 * @example getTokenTop10Owners(10, 5);1716 * @returns array of top 10 owners1717 */1718 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1719 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1720 }17211722 /**1723 * Get number of pieces owned by address1724 * @param collectionId ID of collection1725 * @param tokenId ID of token1726 * @param addressObj address token owner1727 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1728 * @returns number of pieces ownerd by address1729 */1730 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1731 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1732 }17331734 /**1735 * Transfer pieces of token to another address1736 * @param signer keyring of signer1737 * @param collectionId ID of collection1738 * @param tokenId ID of token1739 * @param addressObj address of a new owner1740 * @param amount number of pieces to be transfered1741 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1742 * @returns ```true``` if extrinsic success, otherwise ```false```1743 */1744 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1745 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1746 }17471748 /**1749 * Change ownership of some pieces of RFT on behalf of the owner.1750 * @param signer keyring of signer1751 * @param collectionId ID of collection1752 * @param tokenId ID of token1753 * @param fromAddressObj address on behalf of which the token will be sent1754 * @param toAddressObj new token owner1755 * @param amount number of pieces to be transfered1756 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1757 * @returns ```true``` if extrinsic success, otherwise ```false```1758 */1759 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1760 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1761 }17621763 /**1764 * Mint new collection1765 * @param signer keyring of signer1766 * @param collectionOptions Collection options1767 * @example1768 * mintCollection(aliceKeyring, {1769 * name: 'New',1770 * description: 'New collection',1771 * tokenPrefix: 'NEW',1772 * })1773 * @returns object of the created collection1774 */1775 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1776 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1777 }17781779 /**1780 * Mint new token1781 * @param signer keyring of signer1782 * @param data token data1783 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1784 * @returns created token object1785 */1786 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1787 const creationResult = await this.helper.executeExtrinsic(1788 signer,1789 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1790 refungible: {1791 pieces: data.pieces,1792 properties: data.properties,1793 },1794 }],1795 true,1796 );1797 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1798 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1799 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1800 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1801 }18021803 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1804 throw Error('Not implemented');1805 const creationResult = await this.helper.executeExtrinsic(1806 signer,1807 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1808 true, // `Unable to mint RFT tokens for ${label}`,1809 );1810 const collection = this.getCollectionObject(collectionId);1811 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1812 }18131814 /**1815 * Mint multiple RFT tokens with one owner1816 * @param signer keyring of signer1817 * @param collectionId ID of collection1818 * @param owner tokens owner1819 * @param tokens array of tokens with properties and pieces1820 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1821 * @returns array of newly created RFT tokens1822 */1823 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1824 const rawTokens = [];1825 for (const token of tokens) {1826 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1827 rawTokens.push(raw);1828 }1829 const creationResult = await this.helper.executeExtrinsic(1830 signer,1831 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1832 true,1833 );1834 const collection = this.getCollectionObject(collectionId);1835 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1836 }18371838 /**1839 * Destroys a concrete instance of RFT.1840 * @param signer keyring of signer1841 * @param collectionId ID of collection1842 * @param tokenId ID of token1843 * @param amount number of pieces to be burnt1844 * @example burnToken(aliceKeyring, 10, 5);1845 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1846 */1847 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1848 return await super.burnToken(signer, collectionId, tokenId, amount);1849 }18501851 /**1852 * Destroys a concrete instance of RFT on behalf of the owner.1853 * @param signer keyring of signer1854 * @param collectionId ID of collection1855 * @param tokenId ID of token1856 * @param fromAddressObj address on behalf of which the token will be burnt1857 * @param amount number of pieces to be burnt1858 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1859 * @returns ```true``` if extrinsic success, otherwise ```false```1860 */1861 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1862 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1863 }18641865 /**1866 * Set, change, or remove approved address to transfer the ownership of the RFT.1867 *1868 * @param signer keyring of signer1869 * @param collectionId ID of collection1870 * @param tokenId ID of token1871 * @param toAddressObj address to approve1872 * @param amount number of pieces to be approved1873 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1874 * @returns true if the token success, otherwise false1875 */1876 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1877 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1878 }18791880 /**1881 * Get total number of pieces1882 * @param collectionId ID of collection1883 * @param tokenId ID of token1884 * @example getTokenTotalPieces(10, 5);1885 * @returns number of pieces1886 */1887 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1888 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1889 }18901891 /**1892 * Change number of token pieces. Signer must be the owner of all token pieces.1893 * @param signer keyring of signer1894 * @param collectionId ID of collection1895 * @param tokenId ID of token1896 * @param amount new number of pieces1897 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1898 * @returns true if the repartion was success, otherwise false1899 */1900 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1901 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1902 const repartitionResult = await this.helper.executeExtrinsic(1903 signer,1904 'api.tx.unique.repartition', [collectionId, tokenId, amount],1905 true,1906 );1907 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1908 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1909 }1910}191119121913class FTGroup extends CollectionGroup {1914 /**1915 * Get collection object1916 * @param collectionId ID of collection1917 * @example getCollectionObject(2);1918 * @returns instance of UniqueFTCollection1919 */1920 getCollectionObject(collectionId: number): UniqueFTCollection {1921 return new UniqueFTCollection(collectionId, this.helper);1922 }19231924 /**1925 * Mint new fungible collection1926 * @param signer keyring of signer1927 * @param collectionOptions Collection options1928 * @param decimalPoints number of token decimals1929 * @example1930 * mintCollection(aliceKeyring, {1931 * name: 'New',1932 * description: 'New collection',1933 * tokenPrefix: 'NEW',1934 * }, 18)1935 * @returns newly created fungible collection1936 */1937 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1938 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1939 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1940 collectionOptions.mode = {fungible: decimalPoints};1941 for (const key of ['name', 'description', 'tokenPrefix']) {1942 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1943 }1944 const creationResult = await this.helper.executeExtrinsic(1945 signer,1946 'api.tx.unique.createCollectionEx', [collectionOptions],1947 true,1948 );1949 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1950 }19511952 /**1953 * Mint tokens1954 * @param signer keyring of signer1955 * @param collectionId ID of collection1956 * @param owner address owner of new tokens1957 * @param amount amount of tokens to be meanted1958 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1959 * @returns ```true``` if extrinsic success, otherwise ```false```1960 */1961 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1962 const creationResult = await this.helper.executeExtrinsic(1963 signer,1964 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1965 fungible: {1966 value: amount,1967 },1968 }],1969 true, // `Unable to mint fungible tokens for ${label}`,1970 );1971 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1972 }19731974 /**1975 * Mint multiple Fungible tokens with one owner1976 * @param signer keyring of signer1977 * @param collectionId ID of collection1978 * @param owner tokens owner1979 * @param tokens array of tokens with properties and pieces1980 * @returns ```true``` if extrinsic success, otherwise ```false```1981 */1982 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1983 const rawTokens = [];1984 for (const token of tokens) {1985 const raw = {Fungible: {Value: token.value}};1986 rawTokens.push(raw);1987 }1988 const creationResult = await this.helper.executeExtrinsic(1989 signer,1990 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1991 true,1992 );1993 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1994 }19951996 /**1997 * Get the top 10 owners with the largest balance for the Fungible collection1998 * @param collectionId ID of collection1999 * @example getTop10Owners(10);2000 * @returns array of ```ICrossAccountId```2001 */2002 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2003 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2004 }20052006 /**2007 * Get account balance2008 * @param collectionId ID of collection2009 * @param addressObj address of owner2010 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2011 * @returns amount of fungible tokens owned by address2012 */2013 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2014 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2015 }20162017 /**2018 * Transfer tokens to address2019 * @param signer keyring of signer2020 * @param collectionId ID of collection2021 * @param toAddressObj address recipient2022 * @param amount amount of tokens to be sent2023 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2024 * @returns ```true``` if extrinsic success, otherwise ```false```2025 */2026 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2027 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2028 }20292030 /**2031 * Transfer some tokens on behalf of the owner.2032 * @param signer keyring of signer2033 * @param collectionId ID of collection2034 * @param fromAddressObj address on behalf of which tokens will be sent2035 * @param toAddressObj address where token to be sent2036 * @param amount number of tokens to be sent2037 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2038 * @returns ```true``` if extrinsic success, otherwise ```false```2039 */2040 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2041 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2042 }20432044 /**2045 * Destroy some amount of tokens2046 * @param signer keyring of signer2047 * @param collectionId ID of collection2048 * @param amount amount of tokens to be destroyed2049 * @example burnTokens(aliceKeyring, 10, 1000n);2050 * @returns ```true``` if extrinsic success, otherwise ```false```2051 */2052 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2053 return await super.burnToken(signer, collectionId, 0, amount);2054 }20552056 /**2057 * Burn some tokens on behalf of the owner.2058 * @param signer keyring of signer2059 * @param collectionId ID of collection2060 * @param fromAddressObj address on behalf of which tokens will be burnt2061 * @param amount amount of tokens to be burnt2062 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2063 * @returns ```true``` if extrinsic success, otherwise ```false```2064 */2065 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2066 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2067 }20682069 /**2070 * Get total collection supply2071 * @param collectionId2072 * @returns2073 */2074 async getTotalPieces(collectionId: number): Promise<bigint> {2075 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2076 }20772078 /**2079 * Set, change, or remove approved address to transfer tokens.2080 *2081 * @param signer keyring of signer2082 * @param collectionId ID of collection2083 * @param toAddressObj address to be approved2084 * @param amount amount of tokens to be approved2085 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2086 * @returns ```true``` if extrinsic success, otherwise ```false```2087 */2088 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2089 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2090 }20912092 /**2093 * Get amount of fungible tokens approved to transfer2094 * @param collectionId ID of collection2095 * @param fromAddressObj owner of tokens2096 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2097 * @returns number of tokens approved for the transfer2098 */2099 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2100 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2101 }2102}210321042105class ChainGroup extends HelperGroup<ChainHelperBase> {2106 /**2107 * Get system properties of a chain2108 * @example getChainProperties();2109 * @returns ss58Format, token decimals, and token symbol2110 */2111 getChainProperties(): IChainProperties {2112 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2113 return {2114 ss58Format: properties.ss58Format.toJSON(),2115 tokenDecimals: properties.tokenDecimals.toJSON(),2116 tokenSymbol: properties.tokenSymbol.toJSON(),2117 };2118 }21192120 /**2121 * Get chain header2122 * @example getLatestBlockNumber();2123 * @returns the number of the last block2124 */2125 async getLatestBlockNumber(): Promise<number> {2126 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2127 }21282129 /**2130 * Get block hash by block number2131 * @param blockNumber number of block2132 * @example getBlockHashByNumber(12345);2133 * @returns hash of a block2134 */2135 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2136 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2137 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2138 return blockHash;2139 }21402141 // TODO add docs2142 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2143 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2144 if (!blockHash) return null;2145 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2146 }21472148 /**2149 * Get account nonce2150 * @param address substrate address2151 * @example getNonce("5GrwvaEF5zXb26Fz...");2152 * @returns number, account's nonce2153 */2154 async getNonce(address: TSubstrateAccount): Promise<number> {2155 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2156 }2157}21582159class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2160 /**2161 * Get substrate address balance2162 * @param address substrate address2163 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2164 * @returns amount of tokens on address2165 */2166 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2167 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2168 }21692170 /**2171 * Transfer tokens to substrate address2172 * @param signer keyring of signer2173 * @param address substrate address of a recipient2174 * @param amount amount of tokens to be transfered2175 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2176 * @returns ```true``` if extrinsic success, otherwise ```false```2177 */2178 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2179 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);21802181 let transfer = {from: null, to: null, amount: 0n} as any;2182 result.result.events.forEach(({event: {data, method, section}}) => {2183 if ((section === 'balances') && (method === 'Transfer')) {2184 transfer = {2185 from: this.helper.address.normalizeSubstrate(data[0]),2186 to: this.helper.address.normalizeSubstrate(data[1]),2187 amount: BigInt(data[2]),2188 };2189 }2190 });2191 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2192 && this.helper.address.normalizeSubstrate(address) === transfer.to2193 && BigInt(amount) === transfer.amount;2194 return isSuccess;2195 }21962197 /**2198 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2199 * @param address substrate address2200 * @returns2201 */2202 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2203 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2204 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2205 }2206}22072208class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2209 /**2210 * Get ethereum address balance2211 * @param address ethereum address2212 * @example getEthereum("0x9F0583DbB855d...")2213 * @returns amount of tokens on address2214 */2215 async getEthereum(address: TEthereumAccount): Promise<bigint> {2216 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2217 }22182219 /**2220 * Transfer tokens to address2221 * @param signer keyring of signer2222 * @param address Ethereum address of a recipient2223 * @param amount amount of tokens to be transfered2224 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2225 * @returns ```true``` if extrinsic success, otherwise ```false```2226 */2227 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2228 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22292230 let transfer = {from: null, to: null, amount: 0n} as any;2231 result.result.events.forEach(({event: {data, method, section}}) => {2232 if ((section === 'balances') && (method === 'Transfer')) {2233 transfer = {2234 from: data[0].toString(),2235 to: data[1].toString(),2236 amount: BigInt(data[2]),2237 };2238 }2239 });2240 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2241 && address === transfer.to2242 && BigInt(amount) === transfer.amount;2243 return isSuccess;2244 }2245}22462247class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2248 subBalanceGroup: SubstrateBalanceGroup<T>;2249 ethBalanceGroup: EthereumBalanceGroup<T>;22502251 constructor(helper: T) {2252 super(helper);2253 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2254 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2255 }22562257 getCollectionCreationPrice(): bigint {2258 return 2n * this.getOneTokenNominal();2259 }2260 /**2261 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2262 * @example getOneTokenNominal()2263 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2264 */2265 getOneTokenNominal(): bigint {2266 const chainProperties = this.helper.chain.getChainProperties();2267 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2268 }22692270 /**2271 * Get substrate address balance2272 * @param address substrate address2273 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2274 * @returns amount of tokens on address2275 */2276 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2277 return this.subBalanceGroup.getSubstrate(address);2278 }22792280 /**2281 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2282 * @param address substrate address2283 * @returns2284 */2285 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2286 return this.subBalanceGroup.getSubstrateFull(address);2287 }22882289 /**2290 * Get ethereum address balance2291 * @param address ethereum address2292 * @example getEthereum("0x9F0583DbB855d...")2293 * @returns amount of tokens on address2294 */2295 getEthereum(address: TEthereumAccount): Promise<bigint> {2296 return this.ethBalanceGroup.getEthereum(address);2297 }22982299 /**2300 * Transfer tokens to substrate address2301 * @param signer keyring of signer2302 * @param address substrate address of a recipient2303 * @param amount amount of tokens to be transfered2304 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2305 * @returns ```true``` if extrinsic success, otherwise ```false```2306 */2307 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2308 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2309 }23102311 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2312 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23132314 let transfer = {from: null, to: null, amount: 0n} as any;2315 result.result.events.forEach(({event: {data, method, section}}) => {2316 if ((section === 'balances') && (method === 'Transfer')) {2317 transfer = {2318 from: this.helper.address.normalizeSubstrate(data[0]),2319 to: this.helper.address.normalizeSubstrate(data[1]),2320 amount: BigInt(data[2]),2321 };2322 }2323 });2324 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2325 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2326 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2327 return isSuccess;2328 }2329}23302331class AddressGroup extends HelperGroup<ChainHelperBase> {2332 /**2333 * Normalizes the address to the specified ss58 format, by default ```42```.2334 * @param address substrate address2335 * @param ss58Format format for address conversion, by default ```42```2336 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2337 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2338 */2339 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2340 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2341 }23422343 /**2344 * Get address in the connected chain format2345 * @param address substrate address2346 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2347 * @returns address in chain format2348 */2349 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2350 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2351 }23522353 /**2354 * Get substrate mirror of an ethereum address2355 * @param ethAddress ethereum address2356 * @param toChainFormat false for normalized account2357 * @example ethToSubstrate('0x9F0583DbB855d...')2358 * @returns substrate mirror of a provided ethereum address2359 */2360 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2361 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2362 }23632364 /**2365 * Get ethereum mirror of a substrate address2366 * @param subAddress substrate account2367 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2368 * @returns ethereum mirror of a provided substrate address2369 */2370 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2371 return CrossAccountId.translateSubToEth(subAddress);2372 }23732374 /**2375 * Encode key to substrate address2376 * @param key key for encoding address2377 * @param ss58Format prefix for encoding to the address of the corresponding network2378 * @returns encoded substrate address2379 */2380 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2381 const u8a :Uint8Array = typeof key === 'string'2382 ? hexToU8a(key)2383 : typeof key === 'bigint'2384 ? hexToU8a(key.toString(16))2385 : key;2386 2387 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2388 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2389 }2390 2391 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2392 if (!allowedDecodedLengths.includes(u8a.length)) {2393 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2394 }2395 2396 const u8aPrefix = ss58Format < 642397 ? new Uint8Array([ss58Format])2398 : new Uint8Array([2399 ((ss58Format & 0xfc) >> 2) | 0x40,2400 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2401 ]);24022403 const input = u8aConcat(u8aPrefix, u8a);2404 2405 return base58Encode(u8aConcat(2406 input,2407 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2408 ));2409 }24102411 /**2412 * Restore substrate address from bigint representation2413 * @param number decimal representation of substrate address2414 * @returns substrate address2415 */2416 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2417 if (this.helper.api === null) {2418 throw 'Not connected';2419 }2420 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2421 if (res === undefined || res === null) {2422 throw 'Restore address error';2423 }2424 return res.toString();2425 }24262427 /**2428 * Convert etherium cross account id to substrate cross account id2429 * @param ethCrossAccount etherium cross account2430 * @returns substrate cross account id2431 */2432 convertCrossAccountFromEthCrossAcoount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2433 if (ethCrossAccount.sub === '0') {2434 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2435 }2436 2437 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2438 return {Substrate: ss58};2439 }24402441 paraSiblingSovereignAccount(paraid: number) {2442 // We are getting a *sibling* parachain sovereign account,2443 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2444 const siblingPrefix = '0x7369626c';24452446 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2447 const suffix = '000000000000000000000000000000000000000000000000';24482449 return siblingPrefix + encodedParaId + suffix;2450 }2451}24522453class StakingGroup extends HelperGroup<UniqueHelper> {2454 /**2455 * Stake tokens for App Promotion2456 * @param signer keyring of signer2457 * @param amountToStake amount of tokens to stake2458 * @param label extra label for log2459 * @returns2460 */2461 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2462 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2463 const _stakeResult = await this.helper.executeExtrinsic(2464 signer, 'api.tx.appPromotion.stake',2465 [amountToStake], true,2466 );2467 // TODO extract info from stakeResult2468 return true;2469 }24702471 /**2472 * Unstake tokens for App Promotion2473 * @param signer keyring of signer2474 * @param amountToUnstake amount of tokens to unstake2475 * @param label extra label for log2476 * @returns block number where balances will be unlocked2477 */2478 async unstake(signer: TSigner, label?: string): Promise<number> {2479 if(typeof label === 'undefined') label = `${signer.address}`;2480 const _unstakeResult = await this.helper.executeExtrinsic(2481 signer, 'api.tx.appPromotion.unstake',2482 [], true,2483 );2484 // TODO extract block number fron events2485 return 1;2486 }24872488 /**2489 * Get total staked amount for address2490 * @param address substrate or ethereum address2491 * @returns total staked amount2492 */2493 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2494 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2495 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2496 }24972498 /**2499 * Get total staked per block2500 * @param address substrate or ethereum address2501 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2502 */2503 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2504 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2505 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2506 return {2507 block: block.toBigInt(),2508 amount: amount.toBigInt(),2509 };2510 });2511 }25122513 /**2514 * Get total pending unstake amount for address2515 * @param address substrate or ethereum address2516 * @returns total pending unstake amount2517 */2518 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2519 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2520 }25212522 /**2523 * Get pending unstake amount per block for address2524 * @param address substrate or ethereum address2525 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2526 */2527 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2528 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2529 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2530 return {2531 block: block.toBigInt(),2532 amount: amount.toBigInt(),2533 };2534 });2535 return result;2536 }2537}25382539class SchedulerGroup extends HelperGroup<UniqueHelper> {2540 constructor(helper: UniqueHelper) {2541 super(helper);2542 }25432544 cancelScheduled(signer: TSigner, scheduledId: string) {2545 return this.helper.executeExtrinsic(2546 signer,2547 'api.tx.scheduler.cancelNamed',2548 [scheduledId],2549 true,2550 );2551 }25522553 changePriority(signer: TSigner, scheduledId: string, priority: number) {2554 return this.helper.executeExtrinsic(2555 signer,2556 'api.tx.scheduler.changeNamedPriority',2557 [scheduledId, priority],2558 true,2559 );2560 }25612562 scheduleAt<T extends UniqueHelper>(2563 scheduledId: string,2564 executionBlockNumber: number,2565 options: ISchedulerOptions = {},2566 ) {2567 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2568 }25692570 scheduleAfter<T extends UniqueHelper>(2571 scheduledId: string,2572 blocksBeforeExecution: number,2573 options: ISchedulerOptions = {},2574 ) {2575 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2576 }25772578 schedule<T extends UniqueHelper>(2579 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2580 scheduledId: string,2581 blocksNum: number,2582 options: ISchedulerOptions = {},2583 ) {2584 // eslint-disable-next-line @typescript-eslint/naming-convention2585 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2586 return this.helper.clone(ScheduledHelperType, {2587 scheduleFn,2588 scheduledId,2589 blocksNum,2590 options,2591 }) as T;2592 }2593}25942595class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2596 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2597 await this.helper.executeExtrinsic(2598 signer,2599 'api.tx.foreignAssets.registerForeignAsset',2600 [ownerAddress, location, metadata],2601 true,2602 );2603 }26042605 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2606 await this.helper.executeExtrinsic(2607 signer,2608 'api.tx.foreignAssets.updateForeignAsset',2609 [foreignAssetId, location, metadata],2610 true,2611 );2612 }2613}26142615class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2616 palletName: string;26172618 constructor(helper: T, palletName: string) {2619 super(helper);26202621 this.palletName = palletName;2622 }26232624 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2625 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2626 }2627}26282629class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2630 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2631 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2632 }26332634 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2635 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2636 }26372638 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2639 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2640 }2641}26422643class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2644 async accounts(address: string, currencyId: any) {2645 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2646 return BigInt(free);2647 }2648}26492650class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2651 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2652 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2653 }26542655 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2656 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2657 }26582659 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2660 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2661 }26622663 async account(assetId: string | number, address: string) {2664 const accountAsset = (2665 await this.helper.callRpc('api.query.assets.account', [assetId, address])2666 ).toJSON()! as any;26672668 if (accountAsset !== null) {2669 return BigInt(accountAsset['balance']);2670 } else {2671 return null;2672 }2673 }2674}26752676class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2677 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2678 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2679 }2680}26812682class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2683 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2684 const apiPrefix = 'api.tx.assetManager.';26852686 const registerTx = this.helper.constructApiCall(2687 apiPrefix + 'registerForeignAsset',2688 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2689 );26902691 const setUnitsTx = this.helper.constructApiCall(2692 apiPrefix + 'setAssetUnitsPerSecond',2693 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2694 );26952696 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2697 const encodedProposal = batchCall?.method.toHex() || '';2698 return encodedProposal;2699 }27002701 async assetTypeId(location: any) {2702 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2703 }2704}27052706class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2707 async notePreimage(signer: TSigner, encodedProposal: string) {2708 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2709 }27102711 externalProposeMajority(proposalHash: string) {2712 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2713 }27142715 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2716 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2717 }27182719 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2720 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2721 }2722}27232724class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2725 collective: string;27262727 constructor(helper: MoonbeamHelper, collective: string) {2728 super(helper);27292730 this.collective = collective;2731 }27322733 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2734 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2735 }27362737 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2738 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2739 }27402741 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2742 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2743 }27442745 async proposalCount() {2746 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2747 }2748}27492750export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2751export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;27522753export class UniqueHelper extends ChainHelperBase {2754 balance: BalanceGroup<UniqueHelper>;2755 collection: CollectionGroup;2756 nft: NFTGroup;2757 rft: RFTGroup;2758 ft: FTGroup;2759 staking: StakingGroup;2760 scheduler: SchedulerGroup;2761 foreignAssets: ForeignAssetsGroup;2762 xcm: XcmGroup<UniqueHelper>;2763 xTokens: XTokensGroup<UniqueHelper>;2764 tokens: TokensGroup<UniqueHelper>;27652766 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2767 super(logger, options.helperBase ?? UniqueHelper);27682769 this.balance = new BalanceGroup(this);2770 this.collection = new CollectionGroup(this);2771 this.nft = new NFTGroup(this);2772 this.rft = new RFTGroup(this);2773 this.ft = new FTGroup(this);2774 this.staking = new StakingGroup(this);2775 this.scheduler = new SchedulerGroup(this);2776 this.foreignAssets = new ForeignAssetsGroup(this);2777 this.xcm = new XcmGroup(this, 'polkadotXcm');2778 this.xTokens = new XTokensGroup(this);2779 this.tokens = new TokensGroup(this);2780 }27812782 getSudo<T extends UniqueHelper>() {2783 // eslint-disable-next-line @typescript-eslint/naming-convention2784 const SudoHelperType = SudoHelper(this.helperBase);2785 return this.clone(SudoHelperType) as T;2786 }2787}27882789export class XcmChainHelper extends ChainHelperBase {2790 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2791 const wsProvider = new WsProvider(wsEndpoint);2792 this.api = new ApiPromise({2793 provider: wsProvider,2794 });2795 await this.api.isReadyOrError;2796 this.network = await UniqueHelper.detectNetwork(this.api);2797 }2798}27992800export class RelayHelper extends XcmChainHelper {2801 xcm: XcmGroup<RelayHelper>;28022803 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2804 super(logger, options.helperBase ?? RelayHelper);28052806 this.xcm = new XcmGroup(this, 'xcmPallet');2807 }2808}28092810export class WestmintHelper extends XcmChainHelper {2811 balance: SubstrateBalanceGroup<WestmintHelper>;2812 xcm: XcmGroup<WestmintHelper>;2813 assets: AssetsGroup<WestmintHelper>;2814 xTokens: XTokensGroup<WestmintHelper>;28152816 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2817 super(logger, options.helperBase ?? WestmintHelper);28182819 this.balance = new SubstrateBalanceGroup(this);2820 this.xcm = new XcmGroup(this, 'polkadotXcm');2821 this.assets = new AssetsGroup(this);2822 this.xTokens = new XTokensGroup(this);2823 }2824}28252826export class MoonbeamHelper extends XcmChainHelper {2827 balance: EthereumBalanceGroup<MoonbeamHelper>;2828 assetManager: MoonbeamAssetManagerGroup;2829 assets: AssetsGroup<MoonbeamHelper>;2830 xTokens: XTokensGroup<MoonbeamHelper>;2831 democracy: MoonbeamDemocracyGroup;2832 collective: {2833 council: MoonbeamCollectiveGroup,2834 techCommittee: MoonbeamCollectiveGroup,2835 };28362837 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2838 super(logger, options.helperBase ?? MoonbeamHelper);28392840 this.balance = new EthereumBalanceGroup(this);2841 this.assetManager = new MoonbeamAssetManagerGroup(this);2842 this.assets = new AssetsGroup(this);2843 this.xTokens = new XTokensGroup(this);2844 this.democracy = new MoonbeamDemocracyGroup(this);2845 this.collective = {2846 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2847 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2848 };2849 }2850}28512852export class AcalaHelper extends XcmChainHelper {2853 balance: SubstrateBalanceGroup<AcalaHelper>;2854 assetRegistry: AcalaAssetRegistryGroup;2855 xTokens: XTokensGroup<AcalaHelper>;2856 tokens: TokensGroup<AcalaHelper>;28572858 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2859 super(logger, options.helperBase ?? AcalaHelper);28602861 this.balance = new SubstrateBalanceGroup(this);2862 this.assetRegistry = new AcalaAssetRegistryGroup(this);2863 this.xTokens = new XTokensGroup(this);2864 this.tokens = new TokensGroup(this);2865 }28662867 getSudo<T extends AcalaHelper>() {2868 // eslint-disable-next-line @typescript-eslint/naming-convention2869 const SudoHelperType = SudoHelper(this.helperBase);2870 return this.clone(SudoHelperType) as T;2871 }2872}28732874// eslint-disable-next-line @typescript-eslint/naming-convention2875function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2876 return class extends Base {2877 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2878 scheduledId: string;2879 blocksNum: number;2880 options: ISchedulerOptions;28812882 constructor(...args: any[]) {2883 const logger = args[0] as ILogger;2884 const options = args[1] as {2885 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2886 scheduledId: string,2887 blocksNum: number,2888 options: ISchedulerOptions2889 };28902891 super(logger);28922893 this.scheduleFn = options.scheduleFn;2894 this.scheduledId = options.scheduledId;2895 this.blocksNum = options.blocksNum;2896 this.options = options.options;2897 }28982899 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2900 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2901 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;29022903 return super.executeExtrinsic(2904 sender,2905 extrinsic,2906 [2907 this.scheduledId,2908 this.blocksNum,2909 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2910 this.options.priority ?? null,2911 {Value: scheduledTx},2912 ],2913 expectSuccess,2914 );2915 }2916 };2917}29182919// eslint-disable-next-line @typescript-eslint/naming-convention2920function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2921 return class extends Base {2922 constructor(...args: any[]) {2923 super(...args);2924 }29252926 executeExtrinsic (2927 sender: IKeyringPair,2928 extrinsic: string,2929 params: any[],2930 expectSuccess?: boolean,2931 ): Promise<ITransactionResult> {2932 const call = this.constructApiCall(extrinsic, params);2933 return super.executeExtrinsic(2934 sender,2935 'api.tx.sudo.sudo',2936 [call],2937 expectSuccess,2938 );2939 }2940 };2941}29422943export class UniqueBaseCollection {2944 helper: UniqueHelper;2945 collectionId: number;29462947 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2948 this.collectionId = collectionId;2949 this.helper = uniqueHelper;2950 }29512952 async getData() {2953 return await this.helper.collection.getData(this.collectionId);2954 }29552956 async getLastTokenId() {2957 return await this.helper.collection.getLastTokenId(this.collectionId);2958 }29592960 async doesTokenExist(tokenId: number) {2961 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2962 }29632964 async getAdmins() {2965 return await this.helper.collection.getAdmins(this.collectionId);2966 }29672968 async getAllowList() {2969 return await this.helper.collection.getAllowList(this.collectionId);2970 }29712972 async getEffectiveLimits() {2973 return await this.helper.collection.getEffectiveLimits(this.collectionId);2974 }29752976 async getProperties(propertyKeys?: string[] | null) {2977 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2978 }29792980 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2981 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2982 }29832984 async getOptions() {2985 return await this.helper.collection.getCollectionOptions(this.collectionId);2986 }29872988 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2989 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2990 }29912992 async confirmSponsorship(signer: TSigner) {2993 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2994 }29952996 async removeSponsor(signer: TSigner) {2997 return await this.helper.collection.removeSponsor(signer, this.collectionId);2998 }29993000 async setLimits(signer: TSigner, limits: ICollectionLimits) {3001 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3002 }30033004 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3005 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3006 }30073008 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3009 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3010 }30113012 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3013 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3014 }30153016 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3017 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3018 }30193020 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3021 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3022 }30233024 async setProperties(signer: TSigner, properties: IProperty[]) {3025 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3026 }30273028 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3029 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3030 }30313032 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3033 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3034 }30353036 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3037 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3038 }30393040 async disableNesting(signer: TSigner) {3041 return await this.helper.collection.disableNesting(signer, this.collectionId);3042 }30433044 async burn(signer: TSigner) {3045 return await this.helper.collection.burn(signer, this.collectionId);3046 }30473048 scheduleAt<T extends UniqueHelper>(3049 scheduledId: string,3050 executionBlockNumber: number,3051 options: ISchedulerOptions = {},3052 ) {3053 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3054 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3055 }30563057 scheduleAfter<T extends UniqueHelper>(3058 scheduledId: string,3059 blocksBeforeExecution: number,3060 options: ISchedulerOptions = {},3061 ) {3062 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3063 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3064 }30653066 getSudo<T extends UniqueHelper>() {3067 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3068 }3069}307030713072export class UniqueNFTCollection extends UniqueBaseCollection {3073 getTokenObject(tokenId: number) {3074 return new UniqueNFToken(tokenId, this);3075 }30763077 async getTokensByAddress(addressObj: ICrossAccountId) {3078 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3079 }30803081 async getToken(tokenId: number, blockHashAt?: string) {3082 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3083 }30843085 async getTokenOwner(tokenId: number, blockHashAt?: string) {3086 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3087 }30883089 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3090 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3091 }30923093 async getTokenChildren(tokenId: number, blockHashAt?: string) {3094 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3095 }30963097 async getPropertyPermissions(propertyKeys: string[] | null = null) {3098 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3099 }31003101 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3102 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3103 }31043105 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3106 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3107 }31083109 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3110 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3111 }31123113 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3114 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3115 }31163117 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3118 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3119 }31203121 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3122 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3123 }31243125 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3126 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3127 }31283129 async burnToken(signer: TSigner, tokenId: number) {3130 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3131 }31323133 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3134 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3135 }31363137 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3138 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3139 }31403141 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3142 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3143 }31443145 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3146 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3147 }31483149 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3150 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3151 }31523153 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3154 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3155 }31563157 scheduleAt<T extends UniqueHelper>(3158 scheduledId: string,3159 executionBlockNumber: number,3160 options: ISchedulerOptions = {},3161 ) {3162 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3163 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3164 }31653166 scheduleAfter<T extends UniqueHelper>(3167 scheduledId: string,3168 blocksBeforeExecution: number,3169 options: ISchedulerOptions = {},3170 ) {3171 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3172 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3173 }31743175 getSudo<T extends UniqueHelper>() {3176 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3177 }3178}317931803181export class UniqueRFTCollection extends UniqueBaseCollection {3182 getTokenObject(tokenId: number) {3183 return new UniqueRFToken(tokenId, this);3184 }31853186 async getToken(tokenId: number, blockHashAt?: string) {3187 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3188 }31893190 async getTokensByAddress(addressObj: ICrossAccountId) {3191 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3192 }31933194 async getTop10TokenOwners(tokenId: number) {3195 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3196 }31973198 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3199 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3200 }32013202 async getTokenTotalPieces(tokenId: number) {3203 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3204 }32053206 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3207 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3208 }32093210 async getPropertyPermissions(propertyKeys: string[] | null = null) {3211 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3212 }32133214 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3215 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3216 }32173218 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3219 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3220 }32213222 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3223 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3224 }32253226 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3227 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3228 }32293230 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3231 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3232 }32333234 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3235 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3236 }32373238 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3239 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3240 }32413242 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3243 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3244 }32453246 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3247 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3248 }32493250 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3251 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3252 }32533254 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3255 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3256 }32573258 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3259 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3260 }32613262 scheduleAt<T extends UniqueHelper>(3263 scheduledId: string,3264 executionBlockNumber: number,3265 options: ISchedulerOptions = {},3266 ) {3267 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3268 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3269 }32703271 scheduleAfter<T extends UniqueHelper>(3272 scheduledId: string,3273 blocksBeforeExecution: number,3274 options: ISchedulerOptions = {},3275 ) {3276 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3277 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3278 }32793280 getSudo<T extends UniqueHelper>() {3281 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3282 }3283}328432853286export class UniqueFTCollection extends UniqueBaseCollection {3287 async getBalance(addressObj: ICrossAccountId) {3288 return await this.helper.ft.getBalance(this.collectionId, addressObj);3289 }32903291 async getTotalPieces() {3292 return await this.helper.ft.getTotalPieces(this.collectionId);3293 }32943295 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3296 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3297 }32983299 async getTop10Owners() {3300 return await this.helper.ft.getTop10Owners(this.collectionId);3301 }33023303 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3304 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3305 }33063307 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3308 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3309 }33103311 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3312 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3313 }33143315 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3316 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3317 }33183319 async burnTokens(signer: TSigner, amount=1n) {3320 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3321 }33223323 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3324 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3325 }33263327 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3328 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3329 }33303331 scheduleAt<T extends UniqueHelper>(3332 scheduledId: string,3333 executionBlockNumber: number,3334 options: ISchedulerOptions = {},3335 ) {3336 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3337 return new UniqueFTCollection(this.collectionId, scheduledHelper);3338 }33393340 scheduleAfter<T extends UniqueHelper>(3341 scheduledId: string,3342 blocksBeforeExecution: number,3343 options: ISchedulerOptions = {},3344 ) {3345 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3346 return new UniqueFTCollection(this.collectionId, scheduledHelper);3347 }33483349 getSudo<T extends UniqueHelper>() {3350 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3351 }3352}335333543355export class UniqueBaseToken {3356 collection: UniqueNFTCollection | UniqueRFTCollection;3357 collectionId: number;3358 tokenId: number;33593360 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3361 this.collection = collection;3362 this.collectionId = collection.collectionId;3363 this.tokenId = tokenId;3364 }33653366 async getNextSponsored(addressObj: ICrossAccountId) {3367 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3368 }33693370 async getProperties(propertyKeys?: string[] | null) {3371 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3372 }33733374 async setProperties(signer: TSigner, properties: IProperty[]) {3375 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3376 }33773378 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3379 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3380 }33813382 async doesExist() {3383 return await this.collection.doesTokenExist(this.tokenId);3384 }33853386 nestingAccount() {3387 return this.collection.helper.util.getTokenAccount(this);3388 }33893390 scheduleAt<T extends UniqueHelper>(3391 scheduledId: string,3392 executionBlockNumber: number,3393 options: ISchedulerOptions = {},3394 ) {3395 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3396 return new UniqueBaseToken(this.tokenId, scheduledCollection);3397 }33983399 scheduleAfter<T extends UniqueHelper>(3400 scheduledId: string,3401 blocksBeforeExecution: number,3402 options: ISchedulerOptions = {},3403 ) {3404 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3405 return new UniqueBaseToken(this.tokenId, scheduledCollection);3406 }34073408 getSudo<T extends UniqueHelper>() {3409 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3410 }3411}341234133414export class UniqueNFToken extends UniqueBaseToken {3415 collection: UniqueNFTCollection;34163417 constructor(tokenId: number, collection: UniqueNFTCollection) {3418 super(tokenId, collection);3419 this.collection = collection;3420 }34213422 async getData(blockHashAt?: string) {3423 return await this.collection.getToken(this.tokenId, blockHashAt);3424 }34253426 async getOwner(blockHashAt?: string) {3427 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3428 }34293430 async getTopmostOwner(blockHashAt?: string) {3431 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3432 }34333434 async getChildren(blockHashAt?: string) {3435 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3436 }34373438 async nest(signer: TSigner, toTokenObj: IToken) {3439 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3440 }34413442 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3443 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3444 }34453446 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3447 return await this.collection.transferToken(signer, this.tokenId, addressObj);3448 }34493450 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3451 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3452 }34533454 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3455 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3456 }34573458 async isApproved(toAddressObj: ICrossAccountId) {3459 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3460 }34613462 async burn(signer: TSigner) {3463 return await this.collection.burnToken(signer, this.tokenId);3464 }34653466 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3467 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3468 }34693470 scheduleAt<T extends UniqueHelper>(3471 scheduledId: string,3472 executionBlockNumber: number,3473 options: ISchedulerOptions = {},3474 ) {3475 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3476 return new UniqueNFToken(this.tokenId, scheduledCollection);3477 }34783479 scheduleAfter<T extends UniqueHelper>(3480 scheduledId: string,3481 blocksBeforeExecution: number,3482 options: ISchedulerOptions = {},3483 ) {3484 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3485 return new UniqueNFToken(this.tokenId, scheduledCollection);3486 }34873488 getSudo<T extends UniqueHelper>() {3489 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3490 }3491}34923493export class UniqueRFToken extends UniqueBaseToken {3494 collection: UniqueRFTCollection;34953496 constructor(tokenId: number, collection: UniqueRFTCollection) {3497 super(tokenId, collection);3498 this.collection = collection;3499 }35003501 async getData(blockHashAt?: string) {3502 return await this.collection.getToken(this.tokenId, blockHashAt);3503 }35043505 async getTop10Owners() {3506 return await this.collection.getTop10TokenOwners(this.tokenId);3507 }35083509 async getBalance(addressObj: ICrossAccountId) {3510 return await this.collection.getTokenBalance(this.tokenId, addressObj);3511 }35123513 async getTotalPieces() {3514 return await this.collection.getTokenTotalPieces(this.tokenId);3515 }35163517 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3518 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3519 }35203521 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3522 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3523 }35243525 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3526 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3527 }35283529 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3530 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3531 }35323533 async repartition(signer: TSigner, amount: bigint) {3534 return await this.collection.repartitionToken(signer, this.tokenId, amount);3535 }35363537 async burn(signer: TSigner, amount=1n) {3538 return await this.collection.burnToken(signer, this.tokenId, amount);3539 }35403541 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3542 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3543 }35443545 scheduleAt<T extends UniqueHelper>(3546 scheduledId: string,3547 executionBlockNumber: number,3548 options: ISchedulerOptions = {},3549 ) {3550 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3551 return new UniqueRFToken(this.tokenId, scheduledCollection);3552 }35533554 scheduleAfter<T extends UniqueHelper>(3555 scheduledId: string,3556 blocksBeforeExecution: number,3557 options: ISchedulerOptions = {},3558 ) {3559 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3560 return new UniqueRFToken(this.tokenId, scheduledCollection);3561 }35623563 getSudo<T extends UniqueHelper>() {3564 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3565 }3566}