Skip to content

Suggestion: A few minor gas optimizations for the example contracts #46

@ebgd

Description

@ebgd

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:

  1. Deployment: A small saving by not storing the 23-byte revert string in the contract bytecode.
  2. 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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions