hats-finance / Palmera-0x5fee7541ddcd51ba9f4af606f87b2c42eea655be

Palmera hierarchical module
0 stars 1 forks source link

Code Refactor - Gas Report #67

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): 0x3c0a8755401cf1a326a3da16e49ed99c936ecb0eca3b015edd6d13a8b5e7b5d1 Severity: gas saving

Description: Description\ If orgHash is large, iterating through the entire array could be gas-intensive. Consider optimizing the data structure or caching results for frequently accessed safeId values.

Attachments

  1. Original Code
    /// @notice call to get the orgHash based on safe id
    /// @dev Method to get the hashed orgHash based on safe id
    /// @param safeId uint256 of the safe
    /// @return orgSafe Hash (On-chain Organisation)
    function getOrgBySafe(uint256 safeId)
        public
        view
        returns (bytes32 orgSafe)
    {
        if ((safeId == 0) || (safeId > indexId)) revert Errors.InvalidSafeId();
        for (uint256 i; i < orgHash.length;) {
            if (safes[orgHash[i]][safeId].safe != address(0)) {
                orgSafe = orgHash[i];
            }
            unchecked {
                ++i;
            }
        }
        if (orgSafe == bytes32(0)) revert Errors.SafeIdNotRegistered(safeId);
    }
  2. Changed Code

    function getOrgBySafe(uint256 safeId) public view returns (bytes32 orgSafe) {
        // Validate the safeId
        if ((safeId == 0) || (safeId > indexId)) revert Errors.InvalidSafeId();
    
        // Iterate over the orgHash array to find the matching safeId
        for (uint256 i = 0; i < orgHash.length;) {
            if (safes[orgHash[i]][safeId].safe != address(0)) {
                // Return the orgHash as soon as a match is found
                return orgHash[i];
            }
            unchecked {
                ++i;
            }
        }
    
        // Revert if no matching safeId is found
        revert Errors.SafeIdNotRegistered(safeId);
    }

Files:

0xmahdirostami commented 4 days ago

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