Loading...

Assert() vs Require() in Solidity – Key Difference & What to Use

Assert() vs Require() in Solidity – Key Difference & What to Use

Assert() vs Require() in Solidity

assert() and require() were introduced in Solidity version 0.4.10. assert and require functions that check for conditions and when the conditions are not met they throw an error or an exception.

So how to decide when to use which?

When we want to validate inputs and conditions before execution we use require.

When we want to check for code that can and should never be false. If it fails that means that there is a bug, in such conditions we should use assert.

Let’s dive deeper into this. There are two perspectives to consider when there is a decision to be made between choosing assert() and require().

  1. Gas Efficiency
  2. Bytecode Analysis

The efficiency of Gas Optimization: If assert() returns a false statement it compiles to 0xfe, which is an invalid opcode, which uses up all the remaining gas and thus, reverts the changes entirely. If require() returns a false statement it compiles to 0xfd, which is the opcode for a REVERT meaning that it will return the remaining gas.

Use require() when: 

  • Validating state condition before stage changing operations.
  • Generally, you are better off using require().
  • Generally, it is used before a function.
  • To Validate user inputs.
  • Validate the response that is sent from an external contract.

Use assert() when: 

  • Checking for overflow and underflow when using uint8, etc.
  • Validating the state of a contract after making changes to it.
  • To avoid conditions that should never be possible.
  • Generally, assert() should be used less often.
  • It is used at the end of a function generally.

 

Sharing is caring

Did you like what Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, Arif Shaikh, wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far