code-423n4 / 2022-06-nibbl-findings

1 stars 0 forks source link

Gas Optimizations #309

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

1. Cache secondaryReserveBalance in _chargeFee() function can save gas

In NibbleVault._chargeFee() function, secondaryReserveBalance is loaded from storage 2 times and stored in storage 1 time. We can save gas by loading it to memory to do calculation and only save to storage after all. For example

uint256 _tmp = secondaryReserveBalance;
uint256 _maxSecondaryBalanceIncrease = fictitiousPrimaryReserveBalance - _tmp;

_tmp += _feeCurve;
secondaryReserveRatio = uint32((_tmp * SCALE * 1e18) / (initialTokenSupply * initialTokenPrice));

secondaryReserveBalance = _tmp;

Affected Code

https://github.com/code-423n4/2022-06-nibbl/blob/8c3dbd6adf350f35c58b31723d42117765644110/contracts/NibblVault.sol#L222-L226

2. Should use _feeAdmin in check before transfer ETH to factory

In _chargeFee() function, it checks if _adminFeeAmt > 0 before sending ETH to factory. _adminFeeAmt is not sent amount but _feeAdmin and when _amount is small, _feeAdmin can be 0 even though _adminFeeAmt > 0 due to division round down. In that case, transfer 0 wei is unnecessary and cost gas. So we should check _feeAdmin > 0 instead.

Affected Codes

https://github.com/code-423n4/2022-06-nibbl/blob/8c3dbd6adf350f35c58b31723d42117765644110/contracts/NibblVault.sol#L227

https://github.com/code-423n4/2022-06-nibbl/blob/8c3dbd6adf350f35c58b31723d42117765644110/contracts/NibblVault.sol#L243

3. Should use constant for UPDATE_TIME to save gas

UPDATE_TIME is not changed anywhere in the codebase, so it should be marked constant to save gas

Affected Codes

https://github.com/code-423n4/2022-06-nibbl/blob/8c3dbd6adf350f35c58b31723d42117765644110/contracts/Utilities/NibblVaultFactoryData.sol#L6