Use Custom Weights

Here, you'll learn how to use the weights in your pallet from the output of benchmarking your pallet's extrinsics. It assumes that you have a file in your pallet's directory called weights.rs, containing the auto generated weights from running FRAME's benchmarking tool.

Goal

Use weights generated by FRAME's benchmarking tool in the extrinsics of your pallet.

Use Cases

Using accurate weights generated from benchmarking for a pallet's extrinsics.

Steps

1. Define the WeightInfo trait in your pallet's weight.rs file

In order to use the weights.rs file generated by the benchmarking tool in your pallet (an example of Substrate pallet-example weights here), define a trait that will make it easy to access its functions. For example:

pallets/example/src/weights.rs

pub trait WeightInfo {
  fn example(len: usize,) -> Weight;
}

2. Include WeightInfo in your pallet

In your pallet's lib.rs, declare pub mod weights; at the top and introduce pub use crate::weights::WeightInfo; to expose the WeightInfo trait to your pallet. Then, introduce a WeightInfo type into the Config trait of your pallet:

pallets/example/src/lib.rs

pub mod weights;
pub use weights::*;

// -- snip --

pub trait Config: frame_system::Config {
    // -- snip --

    /// Information on runtime weights.
    type WeightInfo: WeightInfo;
}

3. Write the custom weight declaration

For each of your dispatchables, introduce an appropriate weights line to determine the weight using the configured WeightInfo type. For example, T::WeightInfo::example would be the weight function returned from weights.rs for the example extrinsic:

pallets/example/src/lib.rs

#[pallet::weight(T::WeightInfo::example(x.len()))]
fn example(origin: OriginFor<T>, arg: Vec<u32>) -> DispatchResult {
  // -- snip --
}

4. Define the WeightInfo type in Config trait impls

You'll need to define the WeightInfo trait in both your pallet's tests mockup mock.rs and your Substrate node's runtime.

In your pallet's Config trait impl in mock.rs, introduce the following line to exclude weights in our testing.

In pallets/example/src/mock.rs or pallets/example/src/test.rs:

impl Config for TestRuntime {
  // -- snip --
  type WeightInfo = ();
}

In your pallet's Config trait impl in runtime/src/lib.rs, introduce the following line to include weights in our runtime.

impl pallet_example::Config for Runtime {
  // -- snip --
  type WeightInfo = pallet_example::weights::SubstrateWeight<Runtime>;
}

Once you recompile your node, your extrinsic will now be using the custom weights defined in pallets/example/src/weights.rs.

Examples

Last updated