protocols icon indicating copy to clipboard operation
protocols copied to clipboard

Use Local Memory Type Variable Instead of Global Storage Type Variable in Event to Save Gas

Open HighBe opened this issue 3 years ago • 0 comments

Hi, we recently have conducted a systematic study about Solidity event usage, evolution, and impact, and we are attempting to build a tool to improve the practice of Solidity event use based on our findings. We have tried our prototype tool on some of the most popular GitHub Solidity repositories, and for your repository, we find a potential optimization of gas consumption arisen from event use.

The point is that when we use emit operation to store the value of a certain variable, local memory type variable would be preferable to global storage type (state) variable if they hold the same value. The reason is that an extra SLOAD operation would be needed to access the variable if it is storage type, and the SLOAD operation costs 800 gas.

For your repository, we find that the following event use can be improved:

  • ControllerImpl.sol function name:initWalletFactory event name:  AddressChanged variable:    walletFactory->_walletFactory
    function initWalletFactory(address _walletFactory)
        external
        onlyOwner
    {
        require(walletFactory == address(0), "INITIALIZED_ALREADY");
        require(_walletFactory != address(0), "ZERO_ADDRESS");
        walletFactory = _walletFactory;
        emit AddressChanged("WalletFactory", walletFactory);
    }
  • ControllerImpl.sol function name:setCollectTo event name:  ValueChanged variable:    collectTo->_collectTo
    function setCollectTo(address _collectTo)
        external
        onlyOwner
    {
        require(_collectTo != address(0), "ZERO_ADDRESS");
        collectTo = _collectTo;
        emit ValueChanged("CollectTo", collectTo);
    }
    function start(uint _startTime) public onlyOwner {
        require(startTime == 0);

        lrcInitialBalance = Token(lrcTokenAddress).balanceOf(address(this));
        require(lrcInitialBalance > 0);

        lrcUnlockPerMonth = lrcInitialBalance.div(24); // 24 month
        startTime = _startTime;

        emit Started(startTime);
    }
    function start(uint _startTime) public onlyOwner {
        require(startTime == 0);

        lrcInitialBalance = Token(lrcTokenAddress).balanceOf(address(this));
        require(lrcInitialBalance > 0);

        lrcUnlockPerMonth = lrcInitialBalance.div(24); // 24 month
        startTime = _startTime;

        emit Started(startTime);
    }

Do you find our results useful? Your reply and invaluable suggestions would be greatly appreciated, and are vital for improving our tool. Thanks a lot for your time!

HighBe avatar Aug 19 '22 02:08 HighBe