Been here long enough to know these weights are actually pretty darn important ...
This guide shows a basic procedure for confirguring weights. There are more advanced methods that suit different use cases. For simple functions with fixed amount of storage reads, this method works well.
Understand how to calculate transaction weights for a basic dispatch function.
- Assign the correct weight before a function call to storage.
- Calculate transaction fees.
Weights are an important part of Substrate development as they provide information about what the maximum cost a function can be in terms of the block size it will take up. This way, the weighting system checks what the cost will be before a function is executed. As runtime engineers, we care a lot about weights. Not only do they help add security checks around the functions we create, but they also force us to think about the computational ressources consumed by a transaction. From that, we can figure out what fees to charge users.
This guide will cover how to calculate the maximum weight for a dispatch call; calculate the actual weight after execution; and reimburse the difference.
Here's an overview of the traits we'll be implementing:
PaysFee: to specify whether or not a dispatch pays the fee.
GetDispatchInfo: carries weight information using the
DispatchResultWithPostInfo: provides new weight info once the extrinsic function has been executed.
Make sure you have the right dependencies:
call.get_dispatch_info(), calculate the maximum possible weight before the function is declared:
GetDispatchInfo provides the
get_dispatch_info() method we need to retrieve information about the function's weight.
The actual weight of a function call depends on the logic of the extrinsic. After execution, we can give back fees once the actual weight has been calculated. Handle this using the
Pays Enum and
For a function whose logic does 3 storage reads, calculate it using
DbWeight and return it at the end of the function: