Solidity.

Post

Share your knowledge.

0x914b...756b.
Feb 16, 2024
Discussion

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
2
1
Share
Comments
.

Answers

1
Sergey Ilin.
Feb 16 2024, 15:27

There 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.

1
Comments
.

Do you know the answer?

Please log in and share it.

We use cookies to ensure you get the best experience on our website.
More info