Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use unchecked for ERC721 balance updates #3524

Merged
merged 8 commits into from Aug 23, 2022
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 21 additions & 4 deletions contracts/token/ERC721/ERC721.sol
Expand Up @@ -282,7 +282,13 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {

_beforeTokenTransfer(address(0), to, tokenId);

_balances[to] += 1;
unchecked {
// Will not overflow unless all 2**256 token ids are minted to the same owner.
// Given that tokens are minted one by one, it is impossible in practice that
// this ever happens. Might change if allow batch minting.
Amxx marked this conversation as resolved.
Show resolved Hide resolved
// The ERC fails to describe this case.
_balances[to] += 1;
}
_owners[tokenId] = to;

emit Transfer(address(0), to, tokenId);
Expand All @@ -308,7 +314,11 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
// Clear approvals
_approve(address(0), tokenId);

_balances[owner] -= 1;
unchecked {
// Cannot overflow, as that would require more tokens to be burned/transfered
// out then the owner initialy received through minting and transfering in.
_balances[owner] -= 1;
}
Amxx marked this conversation as resolved.
Show resolved Hide resolved
delete _owners[tokenId];

emit Transfer(owner, address(0), tokenId);
Expand Down Expand Up @@ -340,8 +350,15 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
// Clear approvals from the previous owner
_approve(address(0), tokenId);

_balances[from] -= 1;
_balances[to] += 1;
unchecked {
// `_balances[from]` cannot overflow for the same reason as described in `_burn`:
// `from`'s balance is the number of token held, which is at least one before the current
// transfer.
// `_balances[to]` could overflow in the conditions described in `_mint`. That would require
// all 2**256 token ids to be minted, which in practice is impossible.
_balances[from] -= 1;
Amxx marked this conversation as resolved.
Show resolved Hide resolved
_balances[to] += 1;
}
_owners[tokenId] = to;

emit Transfer(from, to, tokenId);
Expand Down