Last active
June 15, 2023 05:42
-
-
Save MiloTruck/887e37959e805e02e324b527a9145ec8 to your computer and use it in GitHub Desktop.
Using `delete` on OpenZeppelin's EnumerableSet/EnumerableMap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: UNLICENSED | |
pragma solidity ^0.8.13; | |
import "forge-std/Test.sol"; | |
import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol"; | |
contract EnumerableMapTest is Test { | |
using EnumerableMap for EnumerableMap.AddressToUintMap; | |
EnumerableMap.AddressToUintMap map; | |
function testDeleteEnumerableMap() public { | |
// Add address(1) to the map | |
map.set(address(1), 1); | |
// Using the "delete" keyword on the map corrupts it | |
delete map; | |
// The map's length is reset | |
assertEq(map.length(), 0); | |
// However, contains() still returns true for address(1) | |
assertTrue(map.contains(address(1))); | |
// The value of address(1) can still be retrieved | |
assertEq(map.get(address(1)), 1); | |
// Attempt to set address(1) to a different value | |
map.set(address(1), 2); | |
// Its value changes | |
assertEq(map.get(address(1)), 2); | |
// However, the map's length does not increase | |
assertEq(map.length(), 0); | |
// Add a new address to the map | |
map.set(address(2), 3); | |
// at() only works for key/value pairs that were not | |
// in the set before the "delete" keyword was used | |
assertEq(map.length(), 1); | |
(address addr, ) = map.at(0); | |
assertEq(addr, address(2)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: UNLICENSED | |
pragma solidity ^0.8.13; | |
import "forge-std/Test.sol"; | |
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; | |
contract EnumerableSetTest is Test { | |
using EnumerableSet for EnumerableSet.UintSet; | |
EnumerableSet.UintSet set; | |
function testDeleteEnumerableSet() public { | |
// Add 1 to set | |
set.add(1); | |
// Using the "delete" keyword causes data corruption | |
delete set; | |
// The set's length is reset | |
assertEq(set.length(), 0); | |
// However, contains() still returns true for 1 | |
assertTrue(set.contains(1)); | |
// add() returns false as it relies on contains() | |
assertFalse(set.add(1)); | |
// remove() reverts due to arithmetic underflow | |
vm.expectRevert(); | |
set.remove(1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment