I was reading through the source code for Openzeppelin's CountersUpgradeable library v4.3.0 and realised that the arithmetic operation in the increment / decrement functions is wrapped by an unchecked block. As I understand it, the unchecked block would allow for overflow / underflow situations so isn't this a bad idea?


It's cheaper to use unchecked blocks and check for overflows and underflows manually than let Solidity do it. Refer to Is the modulo operation cheaper in unchecked arithmetic? for more details.

  • Thanks! I'm still wondering why gas savings has been prioritised over SafeMath operations in the contract in question. This contract is an optional extension on the standard OpenZeppelin contract suite to add auto increment token ID to an ERC 721 contract. Expecting the calling contract to manually check before invoking the counter seems like an anti-pattern?
    – palanisn
    Aug 19 at 0:28
  • To be frank I don't know, I am not part of the OpenZeppelin team. You might want to ask this question on forum.openzeppelin.com. Aug 19 at 9:38

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.