sherlock-audit / 2022-11-nounsdao-judging

4 stars 0 forks source link

perseverancesuccess - [Gas Optimization] In Stream.sol can move The code segment L347-L351 to be before L335_L345 in the function _recipientBalance() to save gas #55

Closed sherlock-admin closed 1 year ago

sherlock-admin commented 1 year ago

perseverancesuccess

unlabeled

[Gas Optimization] In Stream.sol can move The code segment L347-L351 to be before L335_L345 in the function _recipientBalance() to save gas

Summary

In Stream.sol can move The code segment L347-L351 to be before L335_L345 in the function _recipientBalance() to save gas

Vulnerability Detail

Gas optimization @suggestion For the code section in Stream.sol L347-L351 https://github.com/sherlock-audit/2022-11-nounsdao/blob/main/src/Stream.sol#L347-L351

        uint256 remainingBalance_ = remainingBalance;

        // When this function is called after the stream has been cancelled, when balance is less than
        // tokenAmount, without this early exit, the withdrawal calculation below results in an underflow error.
        if (remainingBalance_ == 0) return 0;

In case remainingBalance_ is 0, then all the calculation from Line 335 to 345 is useless because the function still return 0. https://github.com/sherlock-audit/2022-11-nounsdao/blob/main/src/Stream.sol#L335_L345

    uint256 balance;
        if (blockTime >= stopTime()) {
            balance = tokenAmount_;
        } else {
            // This is safe because: blockTime > startTime_ (checked above).
            unchecked {
                uint256 elapsedTime_ = blockTime - startTime_;
                balance = (elapsedTime_ * ratePerSecond()) / RATE_DECIMALS_MULTIPLIER; 
            }
        }

Impact

Gas optimization

Code Snippet

Tool used

Manual Review

Recommendation

Change the implementation to. Rerun all the tests -> Results passed

    uint256 startTime_ = startTime();
        uint256 blockTime = block.timestamp;

        if (blockTime <= startTime_) return 0;

    uint256 remainingBalance_ = remainingBalance;

        // When this function is called after the stream has been cancelled, when balance is less than
        // tokenAmount, without this early exit, the withdrawal calculation below results in an underflow error.
        if (remainingBalance_ == 0) return 0; 

    uint256 tokenAmount_ = tokenAmount();

       uint256 balance;
        if (blockTime >= stopTime()) {
            balance = tokenAmount_;
        } else {
            // This is safe because: blockTime > startTime_ (checked above).
            unchecked {
                uint256 elapsedTime_ = blockTime - startTime_;
                balance = (elapsedTime_ * ratePerSecond()) / RATE_DECIMALS_MULTIPLIER; 
            }
        }