Use Conditional Weights
Substrate provides a mechanism known as transaction weighting 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\>)
Objectives
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:
`WeighData`: Weigh the data in a function. `pallet::weight` expects whatever implements `WeighData` to replace `T` with a tuple of the dispatch arguments.
`PaysFee`: Designate whether the dispatch pays a fee or not.
`ClassifyDispatch`: A way to tell the runtime about the type of dispatch being made.
Write the Weight struct
Open
lib.rs
file for your pallet in a text editor.Import
DispatchClass
andPays
by declaringuse frame_support::dispatch::{DispatchClass, Pays}
.Import
weights
primitives into the pallet.Declare a struct called
Conditional
and write an implementation ofWeighData
forConditional
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.
Classify dispatch calls
Add dispatch::{ClassifyDispatch, DispatchClass, Pays}
to your pallet's frame_support
imports. Since this implementation requires a DispatchClass
, use default
to classify all calls as normal:
Open
lib.rs
file for your pallet in a text editor.Import
DispatchClass
andPays
by declaringuse frame_support::dispatch::{DispatchClass, Pays}
.
Use the weighting struct for an extrinsic
Use the conditional weighting struct on your pallet's extrinsics like this:
Examples
Related material
Last updated