Hi team,
First of all, thanks for this excellent Foundry starter kit! It's a great resource for the community.
While looking through the example contracts (VRFConsumerV2.sol and KeepersCounter.sol), I noticed a couple of small gas optimization opportunities that could be nice additions to make the templates even more efficient.
1. Make s_owner immutable in VRFConsumerV2.sol
The s_owner state variable is set in the constructor and never changed afterwards. Marking it as immutable would save significant gas on every read by replacing an expensive SLOAD opcode with a cheap PUSH of the value directly from the contract's bytecode.
Suggestion:
- address public s_owner;
+ address public immutable s_owner;
Approximate Gas Savings: This typically saves ~2000 gas each time the onlyOwner modifier is checked, as it avoids a storage read.
2. Use Custom Errors in KeepersCounter.sol
The require statement in performUpkeep uses a string message ("Time interval not met"). Since Solidity 0.8.4, using custom errors is more gas-efficient both at deployment and during runtime reverts.
Suggestion:
// At the contract level, above the constructor
+ error UpkeepNotNeeded();
// In the performUpkeep() function
- require(upkeepNeeded, "Time interval not met");
+ if (!upkeepNeeded) {
+ revert UpkeepNotNeeded();
+ }
Approximate Gas Savings: This provides two benefits:
- Deployment: A small saving by not storing the 23-byte revert string in the contract bytecode.
- Runtime (on revert): A more significant saving of ~250-400 gas each time the transaction reverts. This is because a custom error avoids the memory allocation and copying operations required for a revert string.
These are just small suggestions to make the starter kit even better. Thanks again for the great work!
Hi team,
First of all, thanks for this excellent Foundry starter kit! It's a great resource for the community.
While looking through the example contracts (
VRFConsumerV2.solandKeepersCounter.sol), I noticed a couple of small gas optimization opportunities that could be nice additions to make the templates even more efficient.1. Make
s_ownerimmutable inVRFConsumerV2.solThe
s_ownerstate variable is set in the constructor and never changed afterwards. Marking it asimmutablewould save significant gas on every read by replacing an expensiveSLOADopcode with a cheapPUSHof the value directly from the contract's bytecode.Suggestion:
Approximate Gas Savings: This typically saves ~2000 gas each time the
onlyOwnermodifier is checked, as it avoids a storage read.2. Use Custom Errors in
KeepersCounter.solThe
requirestatement inperformUpkeepuses a string message ("Time interval not met"). Since Solidity 0.8.4, using custom errors is more gas-efficient both at deployment and during runtime reverts.Suggestion:
Approximate Gas Savings: This provides two benefits:
These are just small suggestions to make the starter kit even better. Thanks again for the great work!