difftreelog
feat(Scheduler) most critical improvements done, polishing needed
in: master
6 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6108,7 +6108,7 @@
[[package]]
name = "pallet-template-transaction-payment"
version = "3.0.0"
-source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#858001a6fd841614eb3bc47562e1a08685e6c8df"
+source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#0f6291079a781cb9f8815efd5113a6a61059ce97"
dependencies = [
"frame-benchmarking",
"frame-support",
@@ -6272,7 +6272,6 @@
"parity-scale-codec",
"scale-info",
"serde",
- "sp-api",
"sp-core",
"sp-io",
"sp-runtime",
@@ -11313,7 +11312,7 @@
"chrono",
"lazy_static",
"matchers",
- "parking_lot 0.11.2",
+ "parking_lot 0.10.2",
"regex",
"serde",
"serde_json",
@@ -11443,7 +11442,7 @@
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ee73e6e4924fe940354b8d4d98cad5231175d615cd855b758adc658c0aac6a0"
dependencies = [
- "cfg-if 1.0.0",
+ "cfg-if 0.1.10",
"rand 0.8.4",
"static_assertions",
]
@@ -11812,7 +11811,7 @@
[[package]]
name = "up-sponsorship"
version = "0.1.0"
-source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#858001a6fd841614eb3bc47562e1a08685e6c8df"
+source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#0f6291079a781cb9f8815efd5113a6a61059ce97"
dependencies = [
"impl-trait-for-tuples",
]
pallets/scheduler/Cargo.tomldiffbeforeafterboth--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -20,11 +20,11 @@
sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring", branch = 'polkadot-v0.9.14' }
log = { version = "0.4.14", default-features = false }
[dev-dependencies]
-sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
substrate-test-utils = { git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
[features]
@@ -38,6 +38,7 @@
"up-sponsorship/std",
"sp-io/std",
"sp-std/std",
+ "sp-core/std",
"log/std",
]
runtime-benchmarks = [
pallets/scheduler/src/lib.rsdiffbeforeafterboth60use sp_runtime::{60use sp_runtime::{61 RuntimeDebug,61 RuntimeDebug,62 traits::{Zero, One, BadOrigin, Saturating},62 traits::{Zero, One, BadOrigin, Saturating},63 transaction_validity::TransactionValidityError,64 DispatchErrorWithPostInfo,63};65};64use frame_support::{66use frame_support::{65 decl_module, decl_storage, decl_event, decl_error,67 decl_module, decl_storage, decl_event, decl_error,69 schedule::{self, DispatchTime},71 schedule::{self, DispatchTime},70 OriginTrait, EnsureOrigin, IsType,72 OriginTrait, EnsureOrigin, IsType,71 },73 },72 weights::{GetDispatchInfo, Weight},74 weights::{GetDispatchInfo, Weight, PostDispatchInfo},73};75};74use frame_system::{self as system, ensure_signed};76use frame_system::{self as system, ensure_signed};75pub use weights::WeightInfo;77pub use weights::WeightInfo;76use scale_info::TypeInfo;78use up_sponsorship::SponsorshipHandler;77use sp_runtime::ApplyExtrinsicResult;79use scale_info::TypeInfo;78use sp_runtime::traits::{IdentifyAccount, Verify};80use sp_core::H160;79use sp_runtime::{MultiSignature};8081pub trait ApplyExtrinsic<C: Dispatchable> {82 fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult;83}8485/// The address format for describing accounts.86pub type Signature = MultiSignature;87pub type Address = sp_runtime::MultiAddress<AccountId, ()>;88pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;898190/// Our pallet's configuration trait. All our types and constants go in here. If the82/// Our pallet's configuration trait. All our types and constants go in here. If the91/// pallet is dependent on specific other pallets, then their configuration traits83/// pallet is dependent on specific other pallets, then their configuration traits122 /// Not strictly enforced, but used for weight estimation.114 /// Not strictly enforced, but used for weight estimation.123 type MaxScheduledPerBlock: Get<u32>;115 type MaxScheduledPerBlock: Get<u32>;116117 /// Sponsoring function.118 type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;124119125 /// Weight information for extrinsics in this pallet.120 /// Weight information for extrinsics in this pallet.126 type WeightInfo: WeightInfo;121 type WeightInfo: WeightInfo;127122123 /// The helper type used for custom transaction fee logic.128 type Executor: ApplyExtrinsic<<Self as Config>::Call>;124 type CallExecutor: DispatchCall<Self, H160>;129}125}126127/// A Scheduler-Runtime interface for finer payment handling.128pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {129 /// The type that encodes information that can be passed from pre_dispatch to post-dispatch.130 type Pre: Default + Codec + Clone + TypeInfo;131132 /// Resolve the call dispatch, including any post-dispatch operations.133 fn dispatch_call(134 pre_dispatch: Self::Pre,135 function: <T as Config>::Call,136 ) -> Result<137 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,138 TransactionValidityError,139 >;140141 /// Prepare for the scheduled call (e.g. by withdrawing the fee in advance).142 fn pre_dispatch(143 signer: T::AccountId,144 function: <T as Config>::Call,145 ) -> Result<Self::Pre, TransactionValidityError>;146147 /// Perform a clean-up after a cancelled call (e.g. by returning the remaining fee).148 fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError>;149}130150131pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;151pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;132152139/// The location of a scheduled task that can be used to remove it.159/// The location of a scheduled task that can be used to remove it.140pub type TaskAddress<BlockNumber> = (BlockNumber, u32);160pub type TaskAddress<BlockNumber> = (BlockNumber, u32);141161142#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]162/*#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))] todo remove completely?143#[derive(Clone, RuntimeDebug, Encode, Decode)]163#[derive(Clone, RuntimeDebug, Encode, Decode)]144struct ScheduledV1<Call, BlockNumber> {164struct ScheduledV1<Call, BlockNumber> {145 maybe_id: Option<Vec<u8>>,165 maybe_id: Option<Vec<u8>>,146 priority: schedule::Priority,166 priority: schedule::Priority,147 call: Call,167 call: Call,148 maybe_periodic: Option<schedule::Period<BlockNumber>>,168 maybe_periodic: Option<schedule::Period<BlockNumber>>,149}169}*/150170151/// Information regarding an item to be executed in the future.171/// Information regarding an item to be executed in the future.152#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]172#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]153#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]173#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]154pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {174pub struct Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> {155 /// The unique identity for this task, if there is one.175 /// The unique identity for this task, if there is one.156 maybe_id: Option<Vec<u8>>,176 maybe_id: Option<Vec<u8>>,157 /// This task's priority.177 /// This task's priority.162 maybe_periodic: Option<schedule::Period<BlockNumber>>,182 maybe_periodic: Option<schedule::Period<BlockNumber>>,163 /// The origin to dispatch the call.183 /// The origin to dispatch the call.164 origin: PalletsOrigin,184 origin: PalletsOrigin,185 /// The information regarding the call's preparation for dispatch, in particular the fee, to be sent to post-dispatch.186 pre_dispatch: PreDispatch,165 _phantom: PhantomData<AccountId>,187 _phantom: PhantomData<AccountId>,166}188}167189168/// The current version of Scheduled struct.190/// The current version of Scheduled struct.169pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =191/*pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> =170 ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;192 ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch>;*/171193172// A value placed in storage that represents the current version of the Scheduler storage.194// A value placed in storage that represents the current version of the Scheduler storage.173// This value is used by the `on_runtime_upgrade` logic to determine whether we run195// This value is used by the `on_runtime_upgrade` logic to determine whether we run174// storage migration logic.196// storage migration logic.175#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]197/*#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] todo remove completely?176enum Releases {198enum Releases {177 V1,199 V1,178 V2,200 V2,179}201}180202181impl Default for Releases {203impl Default for Releases {182 fn default() -> Self {204 fn default() -> Self {183 Releases::V1205 Releases::V1184 }206 }185}207}*/186208187#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]209#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]188pub struct CallSpec {210pub struct CallSpec {194 trait Store for Module<T: Config> as Scheduler {216 trait Store for Module<T: Config> as Scheduler {195 /// Items to be executed, indexed by the block number that they should be executed on.217 /// Items to be executed, indexed by the block number that they should be executed on.196 pub Agenda: map hasher(twox_64_concat) T::BlockNumber218 pub Agenda: map hasher(twox_64_concat) T::BlockNumber197 => Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;219 => Vec<Option<Scheduled<198220 <T as Config>::Call,221 T::BlockNumber,222 T::PalletsOrigin,223 T::AccountId,199 pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber224 <<T as Config>::CallExecutor as DispatchCall<T, H160>>::Pre200 => Vec<Option<CallSpec>>;225 >>>;226227 /*pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber todo remove completely?228 => Vec<Option<CallSpec>>;*/201229202 /// Lookup from identity to the block number and index of the task.230 /// Lookup from identity to the block number and index of the task.203 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;231 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;204232205 /// Storage version of the pallet.233 // / Storage version of the pallet.206 ///234 // /207 /// New networks start with last version.235 // / New networks start with last version.208 StorageVersion build(|_| Releases::V2): Releases;236 //StorageVersion build(|_| Releases::V2): Releases; todo remove completely?209 }237 }210}238}211239418 Some((order, index, *cumulative_weight, s))446 Some((order, index, *cumulative_weight, s))419 })447 })420 .filter_map(|(order, index, cumulative_weight, mut s)| {448 .filter_map(|(order, index, cumulative_weight, mut s)| {421 // We allow a scheduled call if any is true:449 // We allow a scheduled call if:422 // - It's priority is `HARD_DEADLINE`450 // - It's priority is `HARD_DEADLINE`423 // - It does not push the weight past the limit.451 // - It does not push the weight past the limit452 // or, alternatively,424 // - It is the first item in the schedule453 // - It is the first item in the schedule425 if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {454 if s.priority <= schedule::HARD_DEADLINE && cumulative_weight <= limit || order == 0 {426455 let r = T::CallExecutor::dispatch_call(s.pre_dispatch.clone(), s.call.clone());427 // let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(456428 // s.origin.clone()457 if let Err(_) = r {429 // ).into();458 log::warn!(430 // let sender = ensure_signed(origin).unwrap_or_default();459 target: "runtime::scheduler",431 // let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);460 "Warning: Scheduler has failed to execute a post-dispatch transaction. \432 // let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));461 This block might have become invalid.",433 // let r = s.call.clone().dispatch(sponsor.into());462 );463 // todo possibly force a skip/return here, do something with the error464 }465466 let r = r.unwrap(); // todo dangerous! but it shouldn't come to that, and if it does, the error is critical, is it safe to panic?467434 let maybe_id = s.maybe_id.clone();468 let maybe_id = s.maybe_id.clone();435 if let Some((period, count)) = s.maybe_periodic {469 if let Some((period, count)) = s.maybe_periodic {451 Self::deposit_event(RawEvent::Dispatched(485 Self::deposit_event(RawEvent::Dispatched(452 (now, index),486 (now, index),453 maybe_id,487 maybe_id,454 Ok(())// r.map(|_| ()).map_err(|e| e.error)488 r.map(|_| ()).map_err(|e| e.error)455 ));489 ));456 total_weight = cumulative_weight;490 total_weight = cumulative_weight;457 None491 None500 let sender = ensure_signed(534 let sender = ensure_signed(501 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),535 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),502 )536 )503 .unwrap_or_default();537 .unwrap_or_default(); // todo sponsoring doesn't work with the line below -- found sponsoring is already checked for in transaction_payment504 let who_will_pay = sender; // T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);538 //let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);505 let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));539 //let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay.clone()));540 //let r = call.clone().dispatch(sponsor.into());541506 let r = call.clone().dispatch(sponsor.into());542 let pre_dispatch = match T::CallExecutor::pre_dispatch(sender.clone(), call.clone()) {507543 Ok(pre_dispatch) => pre_dispatch,508 //T::PaymentHandler::apply();544 Err(_) => return Err(Error::<T>::FailedToSchedule.into()),509 //T::PaymentHandler::validate(sponsor.into(), call.clone(), ); todo dispatch extrinsic here545 };546547 // todo continually pre-dispatch according to maybe_periodic -- but it's called only once?548 // no, reschedule and cancel rely on scheduled being only the next instance549 // actually can count with OnChargePayment, so no need to run around. expand Pre with unspent_total_fee and single_fee, deduct single_fee510550511 // sanitize maybe_periodic551 // sanitize maybe_periodic512 let maybe_periodic = maybe_periodic552 let maybe_periodic = maybe_periodic513 .filter(|p| p.1 > 1 && !p.0.is_zero())553 .filter(|p| p.1 > 1 && !p.0.is_zero())514 // Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.554 // Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.515 .map(|(p, c)| (p, cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));555 .map(|(p, c)| (p, cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));556557 if let Some(periodic) = maybe_periodic {558 for _i in 0..=periodic.1 {559 // displace to runtime and count the total required fee, then deduct. find a way to use OnChargePayment560 // send constants and priority to runtime for fee computation, too. should create constants here or just declare them in runtime?561 // roadblock - they will return on post_dispatch -- oh! tips?562 }563 }516564517 let s = Some(Scheduled {565 let s = Some(Scheduled {518 maybe_id,566 maybe_id,519 priority,567 priority,520 call,568 call,521 maybe_periodic,569 maybe_periodic,522 origin,570 origin,571 pre_dispatch,523 _phantom: PhantomData::<T::AccountId>::default(),572 _phantom: PhantomData::<T::AccountId>::default(),524 });573 });525 Agenda::<T>::append(when, s);574 Agenda::<T>::append(when, s);557 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {606 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {558 agenda.get_mut(index as usize).map_or(607 agenda.get_mut(index as usize).map_or(559 Ok(None),608 Ok(None),560 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {609 |s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {561 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {610 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {562 if *o != s.origin {611 if *o != s.origin {563 return Err(BadOrigin.into());612 return Err(BadOrigin.into());570 if let Some(s) = scheduled {619 if let Some(s) = scheduled {571 if let Some(id) = s.maybe_id {620 if let Some(id) = s.maybe_id {572 Lookup::<T>::remove(id);621 Lookup::<T>::remove(id);573 // todo add back money / displace to another function for consistency574 }622 }623 if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone()) {624 log::warn!(625 target: "runtime::scheduler",626 "Warning: Scheduler has failed to execute a post-dispatch transaction. \627 This block might have become invalid.",628 );629 } // maybe do something with the error?575 Self::deposit_event(RawEvent::Canceled(when, index));630 Self::deposit_event(RawEvent::Canceled(when, index));576 Ok(())631 Ok(())577 } else {632 } else {643 if *o != s.origin {698 if *o != s.origin {644 return Err(BadOrigin.into());699 return Err(BadOrigin.into());645 }700 }701 if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone())702 {703 log::warn!(704 target: "runtime::scheduler",705 "Warning: Scheduler has failed to execute a post-dispatch transaction. \706 This block might have become invalid.",707 );708 } // maybe do something with the error?646 }709 }647 *s = None;710 *s = None;648 }711 }649 Ok(())712 Ok(())650 })?;713 })?;651 // todo add money back / displace to another function652 Self::deposit_event(RawEvent::Canceled(when, index));714 Self::deposit_event(RawEvent::Canceled(when, index));653 Ok(())715 Ok(())654 } else {716 } else {842 }904 }843 }905 }844906845 pub struct DummyExecutor; // todo do something with naming and function body907 pub struct DummyExecutor;846 impl<C: Dispatchable> ApplyExtrinsic<C> for DummyExecutor {908 impl<T: frame_system::Config + Config, SelfContainedSignedInfo>909 DispatchCall<T, SelfContainedSignedInfo> for DummyExecutor910 {911 type Pre = ();912913 fn dispatch_call(914 _pre: Self::Pre,915 _call: <T as Config>::Call,916 ) -> Result<917 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,918 TransactionValidityError,919 > {920 todo!()921 }922847 fn apply_extrinsic(_signer: Address, _function: C) -> ApplyExtrinsicResult {923 fn pre_dispatch(924 _signer: <T as frame_system::Config>::AccountId,925 _call: <T as Config>::Call,926 ) -> Result<Self::Pre, TransactionValidityError> {848 todo!()927 todo!()849 }928 }929930 fn cancel_dispatch(_pre: Self::Pre) -> Result<(), TransactionValidityError> {931 todo!()932 }850 }933 }851934852 parameter_types! {935 parameter_types! {898 type MaximumWeight = MaximumSchedulerWeight;981 type MaximumWeight = MaximumSchedulerWeight;899 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;982 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;900 type MaxScheduledPerBlock = MaxScheduledPerBlock;983 type MaxScheduledPerBlock = MaxScheduledPerBlock;984 type SponsorshipHandler = ();901 type WeightInfo = ();985 type WeightInfo = ();902 type Executor = DummyExecutor;986 type CallExecutor = DummyExecutor;903 }987 }904}988}905989runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -17,6 +17,8 @@
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};
use sp_runtime::DispatchError;
+use fp_self_contained::*;
+use sp_runtime::traits::{SignedExtension, Member};
// #[cfg(any(feature = "std", test))]
// pub use sp_runtime::BuildStorage;
@@ -54,7 +56,7 @@
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,
},
};
-use pallet_unq_scheduler::ApplyExtrinsic;
+use pallet_unq_scheduler::DispatchCall;
use up_data_structs::*;
// use pallet_contracts::weights::WeightInfo;
// #[cfg(any(feature = "std", test))]
@@ -66,6 +68,7 @@
traits::{BaseArithmetic, Unsigned},
};
use smallvec::smallvec;
+use scale_info::TypeInfo;
use codec::{Encode, Decode};
use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};
use fp_rpc::TransactionStatus;
@@ -73,6 +76,7 @@
use sp_runtime::{
traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},
transaction_validity::TransactionValidityError,
+ DispatchErrorWithPostInfo,
};
// pub use pallet_timestamp::Call as TimestampCall;
@@ -805,30 +809,114 @@
pub const MaxScheduledPerBlock: u32 = 50;
}
-type EvmSponsorshipHandler = (
- pallet_unique::UniqueEthSponsorshipHandler<Runtime>,
- pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
-);
-type SponsorshipHandler = (
- pallet_unique::UniqueSponsorshipHandler<Runtime>,
- //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
- pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
-);
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+
+/*fn get_signed_extra(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtra {
+ (
+ 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(),
+ ChargeTransactionPayment::new(0),
+ )
+}*/
-// pub fn sign(xt: CheckedExtrinsic) -> UncheckedExtrinsic {
-// node_testing::keyring::sign(xt, SPEC_VERSION, TRANSACTION_VERSION, GENESIS_HASH)
-// }
+#[derive(Default, Encode, Decode, Clone, TypeInfo)]
+pub struct SchedulerPreDispatch {
+ tip: Balance,
+ signer: AccountId,
+ fee: Option<Balance>,
+}
pub struct SchedulerPaymentExecutor;
-impl<C: Dispatchable> ApplyExtrinsic<C> for SchedulerPaymentExecutor {
- fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult {
- /*let extrinsic = sign(fp_self_contained::CheckedExtrinsic {
- signed: fp_self_contained::CheckedSignature::SelfContained(None),
- function,
- });
+impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>
+ DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
+where
+ <T as frame_system::Config>::Call: Member
+ + Dispatchable<Origin = Origin, Info = DispatchInfo>
+ + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
+ + GetDispatchInfo
+ + From<frame_system::Call<Runtime>>,
+ SelfContainedSignedInfo: Send + Sync + 'static,
+ Call: From<<T as frame_system::Config>::Call>
+ + From<<T as pallet_unq_scheduler::Config>::Call>
+ + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
+ sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
+{
+ type Pre = SchedulerPreDispatch;
+
+ fn dispatch_call(
+ //signer: <T as frame_system::Config>::AccountId,
+ pre_dispatch: Self::Pre,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ > {
+ /*let dispatch_info = call.get_dispatch_info();
+
+ let extrinsic = fp_self_contained::CheckedExtrinsic::<
+ AccountId,
+ Call,
+ SignedExtra,
+ SelfContainedSignedInfo,
+ > {
+ signed: CheckedSignature::<AccountId, SignedExtra, SelfContainedSignedInfo>::Signed(
+ signer.clone().into(),
+ get_signed_extra(signer.clone().into()),
+ ),
+ function: call.clone().into(),
+ };
+
+ extrinsic.apply::<Runtime>(&dispatch_info, 0)*/
+ let dispatch_info = call.get_dispatch_info();
+ let pre = (
+ pre_dispatch.tip,
+ pre_dispatch.signer.clone().into(),
+ pre_dispatch.fee.map(|fee| NegativeImbalance::new(fee)),
+ );
+
+ let maybe_who = Some(pre_dispatch.signer.clone().into());
+ let res = Call::from(call.clone()).dispatch(Origin::from(maybe_who));
+ let post_info = match res {
+ Ok(dispatch_info) => dispatch_info,
+ Err(err) => err.post_info,
+ };
+ SignedExtra::post_dispatch(
+ ((), (), (), (), (), pre),
+ &dispatch_info,
+ &post_info,
+ 0,
+ &res.map(|_| ()).map_err(|e| e.error),
+ )?;
+ Ok(res)
+ }
+
+ fn pre_dispatch(
+ signer: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<Self::Pre, TransactionValidityError> {
+ let dispatch_info = call.get_dispatch_info();
+ //<T as Config>::OnChargeTransaction::withdraw_fee();
+ let fee_charger = ChargeTransactionPayment::new(
+ // Linear scaling of the fee tip if the priority is high enough
+ 0, //if priority > HARD_DEADLINE { 0 } else { (HARD_DEADLINE - priority + 1) / HARD_DEADLINE * PRIORITY_TIP_MULTIPLIER * total_fee }
+ );
+ let pre = fee_charger.pre_dispatch(&signer.into(), &call.into(), &dispatch_info, 0)?;
+
+ Ok(SchedulerPreDispatch {
+ tip: pre.0,
+ signer: pre.1,
+ fee: pre.2.map(|imbalance| imbalance.peek()),
+ })
+ }
- Executive::apply_extrinsic(extrinsic)*/
+ fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError> {
todo!()
+ // simply call post_dispatch with 0 actual fee and the whole remaining, already withdrawn, fee
}
}
@@ -840,10 +928,22 @@
type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureSigned<AccountId>;
type MaxScheduledPerBlock = MaxScheduledPerBlock;
+ type SponsorshipHandler = SponsorshipHandler;
type WeightInfo = ();
- type Executor = SchedulerPaymentExecutor;
+ type CallExecutor = SchedulerPaymentExecutor;
}
+type EvmSponsorshipHandler = (
+ pallet_unique::UniqueEthSponsorshipHandler<Runtime>,
+ pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
+);
+
+type SponsorshipHandler = (
+ pallet_unique::UniqueSponsorshipHandler<Runtime>,
+ //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
+ pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
+);
+
impl pallet_evm_transaction_payment::Config for Runtime {
type EvmSponsorshipHandler = EvmSponsorshipHandler;
type Currency = Balances;
@@ -965,7 +1065,7 @@
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
- pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+ ChargeTransactionPayment,
//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
tests/src/scheduler.test.tsdiffbeforeafterboth--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -3,22 +3,41 @@
// file 'LICENSE', which is part of this source code package.
//
-import chai from 'chai';
+import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
-import usingApi from './substrate/substrate-api';
import {
+ default as usingApi,
+ submitTransactionAsync,
+ submitTransactionExpectFailAsync,
+} from './substrate/substrate-api';
+import {
createItemExpectSuccess,
createCollectionExpectSuccess,
scheduleTransferExpectSuccess,
+ scheduleTransferAndWaitExpectSuccess,
setCollectionSponsorExpectSuccess,
confirmSponsorshipExpectSuccess,
+ findUnusedAddress,
+ UNIQUE,
+ enablePublicMintingExpectSuccess,
+ addToAllowListExpectSuccess,
+ waitNewBlocks,
+ normalizeAccountId,
+ getTokenOwner,
+ getGenericResult,
+ scheduleTransferFundsPeriodicExpectSuccess,
+ setCollectionLimitsExpectSuccess,
+ getDetailedCollectionInfo,
+ getFreeBalance,
+ confirmSponsorshipByKeyExpectSuccess,
} from './util/helpers';
import {IKeyringPair} from '@polkadot/types/types';
+import {getBalanceSingle} from './substrate/get-balance';
chai.use(chaiAsPromised);
-describe('Integration Test scheduler base transaction', () => {
+describe('Scheduling token and balance transfers', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
@@ -29,7 +48,7 @@
});
});
- it('User can transfer owned token with delay (scheduler)', async () => {
+ it('Can schedule a transfer of an owned token with delay', async () => {
await usingApi(async () => {
// nft
const nftCollectionId = await createCollectionExpectSuccess();
@@ -37,7 +56,219 @@
await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
await confirmSponsorshipExpectSuccess(nftCollectionId);
- await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+ await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+ });
+ });
+
+ it('Can transfer funds periodically', async () => {
+ await usingApi(async (api) => {
+ const waitForBlocks = 4;
+ const period = 2;
+ await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, period, 2);
+ const bobsBalanceBefore = await getBalanceSingle(api, bob.address);
+
+ // discounting already waited-for operations
+ await waitNewBlocks(waitForBlocks - 2);
+ const bobsBalanceAfterFirst = await getBalanceSingle(api, bob.address);
+ expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
+
+ await waitNewBlocks(period);
+ const bobsBalanceAfterSecond = await getBalanceSingle(api, bob.address);
+ expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;
+ });
+ });
+
+ it('Can sponsor scheduling a transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async () => {
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ const aliceBalanceBefore = await getFreeBalance(alice);
+ // no need to wait to check, fees must be deducted on scheduling, immediately
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, 4);
+ const aliceBalanceAfter = await getFreeBalance(alice);
+ expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+ });
+ });
+
+ /*it('Can\'t schedule a transaction with no funds', async () => {
+ await usingApi(async (api) => {
+ // Find an empty, unused account
+ const zeroBalance = await findUnusedAddress(api);
+
+ const collectionId = await createCollectionExpectSuccess();
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+
+ await transferExpectSuccess(collectionId, tokenId, alice, zeroBalance);
+
+ await scheduleTransferAndWaitExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
+ });
+ });*/
+
+ it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
+ await usingApi(async (api) => {
+ // Find an empty, unused account
+ const zeroBalance = await findUnusedAddress(api);
+
+ const collectionId = await createCollectionExpectSuccess();
+
+ // Add zeroBalance address to allow list
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ // Grace zeroBalance with money, enough to cover future transactions
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ // Mint a fresh NFT
+ const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+
+ // Schedule transfer of the NFT a few blocks ahead
+ const waitForBlocks = 5;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks);
+
+ // Get rid of the account's funds before the scheduled transaction takes place
+ const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;
+
+ // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
+ await waitNewBlocks(waitForBlocks - 3);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+ });
+ });
+
+ /*it.skip('Going bankrupt after sponsoring a scheduled transaction does not nullify the transaction', async () => {
+ await usingApi(async (api) => {
+ // Find two empty, unused accounts
+ const zeroBalance = await findUnusedAddress(api);
+ const zeroBalanceSponsor = await findUnusedAddress(api);
+
+ const collectionId = await createCollectionExpectSuccess();
+
+ // Grace these with money, enough to cover future transactions
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ // Grace these with money, enough to cover future transactions
+ const balanceSponsorTx = api.tx.balances.transfer(zeroBalanceSponsor.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceSponsorTx);
+
+ // Set a collection sponsor
+ await setCollectionSponsorExpectSuccess(collectionId, zeroBalanceSponsor.address);
+ await confirmSponsorshipExpectSuccess(collectionId);
+
+ // Add zeroBalance address to allow list
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ // Mint a fresh NFT
+ const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+
+ // Schedule transfer of the NFT a few blocks ahead
+ // const waitForBlocks = 4;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
+ //await waitAfterScheduleExpectSuccess(collectionId, tokenId, alice, 3);
+
+ // Get rid of the account's funds before the scheduled transaction takes place
+ const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalanceSponsor.address, 0, 0);
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;
+
+ // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
+ await waitNewBlocks(4);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+ });
+ });*/
+
+ it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+
+ await usingApi(async (api) => {
+ const zeroBalance = await findUnusedAddress(api);
+
+ /*await setCollectionLimitsExpectSuccess(alice, nftCollectionId, {
+ sponsoredDataRateLimit: 2,
+ });*/
+ //console.log(await getDetailedCollectionInfo(api, nftCollectionId));
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
+
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, 5);
+
+ const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;
+
+ // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
+ await waitNewBlocks(2);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
+ });
+ });
+});
+
+describe.skip('Scheduling EVM smart contracts', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async() => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ // todo contract testing
+ it.skip('NFT: Sponsoring of transfers is rate limited', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async (api) => {
+ // Find unused address
+ const zeroBalance = await findUnusedAddress(api);
+
+ // Mint token for alice
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ // Transfer this token from Alice to unused address and back
+ // Alice to Zero gets sponsored
+ const aliceToZero = api.tx.unique.transfer(normalizeAccountId(zeroBalance.address), collectionId, itemId, 0);
+ const events1 = await submitTransactionAsync(alice, aliceToZero);
+ const result1 = getGenericResult(events1);
+
+ // Second transfer should fail
+ const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
+ const zeroToAlice = api.tx.unique.transfer(normalizeAccountId(alice.address), collectionId, itemId, 0);
+ const badTransaction = async function () {
+ await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
+ };
+ await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');
+ const sponsorBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();
+
+ // Try again after Zero gets some balance - now it should succeed
+ const balancetx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balancetx);
+ const events2 = await submitTransactionAsync(zeroBalance, zeroToAlice);
+ const result2 = getGenericResult(events2);
+
+ expect(result1.success).to.be.true;
+ expect(result2.success).to.be.true;
+ expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
});
});
});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -481,10 +481,16 @@
}
export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async () => {
+ const sender = privateKey(senderSeed);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);
+ });
+}
+
+export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {
await usingApi(async (api) => {
// Run the transaction
- const sender = privateKey(senderSeed);
const tx = api.tx.unique.confirmSponsorship(collectionId);
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -792,7 +798,7 @@
}
/* eslint no-async-promise-executor: "off" */
-async function getBlockNumber(api: ApiPromise): Promise<number> {
+export async function getBlockNumber(api: ApiPromise): Promise<number> {
return new Promise<number>(async (resolve) => {
const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {
unsubscribe();
@@ -822,6 +828,31 @@
}
export async function
+scheduleTransferAndWaitExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule);
+
+ const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+ console.log(await getFreeBalance(sender));
+
+ // sleep for n + 1 blocks
+ await waitNewBlocks(blockSchedule + 1);
+
+ const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
+ expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
+ });
+}
+
+export async function
scheduleTransferExpectSuccess(
collectionId: number,
tokenId: number,
@@ -838,19 +869,36 @@
const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);
- await submitTransactionAsync(sender, scheduleTx);
+ const events = await submitTransactionAsync(sender, scheduleTx);
+ expect(getGenericResult(events).success).to.be.true;
- const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
+ });
+}
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
+export async function
+scheduleTransferFundsPeriodicExpectSuccess(
+ amount: bigint,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ blockSchedule: number,
+ period: number,
+ repetitions: number,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const blockNumber: number | undefined = await getBlockNumber(api);
+ const expectedBlockNumber = blockNumber + blockSchedule;
- // sleep for 4 blocks
- await waitNewBlocks(blockSchedule + 1);
+ const balanceBefore = await getFreeBalance(recipient);
+
+ expect(blockNumber).to.be.greaterThan(0);
+ const transferTx = api.tx.balances.transfer(recipient.address, amount);
+ const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, [period, repetitions], 0, transferTx as any);
- const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+ const events = await submitTransactionAsync(sender, scheduleTx);
+ expect(getGenericResult(events).success).to.be.true;
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
- expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
+ expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
});
}