Using helper functions
Building up key components for adding functionality to your pallets.
#
GoalUse helper functions inside a pallet to improve code readability and reusability.
#
Use casesRe-use helper functions to perform common "verify" checks across multiple pallets.
#
OverviewSometimes 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.
#
Steps#
1. Create your helper functionThe helper we'll refer to is called fn _adder
: it checks that there is no overflow when adding two integers of type u32
.
It takes two u32
integers, uses checked_add
and 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:
#
2. Use it in your dispatchablesIdentify 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:
#
Examples- example-offchain-worker: the
add_price
helper function used in this pallet's dispatchable.