3

Even though require() is used substantially more than assert(), there are places where assert() gets used. One example would be in the widely adopted SafeMath library by OpenZeppelin:

function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; }

where a + b is checked after summation to prevent overflow.

It seems like require(c >= a) can be used in place of assert(c >= a) for same functionality with an additional opportunity to refund unused gas. Are there any reason not to use require() here? Is assert() used just to force people not to perform operations that result in bad consequences like overflow/underflow?

Cheers

  • I would use it to punish a user that sends wrong arguments on purpose – cAos May 22 '18 at 20:08
3

require is for making sure that an illegal input has not been passed to the function.

assert is for making sure that something which is never supposed to happen - does not happen.

In other words, require is for when you want to protect from a possible scenario, and assert is for when you want to protect from an impossible scenario (i.e., a bug in your code).

Think of assert as something that you would ultimately remove if you were 100% certain that your code was flawless.

4

Prior to the Byzantium network upgrade, require() and assert() actually behave identically, but their bytecode output is slightly different.

assert() uses the 0xfe opcode to cause an error condition require() uses the 0xfd opcode to cause an error condition

A very important the primary difference between the opcode is that assert() will cost you gas while require() will not!

Please take a look at the very detailed and great description at:

https://medium.com/blockchannel/the-use-of-revert-assert-and-require-in-solidity-and-the-new-revert-opcode-in-the-evm-1a3a7990e06e

Hope this helps!

  • Thank you for elaborating on the differences between require() and assert() but you did not answer my question directly. My question is why not use require() in place of assert() since it can save user's gas even when something goes wrong. I have a similar idea with siid that assert() can be used to force people not to perform operations that result in bad consequences like overflow/underflow. @goodvibration had a good explanation on it. – Zhen Hong May 24 '18 at 19:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.