[Solidity] How to resolve "Function declared as pure, but this expression (potentially) reads from the environment or state and thus requires "view"" error?

When you first started writing Solidity, you would often encounter the error 'Function declared as pure, but this expression (potentially) reads from the environment or state and thus requires "view"'.

This article describes the solution.

Error Meaning

First, this error means, as it says, 'Function declared as pure, but this expression (potentially) reads from the environment or state and thus requires "view"', it means that "even though it is defined as a pure function, it reads a state variable".

I know this doesn't make sense, so I will explain based on the actual code.

Code with 'Function declared as pure, but this expression (potentially) reads from the environment or state and thus requires "view"' error
Code with 'Function declared as pure, but this expression (potentially) reads from the environment or state and thus requires "view"' error

The above figure shows the code in which this error occurs.

As long as the pure modifier is qualified, a state variable called multiplier is read in the function, even though state variables (variables outside the function) should not be read/write inside the function.

Non-pure functions (functions that read/write state variables within the function) need to be qualified with view instead of pure, which is why the error occurred.

Error Resolution

The solution is simple: for non-pure functions, qualify with view instead of pure.

The fixed code is as follows.

Code after fixing 'Function declared as pure, but this expression (potentially) reads from the environment or state and thus requires "view"' error
Code after fixing 'Function declared as pure, but this expression (potentially) reads from the environment or state and thus requires "view"' error

As you can see, the only change is to rewrite pure as view.

Note

I would like to add a note about pure functions.

As mentioned above, "functions that read/write state variables (variables outside the function)" are called non-pure functions.

Examples of non-pure functions
Examples of non-pure functions

The above figures are all non-pure functions, so they are qualified with view, but of course, no errors are occurred.

On the other hand, if we qualify the previous function with pure instead of view, an error occurs.

This is because "read/write state variables (variables outside the function) within the function = non-pure function", and therefore, pure, which should be used for pure functions (functions that do not read/write state variables within the function), cannot be used.

At first, you may be confused as to whether you are using pure or view. Remember that pure functions (which do not use state variables within the function) are qualified with pure and non-pure functions (which use state variables within the function) are qualified with view.

タイトルとURLをコピーしました