View & Pure Modifiers

In Solidity, view and pure are function modifiers that indicate that a function doesn't modify the state of the contract.

The view modifier is used for functions that don't change the state of the contract, but rather just read from it. For example, a function that returns the current balance of a contract wouldn't need to modify the state, but would just read it. Functions marked with view can be called without sending a transaction, and are free to execute on any node in the network. The view modifier was introduced in Solidity version 0.5.0.

The pure modifier is used for functions that don't read from or modify the state of the contract, but rather perform some computation based on inputs. For example, a function that calculates the sum of two numbers wouldn't need to access the state, but would just perform a computation. Functions marked with pure can also be called without sending a transaction, and are free to execute on any node in the network. The pure modifier was also introduced in Solidity version 0.5.0.

Pure and view functions still cost gas if they are called internally from another function. They are only free if they are called externally, from outside of the blockchain.

Example

pragma solidity ^0.8.0;

contract MyContract {
    uint public x;

    function calculateSquare(uint _x) public pure returns (uint) {
        return _x * _x;
    }

    function setX(uint _x) public {
        x = _x;
    }

    function getXSquare() public view returns (uint) {
        return calculateSquare(x);
    }
}

In this example, we have a MyContract with three functions.

The calculateSquare function is declared as pure, which means it does not read or modify the state of the contract. It takes an input parameter _x, multiplies it by itself, and returns the result.

The setX function is a regular function that takes an input parameter _x, and sets the value of the state variable x to the input parameter.

The getXSquare function is declared as view, which means it does not modify the state of the contract, but can read the state. It calls the calculateSquare function with the current value of x, and returns the result.

Last updated