Omniscia Mean Finance Audit

PermissionMath Code Style Findings

PermissionMath Code Style Findings

PMH-01C: Optimization of Permission Encoding

Description:

The PermissionMath::encode function is relatively inefficient as it will construct the encoded result of multiple permissions using a uint192 data type redundantly.

As a uint192 cast is performed on each bitwise shift operation of a _permission, the code will redundantly clear the upper 64 bits of the bitwise shift result under the hood as it performs a cast to the uint192 data type.

Example:

src/libraries/PermissionMath.sol
20function encode(INFTPermissions.Permission[] memory _permissions) internal pure returns (NFTPermissions.EncodedPermissions) {
21 uint192 _encodedResult;
22 for (uint256 i = 0; i < _permissions.length;) {
23 uint8 _permission = INFTPermissions.Permission.unwrap(_permissions[i]);
24 if (_permission >= 192) {
25 revert InvalidPermission(_permission);
26 }
27 _encodedResult |= uint192(1 << _permission);
28 unchecked {
29 i++;
30 }
31 }
32 return NFTPermissions.EncodedPermissions.wrap(_encodedResult);
33}

Recommendation:

Given that the code already ensures the _permission value unwrapped is strictly less-than 192, we advise the _encodedResult to be set as a uint256 value and each bitwise shift to be utilized as-is.

As a last step, the wrapping operation should pass in the _encodedResult cast to a uint192 value which is guaranteed to be a safe cast. These changes will result in an observable optimization of the function's gas cost.

Alleviation:

All statements in the code have been updated per our recommendation, ensuring that the encoding function exposed by PermissionMath is as optimal as possible.