Skip to content

Commit

Permalink
Optimize nested mapping access in ERC721Enumerable (#4545)
Browse files Browse the repository at this point in the history
Co-authored-by: Hadrien Croubois <[email protected]>
  • Loading branch information
0xVolosnikov and Amxx authored Mar 25, 2024
1 parent 159fc11 commit ad27fb6
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions contracts/token/ERC721/extensions/ERC721Enumerable.sol
Original file line number Diff line number Diff line change
Expand Up @@ -122,17 +122,19 @@ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
uint256 lastTokenIndex = balanceOf(from);
uint256 tokenIndex = _ownedTokensIndex[tokenId];

mapping(uint256 index => uint256) storage _ownedTokensByOwner = _ownedTokens[from];

// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
uint256 lastTokenId = _ownedTokensByOwner[lastTokenIndex];

_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensByOwner[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}

// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
delete _ownedTokensByOwner[lastTokenIndex];
}

/**
Expand Down

0 comments on commit ad27fb6

Please sign in to comment.