0

Looking at https://docs.soliditylang.org/en/v0.8.11/contracts.html#view-functions I understood the solidity view function can work with any function unless it mutate states, emit events or perform any other mutative operations.

Meanwhile I noticed the following does not work (at least in Remix). Returning the stored blockNumber or the block.number works but not returning their difference blockNumber - block.number.

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

contract ThrowsError {

    uint256 private blockNumber;

    constructor () {
        blockNumber = block.number;
    }

    function viewFunction() public view returns (uint256) {
        return blockNumber - block.number;
    }
}

Here's the error that Remix Javascript VM throws:

call to ThrowsError.viewFunction errored: VM error: revert.

revert
    The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.
Debug the transaction to get more information.

Are there more restrictions on view functions? Could it be a problem with the Javascript VM?

2 Answers 2

1

As blocks get mined the block.number will increase. The stored block number will be smaller than the current. Subtracting the two reverts because the result underflows (you can think of it like negative values). In solidity 0.8+ underflows are reverted by default.

The error has nothing to do with visibility otherwise the compiler would have already warned you

Hope that helps

From https://www.reddit.com/r/ethdev/comments/s9blc7/how_to_use_the_view_function_with_blocknumber/htlsyox/

0

Your issue is not related to the view function. You assign blockNumber at constructor time and then at some later point call viewFunction, therefore block.number will always be greater (or if done in the deployment block equal) to blockNumber. So if you subtract blockNumber - block.number and type it as a uint then this will cause an underflow error.

All restrictions for view functions can be found in the official Solidity docs: https://docs.soliditylang.org/en/v0.8.11/contracts.html?highlight=view#view-functions

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.