0

My code on Solidity is:

contract Recoverable is Ownable {

  /// @dev Empty constructor (for now)
  function Recoverable() public {
  }

  /// @dev This will be invoked by the owner, when owner wants to rescue tokens
  /// @param token Token which will we rescue to the owner from the contract
  function recoverTokens(ERC20Basic token) onlyOwner public {
    token.transfer(owner, tokensToBeReturned(token));
  }

  /// @dev Interface function, can be overwritten by the superclass
  /// @param token Token which balance we will check and return
  /// @return The amount of tokens (in smallest denominator) the contract owns
  function tokensToBeReturned(ERC20Basic token) public returns (uint) {
    return token.balanceOf(this);
  }
}

And I get next error: Function state mutability can be restricted to view function tokensToBeReturned(ERC20Basic token) public returns (uint) { ^ (Relevant source part starts here and spans across multiple lines).

I take this example from GitHub, and when I try куdeclare a function as internal pure, then get the next error:

function declared as pure, but this expression (potentially) reads from the environment or state and thus requires "view".
    return token.balanceOf(this);
                           ^--^

P.S. Help me, I really don`t understand.

2

tokensToBeReturned is a function that does not alter the state of the blockchain. It's just reading from it: it read the balance of the current contract. Therefore, a node could call it without creating a transaction.

A function that doesn't alter the state, should be declared as view, which means that nodes can decide not to create a transaction in order to get it's return value.

Functions declared as pure can not even read from the blockchain state. They can only return values that are either fully dependent on the calldata, or constant.

change

function tokensToBeReturned(ERC20Basic token) public returns (uint) {
    return token.balanceOf(this);
}

to

function tokensToBeReturned(ERC20Basic token) public view returns (uint) {
    return token.balanceOf(this);
}

Documentation links:

  • Shuld I declared all functions as view or pure? Whatll hapens if I dont set it? – Makarenko_I_V Aug 8 '18 at 9:12
  • Check out the pages to which I added links – Henk Aug 8 '18 at 9:18
  • so why function canUpgrade() public view returns(bool) { return true; } is wrong and compilator ask: Function state mutability can be restricted to pure ? – Makarenko_I_V Aug 8 '18 at 9:43
  • Because canUpgrade does not alter the state, AND it does not read from it. It just returns true, a constant. – Henk Aug 8 '18 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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