Create Module Contract
Prerequisite: Read “Create Core Contract” before creating a Module.
Installation
Install Forge from Foundry
For assistance, refer to the Foundry installation guide.
Create a New Module File
Create a new file called
CounterModule.sol
in thesrc
folder and start with the following code:Note
TheModule
contract is the base contract that needs to be inherited for this contract to be recognized as a Module Contract.Create a Storage Library
Create a library called
CounterStorage
responsible for holding the state of the Module Contract:Note
The libraryCounterStorage
uses the ERC-7201: Namespace storage layout to store the data. Learn more about ERC-7201.Set Up Storage Access Function
Set up the function
_counterStorage
to access the storage from theCounterStorage
library:Set Up Fallback Functions
Set up fallback functions that act as the setters and getters for
step
:Note
Fallback functions are extra functionalities that a core contract can use via the Solidityfallback
function.Set Up Callback Function
Set up a callback function
beforeIncrement
that increases the given count bystep
:Note
Callback functions are hook-like functionalities that can be used before or after the main functionality of a core contract. In this snippet, thebeforeIncrement
callback is used before the main increment functionality.Set Up Install and Uninstall Functions
Add the
onInstall
andonUninstall
functions along with helper functionsencodeBytesOnInstall
andencodeBytesOnUninstall
:Set Up Module Config
Lastly, set up the
getModuleConfig
function which is responsible for communicating to the core contract:
Create Module
In the next tutorial, learn how to deploy this modular contract and attach it to the Core contract.