npkp
npkp

Reputation: 1241

solidity error - Member "sub" not found or not visible after argument-dependent lookup in uint256

I wrote a simple smart contract but it has an error in the transfer function Member "sub" not found or not visible after argument-dependent lookup in uint256. what could be causing the error? is it due to the solidity version?

pragma solidity ^0.5.16;

contract Token {
    string public name = "Token";
    string public symbol = "TK";
    uint256 public decimals = 18;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf; //Track balance

    constructor() public {
        totalSupply = 1000000 * (10 ** decimals);
        balanceOf[msg.sender] = totalSupply;
    }

     //Send Token
    function transfer(address _to, uint256 _value) public returns(bool success){
        balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); //error on this line
        balanceOf[_to] = balanceOf[_to].add(_value);
        return true;
    } 
}

Upvotes: 0

Views: 1550

Answers (1)

Wang Liang
Wang Liang

Reputation: 4444

We need import SafeMath.sol library and declare its usage. after that, we can call .sub, .add function with uint256 variable.

// SPDX-License-Identifier: MIT
pragma solidity ^0.5.16;

// Import SafeMath library
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
// Or we can import from online
import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/math/SafeMath.sol";

contract Token {
    // declar SafeMath libary usage for uint256
    using SafeMath for uint256;

    string public name = "Token";
    string public symbol = "TK";
    uint256 public decimals = 18;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf; //Track balance

    constructor() public {
        totalSupply = 1000000 * (10 ** decimals);
        balanceOf[msg.sender] = totalSupply;
    }

     //Send Token
    function transfer(address _to, uint256 _value) public returns(bool success){
        balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); //error on this line
        balanceOf[_to] = balanceOf[_to].add(_value);
        return true;
    } 
}

Upvotes: 3

Related Questions