code-423n4 / 2022-02-skale-findings

0 stars 0 forks source link

Gas Optimizations #55

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 https://github.com/skalenetwork/ima-c4-audit/blob/11d6a6ae5bf16af552edd75183791375e501915f/contracts/mainnet/DepositBoxes/DepositBoxEth.sol#L122

require(approveTransfers[msg.sender] > 0, "User has insufficient ETH");

Reuse value from storage

https://github.com/skalenetwork/ima-c4-audit/blob/11d6a6ae5bf16af552edd75183791375e501915f/contracts/mainnet/CommunityPool.sol#L98

        uint userWalletBal = _userWallets[user][schainHash];
        if (amount > userWalletBal) {
            amount = userWalletBal;
            _userWallets[user][schainHash] = 0;
        }else{
            _userWallets[user][schainHash] = userWalletBal - amount;
        }

https://github.com/skalenetwork/ima-c4-audit/blob/11d6a6ae5bf16af552edd75183791375e501915f/contracts/mainnet/CommunityPool.sol#L171

        uint userWalletBal = _userWallets[msg.sender][schainHash];
        require(amount <= userWalletBal, "Balance is too low");
        require(!messageProxy.messageInProgress(), "Message is in progress");
        _userWallets[msg.sender][schainHash] = userWalletBal - amount;

Precalc keeack constant

The keccak256(abi.encodePacked("Mainnet")) can be precalculated as constant https://github.com/skalenetwork/ima-c4-audit/blob/11d6a6ae5bf16af552edd75183791375e501915f/contracts/mainnet/DepositBox.sol

Save gas by using schainName hash as input directly

It is a bit wasteful to use string schainName as input and hash it repeatedly onchain

Optimistic erc20 transfer

Can save some gas by skiping the balance check and let it revert during the transfer https://github.com/skalenetwork/ima-c4-audit/blob/11d6a6ae5bf16af552edd75183791375e501915f/contracts/mainnet/DepositBoxes/DepositBoxERC20.sol#L157

require(ERC20Upgradeable(message.token).balanceOf(address(this)) >= message.amount, "Not enough money");
yavrsky commented 2 years ago

Only marginal gas improvements.

GalloDaSballo commented 2 years ago

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

Saves 3 gas

Reuse value from storage

100 gas saved * 2 = 200

Precalc keeack constant

Saves 30 gas for the calculation

Save gas by using schainName hash as input directly

Would have liked to see further detail here, as there's potential downsides to applying this advice, for this reason will not give it any points

Optimistic erc20 transfer

Agree, this would save STATICCALL + the Storage check = 200 gas

GalloDaSballo commented 2 years ago

Total Gas Saved 433