code-423n4 / 2022-03-maple-findings

0 stars 0 forks source link

Gas Optimizations #6

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Use custom errors

Solidity ^0.8.4 allow the use of custom errors to optimize gas usage. https://blog.soliditylang.org/2021/04/21/custom-errors/

> 0 is less efficient than != 0 for uint in require condition

Ref: https://twitter.com/GalloDaSballo/status/1485430908165443590 https://github.com/maple-labs/loan/blob/4c6fe2cd91d6d16b8434c426fe7eb6d2bc77bc30/contracts/MapleLoanInternals.sol#L112 https://github.com/maple-labs/mpl-migration/blob/a99549d96ed12cd4589a02bccf70747dbaebeb5b/contracts/Migrator.sol#L25

For loop optimization

Instead of

for (uint256 i = 1; i <= something; ++i){...}

we can do

for (uint256 i = 1; i <= something; ){...unchecked{++i;}}

https://github.com/maple-labs/loan/blob/4c6fe2cd91d6d16b8434c426fe7eb6d2bc77bc30/contracts/MapleLoanInternals.sol#L258

Float multiplication optimization

We can use the following function to save gas on float multiplications

// out = x * y unchecked{/} z
function fmul(uint256 x, uint256 y, uint256 z) internal pure returns(uint256 out){
assembly{
 if iszero(eq(div(mul(x,y),x),y)) {revert(0,0)}
 out := div(mul(x,y),z)
}
}

https://github.com/maple-labs/loan/blob/4c6fe2cd91d6d16b8434c426fe7eb6d2bc77bc30/contracts/MapleLoanInternals.sol#L488

Variables can be set immutable

https://github.com/maple-labs/revenue-distribution-token/blob/41a3e40bf8c109ff19b38b80fde300c44fd42a3d/contracts/RevenueDistributionToken.sol#L22

Unchecked safe math

https://github.com/maple-labs/loan/blob/4c6fe2cd91d6d16b8434c426fe7eb6d2bc77bc30/contracts/MapleLoanInternals.sol#L587

        unchecked{
            uint256 fullDaysLate = (((currentTime_ - nextPaymentDueDate_ - 1) / 1 days) + 1) * 1 days;
        }
lucas-manuel commented 2 years ago

Ignore