hats-finance / Palmera-0x5fee7541ddcd51ba9f4af606f87b2c42eea655be

Palmera hierarchical module
0 stars 1 forks source link

Code Refactor - Gas Report #68

Open hats-bug-reporter[bot] opened 4 days ago

hats-bug-reporter[bot] commented 4 days ago

Github username: @mhhacker111 Twitter username: -- Submission hash (on-chain): 0xcea1752c080636510532dc99adba644ff67c6c4abcf9c0ba404593b2200fc9b4 Severity: gas saving

Description: Description\ Caching indexSafe[org] in Memory: By storing indexSafe[org] in the orgSafes memory array, we reduce repeated SLOAD operations, which are costly.

  1. Original Code
    function getSafeIdBySafe(bytes32 org, address safe)
        public
        view
        returns (uint256)
    {
        if (!isOrgRegistered(org)) {
            revert Errors.OrgNotRegistered(org);
        }
        /// Check if the Safe address is into an Safe mapping
        for (uint256 i; i < indexSafe[org].length;) {
            if (safes[org][indexSafe[org][i]].safe == safe) {
                return indexSafe[org][i];
            }
            unchecked {
                ++i;
            }
        }
        return 0;
    }
  2. Changed Code

    function getSafeIdBySafe(bytes32 org, address safe)
    public
    view
    returns (uint256)
    {
    if (!isOrgRegistered(org)) {
        revert Errors.OrgNotRegistered(org);
    }
    
    // Cache the indexSafe array in memory
    uint256[] memory orgSafes = indexSafe[org];
    uint256 len = orgSafes.length;
    
    // Iterate through the cached array
    for (uint256 i = 0; i < len;) {
        if (safes[org][orgSafes[i]].safe == safe) {
            return orgSafes[i];
        }
        unchecked {
            ++i;
        }
    }
    
    return 0;
    }

Files:

0xmahdirostami commented 4 days ago

https://github.com/hats-finance/Palmera-0x5fee7541ddcd51ba9f4af606f87b2c42eea655be/issues/65#issuecomment-2197337983