40,000 USDC
View results
Submission Details
Severity: gas
Valid

Use Constants instead of Enum

Summary

Enum is used in Escrow contract for managing various states of functions. But Enums are gas expensive and it can be done cheaper by using constants. One of the examples of using constants instead of enums is Openzeppelin's ReentrancyGuard.sol contract.
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol

Vulnerability Details

It costs so much less gas to read and write constant values than reading and writing from Enums.

Savings

Savings for confirmReceipt function:

Average Median Max
Before 24518 40322 40322
After 12942 22770 22770

Savings for initiateDispute function:

Average Median Max
Before 16855 23603 23603
After 1280 1657 1657

Savings for resolveDispute function:

Average Median Max
Before 27017 22342 62560
After 26717 21799 62419

Tools Used

Manual Analysis and Gas Savings are calculated via $ forge test --gas-report

Implementation

Implementing constants in place of Enum in Escrow contract requires quiet a bit of refactoring in Escrow.sol, IEscrow.sol and EscrowTest.t.sol. But for testing purposes, I have already modified all these contracts and they can be found here: https://github.com/0xSandip/EscrowGasChanges

Basically what i did was:

  1. Made new constants:

/Escrow.sol
uint256 private constant CREATED = 1;
uint256 private constant CONFIRMED = 2;
uint256 private constant DISPUTED = 3;
uint256 private constant RESOLVED = 4;
  1. Made a new state variable to keep track of the state:

/Escrow.sol
uint256 private s_state;
  1. Initialized the s_state as CREATED in the constructor:

/Escrow.sol
constructor(
...
) {
...
s_state = CREATED;
}
  1. Changed the inState modifier:

/Escrow.sol
modifier inState(uint256 expectedState) {
if (s_state != expectedState) {
revert Escrow__InWrongState(s_state, expectedState); //error also changed for uint256
}
_;
}

and modified all the instances of the state and values everywhere in the Escrow, IEscrow and EscrowTest.t.sol contract which can be referenced from the above link.

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.