- Modularity: Easily pluggable into multiple contracts.
- Reusable Logic: Encapsulates specific functionalities.
- Not Standalone: Cannot be declared or deployed independently.
How to create a component
The following example shows a simpleSwitchable component that can be used to add a switch that can be either on or off.
It contains a storage variable switchable_value, a function switch and an event Switch.
It is a good practice to prefix the component storage variables with the component name to avoid collisions.
- An interface defining entrypoints (
ISwitchableComponent<TContractState>) - A Storage struct
- Events
- Internal functions
_init internal function and call it from the contract’s constructor. In the previous example, the _off function will be used this way.
It’s currently not possible to use the same component multiple times in the same contract.
This is a known limitation that may be lifted in the future.For now, you can view components as implementations of specific interfaces or features (
Ownable, Upgradeable, … ~able).
This is why we called the component in the above example Switchable, and not Switch; the contract is switchable, it does not have a switch.How to use a component
Now that we have a component, we can use it in a contract. The following contract incorporates theSwitchable component:
How to test a component
In order to effectively test a component, you need to test it in the context of a contract. A common practice is to declare aMock contract that has the only purpose of testing the component.
To test the Switchable component, we can use the previous SwitchableContract: