Calculating transaction weights
Been here long enough to know these weights are actually pretty darn important ...
info
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.
#
GoalUnderstand how to calculate transaction weights for a basic dispatch function.
#
Use cases- Assign the correct weight before a function call to storage.
- Calculate transaction fees.
#
OverviewWeights 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#[weight]
attribute.DispatchResultWithPostInfo
: provides new weight info once the extrinsic function has been executed.
#
Steps#
1. Import weight configuration toolsMake sure you have the right dependencies:
#
2. Calculate maximum weight before a functionUsing 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.
#
3. Calculate the actual weight linked to function's logicThe 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 DbWeight
.
For a function whose logic does 3 storage reads, calculate it using DbWeight
and return it at the end of the function: