I am just trying to understand how it actually works and how the assets stored on blockchain are protected. Since ABI definitions are public, contract address too is available, can anyone interact with a smart contract? If yes, how do you restrict it?

As an example, if there is an ERC20 token which implements transferFrom then can't someone call this function setting _to address to his own?


From the ERC20 standard, the transferFrom function can be called by anyone. But in order to succeed, the token owner must have allowed the spender to spend his token.

The example online are not correct, but here is one:

  function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
        uint256 value = _value * 10 ** uint256(decimals);
        require(value <= allowance[_from][msg.sender]);
        allowance[_from][msg.sender] -= value;
        _transfer(_from, _to, _value);
        return true;

See the require line, if this is false, the revert function will be called and the EVM state reverted to what it was before this transaction.

Note: As Smarx said in comments, the following line:

uint256 value = _value * 10 ** uint256(decimals);

Is speific to my code, don't use it in yours unless you know what you do (even if it works fine)

  • Isn't allowance meant for something else? May be my understanding is wrong but from what I know, allowance is meant for approving someone to spend money on on their behalf. As an example, accounts department may approve each employee to spend 100 tokens per month even when employees themselves don't hold any tokens.
    – eth.block
    Jan 28 '18 at 10:18
  • Unrelated to the question here, I just wanted to point out that multiplying by 10 ** decimals here is non-standard and probably a bad idea. The point of decimals is to allow people to transfer amounts like "0.01 tokens." If you multiply all your arguments by 10 ** decimals, you remove the ability to do that. (You may as well have just set decimals to 0.)
    – user19510
    Jan 28 '18 at 10:30
  • @eth.block "...from what I know, allowance is meant for approving someone to spend money on on their behalf." Exactly. For you to call transferFrom(foo, ...) successfully, foo must have first authorized you to spend their ether. That's what this code does.
    – user19510
    Jan 28 '18 at 10:34
  • So transferFrom requires prior approval. Fine. What about transfer? What if I pass _to as my own address and set _from to an address which I know has enough tokens? Is that even possible?
    – eth.block
    Jan 28 '18 at 10:44
  • 1
    @Andromelus I can't speak to that; I just wanted to point out to other readers that this is not something they should copy into their own contracts.
    – user19510
    Jan 28 '18 at 11:11

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .