Use Conditional Weights
Last updated
Last updated
Substrate provides a mechanism known as to quantify the resources consumed while executing a transaction. Typically, we use the weight functions returned from our benchmarking for this. But Substrate also allow us to apply a totally different weight function based on certain condition. We will walk through an example in this guide. Once defined, it can be used directly in your pallet, written as such:
#[pallet::weight(Conditional(\<your condition\>)
Create and use custom weighting in your pallet.
Apply different weight functions based on certain condition on computing extrinsic's weight value.
Here are the different traits we'll be implementing:
: Weigh the data in a function. `pallet::weight` expects whatever implements `WeighData` to replace `T` with a tuple of the dispatch arguments.
: Designate whether the dispatch pays a fee or not.
: A way to tell the runtime about the type of dispatch being made.
Open lib.rs
file for your pallet in a text editor.
Import DispatchClass
and Pays
by declaring use frame_support::dispatch::{DispatchClass, Pays}
.
Import weights
primitives into the pallet.
Declare a struct called Conditional
and write an implementation of WeighData
for Conditional
where the first parameter is the condition that evaluates to a boolean value.
In the following example, if the condition is true, the weight will be linear to the input. Otherwise the weight will be a constant.
Open lib.rs
file for your pallet in a text editor.
Import DispatchClass
and Pays
by declaring use frame_support::dispatch::{DispatchClass, Pays}
.
Use the conditional weighting struct on your pallet's extrinsics like this:
Add dispatch::{ClassifyDispatch, DispatchClass, Pays}
to your pallet's frame_support
imports. Since this implementation requires a , use default
to classify all calls as normal: