What is the meaning of : require(newKittenId == uint256(uint32(newKittenId)));


Complete relevant code:

uint256 newKittenId = kitties.push(_kitty) - 1;

// It's probably never going to happen, 4 billion cats is A LOT, but
// let's just be 100% sure we never let this happen.
require(newKittenId == uint256(uint32(newKittenId)));
  • This question is not related to ERC-721. It is a Kitties-specific question. Tags edited. Dec 20 '18 at 16:29

Ensuring that newKittenId < 2 ** 32.

This can also be achieved simply by declaring newKittenId as uint32.

A possible reason for declaring it as uint256 is performance optimization.


Following your edit, it is clear why newKittenId was declared uint256, as push returns the length of the array, whose type is uint256. Yet the author wanted to ensure that this actual length never reaches 2 ** 32 (revert the operation upon such attempt).

  • Declaring newKittenId as a uint32 would not allow you to detect this problem. But require(newKittenId < 2**32); seems like a fine solution. (Again, perhaps there was some type of optimization happening?)
    – user19510
    Dec 20 '18 at 16:46
  • .push returns a uint256. Casting to a uint32 could potentially cause two kittens to have the same id, which is what is being avoided here. Dec 20 '18 at 17:36
  • @TjadenHess: There was no push in the question at the time I answered it, just a single require expression. Dec 20 '18 at 19:41
  • @smarx: The assignment uint256 newKittenId = kitties.push(_kitty) - 1 wasn't in the question when I answered it. Only the require expression at the top of the question was there, and this dude was asking what it meant, so I just took my best guess to explain it. Dec 20 '18 at 19:43
  • @goodvibration The answer is good; I'm just objecting to the line "This can also be achieved simply by declaring newKittenId as uint32." That line would not do what the require is doing.
    – user19510
    Dec 20 '18 at 20:02

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.