Building up key components for adding functionality to your pallets.
Use helper functions inside a pallet to improve code readability and reusability.
Re-use helper functions to perform common "verify" checks across multiple pallets.
Sometimes a disptachable function inside a pallet reuse logic that's common to other dispatchables. In this case, it's useful to refactor this logic into its own separate function, private to the pallet. Other times, dispatchable functions get increasingly difficult to read as the amount of code increases to perform various checks within the dispatchable. In both instances, using helper functions that cannot be accessed from outside the pallet are a useful tool to optimize for code readability and reusability.
In this guide, we'll step through how to create an adder helper that checks for arithmetic overflow and can be reused in any dispatchable.
The helper we'll refer to is called
fn _adder: it checks that there is no overflow when adding two integers of type
It takes two
u32 integers, uses
ok_or to check that there is no overflow. If there is, it returns an error; otherwise
it returns the result.
Here's what it looks like as a helper function. This would go at the bottom of your pallet:
Identify the places where you've needed to verify for overflow when performing an addition. Use the helper function instead of rewriting the same code. Below is a simple example of a dispatchable that allows a signed extrinsic to add a value to the existing storage value:
- example-offchain-worker: the
add_pricehelper function used in this pallet's dispatchable.