difftreelog
feat(Scheduler) most critical improvements done, polishing needed
in: master
6 files changed
Cargo.lockdiffbeforeafterboth6108[[package]]6108[[package]]6109name = "pallet-template-transaction-payment"6109name = "pallet-template-transaction-payment"6110version = "3.0.0"6110version = "3.0.0"6111source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#858001a6fd841614eb3bc47562e1a08685e6c8df"6111source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#0f6291079a781cb9f8815efd5113a6a61059ce97"6112dependencies = [6112dependencies = [6113 "frame-benchmarking",6113 "frame-benchmarking",6114 "frame-support",6114 "frame-support",6272 "parity-scale-codec",6272 "parity-scale-codec",6273 "scale-info",6273 "scale-info",6274 "serde",6274 "serde",6275 "sp-api",6276 "sp-core",6275 "sp-core",6277 "sp-io",6276 "sp-io",6278 "sp-runtime",6277 "sp-runtime",11313 "chrono",11312 "chrono",11314 "lazy_static",11313 "lazy_static",11315 "matchers",11314 "matchers",11316 "parking_lot 0.11.2",11315 "parking_lot 0.10.2",11317 "regex",11316 "regex",11318 "serde",11317 "serde",11319 "serde_json",11318 "serde_json",11443source = "registry+https://github.com/rust-lang/crates.io-index"11442source = "registry+https://github.com/rust-lang/crates.io-index"11444checksum = "4ee73e6e4924fe940354b8d4d98cad5231175d615cd855b758adc658c0aac6a0"11443checksum = "4ee73e6e4924fe940354b8d4d98cad5231175d615cd855b758adc658c0aac6a0"11445dependencies = [11444dependencies = [11446 "cfg-if 1.0.0",11445 "cfg-if 0.1.10",11447 "rand 0.8.4",11446 "rand 0.8.4",11448 "static_assertions",11447 "static_assertions",11449]11448]11812[[package]]11811[[package]]11813name = "up-sponsorship"11812name = "up-sponsorship"11814version = "0.1.0"11813version = "0.1.0"11815source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#858001a6fd841614eb3bc47562e1a08685e6c8df"11814source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#0f6291079a781cb9f8815efd5113a6a61059ce97"11816dependencies = [11815dependencies = [11817 "impl-trait-for-tuples",11816 "impl-trait-for-tuples",11818]11817]pallets/scheduler/Cargo.tomldiffbeforeafterboth20sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }20sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }21frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }21frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }222223sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }23up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring", branch = 'polkadot-v0.9.14' }24up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring", branch = 'polkadot-v0.9.14' }24log = { version = "0.4.14", default-features = false }25log = { version = "0.4.14", default-features = false }252626[dev-dependencies]27[dev-dependencies]27sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }28substrate-test-utils = { git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }28substrate-test-utils = { git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }292930[features]30[features]38 "up-sponsorship/std",38 "up-sponsorship/std",39 "sp-io/std",39 "sp-io/std",40 "sp-std/std",40 "sp-std/std",41 "sp-core/std",41 "log/std",42 "log/std",42]43]43runtime-benchmarks = [44runtime-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.rsdiffbeforeafterboth17use sp_api::impl_runtime_apis;17use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19use sp_runtime::DispatchError;19use sp_runtime::DispatchError;20use fp_self_contained::*;21use sp_runtime::traits::{SignedExtension, Member};20// #[cfg(any(feature = "std", test))]22// #[cfg(any(feature = "std", test))]21// pub use sp_runtime::BuildStorage;23// pub use sp_runtime::BuildStorage;222454 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,56 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55 },57 },56};58};57use pallet_unq_scheduler::ApplyExtrinsic;59use pallet_unq_scheduler::DispatchCall;58use up_data_structs::*;60use up_data_structs::*;59// use pallet_contracts::weights::WeightInfo;61// use pallet_contracts::weights::WeightInfo;60// #[cfg(any(feature = "std", test))]62// #[cfg(any(feature = "std", test))]66 traits::{BaseArithmetic, Unsigned},68 traits::{BaseArithmetic, Unsigned},67};69};68use smallvec::smallvec;70use smallvec::smallvec;71use scale_info::TypeInfo;69use codec::{Encode, Decode};72use codec::{Encode, Decode};70use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};73use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};71use fp_rpc::TransactionStatus;74use fp_rpc::TransactionStatus;72use sp_core::crypto::Public;75use sp_core::crypto::Public;73use sp_runtime::{76use sp_runtime::{74 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},77 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},75 transaction_validity::TransactionValidityError,78 transaction_validity::TransactionValidityError,79 DispatchErrorWithPostInfo,76};80};778178// pub use pallet_timestamp::Call as TimestampCall;82// pub use pallet_timestamp::Call as TimestampCall;805 pub const MaxScheduledPerBlock: u32 = 50;809 pub const MaxScheduledPerBlock: u32 = 50;806}810}811812type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;813814/*fn get_signed_extra(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtra {815 (816 frame_system::CheckSpecVersion::<Runtime>::new(),817 frame_system::CheckGenesis::<Runtime>::new(),818 frame_system::CheckEra::<Runtime>::from(Era::Immortal),819 frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(820 from,821 )),822 frame_system::CheckWeight::<Runtime>::new(),823 ChargeTransactionPayment::new(0),824 )825}*/826827#[derive(Default, Encode, Decode, Clone, TypeInfo)]828pub struct SchedulerPreDispatch {829 tip: Balance,830 signer: AccountId,831 fee: Option<Balance>,832}833834pub struct SchedulerPaymentExecutor;835impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>836 DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor837where838 <T as frame_system::Config>::Call: Member839 + Dispatchable<Origin = Origin, Info = DispatchInfo>840 + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>841 + GetDispatchInfo842 + From<frame_system::Call<Runtime>>,843 SelfContainedSignedInfo: Send + Sync + 'static,844 Call: From<<T as frame_system::Config>::Call>845 + From<<T as pallet_unq_scheduler::Config>::Call>846 + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,847 sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,848{849 type Pre = SchedulerPreDispatch;850851 fn dispatch_call(852 //signer: <T as frame_system::Config>::AccountId,853 pre_dispatch: Self::Pre,854 call: <T as pallet_unq_scheduler::Config>::Call,855 ) -> Result<856 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,857 TransactionValidityError,858 > {859 /*let dispatch_info = call.get_dispatch_info();860861 let extrinsic = fp_self_contained::CheckedExtrinsic::<862 AccountId,863 Call,864 SignedExtra,865 SelfContainedSignedInfo,866 > {867 signed: CheckedSignature::<AccountId, SignedExtra, SelfContainedSignedInfo>::Signed(868 signer.clone().into(),869 get_signed_extra(signer.clone().into()),870 ),871 function: call.clone().into(),872 };873874 extrinsic.apply::<Runtime>(&dispatch_info, 0)*/875 let dispatch_info = call.get_dispatch_info();876 let pre = (877 pre_dispatch.tip,878 pre_dispatch.signer.clone().into(),879 pre_dispatch.fee.map(|fee| NegativeImbalance::new(fee)),880 );881882 let maybe_who = Some(pre_dispatch.signer.clone().into());883 let res = Call::from(call.clone()).dispatch(Origin::from(maybe_who));884 let post_info = match res {885 Ok(dispatch_info) => dispatch_info,886 Err(err) => err.post_info,887 };888 SignedExtra::post_dispatch(889 ((), (), (), (), (), pre),890 &dispatch_info,891 &post_info,892 0,893 &res.map(|_| ()).map_err(|e| e.error),894 )?;895 Ok(res)896 }897898 fn pre_dispatch(899 signer: <T as frame_system::Config>::AccountId,900 call: <T as pallet_unq_scheduler::Config>::Call,901 ) -> Result<Self::Pre, TransactionValidityError> {902 let dispatch_info = call.get_dispatch_info();903 //<T as Config>::OnChargeTransaction::withdraw_fee();904 let fee_charger = ChargeTransactionPayment::new(905 // Linear scaling of the fee tip if the priority is high enough906 0, //if priority > HARD_DEADLINE { 0 } else { (HARD_DEADLINE - priority + 1) / HARD_DEADLINE * PRIORITY_TIP_MULTIPLIER * total_fee }907 );908 let pre = fee_charger.pre_dispatch(&signer.into(), &call.into(), &dispatch_info, 0)?;909910 Ok(SchedulerPreDispatch {911 tip: pre.0,912 signer: pre.1,913 fee: pre.2.map(|imbalance| imbalance.peek()),914 })915 }916917 fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError> {918 todo!()919 // simply call post_dispatch with 0 actual fee and the whole remaining, already withdrawn, fee920 }921}922923impl pallet_unq_scheduler::Config for Runtime {924 type Event = Event;925 type Origin = Origin;926 type PalletsOrigin = OriginCaller;927 type Call = Call;928 type MaximumWeight = MaximumSchedulerWeight;929 type ScheduleOrigin = EnsureSigned<AccountId>;930 type MaxScheduledPerBlock = MaxScheduledPerBlock;931 type SponsorshipHandler = SponsorshipHandler;932 type WeightInfo = ();933 type CallExecutor = SchedulerPaymentExecutor;934}807935808type EvmSponsorshipHandler = (936type EvmSponsorshipHandler = (809 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,937 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,815 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,944 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,816);945);817818// pub fn sign(xt: CheckedExtrinsic) -> UncheckedExtrinsic {819// node_testing::keyring::sign(xt, SPEC_VERSION, TRANSACTION_VERSION, GENESIS_HASH)820// }821822pub struct SchedulerPaymentExecutor;823impl<C: Dispatchable> ApplyExtrinsic<C> for SchedulerPaymentExecutor {824 fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult {825 /*let extrinsic = sign(fp_self_contained::CheckedExtrinsic {826 signed: fp_self_contained::CheckedSignature::SelfContained(None),827 function,828 });829830 Executive::apply_extrinsic(extrinsic)*/831 todo!()832 }833}834835impl pallet_unq_scheduler::Config for Runtime {836 type Event = Event;837 type Origin = Origin;838 type PalletsOrigin = OriginCaller;839 type Call = Call;840 type MaximumWeight = MaximumSchedulerWeight;841 type ScheduleOrigin = EnsureSigned<AccountId>;842 type MaxScheduledPerBlock = MaxScheduledPerBlock;843 type WeightInfo = ();844 type Executor = SchedulerPaymentExecutor;845}846946847impl pallet_evm_transaction_payment::Config for Runtime {947impl pallet_evm_transaction_payment::Config for Runtime {848 type EvmSponsorshipHandler = EvmSponsorshipHandler;948 type EvmSponsorshipHandler = EvmSponsorshipHandler;965 frame_system::CheckEra<Runtime>,1065 frame_system::CheckEra<Runtime>,966 frame_system::CheckNonce<Runtime>,1066 frame_system::CheckNonce<Runtime>,967 frame_system::CheckWeight<Runtime>,1067 frame_system::CheckWeight<Runtime>,968 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1068 ChargeTransactionPayment,969 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1069 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,970);1070);971/// Unchecked extrinsic type as expected by this runtime.1071/// Unchecked extrinsic type as expected by this runtime.tests/src/scheduler.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import chai from 'chai';6import chai, { expect } from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import privateKey from './substrate/privateKey';8import privateKey from './substrate/privateKey';9import usingApi from './substrate/substrate-api';9import {10 default as usingApi, 11 submitTransactionAsync,12 submitTransactionExpectFailAsync,13} from './substrate/substrate-api';10import {14import {11 createItemExpectSuccess,15 createItemExpectSuccess,12 createCollectionExpectSuccess,16 createCollectionExpectSuccess,13 scheduleTransferExpectSuccess,17 scheduleTransferExpectSuccess,18 scheduleTransferAndWaitExpectSuccess,14 setCollectionSponsorExpectSuccess,19 setCollectionSponsorExpectSuccess,15 confirmSponsorshipExpectSuccess,20 confirmSponsorshipExpectSuccess,21 findUnusedAddress,22 UNIQUE,23 enablePublicMintingExpectSuccess,24 addToAllowListExpectSuccess,25 waitNewBlocks,26 normalizeAccountId,27 getTokenOwner,28 getGenericResult,29 scheduleTransferFundsPeriodicExpectSuccess,30 setCollectionLimitsExpectSuccess,31 getDetailedCollectionInfo,32 getFreeBalance,33 confirmSponsorshipByKeyExpectSuccess,16} from './util/helpers';34} from './util/helpers';17import {IKeyringPair} from '@polkadot/types/types';35import {IKeyringPair} from '@polkadot/types/types';36import {getBalanceSingle} from './substrate/get-balance';183719chai.use(chaiAsPromised);38chai.use(chaiAsPromised);203921describe('Integration Test scheduler base transaction', () => {40describe('Scheduling token and balance transfers', () => {22 let alice: IKeyringPair;41 let alice: IKeyringPair;23 let bob: IKeyringPair;42 let bob: IKeyringPair;244329 });48 });30 });49 });315032 it('User can transfer owned token with delay (scheduler)', async () => {51 it('Can schedule a transfer of an owned token with delay', async () => {33 await usingApi(async () => {52 await usingApi(async () => {34 // nft53 // nft35 const nftCollectionId = await createCollectionExpectSuccess();54 const nftCollectionId = await createCollectionExpectSuccess();36 const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');55 const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');37 await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);56 await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);38 await confirmSponsorshipExpectSuccess(nftCollectionId);57 await confirmSponsorshipExpectSuccess(nftCollectionId);395840 await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);59 await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);41 });60 });42 });61 });6263 it('Can transfer funds periodically', async () => {64 await usingApi(async (api) => {65 const waitForBlocks = 4;66 const period = 2;67 await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, period, 2);68 const bobsBalanceBefore = await getBalanceSingle(api, bob.address);6970 // discounting already waited-for operations71 await waitNewBlocks(waitForBlocks - 2);72 const bobsBalanceAfterFirst = await getBalanceSingle(api, bob.address);73 expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;7475 await waitNewBlocks(period);76 const bobsBalanceAfterSecond = await getBalanceSingle(api, bob.address);77 expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;78 });79 });8081 it('Can sponsor scheduling a transaction', async () => {82 const collectionId = await createCollectionExpectSuccess();83 await setCollectionSponsorExpectSuccess(collectionId, bob.address);84 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');8586 await usingApi(async () => {87 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);8889 const aliceBalanceBefore = await getFreeBalance(alice);90 // no need to wait to check, fees must be deducted on scheduling, immediately91 await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, 4);92 const aliceBalanceAfter = await getFreeBalance(alice);93 expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;94 });95 });9697 /*it('Can\'t schedule a transaction with no funds', async () => {98 await usingApi(async (api) => {99 // Find an empty, unused account100 const zeroBalance = await findUnusedAddress(api);101102 const collectionId = await createCollectionExpectSuccess();103 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');104105 await transferExpectSuccess(collectionId, tokenId, alice, zeroBalance);106107 await scheduleTransferAndWaitExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);108 });109 });*/110111 it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {112 await usingApi(async (api) => {113 // Find an empty, unused account114 const zeroBalance = await findUnusedAddress(api);115116 const collectionId = await createCollectionExpectSuccess();117118 // Add zeroBalance address to allow list119 await enablePublicMintingExpectSuccess(alice, collectionId);120 await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);121122 // Grace zeroBalance with money, enough to cover future transactions123 const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);124 await submitTransactionAsync(alice, balanceTx);125126 // Mint a fresh NFT127 const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');128129 // Schedule transfer of the NFT a few blocks ahead130 const waitForBlocks = 5;131 await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks);132133 // Get rid of the account's funds before the scheduled transaction takes place134 const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?135 const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);136 const events = await submitTransactionAsync(alice, sudoTx);137 expect(getGenericResult(events).success).to.be.true;138139 // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions140 await waitNewBlocks(waitForBlocks - 3);141142 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));143 });144 });145146 /*it.skip('Going bankrupt after sponsoring a scheduled transaction does not nullify the transaction', async () => {147 await usingApi(async (api) => {148 // Find two empty, unused accounts149 const zeroBalance = await findUnusedAddress(api);150 const zeroBalanceSponsor = await findUnusedAddress(api);151152 const collectionId = await createCollectionExpectSuccess();153154 // Grace these with money, enough to cover future transactions155 const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);156 await submitTransactionAsync(alice, balanceTx);157158 // Grace these with money, enough to cover future transactions159 const balanceSponsorTx = api.tx.balances.transfer(zeroBalanceSponsor.address, 1n * UNIQUE);160 await submitTransactionAsync(alice, balanceSponsorTx);161162 // Set a collection sponsor163 await setCollectionSponsorExpectSuccess(collectionId, zeroBalanceSponsor.address);164 await confirmSponsorshipExpectSuccess(collectionId);165166 // Add zeroBalance address to allow list167 await enablePublicMintingExpectSuccess(alice, collectionId);168 await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);169170 // Mint a fresh NFT171 const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');172173 // Schedule transfer of the NFT a few blocks ahead174 // const waitForBlocks = 4;175 await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);176 //await waitAfterScheduleExpectSuccess(collectionId, tokenId, alice, 3);177178 // Get rid of the account's funds before the scheduled transaction takes place179 const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalanceSponsor.address, 0, 0);180 const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);181 const events = await submitTransactionAsync(alice, sudoTx);182 expect(getGenericResult(events).success).to.be.true;183184 // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions185 await waitNewBlocks(4);186187 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));188 });189 });*/190191 it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {192 const collectionId = await createCollectionExpectSuccess();193194 await usingApi(async (api) => {195 const zeroBalance = await findUnusedAddress(api);196197 /*await setCollectionLimitsExpectSuccess(alice, nftCollectionId, {198 sponsoredDataRateLimit: 2,199 });*/200 //console.log(await getDetailedCollectionInfo(api, nftCollectionId));201 const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);202 await submitTransactionAsync(alice, balanceTx);203204 await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);205 await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);206207 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);208209 await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, 5);210211 const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);212 const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);213 const events = await submitTransactionAsync(alice, sudoTx);214 expect(getGenericResult(events).success).to.be.true;215216 // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions217 await waitNewBlocks(2);218219 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));220 });221 });43});222});223224describe.skip('Scheduling EVM smart contracts', () => {225 let alice: IKeyringPair;226 let bob: IKeyringPair;227228 before(async() => {229 await usingApi(async () => {230 alice = privateKey('//Alice');231 bob = privateKey('//Bob');232 });233 });234235 // todo contract testing236 it.skip('NFT: Sponsoring of transfers is rate limited', async () => {237 const collectionId = await createCollectionExpectSuccess();238 await setCollectionSponsorExpectSuccess(collectionId, bob.address);239 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');240241 await usingApi(async (api) => {242 // Find unused address243 const zeroBalance = await findUnusedAddress(api);244245 // Mint token for alice246 const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);247248 // Transfer this token from Alice to unused address and back249 // Alice to Zero gets sponsored250 const aliceToZero = api.tx.unique.transfer(normalizeAccountId(zeroBalance.address), collectionId, itemId, 0);251 const events1 = await submitTransactionAsync(alice, aliceToZero);252 const result1 = getGenericResult(events1);253254 // Second transfer should fail255 const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();256 const zeroToAlice = api.tx.unique.transfer(normalizeAccountId(alice.address), collectionId, itemId, 0);257 const badTransaction = async function () {258 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);259 };260 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');261 const sponsorBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();262263 // Try again after Zero gets some balance - now it should succeed264 const balancetx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);265 await submitTransactionAsync(alice, balancetx);266 const events2 = await submitTransactionAsync(zeroBalance, zeroToAlice);267 const result2 = getGenericResult(events2);268269 expect(result1.success).to.be.true;270 expect(result2.success).to.be.true;271 expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);272 });273 });274});44275tests/src/util/helpers.tsdiffbeforeafterboth480 });480 });481}481}482483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {484 await usingApi(async () => {485 const sender = privateKey(senderSeed);486 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);487 });488}482489483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {490export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {484 await usingApi(async (api) => {491 await usingApi(async (api) => {485492486 // Run the transaction493 // Run the transaction487 const sender = privateKey(senderSeed);488 const tx = api.tx.unique.confirmSponsorship(collectionId);494 const tx = api.tx.unique.confirmSponsorship(collectionId);489 const events = await submitTransactionAsync(sender, tx);495 const events = await submitTransactionAsync(sender, tx);490 const result = getGenericResult(events);496 const result = getGenericResult(events);792}798}793799794/* eslint no-async-promise-executor: "off" */800/* eslint no-async-promise-executor: "off" */795async function getBlockNumber(api: ApiPromise): Promise<number> {801export async function getBlockNumber(api: ApiPromise): Promise<number> {796 return new Promise<number>(async (resolve) => {802 return new Promise<number>(async (resolve) => {797 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {803 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {798 unsubscribe();804 unsubscribe();821 return balance;827 return balance;822}828}829830export async function831scheduleTransferAndWaitExpectSuccess(832 collectionId: number,833 tokenId: number,834 sender: IKeyringPair,835 recipient: IKeyringPair,836 value: number | bigint = 1,837 blockSchedule: number,838) {839 await usingApi(async (api: ApiPromise) => {840 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule);841842 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();843 console.log(await getFreeBalance(sender));844845 // sleep for n + 1 blocks846 await waitNewBlocks(blockSchedule + 1);847848 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();849850 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));851 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);852 });853}823854824export async function855export async function825scheduleTransferExpectSuccess(856scheduleTransferExpectSuccess(838 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);869 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);839 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);870 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);840871841 await submitTransactionAsync(sender, scheduleTx);872 const events = await submitTransactionAsync(sender, scheduleTx);842843 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();873 expect(getGenericResult(events).success).to.be.true;844874845 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));875 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));846847 // sleep for 4 blocks848 await waitNewBlocks(blockSchedule + 1);849850 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();851852 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));853 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);854 });876 });855}877}878879export async function880scheduleTransferFundsPeriodicExpectSuccess(881 amount: bigint,882 sender: IKeyringPair,883 recipient: IKeyringPair,884 blockSchedule: number,885 period: number,886 repetitions: number,887) {888 await usingApi(async (api: ApiPromise) => {889 const blockNumber: number | undefined = await getBlockNumber(api);890 const expectedBlockNumber = blockNumber + blockSchedule;891892 const balanceBefore = await getFreeBalance(recipient);893 894 expect(blockNumber).to.be.greaterThan(0);895 const transferTx = api.tx.balances.transfer(recipient.address, amount);896 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, [period, repetitions], 0, transferTx as any);897898 const events = await submitTransactionAsync(sender, scheduleTx);899 expect(getGenericResult(events).success).to.be.true;900901 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);902 });903}856904857905858export async function906export async function