【问题标题】:solidity error - Member "sub" not found or not visible after argument-dependent lookup in uint256solidity 错误 - 在 uint256 中进行参数相关查找后,成员“子”未找到或不可见
【发布时间】:2021-10-21 10:49:57
【问题描述】:

我写了一个简单的智能合约,但它在传输函数Member "sub" not found or not visible after argument-dependent lookup in uint256. 中有错误,可能导致错误的原因是什么?是因为solidity版本吗?

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;
    } 
}

【问题讨论】:

  • 你的解决方案是什么?

标签: blockchain solidity


【解决方案1】:

我们需要导入SafeMath.sol 库并声明它的用法。之后,我们可以调用.sub.add函数和uint256变量。

// 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;
    } 
}

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 2019-04-29
    • 1970-01-01
    • 2021-06-22
    • 2021-02-18
    • 2021-08-18
    • 2021-12-29
    相关资源
    最近更新 更多