Solidity Compilation Error – Using SafeMath with OpenZeppelin Contracts

contract-developmentopenzeppelin-contractsremixsafemathsolidity

I am trying to do subtraction operation using the SafeMath library. The following is my code:

pragma solidity ^0.5.1;
library SafeMath {
  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
    assert(b <= a);
    return a - b;
  }
}
contract Underflow1 {
using SafeMath for uint;
    uint8 num= 0;
    function testf2() public returns (uint8){
    //val--;    
    num= num.sub(1);
    return num;
    }
}

I am getting following error message:

browser/UF8-SM.sol:13:10: TypeError: Member "sub" not found or not
visible after argument-dependent lookup in uint8. num= num.sub(1);
^—–^

Somebody please guide me.

Zulfi.

Best Answer

The reason you are getting that error is because num is of type uint8, and the sub() function of SafeMath is looking for type uint256. Additionally you declare using SafeMath for uint;, which confirms that it only works with uint256 (as uint is an alias for uint256).


There are two ways to fix it:

1) Make num a uint256 type. Your code would look as follows:

pragma solidity ^0.5.1;
library SafeMath {
  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
    assert(b <= a);
    return a - b;
  }
}

contract Underflow1 {
using SafeMath for uint;
    uint256 num= 0;
    function testf2() public returns (uint256){
    //val--;    
    num = num.sub(1);
    return num;
    }
}

2) (Not preferred) Allow SafeMath to handle type uint8. Your code would look as follows:

pragma solidity ^0.5.1;
library SafeMath {
  function sub(uint8 a, uint8 b) internal pure returns (uint8) {
    assert(b <= a);
    return a - b;
  }
}

contract Underflow1 {
using SafeMath for uint8;
    uint8 num= 0;
    function testf2() public returns (uint8){
    //val--;    
    num = num.sub(1);
    return num;
    }
}
Related Topic