The Pure modifier is added to a function in Solidity when a function doesn’t read to or write to the blockchain. This is used in cases where the developer wants to create a function to perform computation only. This not only lowers the total size of the contract, it also reduces vulnerabilities by restricting access to variables.
Here is a smart contract that uses 2 pure functions to demonstrate what they can be used for:
//SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
contract pureFunctions{
uint[] public fingersAndToes = [10,10,10,9];
function addTwoNumbers(uint a, uint b) public pure returns (uint) {
return a + b;
}
function getSumOfArray(uint[] memory _input) public pure returns(uint){
uint length = _input.length;
uint totalDigits;
for(uint i = 0; i<length; i++){
totalDigits += _input[i];
}
return totalDigits;
}
function countFingersAndToes() public view returns(uint){
return getSumOfArray(fingersAndToes);
}
}
In this contract, there are 3 functions:
- addTwoNumbers – This function takes two inputs and adds them together. Since this function isn’t changing the blockchain, it can be of type “pure”.
- getSumOfArray – This function adds all the numbers in an array together using a for loop. Since this function takes an array as the input, it does not need to read from the blockchain, and it also doesn’t write to the blockchain, so it can be of type “pure”.
- countFingersAndToes – This function applies our new pure function named getSumOfArray and computes it with an array we previously declared named “fingersAndToes”. The total of all these numbers is 39.
There are 4 different function types available, here is a review of them.
Pure: Can only perform computations.
View: Can only read from the blockchain + perform computations.
Payable: Must accept ETH when being called, and can read and write to the blockchain.
Nonpayable (default): Can not accept ETH, but can read and write to the blockchain. This type is the default type, and so you don’t have to declare it by using the keyword “nonpayable”.
If you use a “pure” function when the function potentially alters the blockchain, you’ll receive this error: “Function declared as pure, but this express (potentially) reads from the environment or state and thus requires “view”. The solution to this is to change pure to “view”.”