code-423n4 / 2022-04-phuture-findings

0 stars 0 forks source link

Gas Optimizations #76

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

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

Ref: https://twitter.com/GalloDaSballo/status/1485430908165443590

contracts/libraries/NAV.sol:49:        require(shares > 0, "NAV: INSUFFICIENT_AMOUNT");
contracts/libraries/NAV.sol:59:        require(amount > 0, "NAV: INSUFFICIENT_SHARES_BURNED");
contracts/libraries/IndexLibrary.sol:29:        require(_assetPerBaseInUQ > 0, "IndexLibrary: ORACLE");
contracts/libraries/FullMath.sol:35:                require(denominator > 0);
contracts/IndexLogic.sol:76:            require(lastAssetBalanceInBase > 0, "Index: INSUFFICIENT_AMOUNT");
contracts/IndexLogic.sol:98:        require(value > 0, "Index: INSUFFICIENT_AMOUNT");
contracts/ChainlinkPriceOracle.sol:86:        require(basePrice > 0 && quotePrice > 0, "ChainlinkPriceOracle: NEGATIVE");

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)
}
}
./contracts/libraries/IndexLibrary.sol:31:        return ((_amountInBase * _weight) / MAX_WEIGHT).mulDiv(_assetPerBaseInUQ, FixedPoint112.Q112);

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/