git.delta.rocks / unique-network / refs/commits / be56642b11cc

difftreelog

feat(Scheduler) most critical improvements done, polishing needed

Fahrrader2022-02-21parents: #1f0f713 #58ec388.patch.diff
in: master

6 files changed

modifiedCargo.lockdiffbeforeafterboth
6108[[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]
modifiedpallets/scheduler/Cargo.tomldiffbeforeafterboth
20sp-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' }
2222
23sp-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 }
2526
26[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' }
2929
30[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 = [
modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
60use 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};
80
81pub trait ApplyExtrinsic<C: Dispatchable> {
82 fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult;
83}
84
85/// 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;
8981
90/// 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 the
91/// pallet is dependent on specific other pallets, then their configuration traits83/// pallet is dependent on specific other pallets, then their configuration traits
122 /// 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>;
116
117 /// Sponsoring function.
118 type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;
124119
125 /// Weight information for extrinsics in this pallet.120 /// Weight information for extrinsics in this pallet.
126 type WeightInfo: WeightInfo;121 type WeightInfo: WeightInfo;
127122
123 /// 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}
126
127/// 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;
131
132 /// 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 >;
140
141 /// 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>;
146
147 /// 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}
130150
131pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;151pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;
132152
139/// 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);
141161
142#[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}*/
150170
151/// 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}
167189
168/// 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>;*/
171193
172// 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 run
174// 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}
180202
181impl Default for Releases {203impl Default for Releases {
182 fn default() -> Self {204 fn default() -> Self {
183 Releases::V1205 Releases::V1
184 }206 }
185}207}*/
186208
187#[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::BlockNumber
197 => 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>>::Pre
200 => Vec<Option<CallSpec>>;225 >>>;
226
227 /*pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber todo remove completely?
228 => Vec<Option<CallSpec>>;*/
201229
202 /// 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>>;
204232
205 /// 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}
211239
418 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 limit
452 // or, alternatively,
424 // - It is the first item in the schedule453 // - It is the first item in the schedule
425 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(456
428 // 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 error
464 }
465
466 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?
467
434 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 None
500 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_payment
504 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());
541
506 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 };
546
547 // 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 instance
549 // actually can count with OnChargePayment, so no need to run around. expand Pre with unspent_total_fee and single_fee, deduct single_fee
510550
511 // sanitize maybe_periodic551 // sanitize maybe_periodic
512 let maybe_periodic = maybe_periodic552 let maybe_periodic = maybe_periodic
513 .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));
556
557 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 OnChargePayment
560 // 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 }
516564
517 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 consistency
574 }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 function
652 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 }
844906
845 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 DummyExecutor
910 {
911 type Pre = ();
912
913 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 }
922
847 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 }
929
930 fn cancel_dispatch(_pre: Self::Pre) -> Result<(), TransactionValidityError> {
931 todo!()
932 }
850 }933 }
851934
852 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}
905989
modifiedruntime/src/lib.rsdiffbeforeafterboth
17use 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;
2224
54 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};
7781
78// 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}
811
812type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
813
814/*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}*/
826
827#[derive(Default, Encode, Decode, Clone, TypeInfo)]
828pub struct SchedulerPreDispatch {
829 tip: Balance,
830 signer: AccountId,
831 fee: Option<Balance>,
832}
833
834pub struct SchedulerPaymentExecutor;
835impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>
836 DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
837where
838 <T as frame_system::Config>::Call: Member
839 + Dispatchable<Origin = Origin, Info = DispatchInfo>
840 + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
841 + GetDispatchInfo
842 + 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;
850
851 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();
860
861 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 };
873
874 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 );
881
882 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 }
897
898 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 enough
906 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)?;
909
910 Ok(SchedulerPreDispatch {
911 tip: pre.0,
912 signer: pre.1,
913 fee: pre.2.map(|imbalance| imbalance.peek()),
914 })
915 }
916
917 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, fee
920 }
921}
922
923impl 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}
807935
808type 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);
817
818// pub fn sign(xt: CheckedExtrinsic) -> UncheckedExtrinsic {
819// node_testing::keyring::sign(xt, SPEC_VERSION, TRANSACTION_VERSION, GENESIS_HASH)
820// }
821
822pub 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 });
829
830 Executive::apply_extrinsic(extrinsic)*/
831 todo!()
832 }
833}
834
835impl 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}
846946
847impl 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.
modifiedtests/src/scheduler.test.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import 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';
1837
19chai.use(chaiAsPromised);38chai.use(chaiAsPromised);
2039
21describe('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;
2443
29 });48 });
30 });49 });
3150
32 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 // nft
35 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);
3958
40 await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);59 await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
41 });60 });
42 });61 });
62
63 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);
69
70 // discounting already waited-for operations
71 await waitNewBlocks(waitForBlocks - 2);
72 const bobsBalanceAfterFirst = await getBalanceSingle(api, bob.address);
73 expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
74
75 await waitNewBlocks(period);
76 const bobsBalanceAfterSecond = await getBalanceSingle(api, bob.address);
77 expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;
78 });
79 });
80
81 it('Can sponsor scheduling a transaction', async () => {
82 const collectionId = await createCollectionExpectSuccess();
83 await setCollectionSponsorExpectSuccess(collectionId, bob.address);
84 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
85
86 await usingApi(async () => {
87 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
88
89 const aliceBalanceBefore = await getFreeBalance(alice);
90 // no need to wait to check, fees must be deducted on scheduling, immediately
91 await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, 4);
92 const aliceBalanceAfter = await getFreeBalance(alice);
93 expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
94 });
95 });
96
97 /*it('Can\'t schedule a transaction with no funds', async () => {
98 await usingApi(async (api) => {
99 // Find an empty, unused account
100 const zeroBalance = await findUnusedAddress(api);
101
102 const collectionId = await createCollectionExpectSuccess();
103 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
104
105 await transferExpectSuccess(collectionId, tokenId, alice, zeroBalance);
106
107 await scheduleTransferAndWaitExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
108 });
109 });*/
110
111 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 account
114 const zeroBalance = await findUnusedAddress(api);
115
116 const collectionId = await createCollectionExpectSuccess();
117
118 // Add zeroBalance address to allow list
119 await enablePublicMintingExpectSuccess(alice, collectionId);
120 await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
121
122 // Grace zeroBalance with money, enough to cover future transactions
123 const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
124 await submitTransactionAsync(alice, balanceTx);
125
126 // Mint a fresh NFT
127 const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
128
129 // Schedule transfer of the NFT a few blocks ahead
130 const waitForBlocks = 5;
131 await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks);
132
133 // Get rid of the account's funds before the scheduled transaction takes place
134 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;
138
139 // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
140 await waitNewBlocks(waitForBlocks - 3);
141
142 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
143 });
144 });
145
146 /*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 accounts
149 const zeroBalance = await findUnusedAddress(api);
150 const zeroBalanceSponsor = await findUnusedAddress(api);
151
152 const collectionId = await createCollectionExpectSuccess();
153
154 // Grace these with money, enough to cover future transactions
155 const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
156 await submitTransactionAsync(alice, balanceTx);
157
158 // Grace these with money, enough to cover future transactions
159 const balanceSponsorTx = api.tx.balances.transfer(zeroBalanceSponsor.address, 1n * UNIQUE);
160 await submitTransactionAsync(alice, balanceSponsorTx);
161
162 // Set a collection sponsor
163 await setCollectionSponsorExpectSuccess(collectionId, zeroBalanceSponsor.address);
164 await confirmSponsorshipExpectSuccess(collectionId);
165
166 // Add zeroBalance address to allow list
167 await enablePublicMintingExpectSuccess(alice, collectionId);
168 await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
169
170 // Mint a fresh NFT
171 const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
172
173 // Schedule transfer of the NFT a few blocks ahead
174 // const waitForBlocks = 4;
175 await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
176 //await waitAfterScheduleExpectSuccess(collectionId, tokenId, alice, 3);
177
178 // Get rid of the account's funds before the scheduled transaction takes place
179 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;
183
184 // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
185 await waitNewBlocks(4);
186
187 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
188 });
189 });*/
190
191 it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
192 const collectionId = await createCollectionExpectSuccess();
193
194 await usingApi(async (api) => {
195 const zeroBalance = await findUnusedAddress(api);
196
197 /*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);
203
204 await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
205 await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
206
207 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
208
209 await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, 5);
210
211 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;
215
216 // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
217 await waitNewBlocks(2);
218
219 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
220 });
221 });
43});222});
223
224describe.skip('Scheduling EVM smart contracts', () => {
225 let alice: IKeyringPair;
226 let bob: IKeyringPair;
227
228 before(async() => {
229 await usingApi(async () => {
230 alice = privateKey('//Alice');
231 bob = privateKey('//Bob');
232 });
233 });
234
235 // todo contract testing
236 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');
240
241 await usingApi(async (api) => {
242 // Find unused address
243 const zeroBalance = await findUnusedAddress(api);
244
245 // Mint token for alice
246 const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
247
248 // Transfer this token from Alice to unused address and back
249 // Alice to Zero gets sponsored
250 const aliceToZero = api.tx.unique.transfer(normalizeAccountId(zeroBalance.address), collectionId, itemId, 0);
251 const events1 = await submitTransactionAsync(alice, aliceToZero);
252 const result1 = getGenericResult(events1);
253
254 // Second transfer should fail
255 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();
262
263 // Try again after Zero gets some balance - now it should succeed
264 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);
268
269 expect(result1.success).to.be.true;
270 expect(result2.success).to.be.true;
271 expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
272 });
273 });
274});
44275
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
480 });480 });
481}481}
482
483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {
484 await usingApi(async () => {
485 const sender = privateKey(senderSeed);
486 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);
487 });
488}
482489
483export 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) => {
485492
486 // Run the transaction493 // Run the transaction
487 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}
793799
794/* 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}
829
830export async function
831scheduleTransferAndWaitExpectSuccess(
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);
841
842 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
843 console.log(await getFreeBalance(sender));
844
845 // sleep for n + 1 blocks
846 await waitNewBlocks(blockSchedule + 1);
847
848 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
849
850 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
851 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
852 });
853}
823854
824export async function855export async function
825scheduleTransferExpectSuccess(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);
840871
841 await submitTransactionAsync(sender, scheduleTx);872 const events = await submitTransactionAsync(sender, scheduleTx);
842
843 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();873 expect(getGenericResult(events).success).to.be.true;
844874
845 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));
846
847 // sleep for 4 blocks
848 await waitNewBlocks(blockSchedule + 1);
849
850 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
851
852 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
853 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
854 });876 });
855}877}
878
879export async function
880scheduleTransferFundsPeriodicExpectSuccess(
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;
891
892 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);
897
898 const events = await submitTransactionAsync(sender, scheduleTx);
899 expect(getGenericResult(events).success).to.be.true;
900
901 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
902 });
903}
856904
857905
858export async function906export async function