Solidity Function Type (View, Pure, Payable)

whiteboard crypto logo
Published by:
Whiteboard Crypto
on

In Solidity, there are 3 main function types which consist of View, Pure, and Payable. These determine if the functions can read or write to the blockchain, and if they can receive ETH upon being called. Here is an example of each of these functions in a smart contract:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.13;

contract typesOfFunctions{

    string public message;

    function regularFunction() public{
        message = "This is a regular non-payable function.";    
    }

    function viewFunction() public view returns (string memory){
        return message;
    }

    function pureFunction(uint _a, uint _b) public pure returns (uint){
        return _a + _b;
    }

    function payableFunction() public payable{
        payable(msg.sender).transfer(address(this).balance);
        //You can send ETH to this function, and it'll be sent back
    }
    
}

In the example above, we create a public string named “message” without initializing what it is. Next, we create a regular function that changes the value of “message”.

Then, we create a view function that simply returns the value of “message”. Since this doesn’t alter the blockchain, it can be view.

A pure function is next, and we create a function that simply accepts two unsigned integers and adds them together, returning the value.

Finally, we have a payable function which accepts ETH upon being called. If you send it 1 ETH, you can see the main line of code here will simply pay you back the 1 ETH using the transfer feature.

A “view” function should be used when the function only reads the blockchain, doesn’t write anything, and you want to return a variable.

A “pure” function should be used when the function doesn’t read the blockchain, change the blockchain, or alter it’s state. Pure functions are generally used for computations on chain that don’t alter the state of the blockchain.

A “payable” function is used when you want to send ETH with the call of a function. This is useful in many cases, and when the payable keyword is added to a function, ETH becomes a requirement to call it.

There is technically a “non-payable” function which isn’t view or pure, but it is the default function. All non-payable functions do not accept ETH directly, and do not explicitly return any values like a view function does.

whiteboard crypto logo

WhiteboardCrypto is the #1 online resource for crypto education that explains topics of the cryptocurrency world using analogies, stories, and examples so that anyone can easily understand them. Growing to over 870,000 Youtube subscribers, the content has been shared around the world, played in public conferences and universities, and even in Congress.