Pure and View in Solidity smart contracts

Pure, view and payable dictate a Solidity functions behavior. If the behavior of a function is not specified by default it will read and modify the the state of the block chain. View functions are read only function and do not modify the state of the block chain (view data on the block chain). Pure functions do not read and do not modify state of the block chain. All the data the pure function is concerned with is either passed in or defined in the functions scope. Payable functions provide a mechanism to receive funds in your contract . Payable functions are annotated with the payable keyword. Click here for more information about payable function modifiers.

  • View functions are read only functions and do not modify the state of the block chain. In other words if you want to read data from the block chain one can use view. Getter method are by default view functions. These functions cannot:
    • Write to state variables – update the block chain
    • Emit events
    • Create contracts or use self destruct
    • Send ether

pragma solidity ^0.7.0;

contract viewSample {

    //view is specified and function reads data from block chain
    function getBlock() public view returns (uint){
        uint blocknumber = block.number;
        return blocknumber;
    }    
}

Try it in Remix

  • Pure functions are more restrictive then view functions and do not modify the state AND do not read the state of the block chain.  These functions cannot:
    • Read from state variables – read the block chain
    • Access balances
    • Call functions not marked pure

pragma solidity ^0.7.0;

contract pureSample {

   //pure is specified
   //this functions is only concerned about the variables and arithmetic in this function
   function getResult() public pure returns(uint sum){
      uint a = 5; 
      uint b = 7;
      sum = a + b; 
   }
}

Try it in Remix

Comparison of Pure and View

Default
(not specified in function)
View Pure
Ideal ForTransactions that alter data on the block chainGetter functions to view data on the block chainDefined to the scope of the function and do not alter or view data on the block chain
Data Accessread / writereadNone
Transaction TypeSendCallCall

For more information read the docs.

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

Next Review – Function Modifiers in Solidity smart contracts

Ledger Nano X - The secure hardware wallet

Leave a Reply