In Solidity, a pure function is a type of function that does not read or modify the state of the contract. This means that pure functions cannot access any state variables or contract storage. They are used for computations that depend only on their input parameters and return a result based solely on those inputs. Pure functions are particularly useful for utility functions that perform calculations without any side effects.
Purpose of Pure Functions
- Stateless Computation: To perform calculations that do not depend on the contract's state.
- Gas Efficiency: To provide a way to execute logic without consuming gas when called externally.
- Reusability: To create utility functions that can be reused across different contracts or functions.
Syntax
function functionName() public pure returns (returnType) {}
Sample Code for Pure Functions
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract PureExample {
// Pure function to add two numbers
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b; // Return the sum of a and b
}
// Pure function to multiply two numbers
function multiply(uint256 a, uint256 b) public pure returns (uint256) {
return a * b; // Return the product of a and b
}
}
How It Works
In the above example, the PureExample
contract defines two pure functions:
add
: This function takes two unsigned integers as input and returns their sum. It is marked aspure
because it does not read or modify any state variables.multiply
: This function takes two unsigned integers as input and returns their product. Like theadd
function, it is also marked aspure
for the same reasons.
Key Points to Remember
- Pure functions are declared using the
pure
keyword. - They cannot read or modify state variables or contract storage.
- Calling a pure function externally does not consume gas.
- They are useful for performing calculations based solely on input parameters.
Conclusion
Pure functions are an essential feature of Solidity, allowing developers to create stateless utility functions that perform computations without side effects. By using pure functions effectively, developers can enhance the clarity and efficiency of their smart contracts.