Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

custom weight function wrapper #4158

Merged
merged 12 commits into from
Jan 14, 2020
14 changes: 14 additions & 0 deletions paint/example/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,15 @@ decl_module! {
Ok(())
}

// TODO: this stuff will move to a new test.
#[weight = sr_primitives::weights::FunctionOf(
|args: (&u32, &T::AccountId, &BalanceOf<T>)| (args.0 + 100) as Weight,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to have type inferring to avoid unnecessary code?

Suggested change
|args: (&u32, &T::AccountId, &BalanceOf<T>)| (args.0 + 100) as Weight,
|(val, _, _)| val + 100,

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sadly, as far s I tried, no

1u8,
kianenigma marked this conversation as resolved.
Show resolved Hide resolved
)]
fn blah(origin, _a: u32, _b: T::AccountId, _c: BalanceOf<T>) {
let _ = ensure_signed(origin);
}

/// A privileged call; in this case it resets our dummy value to something new.
// Implementation of a privileged call. The `origin` parameter is ROOT because
// it's not (directly) from an extrinsic, but rather the system as a whole has decided
Expand Down Expand Up @@ -774,5 +783,10 @@ mod tests {
let custom_call = <Call<Test>>::set_dummy(20);
let info = custom_call.get_dispatch_info();
assert_eq!(info.weight, 2000);

// must have arg.0 + 100
let custom_call = <Call<Test>>::blah(20u32, 1, 1);
let info = custom_call.get_dispatch_info();
assert_eq!(info.weight, 120);
}
}
32 changes: 32 additions & 0 deletions primitives/sr-primitives/src/weights.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ impl Default for DispatchClass {
}
}

impl From<u8> for DispatchClass {
fn from(x: u8) -> Self {
match x {
0 => DispatchClass::Normal,
1 => DispatchClass::Operational,
_ => panic!("Reserved for other dispatch classes."),
}
}
}

impl From<SimpleDispatchInfo> for DispatchClass {
fn from(tx: SimpleDispatchInfo) -> Self {
match tx {
Expand Down Expand Up @@ -219,3 +229,25 @@ impl SimpleDispatchInfo {
Self::FixedNormal(0)
}
}

pub struct FunctionOf<F, Class>(pub F, pub Class);

impl<Args, F, Class> WeighData<Args> for FunctionOf<F, Class>
where
F : Fn(Args) -> Weight
{
fn weigh_data(&self, args: Args) -> Weight {
(self.0)(args)
}
}

impl<Args, F, Class> ClassifyDispatch<Args> for FunctionOf<F, Class>
where
Class: Into<DispatchClass> + Clone,
{
fn classify_dispatch(&self, _: Args) -> DispatchClass {
self.1.clone().into()
}
}

// TODO: test these stuff with a dedicated `decl_module`. Needs relocating to support first. #4124