3

Hello I have just recently started learning Solidity from Udemy, though after almost completing the lesson I have not understood the difference between assert and require. Don't they both break the function when requirements are not met? Does one over the other have an advantage concerning gas optimization inside the contract?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Vyggor
  • 31
  • 3

2 Answers2

7

from docs

The assert function creates an error of type Panic(uint256)

Assert should only be used to test for internal errors, and to check invariants. Properly functioning code should never create a Panic, not even on invalid external input. If this happens, then there is a bug in your contract which you should fix. Language analysis tools can evaluate your contract to identify the conditions and function calls which will cause a Panic.

Require: Similar to assert, this is used for checking conditions and throws an exception if the condition is not met. The difference is that require is used for validating inputs, return values, or calls to external contracts. The method also results in reverting back to the original state. It can also take an optional parameter to provide a custom error message.

require() situations:

• Check user input. For example if balance is greater than 0

• Check response from external contract, For example “require (external.send (amount))”

• Check the condition before state update

• Use require as early as possible of the function because in case of failure, require does return only unused gas. So if you implemented some logic that costs gas before require, then if the require statement fails, you will not get the gas that is consumed for the logic written before require

Use assert() in the following situations:

assert is used to validate the internal local state of the function. It should be used when you think that a current state has the potential to become inconsistent. That means your code has a bug. you cannot pass a custom error message to assert unlike require

  • Check overflow/underflow. After solidity ^0.8.0 compiler automatically checks for it.
  • Check invariable value
  • Check contract status after some modification
  • Avoid impossible situations

To better understand the benefit of using assert, you can read this: Why assertion is used on this Smart Contract?

Behnia FB
  • 53
  • 4
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
6

The bigger difference between the two keyword is that assert when condition is false tend to consume all gas remaining gas and reverts all the changes made. In reverse, require when the condition is false refund all the remaining gas fees we offered to pay beyond reverts all the changes.

Exactly for this last reason, require is recommended than assert.

More information this.

Antonio Carito
  • 1,287
  • 1
  • 5
  • 10