[Solidity] How to resolve "Function state mutability can be restricted to pure" error?

When you first start writing Solidity, you will often encounter the error "Function state mutability can be restricted to pure".

This article describes the solution.

Error Meaning

First of all, this error means "Function state mutability can be restricted to pure".

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

Code with "Function state mutability can be restricted to pure" error
Code with "Function state mutability can be restricted to pure" error

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

If you look at the processing within the function, you can see that no state variables (variables outside the function) are used.

In other words, this function is a "pure function" that does not read/write state variables (variables outside the function).

Pure functions need to be qualified with "pure" instead of "view," which is why the error occurred.

Error Resolution

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

The fixed code is as follows.

Code after fixing "Function state mutability can be restricted to pure" error
Code after fixing "Function state mutability can be restricted to pure" error

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

Note

I would like to add a note about pure functions.

As mentioned above, a function that does not read/write state variables (variables outside the function) is called a pure function.

Examples of pure functions
Examples of pure functions

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

Examples of not pure functions
Examples of not pure functions

On the other hand, for the previous function, if a variable is put outside the function (made a state variable), an error occurs.

That's because "reading/writing state variables (variables outside the function) within the function = not a pure function".

At first, you may be confused as to whether you are using pure or view. Remember pure for pure functions (not using state variables) and view for non-pure functions (using state variables). Note that you need to use view even if you are just reading a state variable in a function.

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