Post
Share your knowledge.
Clarification on Gas Refunds and Comparison Between "require" and "revert" in Smart Contracts
Hey everyone,
I'm trying to deepen my understanding of certain conditions in smart contract development, and I have a question about a specific scenario.
Let's say there's a "require" condition in a smart contract that must be met. If this condition fails, the contract needs to revert all changes made and refund any gas used in the transaction. My question is, how does the gas refund process work considering that gas is always consumed during computation?
Additionally, I've heard about the "revert" condition but would appreciate some clarification on how it differs from "require" in smart contract development.
- Smart Contract
- Solidity
Answers
1There are 3 functions for validation in Solidity: require
, revert
, and assert
.
Require
- Used at the beginning of a function
- Validates against illegal input
- Verifies state conditions prior to execution
- Refunds leftover gas
Example:
require(msg.sender == owner, "Only. owner can execute this action");
Revert
- Identical to require
- Useful for more complex logic flow gates (i.e., complicated if-then blocks)
- Refunds leftover gas
Example:
revert("Something funky has occured");
Assert
- Used at the end of a function
- Validates something that is impossible
- Critical for static code analysis tools
- Does not refund leftover gas
Example:
assert(num >= 0);
Note that require
and revert
refund only the remaining gas. Any gas used before that statement will be consumed. Both these functions use the same opcode REVERT under the hood.
assert
is different because it does not refund any gas and uses all of the gas available for the transaction. It is expected to be used less frequently and should be used for checking conditions that are abnormal and not expected to happen.
Do you know the answer?
Please log in and share it.
Solidity is an object-oriented, high-level language for implementing smart contracts. It is a curly-bracket language designed to target the Ethereum Virtual Machine (EVM).
- My ERC721 contract successfully deploys, but I can't verify the contract's source code with hardhat21
- Solidity and ethers.js Compute Different Addresses from the Same Signature21
- can't understand what are the locations(uint256)22
- How to reverse keccak256 in solidity22
- Clarification on Gas Refunds and Comparison Between "require" and "revert" in Smart Contracts21