2

I'm a beginner trying to write a Token contract, and I have encountered an error using Solidity 0.4.19. Here is the piece of code with the problem:

  function createTokens () payable {
    require(msg.value >0);

    uint256 tokens = msg.value.mul(RATE);
    balances[msg.sender] = balances[msg.sender].add(tokens);

    owner.transfer(msg.value);
  }

This is the error message:

Member "mul" not found or not visible after argument-dependent lookup in uint256

Can anyone please offer a tip to fix this, thank you very much?

1 Answer 1

8

You stumbled into an advanced pattern.

You could say

uint256 tokens = msg.value * RATE;

That would do the trick except that it might overflow if the result is ever over 2^256. To make sure that and other nasty things don't ever happen, there is a popular SafeMath.sol contract you can use. It's over here: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol

Then you might start out with:

import "./SafeMath.sol";

contract myContract {

  using SafeMath for uint256;

  // ... carry on

Now, type uint256 has a method .mul that the compiler is looking for.

Hope it helps.

3
  • Thank you so much :) It worked but I had exactly the same error on the following line, so I replaced .add with + and that seems to work fine. Thanks again Commented Dec 22, 2017 at 6:09
  • It's the same idea. If the add method isn't present it's probably because balances is cast as something other than uint256. Thanks for the accept. ;-) Commented Dec 22, 2017 at 6:17
  • Too bad they did put shl (shift-left) in there as well... Commented Dec 22, 2017 at 6:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.