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

0 stars 1 forks source link

Gas Optimizations #74

Closed code423n4 closed 2 years ago

code423n4 commented 2 years ago

1. While setting the allowance to 0, using _token.safeApprove() makes less external call to save gas

Snippets from ExchangeHelpers library

  function setMaxAllowance(IERC20 _token, address _spender) internal {
      uint256 _currentAllowance = _token.allowance(address(this), _spender);
      if (_currentAllowance != type(uint256).max) {
          // Decrease to 0 first for tokens mitigating the race condition
          _token.safeDecreaseAllowance(_spender, _currentAllowance);
          _token.safeIncreaseAllowance(_spender, type(uint256).max);
      }
  }

Snippets from Openzeppelin's SafeERC20 library:

    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }
obatirou commented 2 years ago

1. While setting the allowance to 0, using _token.safeApprove() makes less external call to save gas (disputed)

The auditor suggest to use safeApprove to avoid calling allowance, but if you don't call allowance we won't be able to check if the allowance is already at UINT256 maximum or not.