From c1d9da4052a75232dca1fafac80c4a2cb82fe518 Mon Sep 17 00:00:00 2001 From: Hadrien Croubois Date: Tue, 3 Jan 2023 15:38:13 +0100 Subject: [PATCH] Use hardhat-exposed to reduce the need for mocks (#3666) Co-authored-by: Francisco --- .gitignore | 3 + .../mocks/AccessControlCrossChainMock.sol | 16 +- .../mocks/AccessControlEnumerableMock.sol | 17 -- contracts/mocks/AccessControlMock.sol | 17 -- contracts/mocks/AddressImpl.sol | 42 --- contracts/mocks/Base64Mock.sol | 11 - contracts/mocks/BitmapMock.sol | 27 -- contracts/mocks/CallReceiverMock.sol | 8 +- contracts/mocks/CheckpointsMock.sol | 96 ------- contracts/mocks/ClonesMock.sol | 32 --- contracts/mocks/CountersImpl.sol | 27 -- contracts/mocks/Create2Impl.sol | 30 -- contracts/mocks/DoubleEndedQueueMock.sol | 58 ---- contracts/mocks/ECDSAMock.sol | 32 --- ...{EIP712External.sol => EIP712Verifier.sol} | 12 +- contracts/mocks/ERC1155BurnableMock.sol | 13 - contracts/mocks/ERC1155Mock.sol | 33 --- contracts/mocks/ERC1155PausableMock.sol | 29 -- contracts/mocks/ERC1155SupplyMock.sol | 21 -- contracts/mocks/ERC1155URIStorageMock.sol | 22 -- .../ERC165/ERC165InterfacesSupported.sol | 58 ---- contracts/mocks/ERC165CheckerMock.sol | 29 -- contracts/mocks/ERC165Mock.sol | 7 - contracts/mocks/ERC165StorageMock.sol | 11 - contracts/mocks/ERC1820ImplementerMock.sol | 11 - contracts/mocks/ERC20BurnableMock.sol | 16 -- contracts/mocks/ERC20CappedMock.sol | 13 - contracts/mocks/ERC20DecimalsMock.sol | 25 -- contracts/mocks/ERC20Mock.sol | 25 +- contracts/mocks/ERC20PausableMock.sol | 33 --- contracts/mocks/ERC20PermitMock.sol | 20 -- contracts/mocks/ERC20SnapshotMock.sol | 28 -- contracts/mocks/ERC20VotesCompMock.sol | 21 -- contracts/mocks/ERC20VotesMock.sol | 21 -- contracts/mocks/ERC20WrapperMock.sol | 17 -- contracts/mocks/ERC4626Mock.sol | 40 +-- contracts/mocks/ERC721BurnableMock.sol | 25 -- contracts/mocks/ERC721EnumerableMock.sol | 47 --- contracts/mocks/ERC721Mock.sol | 37 --- contracts/mocks/ERC721PausableMock.sol | 41 --- contracts/mocks/ERC721RoyaltyMock.sol | 29 -- contracts/mocks/ERC721URIStorageMock.sol | 51 ---- contracts/mocks/ERC721VotesMock.sol | 25 -- contracts/mocks/ERC777Mock.sol | 42 --- contracts/mocks/EnumerableMapMock.sol | 221 --------------- contracts/mocks/EnumerableSetMock.sol | 111 -------- contracts/mocks/GovernorCompMock.sol | 31 -- contracts/mocks/GovernorMock.sol | 50 ---- contracts/mocks/GovernorVoteMock.sol | 31 -- contracts/mocks/MathMock.sol | 43 --- contracts/mocks/MerkleProofWrapper.sol | 57 ---- contracts/mocks/MulticallTest.sol | 4 +- contracts/mocks/MulticallTokenMock.sol | 10 - contracts/mocks/Ownable2StepMock.sol | 7 - contracts/mocks/OwnableMock.sol | 7 - contracts/mocks/SafeCastMock.sol | 267 ------------------ contracts/mocks/SafeERC20Helper.sol | 182 ------------ contracts/mocks/SafeMathMemoryCheck.sol | 72 +++++ contracts/mocks/SafeMathMock.sol | 126 --------- contracts/mocks/SignatureCheckerMock.sol | 13 - contracts/mocks/SignedMathMock.sol | 23 -- contracts/mocks/SignedSafeMathMock.sol | 23 -- contracts/mocks/StringsMock.sol | 31 -- contracts/mocks/VotesMock.sol | 12 +- .../mocks/governance/GovernorCompMock.sol | 20 ++ .../GovernorCompatibilityBravoMock.sol | 43 +-- contracts/mocks/governance/GovernorMock.sol | 28 ++ .../GovernorPreventLateQuorumMock.sol | 24 +- .../GovernorTimelockCompoundMock.sol | 37 +-- .../GovernorTimelockControlMock.sol | 37 +-- .../mocks/governance/GovernorVoteMock.sol | 20 ++ .../GovernorWithParamsMock.sol | 17 +- contracts/mocks/{ => proxy}/BadBeacon.sol | 0 .../{ => proxy}/ClashingImplementation.sol | 0 .../mocks/{UUPS => proxy}/UUPSLegacy.sol | 0 .../{UUPS => proxy}/UUPSUpgradeableMock.sol | 16 +- .../mocks/{ => token}/ERC1155ReceiverMock.sol | 4 +- contracts/mocks/token/ERC20DecimalsMock.sol | 17 ++ .../mocks/{ => token}/ERC20FlashMintMock.sol | 21 +- contracts/mocks/token/ERC20MulticallMock.sol | 8 + contracts/mocks/token/ERC20NoReturnMock.sol | 21 ++ .../mocks/token/ERC20PermitNoRevertMock.sol | 38 +++ .../mocks/token/ERC20ReturnFalseMock copy.sol | 27 ++ contracts/mocks/token/ERC20ReturnTrueMock.sol | 27 ++ contracts/mocks/token/ERC4626DecimalsMock.sol | 33 +++ .../ERC721ConsecutiveEnumerableMock.sol | 4 +- .../{ => token}/ERC721ConsecutiveMock.sol | 35 +-- .../mocks/{ => token}/ERC721ReceiverMock.sol | 2 +- .../mocks/token/ERC721URIStorageMock.sol | 17 ++ contracts/mocks/token/ERC777Mock.sol | 13 + .../{ => token}/ERC777SenderRecipientMock.sol | 12 +- hardhat.config.js | 22 +- package-lock.json | 176 +++++++++++- package.json | 1 + scripts/generate/run.js | 8 - scripts/generate/templates/CheckpointsMock.js | 80 ------ .../generate/templates/EnumerableMapMock.js | 66 ----- .../generate/templates/EnumerableSetMock.js | 56 ---- scripts/generate/templates/SafeCast.js | 0 scripts/generate/templates/SafeCastMock.js | 50 ---- test/access/AccessControl.behavior.js | 9 +- test/access/AccessControl.test.js | 6 +- test/access/AccessControlCrossChain.test.js | 10 +- test/access/AccessControlEnumerable.test.js | 6 +- test/access/Ownable.test.js | 2 +- test/access/Ownable2Step.test.js | 2 +- test/finance/PaymentSplitter.test.js | 5 +- test/finance/VestingWallet.behavior.js | 12 +- test/finance/VestingWallet.test.js | 6 +- test/governance/Governor.test.js | 29 +- test/governance/TimelockController.test.js | 12 +- .../GovernorCompatibilityBravo.test.js | 10 +- .../extensions/GovernorComp.test.js | 8 +- .../extensions/GovernorERC721.test.js | 10 +- .../GovernorPreventLateQuorum.test.js | 13 +- .../GovernorTimelockCompound.test.js | 16 +- .../GovernorTimelockControl.test.js | 13 +- .../GovernorVotesQuorumFraction.test.js | 17 +- .../extensions/GovernorWithParams.test.js | 8 +- test/governance/utils/Votes.behavior.js | 35 ++- test/governance/utils/Votes.test.js | 14 +- test/helpers/chainid.js | 10 + test/helpers/eip712.js | 32 ++- test/helpers/governance.js | 2 +- test/helpers/map-values.js | 7 + test/metatx/ERC2771Context.test.js | 3 +- test/metatx/MinimalForwarder.test.js | 4 +- test/proxy/Clones.test.js | 36 +-- test/proxy/utils/UUPSUpgradeable.test.js | 4 +- test/token/ERC1155/ERC1155.behavior.js | 16 +- test/token/ERC1155/ERC1155.test.js | 42 +-- .../extensions/ERC1155Burnable.test.js | 8 +- .../extensions/ERC1155Pausable.test.js | 16 +- .../ERC1155/extensions/ERC1155Supply.test.js | 16 +- .../extensions/ERC1155URIStorage.test.js | 16 +- .../token/ERC1155/utils/ERC1155Holder.test.js | 6 +- test/token/ERC20/ERC20.test.js | 27 +- .../ERC20/extensions/ERC20Burnable.test.js | 5 +- .../ERC20/extensions/ERC20Capped.behavior.js | 14 +- .../ERC20/extensions/ERC20Capped.test.js | 14 +- .../ERC20/extensions/ERC20FlashMint.test.js | 13 +- .../ERC20/extensions/ERC20Pausable.test.js | 41 +-- .../ERC20/extensions/ERC20Snapshot.test.js | 29 +- .../token/ERC20/extensions/ERC20Votes.test.js | 39 ++- .../ERC20/extensions/ERC20VotesComp.test.js | 37 ++- .../ERC20/extensions/ERC20Wrapper.test.js | 16 +- test/token/ERC20/extensions/ERC4626.t.sol | 6 +- test/token/ERC20/extensions/ERC4626.test.js | 36 +-- .../extensions/draft-ERC20Permit.test.js | 13 +- test/token/ERC20/utils/SafeERC20.test.js | 77 +++-- test/token/ERC20/utils/TokenTimelock.test.js | 6 +- test/token/ERC721/ERC721.behavior.js | 60 ++-- test/token/ERC721/ERC721.test.js | 4 +- test/token/ERC721/ERC721Enumerable.test.js | 4 +- .../ERC721/extensions/ERC721Burnable.test.js | 11 +- .../extensions/ERC721Consecutive.test.js | 34 +-- .../ERC721/extensions/ERC721Pausable.test.js | 17 +- .../ERC721/extensions/ERC721Royalty.test.js | 17 +- .../extensions/ERC721URIStorage.test.js | 24 +- .../ERC721/extensions/ERC721Votes.test.js | 33 +-- test/token/ERC721/utils/ERC721Holder.test.js | 10 +- test/token/ERC777/ERC777.behavior.js | 10 +- test/token/ERC777/ERC777.test.js | 35 +-- test/token/common/ERC2981.behavior.js | 28 +- test/utils/Address.test.js | 259 ++++++++--------- test/utils/Base64.test.js | 12 +- test/utils/Checkpoints.test.js | 131 +++++---- test/utils/Counters.test.js | 56 ++-- test/utils/Create2.test.js | 74 +++-- test/utils/Multicall.test.js | 10 +- test/utils/Strings.test.js | 46 +-- test/utils/cryptography/ECDSA.test.js | 118 ++++++-- test/utils/cryptography/EIP712.test.js | 36 ++- test/utils/cryptography/MerkleProof.test.js | 45 +-- .../cryptography/SignatureChecker.test.js | 18 +- test/utils/introspection/ERC165.test.js | 4 +- .../utils/introspection/ERC165Checker.test.js | 98 +++---- .../utils/introspection/ERC165Storage.test.js | 8 +- .../introspection/ERC1820Implementer.test.js | 6 +- test/utils/math/Math.test.js | 245 ++++++++-------- test/utils/math/SafeCast.test.js | 52 ++-- test/utils/math/SafeMath.test.js | 122 ++++---- test/utils/math/SignedMath.test.js | 16 +- test/utils/math/SignedSafeMath.test.js | 38 +-- test/utils/structs/BitMap.test.js | 146 +++++----- test/utils/structs/DoubleEndedQueue.test.js | 50 ++-- test/utils/structs/EnumerableMap.behavior.js | 110 ++++---- test/utils/structs/EnumerableMap.test.js | 105 +++++-- test/utils/structs/EnumerableSet.behavior.js | 78 ++--- test/utils/structs/EnumerableSet.test.js | 85 ++++-- 190 files changed, 2297 insertions(+), 4311 deletions(-) delete mode 100644 contracts/mocks/AccessControlEnumerableMock.sol delete mode 100644 contracts/mocks/AccessControlMock.sol delete mode 100644 contracts/mocks/AddressImpl.sol delete mode 100644 contracts/mocks/Base64Mock.sol delete mode 100644 contracts/mocks/BitmapMock.sol delete mode 100644 contracts/mocks/CheckpointsMock.sol delete mode 100644 contracts/mocks/ClonesMock.sol delete mode 100644 contracts/mocks/CountersImpl.sol delete mode 100644 contracts/mocks/Create2Impl.sol delete mode 100644 contracts/mocks/DoubleEndedQueueMock.sol delete mode 100644 contracts/mocks/ECDSAMock.sol rename contracts/mocks/{EIP712External.sol => EIP712Verifier.sol} (63%) delete mode 100644 contracts/mocks/ERC1155BurnableMock.sol delete mode 100644 contracts/mocks/ERC1155Mock.sol delete mode 100644 contracts/mocks/ERC1155PausableMock.sol delete mode 100644 contracts/mocks/ERC1155SupplyMock.sol delete mode 100644 contracts/mocks/ERC1155URIStorageMock.sol delete mode 100644 contracts/mocks/ERC165/ERC165InterfacesSupported.sol delete mode 100644 contracts/mocks/ERC165CheckerMock.sol delete mode 100644 contracts/mocks/ERC165Mock.sol delete mode 100644 contracts/mocks/ERC165StorageMock.sol delete mode 100644 contracts/mocks/ERC1820ImplementerMock.sol delete mode 100644 contracts/mocks/ERC20BurnableMock.sol delete mode 100644 contracts/mocks/ERC20CappedMock.sol delete mode 100644 contracts/mocks/ERC20DecimalsMock.sol delete mode 100644 contracts/mocks/ERC20PausableMock.sol delete mode 100644 contracts/mocks/ERC20PermitMock.sol delete mode 100644 contracts/mocks/ERC20SnapshotMock.sol delete mode 100644 contracts/mocks/ERC20VotesCompMock.sol delete mode 100644 contracts/mocks/ERC20VotesMock.sol delete mode 100644 contracts/mocks/ERC20WrapperMock.sol delete mode 100644 contracts/mocks/ERC721BurnableMock.sol delete mode 100644 contracts/mocks/ERC721EnumerableMock.sol delete mode 100644 contracts/mocks/ERC721Mock.sol delete mode 100644 contracts/mocks/ERC721PausableMock.sol delete mode 100644 contracts/mocks/ERC721RoyaltyMock.sol delete mode 100644 contracts/mocks/ERC721URIStorageMock.sol delete mode 100644 contracts/mocks/ERC721VotesMock.sol delete mode 100644 contracts/mocks/ERC777Mock.sol delete mode 100644 contracts/mocks/EnumerableMapMock.sol delete mode 100644 contracts/mocks/EnumerableSetMock.sol delete mode 100644 contracts/mocks/GovernorCompMock.sol delete mode 100644 contracts/mocks/GovernorMock.sol delete mode 100644 contracts/mocks/GovernorVoteMock.sol delete mode 100644 contracts/mocks/MathMock.sol delete mode 100644 contracts/mocks/MerkleProofWrapper.sol delete mode 100644 contracts/mocks/MulticallTokenMock.sol delete mode 100644 contracts/mocks/Ownable2StepMock.sol delete mode 100644 contracts/mocks/OwnableMock.sol delete mode 100644 contracts/mocks/SafeCastMock.sol delete mode 100644 contracts/mocks/SafeERC20Helper.sol create mode 100644 contracts/mocks/SafeMathMemoryCheck.sol delete mode 100644 contracts/mocks/SafeMathMock.sol delete mode 100644 contracts/mocks/SignatureCheckerMock.sol delete mode 100644 contracts/mocks/SignedMathMock.sol delete mode 100644 contracts/mocks/SignedSafeMathMock.sol delete mode 100644 contracts/mocks/StringsMock.sol create mode 100644 contracts/mocks/governance/GovernorCompMock.sol rename contracts/mocks/{ => governance}/GovernorCompatibilityBravoMock.sol (71%) create mode 100644 contracts/mocks/governance/GovernorMock.sol rename contracts/mocks/{ => governance}/GovernorPreventLateQuorumMock.sol (61%) rename contracts/mocks/{ => governance}/GovernorTimelockCompoundMock.sol (62%) rename contracts/mocks/{ => governance}/GovernorTimelockControlMock.sol (62%) create mode 100644 contracts/mocks/governance/GovernorVoteMock.sol rename contracts/mocks/{ => governance}/GovernorWithParamsMock.sol (72%) rename contracts/mocks/{ => proxy}/BadBeacon.sol (100%) rename contracts/mocks/{ => proxy}/ClashingImplementation.sol (100%) rename contracts/mocks/{UUPS => proxy}/UUPSLegacy.sol (100%) rename contracts/mocks/{UUPS => proxy}/UUPSUpgradeableMock.sol (63%) rename contracts/mocks/{ => token}/ERC1155ReceiverMock.sol (93%) create mode 100644 contracts/mocks/token/ERC20DecimalsMock.sol rename contracts/mocks/{ => token}/ERC20FlashMintMock.sol (52%) create mode 100644 contracts/mocks/token/ERC20MulticallMock.sol create mode 100644 contracts/mocks/token/ERC20NoReturnMock.sol create mode 100644 contracts/mocks/token/ERC20PermitNoRevertMock.sol create mode 100644 contracts/mocks/token/ERC20ReturnFalseMock copy.sol create mode 100644 contracts/mocks/token/ERC20ReturnTrueMock.sol create mode 100644 contracts/mocks/token/ERC4626DecimalsMock.sol rename contracts/mocks/{ => token}/ERC721ConsecutiveEnumerableMock.sol (92%) rename contracts/mocks/{ => token}/ERC721ConsecutiveMock.sol (64%) rename contracts/mocks/{ => token}/ERC721ReceiverMock.sol (95%) create mode 100644 contracts/mocks/token/ERC721URIStorageMock.sol create mode 100644 contracts/mocks/token/ERC777Mock.sol rename contracts/mocks/{ => token}/ERC777SenderRecipientMock.sol (93%) delete mode 100755 scripts/generate/templates/CheckpointsMock.js delete mode 100755 scripts/generate/templates/EnumerableMapMock.js delete mode 100755 scripts/generate/templates/EnumerableSetMock.js mode change 100755 => 100644 scripts/generate/templates/SafeCast.js delete mode 100755 scripts/generate/templates/SafeCastMock.js create mode 100644 test/helpers/chainid.js create mode 100644 test/helpers/map-values.js diff --git a/.gitignore b/.gitignore index 2f5220de1..9350b262e 100644 --- a/.gitignore +++ b/.gitignore @@ -54,6 +54,9 @@ allFiredEvents .coverage_cache .coverage_contracts +# hardat-exposed +contracts-exposed + # Hardhat /cache /artifacts diff --git a/contracts/mocks/AccessControlCrossChainMock.sol b/contracts/mocks/AccessControlCrossChainMock.sol index ffa385c65..cd4c3a5d9 100644 --- a/contracts/mocks/AccessControlCrossChainMock.sol +++ b/contracts/mocks/AccessControlCrossChainMock.sol @@ -5,18 +5,4 @@ pragma solidity ^0.8.4; import "../access/AccessControlCrossChain.sol"; import "../crosschain/arbitrum/CrossChainEnabledArbitrumL2.sol"; -contract AccessControlCrossChainMock is AccessControlCrossChain, CrossChainEnabledArbitrumL2 { - constructor() { - _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); - } - - function setRoleAdmin(bytes32 roleId, bytes32 adminRoleId) public { - _setRoleAdmin(roleId, adminRoleId); - } - - function senderProtected(bytes32 roleId) public onlyRole(roleId) {} - - function crossChainRoleAlias(bytes32 role) public pure returns (bytes32) { - return _crossChainRoleAlias(role); - } -} +contract AccessControlCrossChainMock is AccessControlCrossChain, CrossChainEnabledArbitrumL2 {} diff --git a/contracts/mocks/AccessControlEnumerableMock.sol b/contracts/mocks/AccessControlEnumerableMock.sol deleted file mode 100644 index 7b15e3602..000000000 --- a/contracts/mocks/AccessControlEnumerableMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../access/AccessControlEnumerable.sol"; - -contract AccessControlEnumerableMock is AccessControlEnumerable { - constructor() { - _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); - } - - function setRoleAdmin(bytes32 roleId, bytes32 adminRoleId) public { - _setRoleAdmin(roleId, adminRoleId); - } - - function senderProtected(bytes32 roleId) public onlyRole(roleId) {} -} diff --git a/contracts/mocks/AccessControlMock.sol b/contracts/mocks/AccessControlMock.sol deleted file mode 100644 index 86f51477e..000000000 --- a/contracts/mocks/AccessControlMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../access/AccessControl.sol"; - -contract AccessControlMock is AccessControl { - constructor() { - _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); - } - - function setRoleAdmin(bytes32 roleId, bytes32 adminRoleId) public { - _setRoleAdmin(roleId, adminRoleId); - } - - function senderProtected(bytes32 roleId) public onlyRole(roleId) {} -} diff --git a/contracts/mocks/AddressImpl.sol b/contracts/mocks/AddressImpl.sol deleted file mode 100644 index b06bec372..000000000 --- a/contracts/mocks/AddressImpl.sol +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Address.sol"; - -contract AddressImpl { - string public sharedAnswer; - - event CallReturnValue(string data); - - function isContract(address account) external view returns (bool) { - return Address.isContract(account); - } - - function sendValue(address payable receiver, uint256 amount) external { - Address.sendValue(receiver, amount); - } - - function functionCall(address target, bytes calldata data) external { - bytes memory returnData = Address.functionCall(target, data); - emit CallReturnValue(abi.decode(returnData, (string))); - } - - function functionCallWithValue(address target, bytes calldata data, uint256 value) external payable { - bytes memory returnData = Address.functionCallWithValue(target, data, value); - emit CallReturnValue(abi.decode(returnData, (string))); - } - - function functionStaticCall(address target, bytes calldata data) external { - bytes memory returnData = Address.functionStaticCall(target, data); - emit CallReturnValue(abi.decode(returnData, (string))); - } - - function functionDelegateCall(address target, bytes calldata data) external { - bytes memory returnData = Address.functionDelegateCall(target, data); - emit CallReturnValue(abi.decode(returnData, (string))); - } - - // sendValue's tests require the contract to hold Ether - receive() external payable {} -} diff --git a/contracts/mocks/Base64Mock.sol b/contracts/mocks/Base64Mock.sol deleted file mode 100644 index b255487bc..000000000 --- a/contracts/mocks/Base64Mock.sol +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Base64.sol"; - -contract Base64Mock { - function encode(bytes memory value) external pure returns (string memory) { - return Base64.encode(value); - } -} diff --git a/contracts/mocks/BitmapMock.sol b/contracts/mocks/BitmapMock.sol deleted file mode 100644 index ccf8486f5..000000000 --- a/contracts/mocks/BitmapMock.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/structs/BitMaps.sol"; - -contract BitMapMock { - using BitMaps for BitMaps.BitMap; - - BitMaps.BitMap private _bitmap; - - function get(uint256 index) public view returns (bool) { - return _bitmap.get(index); - } - - function setTo(uint256 index, bool value) public { - _bitmap.setTo(index, value); - } - - function set(uint256 index) public { - _bitmap.set(index); - } - - function unset(uint256 index) public { - _bitmap.unset(index); - } -} diff --git a/contracts/mocks/CallReceiverMock.sol b/contracts/mocks/CallReceiverMock.sol index 926db68bf..344a1054b 100644 --- a/contracts/mocks/CallReceiverMock.sol +++ b/contracts/mocks/CallReceiverMock.sol @@ -3,8 +3,6 @@ pragma solidity ^0.8.0; contract CallReceiverMock { - string public sharedAnswer; - event MockFunctionCalled(); event MockFunctionCalledWithArgs(uint256 a, uint256 b); @@ -50,8 +48,10 @@ contract CallReceiverMock { } } - function mockFunctionWritesStorage() public returns (string memory) { - sharedAnswer = "42"; + function mockFunctionWritesStorage(bytes32 slot, bytes32 value) public returns (string memory) { + assembly { + sstore(slot, value) + } return "0x1234"; } } diff --git a/contracts/mocks/CheckpointsMock.sol b/contracts/mocks/CheckpointsMock.sol deleted file mode 100644 index 874a1d1f2..000000000 --- a/contracts/mocks/CheckpointsMock.sol +++ /dev/null @@ -1,96 +0,0 @@ -// SPDX-License-Identifier: MIT -// This file was procedurally generated from scripts/generate/templates/CheckpointsMock.js. - -pragma solidity ^0.8.0; - -import "../utils/Checkpoints.sol"; - -contract CheckpointsMock { - using Checkpoints for Checkpoints.History; - - Checkpoints.History private _totalCheckpoints; - - function latest() public view returns (uint256) { - return _totalCheckpoints.latest(); - } - - function latestCheckpoint() public view returns (bool, uint256, uint256) { - return _totalCheckpoints.latestCheckpoint(); - } - - function length() public view returns (uint256) { - return _totalCheckpoints.length(); - } - - function push(uint256 value) public returns (uint256, uint256) { - return _totalCheckpoints.push(value); - } - - function getAtBlock(uint256 blockNumber) public view returns (uint256) { - return _totalCheckpoints.getAtBlock(blockNumber); - } - - function getAtProbablyRecentBlock(uint256 blockNumber) public view returns (uint256) { - return _totalCheckpoints.getAtProbablyRecentBlock(blockNumber); - } -} - -contract Checkpoints224Mock { - using Checkpoints for Checkpoints.Trace224; - - Checkpoints.Trace224 private _totalCheckpoints; - - function latest() public view returns (uint224) { - return _totalCheckpoints.latest(); - } - - function latestCheckpoint() public view returns (bool, uint32, uint224) { - return _totalCheckpoints.latestCheckpoint(); - } - - function length() public view returns (uint256) { - return _totalCheckpoints.length(); - } - - function push(uint32 key, uint224 value) public returns (uint224, uint224) { - return _totalCheckpoints.push(key, value); - } - - function lowerLookup(uint32 key) public view returns (uint224) { - return _totalCheckpoints.lowerLookup(key); - } - - function upperLookup(uint32 key) public view returns (uint224) { - return _totalCheckpoints.upperLookup(key); - } -} - -contract Checkpoints160Mock { - using Checkpoints for Checkpoints.Trace160; - - Checkpoints.Trace160 private _totalCheckpoints; - - function latest() public view returns (uint160) { - return _totalCheckpoints.latest(); - } - - function latestCheckpoint() public view returns (bool, uint96, uint160) { - return _totalCheckpoints.latestCheckpoint(); - } - - function length() public view returns (uint256) { - return _totalCheckpoints.length(); - } - - function push(uint96 key, uint160 value) public returns (uint160, uint160) { - return _totalCheckpoints.push(key, value); - } - - function lowerLookup(uint96 key) public view returns (uint160) { - return _totalCheckpoints.lowerLookup(key); - } - - function upperLookup(uint96 key) public view returns (uint160) { - return _totalCheckpoints.upperLookup(key); - } -} diff --git a/contracts/mocks/ClonesMock.sol b/contracts/mocks/ClonesMock.sol deleted file mode 100644 index c65d30cc3..000000000 --- a/contracts/mocks/ClonesMock.sol +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../proxy/Clones.sol"; -import "../utils/Address.sol"; - -contract ClonesMock { - using Address for address; - using Clones for address; - - event NewInstance(address instance); - - function clone(address implementation, bytes calldata initdata) public payable { - _initAndEmit(implementation.clone(), initdata); - } - - function cloneDeterministic(address implementation, bytes32 salt, bytes calldata initdata) public payable { - _initAndEmit(implementation.cloneDeterministic(salt), initdata); - } - - function predictDeterministicAddress(address implementation, bytes32 salt) public view returns (address predicted) { - return implementation.predictDeterministicAddress(salt); - } - - function _initAndEmit(address instance, bytes memory initdata) private { - if (initdata.length > 0) { - instance.functionCallWithValue(initdata, msg.value); - } - emit NewInstance(instance); - } -} diff --git a/contracts/mocks/CountersImpl.sol b/contracts/mocks/CountersImpl.sol deleted file mode 100644 index 651b50baf..000000000 --- a/contracts/mocks/CountersImpl.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Counters.sol"; - -contract CountersImpl { - using Counters for Counters.Counter; - - Counters.Counter private _counter; - - function current() public view returns (uint256) { - return _counter.current(); - } - - function increment() public { - _counter.increment(); - } - - function decrement() public { - _counter.decrement(); - } - - function reset() public { - _counter.reset(); - } -} diff --git a/contracts/mocks/Create2Impl.sol b/contracts/mocks/Create2Impl.sol deleted file mode 100644 index 6b2f4b712..000000000 --- a/contracts/mocks/Create2Impl.sol +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Create2.sol"; -import "../utils/introspection/ERC1820Implementer.sol"; - -contract Create2Impl { - function deploy(uint256 value, bytes32 salt, bytes memory code) public { - Create2.deploy(value, salt, code); - } - - function deployERC1820Implementer(uint256 value, bytes32 salt) public { - Create2.deploy(value, salt, type(ERC1820Implementer).creationCode); - } - - function computeAddress(bytes32 salt, bytes32 codeHash) public view returns (address) { - return Create2.computeAddress(salt, codeHash); - } - - function computeAddressWithDeployer( - bytes32 salt, - bytes32 codeHash, - address deployer - ) public pure returns (address) { - return Create2.computeAddress(salt, codeHash, deployer); - } - - receive() external payable {} -} diff --git a/contracts/mocks/DoubleEndedQueueMock.sol b/contracts/mocks/DoubleEndedQueueMock.sol deleted file mode 100644 index a9436b005..000000000 --- a/contracts/mocks/DoubleEndedQueueMock.sol +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/structs/DoubleEndedQueue.sol"; - -// Bytes32Deque -contract Bytes32DequeMock { - using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque; - - event OperationResult(bytes32 value); - - DoubleEndedQueue.Bytes32Deque private _vector; - - function pushBack(bytes32 value) public { - _vector.pushBack(value); - } - - function pushFront(bytes32 value) public { - _vector.pushFront(value); - } - - function popFront() public returns (bytes32) { - bytes32 value = _vector.popFront(); - emit OperationResult(value); - return value; - } - - function popBack() public returns (bytes32) { - bytes32 value = _vector.popBack(); - emit OperationResult(value); - return value; - } - - function front() public view returns (bytes32) { - return _vector.front(); - } - - function back() public view returns (bytes32) { - return _vector.back(); - } - - function at(uint256 i) public view returns (bytes32) { - return _vector.at(i); - } - - function clear() public { - _vector.clear(); - } - - function length() public view returns (uint256) { - return _vector.length(); - } - - function empty() public view returns (bool) { - return _vector.empty(); - } -} diff --git a/contracts/mocks/ECDSAMock.sol b/contracts/mocks/ECDSAMock.sol deleted file mode 100644 index cfc37d26e..000000000 --- a/contracts/mocks/ECDSAMock.sol +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/cryptography/ECDSA.sol"; - -contract ECDSAMock { - using ECDSA for bytes32; - using ECDSA for bytes; - - function recover(bytes32 hash, bytes memory signature) public pure returns (address) { - return hash.recover(signature); - } - - // solhint-disable-next-line func-name-mixedcase - function recover_v_r_s(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (address) { - return hash.recover(v, r, s); - } - - // solhint-disable-next-line func-name-mixedcase - function recover_r_vs(bytes32 hash, bytes32 r, bytes32 vs) public pure returns (address) { - return hash.recover(r, vs); - } - - function toEthSignedMessageHash(bytes32 hash) public pure returns (bytes32) { - return hash.toEthSignedMessageHash(); - } - - function toEthSignedMessageHash(bytes memory s) public pure returns (bytes32) { - return s.toEthSignedMessageHash(); - } -} diff --git a/contracts/mocks/EIP712External.sol b/contracts/mocks/EIP712Verifier.sol similarity index 63% rename from contracts/mocks/EIP712External.sol rename to contracts/mocks/EIP712Verifier.sol index bc5b1269f..dcef9efbb 100644 --- a/contracts/mocks/EIP712External.sol +++ b/contracts/mocks/EIP712Verifier.sol @@ -5,13 +5,7 @@ pragma solidity ^0.8.0; import "../utils/cryptography/ECDSA.sol"; import "../utils/cryptography/EIP712.sol"; -contract EIP712External is EIP712 { - constructor(string memory name, string memory version) EIP712(name, version) {} - - function domainSeparator() external view returns (bytes32) { - return _domainSeparatorV4(); - } - +abstract contract EIP712Verifier is EIP712 { function verify(bytes memory signature, address signer, address mailTo, string memory mailContents) external view { bytes32 digest = _hashTypedDataV4( keccak256(abi.encode(keccak256("Mail(address to,string contents)"), mailTo, keccak256(bytes(mailContents)))) @@ -19,8 +13,4 @@ contract EIP712External is EIP712 { address recoveredSigner = ECDSA.recover(digest, signature); require(recoveredSigner == signer); } - - function getChainId() external view returns (uint256) { - return block.chainid; - } } diff --git a/contracts/mocks/ERC1155BurnableMock.sol b/contracts/mocks/ERC1155BurnableMock.sol deleted file mode 100644 index 3334523cf..000000000 --- a/contracts/mocks/ERC1155BurnableMock.sol +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC1155/extensions/ERC1155Burnable.sol"; - -contract ERC1155BurnableMock is ERC1155Burnable { - constructor(string memory uri) ERC1155(uri) {} - - function mint(address to, uint256 id, uint256 value, bytes memory data) public { - _mint(to, id, value, data); - } -} diff --git a/contracts/mocks/ERC1155Mock.sol b/contracts/mocks/ERC1155Mock.sol deleted file mode 100644 index 6bfc86cea..000000000 --- a/contracts/mocks/ERC1155Mock.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC1155/ERC1155.sol"; - -/** - * @title ERC1155Mock - * This mock just publicizes internal functions for testing purposes - */ -contract ERC1155Mock is ERC1155 { - constructor(string memory uri) ERC1155(uri) {} - - function setURI(string memory newuri) public { - _setURI(newuri); - } - - function mint(address to, uint256 id, uint256 value, bytes memory data) public { - _mint(to, id, value, data); - } - - function mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) public { - _mintBatch(to, ids, values, data); - } - - function burn(address owner, uint256 id, uint256 value) public { - _burn(owner, id, value); - } - - function burnBatch(address owner, uint256[] memory ids, uint256[] memory values) public { - _burnBatch(owner, ids, values); - } -} diff --git a/contracts/mocks/ERC1155PausableMock.sol b/contracts/mocks/ERC1155PausableMock.sol deleted file mode 100644 index cd068234f..000000000 --- a/contracts/mocks/ERC1155PausableMock.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./ERC1155Mock.sol"; -import "../token/ERC1155/extensions/ERC1155Pausable.sol"; - -contract ERC1155PausableMock is ERC1155Mock, ERC1155Pausable { - constructor(string memory uri) ERC1155Mock(uri) {} - - function pause() external { - _pause(); - } - - function unpause() external { - _unpause(); - } - - function _beforeTokenTransfer( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal override(ERC1155, ERC1155Pausable) { - super._beforeTokenTransfer(operator, from, to, ids, amounts, data); - } -} diff --git a/contracts/mocks/ERC1155SupplyMock.sol b/contracts/mocks/ERC1155SupplyMock.sol deleted file mode 100644 index 9c0cd7b63..000000000 --- a/contracts/mocks/ERC1155SupplyMock.sol +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./ERC1155Mock.sol"; -import "../token/ERC1155/extensions/ERC1155Supply.sol"; - -contract ERC1155SupplyMock is ERC1155Mock, ERC1155Supply { - constructor(string memory uri) ERC1155Mock(uri) {} - - function _beforeTokenTransfer( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal override(ERC1155, ERC1155Supply) { - super._beforeTokenTransfer(operator, from, to, ids, amounts, data); - } -} diff --git a/contracts/mocks/ERC1155URIStorageMock.sol b/contracts/mocks/ERC1155URIStorageMock.sol deleted file mode 100644 index ba12b285d..000000000 --- a/contracts/mocks/ERC1155URIStorageMock.sol +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./ERC1155Mock.sol"; -import "../token/ERC1155/extensions/ERC1155URIStorage.sol"; - -contract ERC1155URIStorageMock is ERC1155Mock, ERC1155URIStorage { - constructor(string memory _uri) ERC1155Mock(_uri) {} - - function uri(uint256 tokenId) public view override(ERC1155, ERC1155URIStorage) returns (string memory) { - return ERC1155URIStorage.uri(tokenId); - } - - function setURI(uint256 tokenId, string memory _tokenURI) public { - _setURI(tokenId, _tokenURI); - } - - function setBaseURI(string memory baseURI) public { - _setBaseURI(baseURI); - } -} diff --git a/contracts/mocks/ERC165/ERC165InterfacesSupported.sol b/contracts/mocks/ERC165/ERC165InterfacesSupported.sol deleted file mode 100644 index 7a5e5bc67..000000000 --- a/contracts/mocks/ERC165/ERC165InterfacesSupported.sol +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../../utils/introspection/IERC165.sol"; - -/** - * https://eips.ethereum.org/EIPS/eip-214#specification - * From the specification: - * > Any attempts to make state-changing operations inside an execution instance with STATIC set to true will instead - * throw an exception. - * > These operations include [...], LOG0, LOG1, LOG2, [...] - * - * therefore, because this contract is staticcall'd we need to not emit events (which is how solidity-coverage works) - * solidity-coverage ignores the /mocks folder, so we duplicate its implementation here to avoid instrumenting it - */ -contract SupportsInterfaceWithLookupMock is IERC165 { - /* - * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 - */ - bytes4 public constant INTERFACE_ID_ERC165 = 0x01ffc9a7; - - /** - * @dev A mapping of interface id to whether or not it's supported. - */ - mapping(bytes4 => bool) private _supportedInterfaces; - - /** - * @dev A contract implementing SupportsInterfaceWithLookup - * implement ERC165 itself. - */ - constructor() { - _registerInterface(INTERFACE_ID_ERC165); - } - - /** - * @dev Implement supportsInterface(bytes4) using a lookup table. - */ - function supportsInterface(bytes4 interfaceId) public view override returns (bool) { - return _supportedInterfaces[interfaceId]; - } - - /** - * @dev Private method for registering an interface. - */ - function _registerInterface(bytes4 interfaceId) internal { - require(interfaceId != 0xffffffff, "ERC165InterfacesSupported: invalid interface id"); - _supportedInterfaces[interfaceId] = true; - } -} - -contract ERC165InterfacesSupported is SupportsInterfaceWithLookupMock { - constructor(bytes4[] memory interfaceIds) { - for (uint256 i = 0; i < interfaceIds.length; i++) { - _registerInterface(interfaceIds[i]); - } - } -} diff --git a/contracts/mocks/ERC165CheckerMock.sol b/contracts/mocks/ERC165CheckerMock.sol deleted file mode 100644 index 9ff7e7df6..000000000 --- a/contracts/mocks/ERC165CheckerMock.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/introspection/ERC165Checker.sol"; - -contract ERC165CheckerMock { - using ERC165Checker for address; - - function supportsERC165(address account) public view returns (bool) { - return account.supportsERC165(); - } - - function supportsInterface(address account, bytes4 interfaceId) public view returns (bool) { - return account.supportsInterface(interfaceId); - } - - function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) public view returns (bool) { - return account.supportsAllInterfaces(interfaceIds); - } - - function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) public view returns (bool[] memory) { - return account.getSupportedInterfaces(interfaceIds); - } - - function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) public view returns (bool) { - return account.supportsERC165InterfaceUnchecked(interfaceId); - } -} diff --git a/contracts/mocks/ERC165Mock.sol b/contracts/mocks/ERC165Mock.sol deleted file mode 100644 index c123d0ab2..000000000 --- a/contracts/mocks/ERC165Mock.sol +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/introspection/ERC165.sol"; - -contract ERC165Mock is ERC165 {} diff --git a/contracts/mocks/ERC165StorageMock.sol b/contracts/mocks/ERC165StorageMock.sol deleted file mode 100644 index 4b0bae908..000000000 --- a/contracts/mocks/ERC165StorageMock.sol +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/introspection/ERC165Storage.sol"; - -contract ERC165StorageMock is ERC165Storage { - function registerInterface(bytes4 interfaceId) public { - _registerInterface(interfaceId); - } -} diff --git a/contracts/mocks/ERC1820ImplementerMock.sol b/contracts/mocks/ERC1820ImplementerMock.sol deleted file mode 100644 index a6012d7ff..000000000 --- a/contracts/mocks/ERC1820ImplementerMock.sol +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/introspection/ERC1820Implementer.sol"; - -contract ERC1820ImplementerMock is ERC1820Implementer { - function registerInterfaceForAddress(bytes32 interfaceHash, address account) public { - _registerInterfaceForAddress(interfaceHash, account); - } -} diff --git a/contracts/mocks/ERC20BurnableMock.sol b/contracts/mocks/ERC20BurnableMock.sol deleted file mode 100644 index 0ed6c0c98..000000000 --- a/contracts/mocks/ERC20BurnableMock.sol +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Burnable.sol"; - -contract ERC20BurnableMock is ERC20Burnable { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) ERC20(name, symbol) { - _mint(initialAccount, initialBalance); - } -} diff --git a/contracts/mocks/ERC20CappedMock.sol b/contracts/mocks/ERC20CappedMock.sol deleted file mode 100644 index e69aadfdf..000000000 --- a/contracts/mocks/ERC20CappedMock.sol +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Capped.sol"; - -contract ERC20CappedMock is ERC20Capped { - constructor(string memory name, string memory symbol, uint256 cap) ERC20(name, symbol) ERC20Capped(cap) {} - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } -} diff --git a/contracts/mocks/ERC20DecimalsMock.sol b/contracts/mocks/ERC20DecimalsMock.sol deleted file mode 100644 index 7677e9dd1..000000000 --- a/contracts/mocks/ERC20DecimalsMock.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/ERC20.sol"; - -contract ERC20DecimalsMock is ERC20 { - uint8 private immutable _decimals; - - constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_) { - _decimals = decimals_; - } - - function decimals() public view override returns (uint8) { - return _decimals; - } - - function mint(address account, uint256 amount) public { - _mint(account, amount); - } - - function burn(address account, uint256 amount) public { - _burn(account, amount); - } -} diff --git a/contracts/mocks/ERC20Mock.sol b/contracts/mocks/ERC20Mock.sol index 16ffad19f..cc75923df 100644 --- a/contracts/mocks/ERC20Mock.sol +++ b/contracts/mocks/ERC20Mock.sol @@ -1,33 +1,16 @@ // SPDX-License-Identifier: MIT - pragma solidity ^0.8.0; -import "../token/ERC20/ERC20.sol"; +import {ERC20} from "../token/ERC20/ERC20.sol"; -// mock class using ERC20 contract ERC20Mock is ERC20 { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) payable ERC20(name, symbol) { - _mint(initialAccount, initialBalance); - } + constructor() ERC20("ERC20Mock", "E20M") {} - function mint(address account, uint256 amount) public { + function mint(address account, uint256 amount) external { _mint(account, amount); } - function burn(address account, uint256 amount) public { + function burn(address account, uint256 amount) external { _burn(account, amount); } - - function transferInternal(address from, address to, uint256 value) public { - _transfer(from, to, value); - } - - function approveInternal(address owner, address spender, uint256 value) public { - _approve(owner, spender, value); - } } diff --git a/contracts/mocks/ERC20PausableMock.sol b/contracts/mocks/ERC20PausableMock.sol deleted file mode 100644 index 19160ba6c..000000000 --- a/contracts/mocks/ERC20PausableMock.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Pausable.sol"; - -// mock class using ERC20Pausable -contract ERC20PausableMock is ERC20Pausable { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) ERC20(name, symbol) { - _mint(initialAccount, initialBalance); - } - - function pause() external { - _pause(); - } - - function unpause() external { - _unpause(); - } - - function mint(address to, uint256 amount) public { - _mint(to, amount); - } - - function burn(address from, uint256 amount) public { - _burn(from, amount); - } -} diff --git a/contracts/mocks/ERC20PermitMock.sol b/contracts/mocks/ERC20PermitMock.sol deleted file mode 100644 index 8daa95587..000000000 --- a/contracts/mocks/ERC20PermitMock.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Permit.sol"; - -contract ERC20PermitMock is ERC20Permit { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) payable ERC20(name, symbol) ERC20Permit(name) { - _mint(initialAccount, initialBalance); - } - - function getChainId() external view returns (uint256) { - return block.chainid; - } -} diff --git a/contracts/mocks/ERC20SnapshotMock.sol b/contracts/mocks/ERC20SnapshotMock.sol deleted file mode 100644 index cb3048322..000000000 --- a/contracts/mocks/ERC20SnapshotMock.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Snapshot.sol"; - -contract ERC20SnapshotMock is ERC20Snapshot { - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) ERC20(name, symbol) { - _mint(initialAccount, initialBalance); - } - - function snapshot() public { - _snapshot(); - } - - function mint(address account, uint256 amount) public { - _mint(account, amount); - } - - function burn(address account, uint256 amount) public { - _burn(account, amount); - } -} diff --git a/contracts/mocks/ERC20VotesCompMock.sol b/contracts/mocks/ERC20VotesCompMock.sol deleted file mode 100644 index 171071fd5..000000000 --- a/contracts/mocks/ERC20VotesCompMock.sol +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20VotesComp.sol"; - -contract ERC20VotesCompMock is ERC20VotesComp { - constructor(string memory name, string memory symbol) ERC20(name, symbol) ERC20Permit(name) {} - - function mint(address account, uint256 amount) public { - _mint(account, amount); - } - - function burn(address account, uint256 amount) public { - _burn(account, amount); - } - - function getChainId() external view returns (uint256) { - return block.chainid; - } -} diff --git a/contracts/mocks/ERC20VotesMock.sol b/contracts/mocks/ERC20VotesMock.sol deleted file mode 100644 index 0975e8b9f..000000000 --- a/contracts/mocks/ERC20VotesMock.sol +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Votes.sol"; - -contract ERC20VotesMock is ERC20Votes { - constructor(string memory name, string memory symbol) ERC20(name, symbol) ERC20Permit(name) {} - - function mint(address account, uint256 amount) public { - _mint(account, amount); - } - - function burn(address account, uint256 amount) public { - _burn(account, amount); - } - - function getChainId() external view returns (uint256) { - return block.chainid; - } -} diff --git a/contracts/mocks/ERC20WrapperMock.sol b/contracts/mocks/ERC20WrapperMock.sol deleted file mode 100644 index cf34a7a52..000000000 --- a/contracts/mocks/ERC20WrapperMock.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC20/extensions/ERC20Wrapper.sol"; - -contract ERC20WrapperMock is ERC20Wrapper { - constructor( - IERC20 _underlyingToken, - string memory name, - string memory symbol - ) ERC20(name, symbol) ERC20Wrapper(_underlyingToken) {} - - function recover(address account) public returns (uint256) { - return _recover(account); - } -} diff --git a/contracts/mocks/ERC4626Mock.sol b/contracts/mocks/ERC4626Mock.sol index 9c13346f0..ef2d1a4cb 100644 --- a/contracts/mocks/ERC4626Mock.sol +++ b/contracts/mocks/ERC4626Mock.sol @@ -1,50 +1,16 @@ // SPDX-License-Identifier: MIT - pragma solidity ^0.8.0; import "../token/ERC20/extensions/ERC4626.sol"; contract ERC4626Mock is ERC4626 { - constructor(IERC20Metadata asset, string memory name, string memory symbol) ERC20(name, symbol) ERC4626(asset) {} + constructor(address underlying) ERC20("ERC4626Mock", "E4626M") ERC4626(IERC20(underlying)) {} - function mockMint(address account, uint256 amount) public { + function mint(address account, uint256 amount) external { _mint(account, amount); } - function mockBurn(address account, uint256 amount) public { + function burn(address account, uint256 amount) external { _burn(account, amount); } } - -contract ERC4626DecimalMock is ERC4626Mock { - using Math for uint256; - - uint8 private immutable _decimals; - - constructor( - IERC20Metadata asset, - string memory name, - string memory symbol, - uint8 decimalsOverride - ) ERC4626Mock(asset, name, symbol) { - _decimals = decimalsOverride; - } - - function decimals() public view virtual override returns (uint8) { - return _decimals; - } - - function _initialConvertToShares( - uint256 assets, - Math.Rounding rounding - ) internal view virtual override returns (uint256 shares) { - return assets.mulDiv(10 ** decimals(), 10 ** super.decimals(), rounding); - } - - function _initialConvertToAssets( - uint256 shares, - Math.Rounding rounding - ) internal view virtual override returns (uint256 assets) { - return shares.mulDiv(10 ** super.decimals(), 10 ** decimals(), rounding); - } -} diff --git a/contracts/mocks/ERC721BurnableMock.sol b/contracts/mocks/ERC721BurnableMock.sol deleted file mode 100644 index ecf427681..000000000 --- a/contracts/mocks/ERC721BurnableMock.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721Burnable.sol"; - -contract ERC721BurnableMock is ERC721Burnable { - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId, bytes memory _data) public { - _safeMint(to, tokenId, _data); - } -} diff --git a/contracts/mocks/ERC721EnumerableMock.sol b/contracts/mocks/ERC721EnumerableMock.sol deleted file mode 100644 index b7ea94ee3..000000000 --- a/contracts/mocks/ERC721EnumerableMock.sol +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721Enumerable.sol"; - -/** - * @title ERC721Mock - * This mock just provides a public safeMint, mint, and burn functions for testing purposes - */ -contract ERC721EnumerableMock is ERC721Enumerable { - string private _baseTokenURI; - - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function _baseURI() internal view override returns (string memory) { - return _baseTokenURI; - } - - function setBaseURI(string calldata newBaseTokenURI) public { - _baseTokenURI = newBaseTokenURI; - } - - function baseURI() public view returns (string memory) { - return _baseURI(); - } - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId, bytes memory _data) public { - _safeMint(to, tokenId, _data); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } -} diff --git a/contracts/mocks/ERC721Mock.sol b/contracts/mocks/ERC721Mock.sol deleted file mode 100644 index a3bc839ae..000000000 --- a/contracts/mocks/ERC721Mock.sol +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/ERC721.sol"; - -/** - * @title ERC721Mock - * This mock just provides a public safeMint, mint, and burn functions for testing purposes - */ -contract ERC721Mock is ERC721 { - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function baseURI() public view returns (string memory) { - return _baseURI(); - } - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId, bytes memory _data) public { - _safeMint(to, tokenId, _data); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } -} diff --git a/contracts/mocks/ERC721PausableMock.sol b/contracts/mocks/ERC721PausableMock.sol deleted file mode 100644 index 753842e90..000000000 --- a/contracts/mocks/ERC721PausableMock.sol +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721Pausable.sol"; - -/** - * @title ERC721PausableMock - * This mock just provides a public mint, burn and exists functions for testing purposes - */ -contract ERC721PausableMock is ERC721Pausable { - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function pause() external { - _pause(); - } - - function unpause() external { - _unpause(); - } - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId, bytes memory _data) public { - _safeMint(to, tokenId, _data); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } -} diff --git a/contracts/mocks/ERC721RoyaltyMock.sol b/contracts/mocks/ERC721RoyaltyMock.sol deleted file mode 100644 index 6f19d5248..000000000 --- a/contracts/mocks/ERC721RoyaltyMock.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721Royalty.sol"; - -contract ERC721RoyaltyMock is ERC721Royalty { - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function setTokenRoyalty(uint256 tokenId, address recipient, uint96 fraction) public { - _setTokenRoyalty(tokenId, recipient, fraction); - } - - function setDefaultRoyalty(address recipient, uint96 fraction) public { - _setDefaultRoyalty(recipient, fraction); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } - - function deleteDefaultRoyalty() public { - _deleteDefaultRoyalty(); - } -} diff --git a/contracts/mocks/ERC721URIStorageMock.sol b/contracts/mocks/ERC721URIStorageMock.sol deleted file mode 100644 index 4bb26b1ad..000000000 --- a/contracts/mocks/ERC721URIStorageMock.sol +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721URIStorage.sol"; - -/** - * @title ERC721Mock - * This mock just provides a public safeMint, mint, and burn functions for testing purposes - */ -contract ERC721URIStorageMock is ERC721URIStorage { - string private _baseTokenURI; - - constructor(string memory name, string memory symbol) ERC721(name, symbol) {} - - function _baseURI() internal view override returns (string memory) { - return _baseTokenURI; - } - - function setBaseURI(string calldata newBaseTokenURI) public { - _baseTokenURI = newBaseTokenURI; - } - - function baseURI() public view returns (string memory) { - return _baseURI(); - } - - function setTokenURI(uint256 tokenId, string memory _tokenURI) public { - _setTokenURI(tokenId, _tokenURI); - } - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - - function safeMint(address to, uint256 tokenId, bytes memory _data) public { - _safeMint(to, tokenId, _data); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } -} diff --git a/contracts/mocks/ERC721VotesMock.sol b/contracts/mocks/ERC721VotesMock.sol deleted file mode 100644 index acb51ebfb..000000000 --- a/contracts/mocks/ERC721VotesMock.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../token/ERC721/extensions/ERC721Votes.sol"; - -contract ERC721VotesMock is ERC721Votes { - constructor(string memory name, string memory symbol) ERC721(name, symbol) EIP712(name, "1") {} - - function getTotalSupply() public view returns (uint256) { - return _getTotalSupply(); - } - - function mint(address account, uint256 tokenId) public { - _mint(account, tokenId); - } - - function burn(uint256 tokenId) public { - _burn(tokenId); - } - - function getChainId() external view returns (uint256) { - return block.chainid; - } -} diff --git a/contracts/mocks/ERC777Mock.sol b/contracts/mocks/ERC777Mock.sol deleted file mode 100644 index 59c00b307..000000000 --- a/contracts/mocks/ERC777Mock.sol +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Context.sol"; -import "../token/ERC777/ERC777.sol"; - -contract ERC777Mock is Context, ERC777 { - event BeforeTokenTransfer(); - - constructor( - address initialHolder, - uint256 initialBalance, - string memory name, - string memory symbol, - address[] memory defaultOperators - ) ERC777(name, symbol, defaultOperators) { - _mint(initialHolder, initialBalance, "", ""); - } - - function mintInternal(address to, uint256 amount, bytes memory userData, bytes memory operatorData) public { - _mint(to, amount, userData, operatorData); - } - - function mintInternalExtended( - address to, - uint256 amount, - bytes memory userData, - bytes memory operatorData, - bool requireReceptionAck - ) public { - _mint(to, amount, userData, operatorData, requireReceptionAck); - } - - function approveInternal(address holder, address spender, uint256 value) public { - _approve(holder, spender, value); - } - - function _beforeTokenTransfer(address, address, address, uint256) internal override { - emit BeforeTokenTransfer(); - } -} diff --git a/contracts/mocks/EnumerableMapMock.sol b/contracts/mocks/EnumerableMapMock.sol deleted file mode 100644 index b60b1e6d9..000000000 --- a/contracts/mocks/EnumerableMapMock.sol +++ /dev/null @@ -1,221 +0,0 @@ -// SPDX-License-Identifier: MIT -// This file was procedurally generated from scripts/generate/templates/EnumerableMapMock.js. - -pragma solidity ^0.8.0; - -import "../utils/structs/EnumerableMap.sol"; - -// UintToAddressMap -contract UintToAddressMapMock { - using EnumerableMap for EnumerableMap.UintToAddressMap; - - event OperationResult(bool result); - - EnumerableMap.UintToAddressMap private _map; - - function contains(uint256 key) public view returns (bool) { - return _map.contains(key); - } - - function set(uint256 key, address value) public { - bool result = _map.set(key, value); - emit OperationResult(result); - } - - function remove(uint256 key) public { - bool result = _map.remove(key); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _map.length(); - } - - function at(uint256 index) public view returns (uint256 key, address value) { - return _map.at(index); - } - - function tryGet(uint256 key) public view returns (bool, address) { - return _map.tryGet(key); - } - - function get(uint256 key) public view returns (address) { - return _map.get(key); - } - - function getWithMessage(uint256 key, string calldata errorMessage) public view returns (address) { - return _map.get(key, errorMessage); - } -} - -// AddressToUintMap -contract AddressToUintMapMock { - using EnumerableMap for EnumerableMap.AddressToUintMap; - - event OperationResult(bool result); - - EnumerableMap.AddressToUintMap private _map; - - function contains(address key) public view returns (bool) { - return _map.contains(key); - } - - function set(address key, uint256 value) public { - bool result = _map.set(key, value); - emit OperationResult(result); - } - - function remove(address key) public { - bool result = _map.remove(key); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _map.length(); - } - - function at(uint256 index) public view returns (address key, uint256 value) { - return _map.at(index); - } - - function tryGet(address key) public view returns (bool, uint256) { - return _map.tryGet(key); - } - - function get(address key) public view returns (uint256) { - return _map.get(key); - } - - function getWithMessage(address key, string calldata errorMessage) public view returns (uint256) { - return _map.get(key, errorMessage); - } -} - -// Bytes32ToBytes32Map -contract Bytes32ToBytes32MapMock { - using EnumerableMap for EnumerableMap.Bytes32ToBytes32Map; - - event OperationResult(bool result); - - EnumerableMap.Bytes32ToBytes32Map private _map; - - function contains(bytes32 key) public view returns (bool) { - return _map.contains(key); - } - - function set(bytes32 key, bytes32 value) public { - bool result = _map.set(key, value); - emit OperationResult(result); - } - - function remove(bytes32 key) public { - bool result = _map.remove(key); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _map.length(); - } - - function at(uint256 index) public view returns (bytes32 key, bytes32 value) { - return _map.at(index); - } - - function tryGet(bytes32 key) public view returns (bool, bytes32) { - return _map.tryGet(key); - } - - function get(bytes32 key) public view returns (bytes32) { - return _map.get(key); - } - - function getWithMessage(bytes32 key, string calldata errorMessage) public view returns (bytes32) { - return _map.get(key, errorMessage); - } -} - -// UintToUintMap -contract UintToUintMapMock { - using EnumerableMap for EnumerableMap.UintToUintMap; - - event OperationResult(bool result); - - EnumerableMap.UintToUintMap private _map; - - function contains(uint256 key) public view returns (bool) { - return _map.contains(key); - } - - function set(uint256 key, uint256 value) public { - bool result = _map.set(key, value); - emit OperationResult(result); - } - - function remove(uint256 key) public { - bool result = _map.remove(key); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _map.length(); - } - - function at(uint256 index) public view returns (uint256 key, uint256 value) { - return _map.at(index); - } - - function tryGet(uint256 key) public view returns (bool, uint256) { - return _map.tryGet(key); - } - - function get(uint256 key) public view returns (uint256) { - return _map.get(key); - } - - function getWithMessage(uint256 key, string calldata errorMessage) public view returns (uint256) { - return _map.get(key, errorMessage); - } -} - -// Bytes32ToUintMap -contract Bytes32ToUintMapMock { - using EnumerableMap for EnumerableMap.Bytes32ToUintMap; - - event OperationResult(bool result); - - EnumerableMap.Bytes32ToUintMap private _map; - - function contains(bytes32 key) public view returns (bool) { - return _map.contains(key); - } - - function set(bytes32 key, uint256 value) public { - bool result = _map.set(key, value); - emit OperationResult(result); - } - - function remove(bytes32 key) public { - bool result = _map.remove(key); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _map.length(); - } - - function at(uint256 index) public view returns (bytes32 key, uint256 value) { - return _map.at(index); - } - - function tryGet(bytes32 key) public view returns (bool, uint256) { - return _map.tryGet(key); - } - - function get(bytes32 key) public view returns (uint256) { - return _map.get(key); - } - - function getWithMessage(bytes32 key, string calldata errorMessage) public view returns (uint256) { - return _map.get(key, errorMessage); - } -} diff --git a/contracts/mocks/EnumerableSetMock.sol b/contracts/mocks/EnumerableSetMock.sol deleted file mode 100644 index f75f38af1..000000000 --- a/contracts/mocks/EnumerableSetMock.sol +++ /dev/null @@ -1,111 +0,0 @@ -// SPDX-License-Identifier: MIT -// This file was procedurally generated from scripts/generate/templates/EnumerableSetMock.js. - -pragma solidity ^0.8.0; - -import "../utils/structs/EnumerableSet.sol"; - -// Bytes32Set -contract EnumerableBytes32SetMock { - using EnumerableSet for EnumerableSet.Bytes32Set; - - event OperationResult(bool result); - - EnumerableSet.Bytes32Set private _set; - - function contains(bytes32 value) public view returns (bool) { - return _set.contains(value); - } - - function add(bytes32 value) public { - bool result = _set.add(value); - emit OperationResult(result); - } - - function remove(bytes32 value) public { - bool result = _set.remove(value); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _set.length(); - } - - function at(uint256 index) public view returns (bytes32) { - return _set.at(index); - } - - function values() public view returns (bytes32[] memory) { - return _set.values(); - } -} - -// AddressSet -contract EnumerableAddressSetMock { - using EnumerableSet for EnumerableSet.AddressSet; - - event OperationResult(bool result); - - EnumerableSet.AddressSet private _set; - - function contains(address value) public view returns (bool) { - return _set.contains(value); - } - - function add(address value) public { - bool result = _set.add(value); - emit OperationResult(result); - } - - function remove(address value) public { - bool result = _set.remove(value); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _set.length(); - } - - function at(uint256 index) public view returns (address) { - return _set.at(index); - } - - function values() public view returns (address[] memory) { - return _set.values(); - } -} - -// UintSet -contract EnumerableUintSetMock { - using EnumerableSet for EnumerableSet.UintSet; - - event OperationResult(bool result); - - EnumerableSet.UintSet private _set; - - function contains(uint256 value) public view returns (bool) { - return _set.contains(value); - } - - function add(uint256 value) public { - bool result = _set.add(value); - emit OperationResult(result); - } - - function remove(uint256 value) public { - bool result = _set.remove(value); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _set.length(); - } - - function at(uint256 index) public view returns (uint256) { - return _set.at(index); - } - - function values() public view returns (uint256[] memory) { - return _set.values(); - } -} diff --git a/contracts/mocks/GovernorCompMock.sol b/contracts/mocks/GovernorCompMock.sol deleted file mode 100644 index c2d8733e0..000000000 --- a/contracts/mocks/GovernorCompMock.sol +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotesComp.sol"; - -contract GovernorCompMock is GovernorVotesComp, GovernorCountingSimple { - constructor(string memory name_, ERC20VotesComp token_) Governor(name_) GovernorVotesComp(token_) {} - - function quorum(uint256) public pure override returns (uint256) { - return 0; - } - - function votingDelay() public pure override returns (uint256) { - return 4; - } - - function votingPeriod() public pure override returns (uint256) { - return 16; - } - - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } -} diff --git a/contracts/mocks/GovernorMock.sol b/contracts/mocks/GovernorMock.sol deleted file mode 100644 index bd2de338a..000000000 --- a/contracts/mocks/GovernorMock.sol +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/extensions/GovernorProposalThreshold.sol"; -import "../governance/extensions/GovernorSettings.sol"; -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotesQuorumFraction.sol"; - -contract GovernorMock is - GovernorProposalThreshold, - GovernorSettings, - GovernorVotesQuorumFraction, - GovernorCountingSimple -{ - constructor( - string memory name_, - IVotes token_, - uint256 votingDelay_, - uint256 votingPeriod_, - uint256 quorumNumerator_ - ) - Governor(name_) - GovernorSettings(votingDelay_, votingPeriod_, 0) - GovernorVotes(token_) - GovernorVotesQuorumFraction(quorumNumerator_) - {} - - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } - - function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) { - return super.proposalThreshold(); - } - - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public override(Governor, GovernorProposalThreshold) returns (uint256) { - return super.propose(targets, values, calldatas, description); - } -} diff --git a/contracts/mocks/GovernorVoteMock.sol b/contracts/mocks/GovernorVoteMock.sol deleted file mode 100644 index 60a3d4135..000000000 --- a/contracts/mocks/GovernorVoteMock.sol +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotes.sol"; - -contract GovernorVoteMocks is GovernorVotes, GovernorCountingSimple { - constructor(string memory name_, IVotes token_) Governor(name_) GovernorVotes(token_) {} - - function quorum(uint256) public pure override returns (uint256) { - return 0; - } - - function votingDelay() public pure override returns (uint256) { - return 4; - } - - function votingPeriod() public pure override returns (uint256) { - return 16; - } - - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } -} diff --git a/contracts/mocks/MathMock.sol b/contracts/mocks/MathMock.sol deleted file mode 100644 index be935f91d..000000000 --- a/contracts/mocks/MathMock.sol +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/math/Math.sol"; - -contract MathMock { - function max(uint256 a, uint256 b) public pure returns (uint256) { - return Math.max(a, b); - } - - function min(uint256 a, uint256 b) public pure returns (uint256) { - return Math.min(a, b); - } - - function average(uint256 a, uint256 b) public pure returns (uint256) { - return Math.average(a, b); - } - - function ceilDiv(uint256 a, uint256 b) public pure returns (uint256) { - return Math.ceilDiv(a, b); - } - - function mulDiv(uint256 a, uint256 b, uint256 denominator, Math.Rounding direction) public pure returns (uint256) { - return Math.mulDiv(a, b, denominator, direction); - } - - function sqrt(uint256 a, Math.Rounding direction) public pure returns (uint256) { - return Math.sqrt(a, direction); - } - - function log2(uint256 a, Math.Rounding direction) public pure returns (uint256) { - return Math.log2(a, direction); - } - - function log10(uint256 a, Math.Rounding direction) public pure returns (uint256) { - return Math.log10(a, direction); - } - - function log256(uint256 a, Math.Rounding direction) public pure returns (uint256) { - return Math.log256(a, direction); - } -} diff --git a/contracts/mocks/MerkleProofWrapper.sol b/contracts/mocks/MerkleProofWrapper.sol deleted file mode 100644 index 60741e41c..000000000 --- a/contracts/mocks/MerkleProofWrapper.sol +++ /dev/null @@ -1,57 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/cryptography/MerkleProof.sol"; - -contract MerkleProofWrapper { - function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) public pure returns (bool) { - return MerkleProof.verify(proof, root, leaf); - } - - function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) public pure returns (bool) { - return MerkleProof.verifyCalldata(proof, root, leaf); - } - - function processProof(bytes32[] memory proof, bytes32 leaf) public pure returns (bytes32) { - return MerkleProof.processProof(proof, leaf); - } - - function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) public pure returns (bytes32) { - return MerkleProof.processProofCalldata(proof, leaf); - } - - function multiProofVerify( - bytes32[] memory proofs, - bool[] memory proofFlag, - bytes32 root, - bytes32[] memory leaves - ) public pure returns (bool) { - return MerkleProof.multiProofVerify(proofs, proofFlag, root, leaves); - } - - function multiProofVerifyCalldata( - bytes32[] calldata proofs, - bool[] calldata proofFlag, - bytes32 root, - bytes32[] memory leaves - ) public pure returns (bool) { - return MerkleProof.multiProofVerifyCalldata(proofs, proofFlag, root, leaves); - } - - function processMultiProof( - bytes32[] memory proofs, - bool[] memory proofFlag, - bytes32[] memory leaves - ) public pure returns (bytes32) { - return MerkleProof.processMultiProof(proofs, proofFlag, leaves); - } - - function processMultiProofCalldata( - bytes32[] calldata proofs, - bool[] calldata proofFlag, - bytes32[] memory leaves - ) public pure returns (bytes32) { - return MerkleProof.processMultiProofCalldata(proofs, proofFlag, leaves); - } -} diff --git a/contracts/mocks/MulticallTest.sol b/contracts/mocks/MulticallTest.sol index 4e527eff1..fcbec6ad8 100644 --- a/contracts/mocks/MulticallTest.sol +++ b/contracts/mocks/MulticallTest.sol @@ -2,11 +2,11 @@ pragma solidity ^0.8.0; -import "./MulticallTokenMock.sol"; +import "./token/ERC20MulticallMock.sol"; contract MulticallTest { function checkReturnValues( - MulticallTokenMock multicallToken, + ERC20MulticallMock multicallToken, address[] calldata recipients, uint256[] calldata amounts ) external { diff --git a/contracts/mocks/MulticallTokenMock.sol b/contracts/mocks/MulticallTokenMock.sol deleted file mode 100644 index de379681b..000000000 --- a/contracts/mocks/MulticallTokenMock.sol +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Multicall.sol"; -import "./ERC20Mock.sol"; - -contract MulticallTokenMock is ERC20Mock, Multicall { - constructor(uint256 initialBalance) ERC20Mock("MulticallToken", "BCT", msg.sender, initialBalance) {} -} diff --git a/contracts/mocks/Ownable2StepMock.sol b/contracts/mocks/Ownable2StepMock.sol deleted file mode 100644 index 606d0c964..000000000 --- a/contracts/mocks/Ownable2StepMock.sol +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../access/Ownable2Step.sol"; - -contract Ownable2StepMock is Ownable2Step {} diff --git a/contracts/mocks/OwnableMock.sol b/contracts/mocks/OwnableMock.sol deleted file mode 100644 index d60f1c40d..000000000 --- a/contracts/mocks/OwnableMock.sol +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../access/Ownable.sol"; - -contract OwnableMock is Ownable {} diff --git a/contracts/mocks/SafeCastMock.sol b/contracts/mocks/SafeCastMock.sol deleted file mode 100644 index 12a0de632..000000000 --- a/contracts/mocks/SafeCastMock.sol +++ /dev/null @@ -1,267 +0,0 @@ -// SPDX-License-Identifier: MIT -// This file was procedurally generated from scripts/generate/templates/SafeCastMock.js. - -pragma solidity ^0.8.0; - -import "../utils/math/SafeCast.sol"; - -contract SafeCastMock { - using SafeCast for uint256; - using SafeCast for int256; - - function toUint256(int256 a) public pure returns (uint256) { - return a.toUint256(); - } - - function toUint248(uint256 a) public pure returns (uint248) { - return a.toUint248(); - } - - function toUint240(uint256 a) public pure returns (uint240) { - return a.toUint240(); - } - - function toUint232(uint256 a) public pure returns (uint232) { - return a.toUint232(); - } - - function toUint224(uint256 a) public pure returns (uint224) { - return a.toUint224(); - } - - function toUint216(uint256 a) public pure returns (uint216) { - return a.toUint216(); - } - - function toUint208(uint256 a) public pure returns (uint208) { - return a.toUint208(); - } - - function toUint200(uint256 a) public pure returns (uint200) { - return a.toUint200(); - } - - function toUint192(uint256 a) public pure returns (uint192) { - return a.toUint192(); - } - - function toUint184(uint256 a) public pure returns (uint184) { - return a.toUint184(); - } - - function toUint176(uint256 a) public pure returns (uint176) { - return a.toUint176(); - } - - function toUint168(uint256 a) public pure returns (uint168) { - return a.toUint168(); - } - - function toUint160(uint256 a) public pure returns (uint160) { - return a.toUint160(); - } - - function toUint152(uint256 a) public pure returns (uint152) { - return a.toUint152(); - } - - function toUint144(uint256 a) public pure returns (uint144) { - return a.toUint144(); - } - - function toUint136(uint256 a) public pure returns (uint136) { - return a.toUint136(); - } - - function toUint128(uint256 a) public pure returns (uint128) { - return a.toUint128(); - } - - function toUint120(uint256 a) public pure returns (uint120) { - return a.toUint120(); - } - - function toUint112(uint256 a) public pure returns (uint112) { - return a.toUint112(); - } - - function toUint104(uint256 a) public pure returns (uint104) { - return a.toUint104(); - } - - function toUint96(uint256 a) public pure returns (uint96) { - return a.toUint96(); - } - - function toUint88(uint256 a) public pure returns (uint88) { - return a.toUint88(); - } - - function toUint80(uint256 a) public pure returns (uint80) { - return a.toUint80(); - } - - function toUint72(uint256 a) public pure returns (uint72) { - return a.toUint72(); - } - - function toUint64(uint256 a) public pure returns (uint64) { - return a.toUint64(); - } - - function toUint56(uint256 a) public pure returns (uint56) { - return a.toUint56(); - } - - function toUint48(uint256 a) public pure returns (uint48) { - return a.toUint48(); - } - - function toUint40(uint256 a) public pure returns (uint40) { - return a.toUint40(); - } - - function toUint32(uint256 a) public pure returns (uint32) { - return a.toUint32(); - } - - function toUint24(uint256 a) public pure returns (uint24) { - return a.toUint24(); - } - - function toUint16(uint256 a) public pure returns (uint16) { - return a.toUint16(); - } - - function toUint8(uint256 a) public pure returns (uint8) { - return a.toUint8(); - } - - function toInt256(uint256 a) public pure returns (int256) { - return a.toInt256(); - } - - function toInt248(int256 a) public pure returns (int248) { - return a.toInt248(); - } - - function toInt240(int256 a) public pure returns (int240) { - return a.toInt240(); - } - - function toInt232(int256 a) public pure returns (int232) { - return a.toInt232(); - } - - function toInt224(int256 a) public pure returns (int224) { - return a.toInt224(); - } - - function toInt216(int256 a) public pure returns (int216) { - return a.toInt216(); - } - - function toInt208(int256 a) public pure returns (int208) { - return a.toInt208(); - } - - function toInt200(int256 a) public pure returns (int200) { - return a.toInt200(); - } - - function toInt192(int256 a) public pure returns (int192) { - return a.toInt192(); - } - - function toInt184(int256 a) public pure returns (int184) { - return a.toInt184(); - } - - function toInt176(int256 a) public pure returns (int176) { - return a.toInt176(); - } - - function toInt168(int256 a) public pure returns (int168) { - return a.toInt168(); - } - - function toInt160(int256 a) public pure returns (int160) { - return a.toInt160(); - } - - function toInt152(int256 a) public pure returns (int152) { - return a.toInt152(); - } - - function toInt144(int256 a) public pure returns (int144) { - return a.toInt144(); - } - - function toInt136(int256 a) public pure returns (int136) { - return a.toInt136(); - } - - function toInt128(int256 a) public pure returns (int128) { - return a.toInt128(); - } - - function toInt120(int256 a) public pure returns (int120) { - return a.toInt120(); - } - - function toInt112(int256 a) public pure returns (int112) { - return a.toInt112(); - } - - function toInt104(int256 a) public pure returns (int104) { - return a.toInt104(); - } - - function toInt96(int256 a) public pure returns (int96) { - return a.toInt96(); - } - - function toInt88(int256 a) public pure returns (int88) { - return a.toInt88(); - } - - function toInt80(int256 a) public pure returns (int80) { - return a.toInt80(); - } - - function toInt72(int256 a) public pure returns (int72) { - return a.toInt72(); - } - - function toInt64(int256 a) public pure returns (int64) { - return a.toInt64(); - } - - function toInt56(int256 a) public pure returns (int56) { - return a.toInt56(); - } - - function toInt48(int256 a) public pure returns (int48) { - return a.toInt48(); - } - - function toInt40(int256 a) public pure returns (int40) { - return a.toInt40(); - } - - function toInt32(int256 a) public pure returns (int32) { - return a.toInt32(); - } - - function toInt24(int256 a) public pure returns (int24) { - return a.toInt24(); - } - - function toInt16(int256 a) public pure returns (int16) { - return a.toInt16(); - } - - function toInt8(int256 a) public pure returns (int8) { - return a.toInt8(); - } -} diff --git a/contracts/mocks/SafeERC20Helper.sol b/contracts/mocks/SafeERC20Helper.sol deleted file mode 100644 index 237e32041..000000000 --- a/contracts/mocks/SafeERC20Helper.sol +++ /dev/null @@ -1,182 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Context.sol"; -import "../token/ERC20/IERC20.sol"; -import "../token/ERC20/extensions/ERC20Permit.sol"; -import "../token/ERC20/utils/SafeERC20.sol"; - -contract ERC20ReturnFalseMock is Context { - uint256 private _allowance; - - // IERC20's functions are not pure, but these mock implementations are: to prevent Solidity from issuing warnings, - // we write to a dummy state variable. - uint256 private _dummy; - - function transfer(address, uint256) public returns (bool) { - _dummy = 0; - return false; - } - - function transferFrom(address, address, uint256) public returns (bool) { - _dummy = 0; - return false; - } - - function approve(address, uint256) public returns (bool) { - _dummy = 0; - return false; - } - - function allowance(address, address) public view returns (uint256) { - require(_dummy == 0); // Dummy read from a state variable so that the function is view - return 0; - } -} - -contract ERC20ReturnTrueMock is Context { - mapping(address => uint256) private _allowances; - - // IERC20's functions are not pure, but these mock implementations are: to prevent Solidity from issuing warnings, - // we write to a dummy state variable. - uint256 private _dummy; - - function transfer(address, uint256) public returns (bool) { - _dummy = 0; - return true; - } - - function transferFrom(address, address, uint256) public returns (bool) { - _dummy = 0; - return true; - } - - function approve(address, uint256) public returns (bool) { - _dummy = 0; - return true; - } - - function setAllowance(uint256 allowance_) public { - _allowances[_msgSender()] = allowance_; - } - - function allowance(address owner, address) public view returns (uint256) { - return _allowances[owner]; - } -} - -contract ERC20NoReturnMock is Context { - mapping(address => uint256) private _allowances; - - // IERC20's functions are not pure, but these mock implementations are: to prevent Solidity from issuing warnings, - // we write to a dummy state variable. - uint256 private _dummy; - - function transfer(address, uint256) public { - _dummy = 0; - } - - function transferFrom(address, address, uint256) public { - _dummy = 0; - } - - function approve(address, uint256) public { - _dummy = 0; - } - - function setAllowance(uint256 allowance_) public { - _allowances[_msgSender()] = allowance_; - } - - function allowance(address owner, address) public view returns (uint256) { - return _allowances[owner]; - } -} - -contract ERC20PermitNoRevertMock is - ERC20("ERC20PermitNoRevertMock", "ERC20PermitNoRevertMock"), - ERC20Permit("ERC20PermitNoRevertMock") -{ - function getChainId() external view returns (uint256) { - return block.chainid; - } - - function permitThatMayRevert( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) public { - super.permit(owner, spender, value, deadline, v, r, s); - } - - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) public override { - try this.permitThatMayRevert(owner, spender, value, deadline, v, r, s) { - // do nothing - } catch { - // do nothing - } - } -} - -contract SafeERC20Wrapper is Context { - using SafeERC20 for IERC20; - - IERC20 private _token; - - constructor(IERC20 token) { - _token = token; - } - - function transfer() public { - _token.safeTransfer(address(0), 0); - } - - function transferFrom() public { - _token.safeTransferFrom(address(0), address(0), 0); - } - - function approve(uint256 amount) public { - _token.safeApprove(address(0), amount); - } - - function increaseAllowance(uint256 amount) public { - _token.safeIncreaseAllowance(address(0), amount); - } - - function decreaseAllowance(uint256 amount) public { - _token.safeDecreaseAllowance(address(0), amount); - } - - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) public { - SafeERC20.safePermit(IERC20Permit(address(_token)), owner, spender, value, deadline, v, r, s); - } - - function setAllowance(uint256 allowance_) public { - ERC20ReturnTrueMock(address(_token)).setAllowance(allowance_); - } - - function allowance() public view returns (uint256) { - return _token.allowance(address(0), address(0)); - } -} diff --git a/contracts/mocks/SafeMathMemoryCheck.sol b/contracts/mocks/SafeMathMemoryCheck.sol new file mode 100644 index 000000000..96946881a --- /dev/null +++ b/contracts/mocks/SafeMathMemoryCheck.sol @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../utils/math/SafeMath.sol"; + +library SafeMathMemoryCheck { + function addMemoryCheck() internal pure returns (uint256 mem) { + uint256 length = 32; + assembly { + mem := mload(0x40) + } + for (uint256 i = 0; i < length; ++i) { + SafeMath.add(1, 1); + } + assembly { + mem := sub(mload(0x40), mem) + } + } + + function subMemoryCheck() internal pure returns (uint256 mem) { + uint256 length = 32; + assembly { + mem := mload(0x40) + } + for (uint256 i = 0; i < length; ++i) { + SafeMath.sub(1, 1); + } + assembly { + mem := sub(mload(0x40), mem) + } + } + + function mulMemoryCheck() internal pure returns (uint256 mem) { + uint256 length = 32; + assembly { + mem := mload(0x40) + } + for (uint256 i = 0; i < length; ++i) { + SafeMath.mul(1, 1); + } + assembly { + mem := sub(mload(0x40), mem) + } + } + + function divMemoryCheck() internal pure returns (uint256 mem) { + uint256 length = 32; + assembly { + mem := mload(0x40) + } + for (uint256 i = 0; i < length; ++i) { + SafeMath.div(1, 1); + } + assembly { + mem := sub(mload(0x40), mem) + } + } + + function modMemoryCheck() internal pure returns (uint256 mem) { + uint256 length = 32; + assembly { + mem := mload(0x40) + } + for (uint256 i = 0; i < length; ++i) { + SafeMath.mod(1, 1); + } + assembly { + mem := sub(mload(0x40), mem) + } + } +} diff --git a/contracts/mocks/SafeMathMock.sol b/contracts/mocks/SafeMathMock.sol deleted file mode 100644 index ef504e3ab..000000000 --- a/contracts/mocks/SafeMathMock.sol +++ /dev/null @@ -1,126 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/math/SafeMath.sol"; - -contract SafeMathMock { - function tryAdd(uint256 a, uint256 b) public pure returns (bool flag, uint256 value) { - return SafeMath.tryAdd(a, b); - } - - function trySub(uint256 a, uint256 b) public pure returns (bool flag, uint256 value) { - return SafeMath.trySub(a, b); - } - - function tryMul(uint256 a, uint256 b) public pure returns (bool flag, uint256 value) { - return SafeMath.tryMul(a, b); - } - - function tryDiv(uint256 a, uint256 b) public pure returns (bool flag, uint256 value) { - return SafeMath.tryDiv(a, b); - } - - function tryMod(uint256 a, uint256 b) public pure returns (bool flag, uint256 value) { - return SafeMath.tryMod(a, b); - } - - // using the do* naming convention to avoid warnings due to clashing opcode names - - function doAdd(uint256 a, uint256 b) public pure returns (uint256) { - return SafeMath.add(a, b); - } - - function doSub(uint256 a, uint256 b) public pure returns (uint256) { - return SafeMath.sub(a, b); - } - - function doMul(uint256 a, uint256 b) public pure returns (uint256) { - return SafeMath.mul(a, b); - } - - function doDiv(uint256 a, uint256 b) public pure returns (uint256) { - return SafeMath.div(a, b); - } - - function doMod(uint256 a, uint256 b) public pure returns (uint256) { - return SafeMath.mod(a, b); - } - - function subWithMessage(uint256 a, uint256 b, string memory errorMessage) public pure returns (uint256) { - return SafeMath.sub(a, b, errorMessage); - } - - function divWithMessage(uint256 a, uint256 b, string memory errorMessage) public pure returns (uint256) { - return SafeMath.div(a, b, errorMessage); - } - - function modWithMessage(uint256 a, uint256 b, string memory errorMessage) public pure returns (uint256) { - return SafeMath.mod(a, b, errorMessage); - } - - function addMemoryCheck() public pure returns (uint256 mem) { - uint256 length = 32; - assembly { - mem := mload(0x40) - } - for (uint256 i = 0; i < length; ++i) { - SafeMath.add(1, 1); - } - assembly { - mem := sub(mload(0x40), mem) - } - } - - function subMemoryCheck() public pure returns (uint256 mem) { - uint256 length = 32; - assembly { - mem := mload(0x40) - } - for (uint256 i = 0; i < length; ++i) { - SafeMath.sub(1, 1); - } - assembly { - mem := sub(mload(0x40), mem) - } - } - - function mulMemoryCheck() public pure returns (uint256 mem) { - uint256 length = 32; - assembly { - mem := mload(0x40) - } - for (uint256 i = 0; i < length; ++i) { - SafeMath.mul(1, 1); - } - assembly { - mem := sub(mload(0x40), mem) - } - } - - function divMemoryCheck() public pure returns (uint256 mem) { - uint256 length = 32; - assembly { - mem := mload(0x40) - } - for (uint256 i = 0; i < length; ++i) { - SafeMath.div(1, 1); - } - assembly { - mem := sub(mload(0x40), mem) - } - } - - function modMemoryCheck() public pure returns (uint256 mem) { - uint256 length = 32; - assembly { - mem := mload(0x40) - } - for (uint256 i = 0; i < length; ++i) { - SafeMath.mod(1, 1); - } - assembly { - mem := sub(mload(0x40), mem) - } - } -} diff --git a/contracts/mocks/SignatureCheckerMock.sol b/contracts/mocks/SignatureCheckerMock.sol deleted file mode 100644 index 5671540ec..000000000 --- a/contracts/mocks/SignatureCheckerMock.sol +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/cryptography/SignatureChecker.sol"; - -contract SignatureCheckerMock { - using SignatureChecker for address; - - function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) public view returns (bool) { - return signer.isValidSignatureNow(hash, signature); - } -} diff --git a/contracts/mocks/SignedMathMock.sol b/contracts/mocks/SignedMathMock.sol deleted file mode 100644 index 5a0b27096..000000000 --- a/contracts/mocks/SignedMathMock.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/math/SignedMath.sol"; - -contract SignedMathMock { - function max(int256 a, int256 b) public pure returns (int256) { - return SignedMath.max(a, b); - } - - function min(int256 a, int256 b) public pure returns (int256) { - return SignedMath.min(a, b); - } - - function average(int256 a, int256 b) public pure returns (int256) { - return SignedMath.average(a, b); - } - - function abs(int256 n) public pure returns (uint256) { - return SignedMath.abs(n); - } -} diff --git a/contracts/mocks/SignedSafeMathMock.sol b/contracts/mocks/SignedSafeMathMock.sol deleted file mode 100644 index 8d1021798..000000000 --- a/contracts/mocks/SignedSafeMathMock.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/math/SignedSafeMath.sol"; - -contract SignedSafeMathMock { - function mul(int256 a, int256 b) public pure returns (int256) { - return SignedSafeMath.mul(a, b); - } - - function div(int256 a, int256 b) public pure returns (int256) { - return SignedSafeMath.div(a, b); - } - - function sub(int256 a, int256 b) public pure returns (int256) { - return SignedSafeMath.sub(a, b); - } - - function add(int256 a, int256 b) public pure returns (int256) { - return SignedSafeMath.add(a, b); - } -} diff --git a/contracts/mocks/StringsMock.sol b/contracts/mocks/StringsMock.sol deleted file mode 100644 index 9f98e2778..000000000 --- a/contracts/mocks/StringsMock.sol +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "../utils/Strings.sol"; - -contract StringsMock { - function toString(uint256 value) public pure returns (string memory) { - return Strings.toString(value); - } - - function toString(int256 value) public pure returns (string memory) { - return Strings.toString(value); - } - - function toHexString(uint256 value) public pure returns (string memory) { - return Strings.toHexString(value); - } - - function toHexString(uint256 value, uint256 length) public pure returns (string memory) { - return Strings.toHexString(value, length); - } - - function toHexString(address addr) public pure returns (string memory) { - return Strings.toHexString(addr); - } - - function equal(string memory a, string memory b) public pure returns (bool) { - return Strings.equal(a, b); - } -} diff --git a/contracts/mocks/VotesMock.sol b/contracts/mocks/VotesMock.sol index f888490da..ece08b075 100644 --- a/contracts/mocks/VotesMock.sol +++ b/contracts/mocks/VotesMock.sol @@ -4,12 +4,10 @@ pragma solidity ^0.8.0; import "../governance/utils/Votes.sol"; -contract VotesMock is Votes { +abstract contract VotesMock is Votes { mapping(address => uint256) private _balances; mapping(uint256 => address) private _owners; - constructor(string memory name) EIP712(name, "1") {} - function getTotalSupply() public view returns (uint256) { return _getTotalSupply(); } @@ -22,19 +20,15 @@ contract VotesMock is Votes { return _balances[account]; } - function mint(address account, uint256 voteId) external { + function _mint(address account, uint256 voteId) internal { _balances[account] += 1; _owners[voteId] = account; _transferVotingUnits(address(0), account, 1); } - function burn(uint256 voteId) external { + function _burn(uint256 voteId) internal { address owner = _owners[voteId]; _balances[owner] -= 1; _transferVotingUnits(owner, address(0), 1); } - - function getChainId() external view returns (uint256) { - return block.chainid; - } } diff --git a/contracts/mocks/governance/GovernorCompMock.sol b/contracts/mocks/governance/GovernorCompMock.sol new file mode 100644 index 000000000..cc368c42f --- /dev/null +++ b/contracts/mocks/governance/GovernorCompMock.sol @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../../governance/extensions/GovernorCountingSimple.sol"; +import "../../governance/extensions/GovernorVotesComp.sol"; + +abstract contract GovernorCompMock is GovernorVotesComp, GovernorCountingSimple { + function quorum(uint256) public pure override returns (uint256) { + return 0; + } + + function votingDelay() public pure override returns (uint256) { + return 4; + } + + function votingPeriod() public pure override returns (uint256) { + return 16; + } +} diff --git a/contracts/mocks/GovernorCompatibilityBravoMock.sol b/contracts/mocks/governance/GovernorCompatibilityBravoMock.sol similarity index 71% rename from contracts/mocks/GovernorCompatibilityBravoMock.sol rename to contracts/mocks/governance/GovernorCompatibilityBravoMock.sol index d3b4f707d..4356bce7f 100644 --- a/contracts/mocks/GovernorCompatibilityBravoMock.sol +++ b/contracts/mocks/governance/GovernorCompatibilityBravoMock.sol @@ -2,30 +2,20 @@ pragma solidity ^0.8.0; -import "../governance/compatibility/GovernorCompatibilityBravo.sol"; -import "../governance/extensions/GovernorTimelockCompound.sol"; -import "../governance/extensions/GovernorSettings.sol"; -import "../governance/extensions/GovernorVotesComp.sol"; +import "../../governance/compatibility/GovernorCompatibilityBravo.sol"; +import "../../governance/extensions/GovernorTimelockCompound.sol"; +import "../../governance/extensions/GovernorSettings.sol"; +import "../../governance/extensions/GovernorVotesComp.sol"; -contract GovernorCompatibilityBravoMock is +abstract contract GovernorCompatibilityBravoMock is GovernorCompatibilityBravo, GovernorSettings, GovernorTimelockCompound, GovernorVotesComp { - constructor( - string memory name_, - ERC20VotesComp token_, - uint256 votingDelay_, - uint256 votingPeriod_, - uint256 proposalThreshold_, - ICompoundTimelock timelock_ - ) - Governor(name_) - GovernorTimelockCompound(timelock_) - GovernorSettings(votingDelay_, votingPeriod_, proposalThreshold_) - GovernorVotesComp(token_) - {} + function quorum(uint256) public pure override returns (uint256) { + return 0; + } function supportsInterface( bytes4 interfaceId @@ -33,10 +23,6 @@ contract GovernorCompatibilityBravoMock is return super.supportsInterface(interfaceId); } - function quorum(uint256) public pure override returns (uint256) { - return 0; - } - function state( uint256 proposalId ) public view override(IGovernor, Governor, GovernorTimelockCompound) returns (ProposalState) { @@ -90,19 +76,6 @@ contract GovernorCompatibilityBravoMock is super._execute(proposalId, targets, values, calldatas, descriptionHash); } - /** - * @notice WARNING: this is for mock purposes only. Ability to the _cancel function should be restricted for live - * deployments. - */ - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } - function _cancel( address[] memory targets, uint256[] memory values, diff --git a/contracts/mocks/governance/GovernorMock.sol b/contracts/mocks/governance/GovernorMock.sol new file mode 100644 index 000000000..8a1db4704 --- /dev/null +++ b/contracts/mocks/governance/GovernorMock.sol @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../../governance/extensions/GovernorProposalThreshold.sol"; +import "../../governance/extensions/GovernorSettings.sol"; +import "../../governance/extensions/GovernorCountingSimple.sol"; +import "../../governance/extensions/GovernorVotesQuorumFraction.sol"; + +abstract contract GovernorMock is + GovernorProposalThreshold, + GovernorSettings, + GovernorVotesQuorumFraction, + GovernorCountingSimple +{ + function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) { + return super.proposalThreshold(); + } + + function propose( + address[] memory targets, + uint256[] memory values, + bytes[] memory calldatas, + string memory description + ) public override(Governor, GovernorProposalThreshold) returns (uint256) { + return super.propose(targets, values, calldatas, description); + } +} diff --git a/contracts/mocks/GovernorPreventLateQuorumMock.sol b/contracts/mocks/governance/GovernorPreventLateQuorumMock.sol similarity index 61% rename from contracts/mocks/GovernorPreventLateQuorumMock.sol rename to contracts/mocks/governance/GovernorPreventLateQuorumMock.sol index b6b5e7619..79d894896 100644 --- a/contracts/mocks/GovernorPreventLateQuorumMock.sol +++ b/contracts/mocks/governance/GovernorPreventLateQuorumMock.sol @@ -2,12 +2,12 @@ pragma solidity ^0.8.0; -import "../governance/extensions/GovernorPreventLateQuorum.sol"; -import "../governance/extensions/GovernorSettings.sol"; -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotes.sol"; +import "../../governance/extensions/GovernorPreventLateQuorum.sol"; +import "../../governance/extensions/GovernorSettings.sol"; +import "../../governance/extensions/GovernorCountingSimple.sol"; +import "../../governance/extensions/GovernorVotes.sol"; -contract GovernorPreventLateQuorumMock is +abstract contract GovernorPreventLateQuorumMock is GovernorSettings, GovernorVotes, GovernorCountingSimple, @@ -15,19 +15,7 @@ contract GovernorPreventLateQuorumMock is { uint256 private _quorum; - constructor( - string memory name_, - IVotes token_, - uint256 votingDelay_, - uint256 votingPeriod_, - uint256 quorum_, - uint64 voteExtension_ - ) - Governor(name_) - GovernorSettings(votingDelay_, votingPeriod_, 0) - GovernorVotes(token_) - GovernorPreventLateQuorum(voteExtension_) - { + constructor(uint256 quorum_) { _quorum = quorum_; } diff --git a/contracts/mocks/GovernorTimelockCompoundMock.sol b/contracts/mocks/governance/GovernorTimelockCompoundMock.sol similarity index 62% rename from contracts/mocks/GovernorTimelockCompoundMock.sol rename to contracts/mocks/governance/GovernorTimelockCompoundMock.sol index 75a2f3c14..b37462819 100644 --- a/contracts/mocks/GovernorTimelockCompoundMock.sol +++ b/contracts/mocks/governance/GovernorTimelockCompoundMock.sol @@ -2,32 +2,17 @@ pragma solidity ^0.8.0; -import "../governance/extensions/GovernorTimelockCompound.sol"; -import "../governance/extensions/GovernorSettings.sol"; -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotesQuorumFraction.sol"; +import "../../governance/extensions/GovernorTimelockCompound.sol"; +import "../../governance/extensions/GovernorSettings.sol"; +import "../../governance/extensions/GovernorCountingSimple.sol"; +import "../../governance/extensions/GovernorVotesQuorumFraction.sol"; -contract GovernorTimelockCompoundMock is +abstract contract GovernorTimelockCompoundMock is GovernorSettings, GovernorTimelockCompound, GovernorVotesQuorumFraction, GovernorCountingSimple { - constructor( - string memory name_, - IVotes token_, - uint256 votingDelay_, - uint256 votingPeriod_, - ICompoundTimelock timelock_, - uint256 quorumNumerator_ - ) - Governor(name_) - GovernorTimelockCompound(timelock_) - GovernorSettings(votingDelay_, votingPeriod_, 0) - GovernorVotes(token_) - GovernorVotesQuorumFraction(quorumNumerator_) - {} - function supportsInterface( bytes4 interfaceId ) public view override(Governor, GovernorTimelockCompound) returns (bool) { @@ -40,18 +25,6 @@ contract GovernorTimelockCompoundMock is return super.quorum(blockNumber); } - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } - - /** - * Overriding nightmare - */ function state( uint256 proposalId ) public view override(Governor, GovernorTimelockCompound) returns (ProposalState) { diff --git a/contracts/mocks/GovernorTimelockControlMock.sol b/contracts/mocks/governance/GovernorTimelockControlMock.sol similarity index 62% rename from contracts/mocks/GovernorTimelockControlMock.sol rename to contracts/mocks/governance/GovernorTimelockControlMock.sol index 671a1e0ea..06309145a 100644 --- a/contracts/mocks/GovernorTimelockControlMock.sol +++ b/contracts/mocks/governance/GovernorTimelockControlMock.sol @@ -2,32 +2,17 @@ pragma solidity ^0.8.0; -import "../governance/extensions/GovernorTimelockControl.sol"; -import "../governance/extensions/GovernorSettings.sol"; -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotesQuorumFraction.sol"; +import "../../governance/extensions/GovernorTimelockControl.sol"; +import "../../governance/extensions/GovernorSettings.sol"; +import "../../governance/extensions/GovernorCountingSimple.sol"; +import "../../governance/extensions/GovernorVotesQuorumFraction.sol"; -contract GovernorTimelockControlMock is +abstract contract GovernorTimelockControlMock is GovernorSettings, GovernorTimelockControl, GovernorVotesQuorumFraction, GovernorCountingSimple { - constructor( - string memory name_, - IVotes token_, - uint256 votingDelay_, - uint256 votingPeriod_, - TimelockController timelock_, - uint256 quorumNumerator_ - ) - Governor(name_) - GovernorTimelockControl(timelock_) - GovernorSettings(votingDelay_, votingPeriod_, 0) - GovernorVotes(token_) - GovernorVotesQuorumFraction(quorumNumerator_) - {} - function supportsInterface( bytes4 interfaceId ) public view override(Governor, GovernorTimelockControl) returns (bool) { @@ -40,18 +25,6 @@ contract GovernorTimelockControlMock is return super.quorum(blockNumber); } - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, descriptionHash); - } - - /** - * Overriding nightmare - */ function state(uint256 proposalId) public view override(Governor, GovernorTimelockControl) returns (ProposalState) { return super.state(proposalId); } diff --git a/contracts/mocks/governance/GovernorVoteMock.sol b/contracts/mocks/governance/GovernorVoteMock.sol new file mode 100644 index 000000000..9b533bddf --- /dev/null +++ b/contracts/mocks/governance/GovernorVoteMock.sol @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../../governance/extensions/GovernorCountingSimple.sol"; +import "../../governance/extensions/GovernorVotes.sol"; + +abstract contract GovernorVoteMocks is GovernorVotes, GovernorCountingSimple { + function quorum(uint256) public pure override returns (uint256) { + return 0; + } + + function votingDelay() public pure override returns (uint256) { + return 4; + } + + function votingPeriod() public pure override returns (uint256) { + return 16; + } +} diff --git a/contracts/mocks/GovernorWithParamsMock.sol b/contracts/mocks/governance/GovernorWithParamsMock.sol similarity index 72% rename from contracts/mocks/GovernorWithParamsMock.sol rename to contracts/mocks/governance/GovernorWithParamsMock.sol index b5da8906a..361c2873e 100644 --- a/contracts/mocks/GovernorWithParamsMock.sol +++ b/contracts/mocks/governance/GovernorWithParamsMock.sol @@ -2,14 +2,12 @@ pragma solidity ^0.8.0; -import "../governance/extensions/GovernorCountingSimple.sol"; -import "../governance/extensions/GovernorVotes.sol"; +import "../../governance/extensions/GovernorCountingSimple.sol"; +import "../../governance/extensions/GovernorVotes.sol"; -contract GovernorWithParamsMock is GovernorVotes, GovernorCountingSimple { +abstract contract GovernorWithParamsMock is GovernorVotes, GovernorCountingSimple { event CountParams(uint256 uintParam, string strParam); - constructor(string memory name_, IVotes token_) Governor(name_) GovernorVotes(token_) {} - function quorum(uint256) public pure override returns (uint256) { return 0; } @@ -49,13 +47,4 @@ contract GovernorWithParamsMock is GovernorVotes, GovernorCountingSimple { } return super._countVote(proposalId, account, support, weight, params); } - - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 salt - ) public returns (uint256 proposalId) { - return _cancel(targets, values, calldatas, salt); - } } diff --git a/contracts/mocks/BadBeacon.sol b/contracts/mocks/proxy/BadBeacon.sol similarity index 100% rename from contracts/mocks/BadBeacon.sol rename to contracts/mocks/proxy/BadBeacon.sol diff --git a/contracts/mocks/ClashingImplementation.sol b/contracts/mocks/proxy/ClashingImplementation.sol similarity index 100% rename from contracts/mocks/ClashingImplementation.sol rename to contracts/mocks/proxy/ClashingImplementation.sol diff --git a/contracts/mocks/UUPS/UUPSLegacy.sol b/contracts/mocks/proxy/UUPSLegacy.sol similarity index 100% rename from contracts/mocks/UUPS/UUPSLegacy.sol rename to contracts/mocks/proxy/UUPSLegacy.sol diff --git a/contracts/mocks/UUPS/UUPSUpgradeableMock.sol b/contracts/mocks/proxy/UUPSUpgradeableMock.sol similarity index 63% rename from contracts/mocks/UUPS/UUPSUpgradeableMock.sol rename to contracts/mocks/proxy/UUPSUpgradeableMock.sol index 35a74c353..deb20a000 100644 --- a/contracts/mocks/UUPS/UUPSUpgradeableMock.sol +++ b/contracts/mocks/proxy/UUPSUpgradeableMock.sol @@ -2,10 +2,22 @@ pragma solidity ^0.8.0; -import "../CountersImpl.sol"; import "../../proxy/utils/UUPSUpgradeable.sol"; +import "../../utils/Counters.sol"; -contract UUPSUpgradeableMock is CountersImpl, UUPSUpgradeable { +contract NonUpgradeableMock { + Counters.Counter internal _counter; + + function current() external view returns (uint256) { + return Counters.current(_counter); + } + + function increment() external { + return Counters.increment(_counter); + } +} + +contract UUPSUpgradeableMock is NonUpgradeableMock, UUPSUpgradeable { // Not having any checks in this function is dangerous! Do not do this outside tests! function _authorizeUpgrade(address) internal override {} } diff --git a/contracts/mocks/ERC1155ReceiverMock.sol b/contracts/mocks/token/ERC1155ReceiverMock.sol similarity index 93% rename from contracts/mocks/ERC1155ReceiverMock.sol rename to contracts/mocks/token/ERC1155ReceiverMock.sol index b2d505c0a..317d72425 100644 --- a/contracts/mocks/ERC1155ReceiverMock.sol +++ b/contracts/mocks/token/ERC1155ReceiverMock.sol @@ -2,8 +2,8 @@ pragma solidity ^0.8.0; -import "../token/ERC1155/IERC1155Receiver.sol"; -import "../utils/introspection/ERC165.sol"; +import "../../token/ERC1155/IERC1155Receiver.sol"; +import "../../utils/introspection/ERC165.sol"; contract ERC1155ReceiverMock is ERC165, IERC1155Receiver { bytes4 private _recRetval; diff --git a/contracts/mocks/token/ERC20DecimalsMock.sol b/contracts/mocks/token/ERC20DecimalsMock.sol new file mode 100644 index 000000000..32f287470 --- /dev/null +++ b/contracts/mocks/token/ERC20DecimalsMock.sol @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../../token/ERC20/ERC20.sol"; + +abstract contract ERC20DecimalsMock is ERC20 { + uint8 private immutable _decimals; + + constructor(uint8 decimals_) { + _decimals = decimals_; + } + + function decimals() public view override returns (uint8) { + return _decimals; + } +} diff --git a/contracts/mocks/ERC20FlashMintMock.sol b/contracts/mocks/token/ERC20FlashMintMock.sol similarity index 52% rename from contracts/mocks/ERC20FlashMintMock.sol rename to contracts/mocks/token/ERC20FlashMintMock.sol index ff6f252e8..b4de7b771 100644 --- a/contracts/mocks/ERC20FlashMintMock.sol +++ b/contracts/mocks/token/ERC20FlashMintMock.sol @@ -2,25 +2,12 @@ pragma solidity ^0.8.0; -import "../token/ERC20/extensions/ERC20FlashMint.sol"; +import "../../token/ERC20/extensions/ERC20FlashMint.sol"; -contract ERC20FlashMintMock is ERC20FlashMint { +abstract contract ERC20FlashMintMock is ERC20FlashMint { uint256 _flashFeeAmount; address _flashFeeReceiverAddress; - constructor( - string memory name, - string memory symbol, - address initialAccount, - uint256 initialBalance - ) ERC20(name, symbol) { - _mint(initialAccount, initialBalance); - } - - function mint(address account, uint256 amount) public { - _mint(account, amount); - } - function setFlashFee(uint256 amount) public { _flashFeeAmount = amount; } @@ -33,10 +20,6 @@ contract ERC20FlashMintMock is ERC20FlashMint { _flashFeeReceiverAddress = receiver; } - function flashFeeReceiver() public view returns (address) { - return _flashFeeReceiver(); - } - function _flashFeeReceiver() internal view override returns (address) { return _flashFeeReceiverAddress; } diff --git a/contracts/mocks/token/ERC20MulticallMock.sol b/contracts/mocks/token/ERC20MulticallMock.sol new file mode 100644 index 000000000..145e97a62 --- /dev/null +++ b/contracts/mocks/token/ERC20MulticallMock.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../../token/ERC20/ERC20.sol"; +import "../../utils/Multicall.sol"; + +abstract contract ERC20MulticallMock is ERC20, Multicall {} diff --git a/contracts/mocks/token/ERC20NoReturnMock.sol b/contracts/mocks/token/ERC20NoReturnMock.sol new file mode 100644 index 000000000..023dab2cb --- /dev/null +++ b/contracts/mocks/token/ERC20NoReturnMock.sol @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +contract ERC20NoReturnMock { + mapping(address => uint256) private _allowances; + + function transfer(address, uint256) public {} + + function transferFrom(address, address, uint256) public {} + + function approve(address, uint256) public {} + + function setAllowance(address account, uint256 allowance_) public { + _allowances[account] = allowance_; + } + + function allowance(address owner, address) public view returns (uint256) { + return _allowances[owner]; + } +} diff --git a/contracts/mocks/token/ERC20PermitNoRevertMock.sol b/contracts/mocks/token/ERC20PermitNoRevertMock.sol new file mode 100644 index 000000000..2b6e2503b --- /dev/null +++ b/contracts/mocks/token/ERC20PermitNoRevertMock.sol @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../../token/ERC20/ERC20.sol"; +import "../../token/ERC20/extensions/draft-ERC20Permit.sol"; + +contract ERC20PermitNoRevertMock is ERC20, ERC20Permit { + constructor() ERC20("ERC20PermitNoRevertMock", "ERC20PermitNoRevertMock") ERC20Permit("ERC20PermitNoRevertMock") {} + + function permitThatMayRevert( + address owner, + address spender, + uint256 value, + uint256 deadline, + uint8 v, + bytes32 r, + bytes32 s + ) public virtual { + super.permit(owner, spender, value, deadline, v, r, s); + } + + function permit( + address owner, + address spender, + uint256 value, + uint256 deadline, + uint8 v, + bytes32 r, + bytes32 s + ) public virtual override { + try this.permitThatMayRevert(owner, spender, value, deadline, v, r, s) { + // do nothing + } catch { + // do nothing + } + } +} diff --git a/contracts/mocks/token/ERC20ReturnFalseMock copy.sol b/contracts/mocks/token/ERC20ReturnFalseMock copy.sol new file mode 100644 index 000000000..3f8f64037 --- /dev/null +++ b/contracts/mocks/token/ERC20ReturnFalseMock copy.sol @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +contract ERC20ReturnFalseMock { + mapping(address => uint256) private _allowances; + + function transfer(address, uint256) public pure returns (bool) { + return false; + } + + function transferFrom(address, address, uint256) public pure returns (bool) { + return false; + } + + function approve(address, uint256) public pure returns (bool) { + return false; + } + + function setAllowance(address account, uint256 allowance_) public { + _allowances[account] = allowance_; + } + + function allowance(address owner, address) public view returns (uint256) { + return _allowances[owner]; + } +} diff --git a/contracts/mocks/token/ERC20ReturnTrueMock.sol b/contracts/mocks/token/ERC20ReturnTrueMock.sol new file mode 100644 index 000000000..8953aad64 --- /dev/null +++ b/contracts/mocks/token/ERC20ReturnTrueMock.sol @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +contract ERC20ReturnTrueMock { + mapping(address => uint256) private _allowances; + + function transfer(address, uint256) public pure returns (bool) { + return true; + } + + function transferFrom(address, address, uint256) public pure returns (bool) { + return true; + } + + function approve(address, uint256) public pure returns (bool) { + return true; + } + + function setAllowance(address account, uint256 allowance_) public { + _allowances[account] = allowance_; + } + + function allowance(address owner, address) public view returns (uint256) { + return _allowances[owner]; + } +} diff --git a/contracts/mocks/token/ERC4626DecimalsMock.sol b/contracts/mocks/token/ERC4626DecimalsMock.sol new file mode 100644 index 000000000..9cce5139c --- /dev/null +++ b/contracts/mocks/token/ERC4626DecimalsMock.sol @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../../token/ERC20/extensions/ERC4626.sol"; + +abstract contract ERC4626DecimalsMock is ERC4626 { + using Math for uint256; + + uint8 private immutable _decimals; + + constructor(uint8 decimals_) { + _decimals = decimals_; + } + + function decimals() public view virtual override returns (uint8) { + return _decimals; + } + + function _initialConvertToShares( + uint256 assets, + Math.Rounding rounding + ) internal view virtual override returns (uint256 shares) { + return assets.mulDiv(10 ** decimals(), 10 ** super.decimals(), rounding); + } + + function _initialConvertToAssets( + uint256 shares, + Math.Rounding rounding + ) internal view virtual override returns (uint256 assets) { + return shares.mulDiv(10 ** super.decimals(), 10 ** decimals(), rounding); + } +} diff --git a/contracts/mocks/ERC721ConsecutiveEnumerableMock.sol b/contracts/mocks/token/ERC721ConsecutiveEnumerableMock.sol similarity index 92% rename from contracts/mocks/ERC721ConsecutiveEnumerableMock.sol rename to contracts/mocks/token/ERC721ConsecutiveEnumerableMock.sol index f4f5c5832..55c40ac17 100644 --- a/contracts/mocks/ERC721ConsecutiveEnumerableMock.sol +++ b/contracts/mocks/token/ERC721ConsecutiveEnumerableMock.sol @@ -2,8 +2,8 @@ pragma solidity ^0.8.0; -import "../token/ERC721/extensions/ERC721Consecutive.sol"; -import "../token/ERC721/extensions/ERC721Enumerable.sol"; +import "../../token/ERC721/extensions/ERC721Consecutive.sol"; +import "../../token/ERC721/extensions/ERC721Enumerable.sol"; contract ERC721ConsecutiveEnumerableMock is ERC721Consecutive, ERC721Enumerable { constructor( diff --git a/contracts/mocks/ERC721ConsecutiveMock.sol b/contracts/mocks/token/ERC721ConsecutiveMock.sol similarity index 64% rename from contracts/mocks/ERC721ConsecutiveMock.sol rename to contracts/mocks/token/ERC721ConsecutiveMock.sol index add5ab160..427f44a19 100644 --- a/contracts/mocks/ERC721ConsecutiveMock.sol +++ b/contracts/mocks/token/ERC721ConsecutiveMock.sol @@ -2,16 +2,15 @@ pragma solidity ^0.8.0; -import "../token/ERC721/extensions/ERC721Burnable.sol"; -import "../token/ERC721/extensions/ERC721Consecutive.sol"; -import "../token/ERC721/extensions/ERC721Enumerable.sol"; -import "../token/ERC721/extensions/ERC721Pausable.sol"; -import "../token/ERC721/extensions/ERC721Votes.sol"; +import "../../token/ERC721/extensions/ERC721Consecutive.sol"; +import "../../token/ERC721/extensions/ERC721Enumerable.sol"; +import "../../token/ERC721/extensions/ERC721Pausable.sol"; +import "../../token/ERC721/extensions/draft-ERC721Votes.sol"; /** * @title ERC721ConsecutiveMock */ -contract ERC721ConsecutiveMock is ERC721Burnable, ERC721Consecutive, ERC721Pausable, ERC721Votes { +contract ERC721ConsecutiveMock is ERC721Consecutive, ERC721Pausable, ERC721Votes { constructor( string memory name, string memory symbol, @@ -28,30 +27,6 @@ contract ERC721ConsecutiveMock is ERC721Burnable, ERC721Consecutive, ERC721Pausa } } - function pause() external { - _pause(); - } - - function unpause() external { - _unpause(); - } - - function exists(uint256 tokenId) public view returns (bool) { - return _exists(tokenId); - } - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } - - function mintConsecutive(address to, uint96 amount) public { - _mintConsecutive(to, amount); - } - - function safeMint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } - function _ownerOf(uint256 tokenId) internal view virtual override(ERC721, ERC721Consecutive) returns (address) { return super._ownerOf(tokenId); } diff --git a/contracts/mocks/ERC721ReceiverMock.sol b/contracts/mocks/token/ERC721ReceiverMock.sol similarity index 95% rename from contracts/mocks/ERC721ReceiverMock.sol rename to contracts/mocks/token/ERC721ReceiverMock.sol index a4923bfd5..dd25788d4 100644 --- a/contracts/mocks/ERC721ReceiverMock.sol +++ b/contracts/mocks/token/ERC721ReceiverMock.sol @@ -2,7 +2,7 @@ pragma solidity ^0.8.0; -import "../token/ERC721/IERC721Receiver.sol"; +import "../../token/ERC721/IERC721Receiver.sol"; contract ERC721ReceiverMock is IERC721Receiver { enum Error { diff --git a/contracts/mocks/token/ERC721URIStorageMock.sol b/contracts/mocks/token/ERC721URIStorageMock.sol new file mode 100644 index 000000000..455c933c8 --- /dev/null +++ b/contracts/mocks/token/ERC721URIStorageMock.sol @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../../token/ERC721/extensions/ERC721URIStorage.sol"; + +abstract contract ERC721URIStorageMock is ERC721URIStorage { + string private _baseTokenURI; + + function _baseURI() internal view virtual override returns (string memory) { + return _baseTokenURI; + } + + function setBaseURI(string calldata newBaseTokenURI) public { + _baseTokenURI = newBaseTokenURI; + } +} diff --git a/contracts/mocks/token/ERC777Mock.sol b/contracts/mocks/token/ERC777Mock.sol new file mode 100644 index 000000000..685277e8b --- /dev/null +++ b/contracts/mocks/token/ERC777Mock.sol @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../../token/ERC777/ERC777.sol"; + +abstract contract ERC777Mock is ERC777 { + event BeforeTokenTransfer(); + + function _beforeTokenTransfer(address, address, address, uint256) internal override { + emit BeforeTokenTransfer(); + } +} diff --git a/contracts/mocks/ERC777SenderRecipientMock.sol b/contracts/mocks/token/ERC777SenderRecipientMock.sol similarity index 93% rename from contracts/mocks/ERC777SenderRecipientMock.sol rename to contracts/mocks/token/ERC777SenderRecipientMock.sol index 8e8c749ce..3bec6d94b 100644 --- a/contracts/mocks/ERC777SenderRecipientMock.sol +++ b/contracts/mocks/token/ERC777SenderRecipientMock.sol @@ -2,12 +2,12 @@ pragma solidity ^0.8.0; -import "../token/ERC777/IERC777.sol"; -import "../token/ERC777/IERC777Sender.sol"; -import "../token/ERC777/IERC777Recipient.sol"; -import "../utils/Context.sol"; -import "../utils/introspection/IERC1820Registry.sol"; -import "../utils/introspection/ERC1820Implementer.sol"; +import "../../token/ERC777/IERC777.sol"; +import "../../token/ERC777/IERC777Sender.sol"; +import "../../token/ERC777/IERC777Recipient.sol"; +import "../../utils/Context.sol"; +import "../../utils/introspection/IERC1820Registry.sol"; +import "../../utils/introspection/ERC1820Implementer.sol"; contract ERC777SenderRecipientMock is Context, IERC777Sender, IERC777Recipient, ERC1820Implementer { event TokensToSendCalled( diff --git a/hardhat.config.js b/hardhat.config.js index 4dbff0e4e..1722faf91 100644 --- a/hardhat.config.js +++ b/hardhat.config.js @@ -51,13 +51,10 @@ const argv = require('yargs/yargs')() require('@nomiclabs/hardhat-truffle5'); require('hardhat-ignore-warnings'); +require('hardhat-exposed'); require('solidity-docgen'); -if (argv.gas) { - require('hardhat-gas-reporter'); -} - for (const f of fs.readdirSync(path.join(__dirname, 'hardhat'))) { require(path.join(__dirname, 'hardhat', f)); } @@ -91,13 +88,24 @@ module.exports = { allowUnlimitedContractSize: !withOptimizations, }, }, - gasReporter: { + exposed: { + exclude: [ + 'vendor/**/*', + // overflow clash + 'utils/Timers.sol', + ], + }, + docgen: require('./docs/config'), +}; + +if (argv.gas) { + require('hardhat-gas-reporter'); + module.exports.gasReporter = { showMethodSig: true, currency: 'USD', outputFile: argv.gasReport, coinmarketcap: argv.coinmarketcap, - }, - docgen: require('./docs/config'), + }; }; if (argv.coverage) { diff --git a/package-lock.json b/package-lock.json index 5524f8a12..172fa0944 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,6 +26,7 @@ "glob": "^8.0.3", "graphlib": "^2.1.8", "hardhat": "^2.9.1", + "hardhat-exposed": "^0.3.0", "hardhat-gas-reporter": "^1.0.4", "hardhat-ignore-warnings": "^0.2.0", "keccak256": "^1.0.2", @@ -6905,6 +6906,19 @@ } } }, + "node_modules/hardhat-exposed": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/hardhat-exposed/-/hardhat-exposed-0.3.0.tgz", + "integrity": "sha512-1p2Aou7QW3VVI0iJhh3q9hgPyF66zggeW7v/PrcipniQqaXK+KxJnnJvzGsLvXYzB8lVp23GIK7MXoTjjyXkHQ==", + "dev": true, + "dependencies": { + "micromatch": "^4.0.4", + "solidity-ast": "^0.4.25" + }, + "peerDependencies": { + "hardhat": "^2.3.0" + } + }, "node_modules/hardhat-gas-reporter": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/hardhat-gas-reporter/-/hardhat-gas-reporter-1.0.9.tgz", @@ -9990,6 +10004,89 @@ "prettier": ">=2.3.0 || >=3.0.0-alpha.0" } }, + "node_modules/prettier-plugin-solidity/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/prettier-plugin-solidity/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/prettier-plugin-solidity/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/prettier-plugin-solidity/node_modules/semver": { + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", + "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/prettier-plugin-solidity/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/prettier-plugin-solidity/node_modules/string-width/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/prettier-plugin-solidity/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/prettier-plugin-solidity/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, "node_modules/process": { "version": "0.11.10", "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", @@ -20019,6 +20116,16 @@ } } }, + "hardhat-exposed": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/hardhat-exposed/-/hardhat-exposed-0.3.0.tgz", + "integrity": "sha512-1p2Aou7QW3VVI0iJhh3q9hgPyF66zggeW7v/PrcipniQqaXK+KxJnnJvzGsLvXYzB8lVp23GIK7MXoTjjyXkHQ==", + "dev": true, + "requires": { + "micromatch": "^4.0.4", + "solidity-ast": "^0.4.25" + } + }, "hardhat-gas-reporter": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/hardhat-gas-reporter/-/hardhat-gas-reporter-1.0.9.tgz", @@ -22186,7 +22293,74 @@ "requires": { "@solidity-parser/parser": "^0.14.5", "semver": "^7.3.8", - "solidity-comments-extractor": "^0.0.7" + "solidity-comments-extractor": "^0.0.7", + "string-width": "^4.2.3" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "requires": { + "yallist": "^4.0.0" + } + }, + "semver": { + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", + "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "dev": true, + "requires": { + "lru-cache": "^6.0.0" + } + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "dependencies": { + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + } + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.1" + } + }, + "yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + } } }, "process": { diff --git a/package.json b/package.json index c20e7f883..3ea1d7301 100644 --- a/package.json +++ b/package.json @@ -67,6 +67,7 @@ "glob": "^8.0.3", "graphlib": "^2.1.8", "hardhat": "^2.9.1", + "hardhat-exposed": "^0.3.0", "hardhat-gas-reporter": "^1.0.4", "hardhat-ignore-warnings": "^0.2.0", "keccak256": "^1.0.2", diff --git a/scripts/generate/run.js b/scripts/generate/run.js index 60dd795d5..51ddba339 100755 --- a/scripts/generate/run.js +++ b/scripts/generate/run.js @@ -16,18 +16,10 @@ function getVersion (path) { } for (const [ file, template ] of Object.entries({ - // SafeCast 'utils/math/SafeCast.sol': './templates/SafeCast.js', - 'mocks/SafeCastMock.sol': './templates/SafeCastMock.js', - // EnumerableSet 'utils/structs/EnumerableSet.sol': './templates/EnumerableSet.js', - 'mocks/EnumerableSetMock.sol': './templates/EnumerableSetMock.js', - // EnumerableMap 'utils/structs/EnumerableMap.sol': './templates/EnumerableMap.js', - 'mocks/EnumerableMapMock.sol': './templates/EnumerableMapMock.js', - // Checkpoints 'utils/Checkpoints.sol': './templates/Checkpoints.js', - 'mocks/CheckpointsMock.sol': './templates/CheckpointsMock.js', })) { const script = path.relative(path.join(__dirname, '../..'), __filename); const input = path.join(path.dirname(script), template); diff --git a/scripts/generate/templates/CheckpointsMock.js b/scripts/generate/templates/CheckpointsMock.js deleted file mode 100755 index 145f08408..000000000 --- a/scripts/generate/templates/CheckpointsMock.js +++ /dev/null @@ -1,80 +0,0 @@ -const format = require('../format-lines'); - -const VALUE_SIZES = [ 224, 160 ]; - -const header = `\ -pragma solidity ^0.8.0; - -import "../utils/Checkpoints.sol"; -`; - -const legacy = () => `\ -contract CheckpointsMock { - using Checkpoints for Checkpoints.History; - - Checkpoints.History private _totalCheckpoints; - - function latest() public view returns (uint256) { - return _totalCheckpoints.latest(); - } - - function latestCheckpoint() public view returns (bool, uint256, uint256) { - return _totalCheckpoints.latestCheckpoint(); - } - - function length() public view returns (uint256) { - return _totalCheckpoints.length(); - } - - function push(uint256 value) public returns (uint256, uint256) { - return _totalCheckpoints.push(value); - } - - function getAtBlock(uint256 blockNumber) public view returns (uint256) { - return _totalCheckpoints.getAtBlock(blockNumber); - } - - function getAtProbablyRecentBlock(uint256 blockNumber) public view returns (uint256) { - return _totalCheckpoints.getAtProbablyRecentBlock(blockNumber); - } -} -`; - -const checkpoint = length => `\ -contract Checkpoints${length}Mock { - using Checkpoints for Checkpoints.Trace${length}; - - Checkpoints.Trace${length} private _totalCheckpoints; - - function latest() public view returns (uint${length}) { - return _totalCheckpoints.latest(); - } - - function latestCheckpoint() public view returns (bool, uint${256 - length}, uint${length}) { - return _totalCheckpoints.latestCheckpoint(); - } - - function length() public view returns (uint256) { - return _totalCheckpoints.length(); - } - - function push(uint${256 - length} key, uint${length} value) public returns (uint${length}, uint${length}) { - return _totalCheckpoints.push(key, value); - } - - function lowerLookup(uint${256 - length} key) public view returns (uint${length}) { - return _totalCheckpoints.lowerLookup(key); - } - - function upperLookup(uint${256 - length} key) public view returns (uint${length}) { - return _totalCheckpoints.upperLookup(key); - } -} -`; - -// GENERATE -module.exports = format( - header, - legacy(), - ...VALUE_SIZES.map(checkpoint), -); diff --git a/scripts/generate/templates/EnumerableMapMock.js b/scripts/generate/templates/EnumerableMapMock.js deleted file mode 100755 index ff26a6aed..000000000 --- a/scripts/generate/templates/EnumerableMapMock.js +++ /dev/null @@ -1,66 +0,0 @@ -const format = require('../format-lines'); - -const TYPES = [ - { name: 'UintToAddressMap', keyType: 'uint256', valueType: 'address' }, - { name: 'AddressToUintMap', keyType: 'address', valueType: 'uint256' }, - { name: 'Bytes32ToBytes32Map', keyType: 'bytes32', valueType: 'bytes32' }, - { name: 'UintToUintMap', keyType: 'uint256', valueType: 'uint256' }, - { name: 'Bytes32ToUintMap', keyType: 'bytes32', valueType: 'uint256' }, -]; - -const header = `\ -pragma solidity ^0.8.0; - -import "../utils/structs/EnumerableMap.sol"; -`; - -const customSetMock = ({ name, keyType, valueType }) => `\ -// ${name} -contract ${name}Mock { - using EnumerableMap for EnumerableMap.${name}; - - event OperationResult(bool result); - - EnumerableMap.${name} private _map; - - function contains(${keyType} key) public view returns (bool) { - return _map.contains(key); - } - - function set(${keyType} key, ${valueType} value) public { - bool result = _map.set(key, value); - emit OperationResult(result); - } - - function remove(${keyType} key) public { - bool result = _map.remove(key); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _map.length(); - } - - function at(uint256 index) public view returns (${keyType} key, ${valueType} value) { - return _map.at(index); - } - - function tryGet(${keyType} key) public view returns (bool, ${valueType}) { - return _map.tryGet(key); - } - - function get(${keyType} key) public view returns (${valueType}) { - return _map.get(key); - } - - function getWithMessage(${keyType} key, string calldata errorMessage) public view returns (${valueType}) { - return _map.get(key, errorMessage); - } -} -`; - -// GENERATE -module.exports = format( - header, - ...TYPES.map(details => customSetMock(details)), -); diff --git a/scripts/generate/templates/EnumerableSetMock.js b/scripts/generate/templates/EnumerableSetMock.js deleted file mode 100755 index fbc9b850c..000000000 --- a/scripts/generate/templates/EnumerableSetMock.js +++ /dev/null @@ -1,56 +0,0 @@ -const format = require('../format-lines'); - -const TYPES = [ - { name: 'Bytes32Set', type: 'bytes32' }, - { name: 'AddressSet', type: 'address' }, - { name: 'UintSet', type: 'uint256' }, -]; - -const header = `\ -pragma solidity ^0.8.0; - -import "../utils/structs/EnumerableSet.sol"; -`; - -const customSetMock = ({ name, type }) => `\ -// ${name} -contract Enumerable${name}Mock { - using EnumerableSet for EnumerableSet.${name}; - - event OperationResult(bool result); - - EnumerableSet.${name} private _set; - - function contains(${type} value) public view returns (bool) { - return _set.contains(value); - } - - function add(${type} value) public { - bool result = _set.add(value); - emit OperationResult(result); - } - - function remove(${type} value) public { - bool result = _set.remove(value); - emit OperationResult(result); - } - - function length() public view returns (uint256) { - return _set.length(); - } - - function at(uint256 index) public view returns (${type}) { - return _set.at(index); - } - - function values() public view returns (${type}[] memory) { - return _set.values(); - } -} -`; - -// GENERATE -module.exports = format( - header, - ...TYPES.map(details => customSetMock(details)), -); diff --git a/scripts/generate/templates/SafeCast.js b/scripts/generate/templates/SafeCast.js old mode 100755 new mode 100644 diff --git a/scripts/generate/templates/SafeCastMock.js b/scripts/generate/templates/SafeCastMock.js deleted file mode 100755 index 196d9b4f1..000000000 --- a/scripts/generate/templates/SafeCastMock.js +++ /dev/null @@ -1,50 +0,0 @@ -const format = require('../format-lines'); -const { range } = require('../../helpers'); - -const LENGTHS = range(8, 256, 8).reverse(); // 248 → 8 (in steps of 8) - -const header = `\ -pragma solidity ^0.8.0; - -import "../utils/math/SafeCast.sol"; -`; - -const toInt = length => `\ -function toInt${length}(uint${length} a) public pure returns (int${length}) { - return a.toInt${length}(); -} -`; - -const toUint = length => `\ -function toUint${length}(int${length} a) public pure returns (uint${length}) { - return a.toUint${length}(); -} -`; - -const toIntDownCast = length => `\ -function toInt${length}(int256 a) public pure returns (int${length}) { - return a.toInt${length}(); -} -`; - -const toUintDownCast = length => `\ -function toUint${length}(uint256 a) public pure returns (uint${length}) { - return a.toUint${length}(); -} -`; - -// GENERATE -module.exports = format( - header, - 'contract SafeCastMock {', - [ - 'using SafeCast for uint256;', - 'using SafeCast for int256;', - '', - toUint(256), - ...LENGTHS.map(toUintDownCast), - toInt(256), - ...LENGTHS.map(toIntDownCast), - ].flatMap(fn => fn.split('\n')).slice(0, -1), - '}', -); diff --git a/test/access/AccessControl.behavior.js b/test/access/AccessControl.behavior.js index 2edd3fd4a..310ac3693 100644 --- a/test/access/AccessControl.behavior.js +++ b/test/access/AccessControl.behavior.js @@ -115,7 +115,7 @@ function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, o describe('setting role admin', function () { beforeEach(async function () { - const receipt = await this.accessControl.setRoleAdmin(ROLE, OTHER_ROLE); + const receipt = await this.accessControl.$_setRoleAdmin(ROLE, OTHER_ROLE); expectEvent(receipt, 'RoleAdminChanged', { role: ROLE, previousAdminRole: DEFAULT_ADMIN_ROLE, @@ -161,19 +161,19 @@ function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, o }); it('do not revert if sender has role', async function () { - await this.accessControl.senderProtected(ROLE, { from: authorized }); + await this.accessControl.methods['$_checkRole(bytes32)'](ROLE, { from: authorized }); }); it('revert if sender doesn\'t have role #1', async function () { await expectRevert( - this.accessControl.senderProtected(ROLE, { from: other }), + this.accessControl.methods['$_checkRole(bytes32)'](ROLE, { from: other }), `${errorPrefix}: account ${other.toLowerCase()} is missing role ${ROLE}`, ); }); it('revert if sender doesn\'t have role #2', async function () { await expectRevert( - this.accessControl.senderProtected(OTHER_ROLE, { from: authorized }), + this.accessControl.methods['$_checkRole(bytes32)'](OTHER_ROLE, { from: authorized }), `${errorPrefix}: account ${authorized.toLowerCase()} is missing role ${OTHER_ROLE}`, ); }); @@ -211,6 +211,7 @@ function shouldBehaveLikeAccessControlEnumerable (errorPrefix, admin, authorized } module.exports = { + DEFAULT_ADMIN_ROLE, shouldBehaveLikeAccessControl, shouldBehaveLikeAccessControlEnumerable, }; diff --git a/test/access/AccessControl.test.js b/test/access/AccessControl.test.js index cd9912adb..a462d5e54 100644 --- a/test/access/AccessControl.test.js +++ b/test/access/AccessControl.test.js @@ -1,12 +1,14 @@ const { + DEFAULT_ADMIN_ROLE, shouldBehaveLikeAccessControl, } = require('./AccessControl.behavior.js'); -const AccessControlMock = artifacts.require('AccessControlMock'); +const AccessControl = artifacts.require('$AccessControl'); contract('AccessControl', function (accounts) { beforeEach(async function () { - this.accessControl = await AccessControlMock.new({ from: accounts[0] }); + this.accessControl = await AccessControl.new({ from: accounts[0] }); + await this.accessControl.$_grantRole(DEFAULT_ADMIN_ROLE, accounts[0]); }); shouldBehaveLikeAccessControl('AccessControl', ...accounts); diff --git a/test/access/AccessControlCrossChain.test.js b/test/access/AccessControlCrossChain.test.js index cb4f3626d..5146848ed 100644 --- a/test/access/AccessControlCrossChain.test.js +++ b/test/access/AccessControlCrossChain.test.js @@ -2,6 +2,7 @@ const { expectRevert } = require('@openzeppelin/test-helpers'); const { BridgeHelper } = require('../helpers/crosschain'); const { + DEFAULT_ADMIN_ROLE, shouldBehaveLikeAccessControl, } = require('./AccessControl.behavior.js'); @@ -10,7 +11,7 @@ const crossChainRoleAlias = (role) => web3.utils.leftPad( 64, ); -const AccessControlCrossChainMock = artifacts.require('AccessControlCrossChainMock'); +const AccessControlCrossChainMock = artifacts.require('$AccessControlCrossChainMock'); const ROLE = web3.utils.soliditySha3('ROLE'); @@ -21,6 +22,7 @@ contract('AccessControl', function (accounts) { beforeEach(async function () { this.accessControl = await AccessControlCrossChainMock.new({ from: accounts[0] }); + await this.accessControl.$_grantRole(DEFAULT_ADMIN_ROLE, accounts[0]); }); shouldBehaveLikeAccessControl('AccessControl', ...accounts); @@ -32,7 +34,7 @@ contract('AccessControl', function (accounts) { }); it('check alliassing', async function () { - expect(await this.accessControl.crossChainRoleAlias(ROLE)).to.be.bignumber.equal(crossChainRoleAlias(ROLE)); + expect(await this.accessControl.$_crossChainRoleAlias(ROLE)).to.be.bignumber.equal(crossChainRoleAlias(ROLE)); }); it('Crosschain calls not authorized to non-aliased addresses', async function () { @@ -40,7 +42,7 @@ contract('AccessControl', function (accounts) { this.bridge.call( accounts[0], this.accessControl, - 'senderProtected', + '$_checkRole(bytes32)', [ ROLE ], ), `AccessControl: account ${accounts[0].toLowerCase()} is missing role ${crossChainRoleAlias(ROLE)}`, @@ -51,7 +53,7 @@ contract('AccessControl', function (accounts) { await this.bridge.call( accounts[1], this.accessControl, - 'senderProtected', + '$_checkRole(bytes32)', [ ROLE ], ); }); diff --git a/test/access/AccessControlEnumerable.test.js b/test/access/AccessControlEnumerable.test.js index fa5b54691..2aa59f4c0 100644 --- a/test/access/AccessControlEnumerable.test.js +++ b/test/access/AccessControlEnumerable.test.js @@ -1,13 +1,15 @@ const { + DEFAULT_ADMIN_ROLE, shouldBehaveLikeAccessControl, shouldBehaveLikeAccessControlEnumerable, } = require('./AccessControl.behavior.js'); -const AccessControlMock = artifacts.require('AccessControlEnumerableMock'); +const AccessControlEnumerable = artifacts.require('$AccessControlEnumerable'); contract('AccessControl', function (accounts) { beforeEach(async function () { - this.accessControl = await AccessControlMock.new({ from: accounts[0] }); + this.accessControl = await AccessControlEnumerable.new({ from: accounts[0] }); + await this.accessControl.$_grantRole(DEFAULT_ADMIN_ROLE, accounts[0]); }); shouldBehaveLikeAccessControl('AccessControl', ...accounts); diff --git a/test/access/Ownable.test.js b/test/access/Ownable.test.js index 894e77c31..b8ca81d28 100644 --- a/test/access/Ownable.test.js +++ b/test/access/Ownable.test.js @@ -3,7 +3,7 @@ const { ZERO_ADDRESS } = constants; const { expect } = require('chai'); -const Ownable = artifacts.require('OwnableMock'); +const Ownable = artifacts.require('$Ownable'); contract('Ownable', function (accounts) { const [ owner, other ] = accounts; diff --git a/test/access/Ownable2Step.test.js b/test/access/Ownable2Step.test.js index 0aeb22465..64d432762 100644 --- a/test/access/Ownable2Step.test.js +++ b/test/access/Ownable2Step.test.js @@ -2,7 +2,7 @@ const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-hel const { ZERO_ADDRESS } = constants; const { expect } = require('chai'); -const Ownable2Step = artifacts.require('Ownable2StepMock'); +const Ownable2Step = artifacts.require('$Ownable2Step'); contract('Ownable2Step', function (accounts) { const [owner, accountA, accountB] = accounts; diff --git a/test/finance/PaymentSplitter.test.js b/test/finance/PaymentSplitter.test.js index 2fa7a26fa..ef74d4f69 100644 --- a/test/finance/PaymentSplitter.test.js +++ b/test/finance/PaymentSplitter.test.js @@ -4,7 +4,7 @@ const { ZERO_ADDRESS } = constants; const { expect } = require('chai'); const PaymentSplitter = artifacts.require('PaymentSplitter'); -const Token = artifacts.require('ERC20Mock'); +const ERC20 = artifacts.require('$ERC20'); contract('PaymentSplitter', function (accounts) { const [ owner, payee1, payee2, payee3, nonpayee1, payer1 ] = accounts; @@ -51,7 +51,8 @@ contract('PaymentSplitter', function (accounts) { this.shares = [20, 10, 70]; this.contract = await PaymentSplitter.new(this.payees, this.shares); - this.token = await Token.new('MyToken', 'MT', owner, ether('1000')); + this.token = await ERC20.new('MyToken', 'MT'); + await this.token.$_mint(owner, ether('1000')); }); it('has total shares', async function () { diff --git a/test/finance/VestingWallet.behavior.js b/test/finance/VestingWallet.behavior.js index d1d2fbf4a..5ab6233ca 100644 --- a/test/finance/VestingWallet.behavior.js +++ b/test/finance/VestingWallet.behavior.js @@ -10,7 +10,7 @@ function releasedEvent (token, amount) { function shouldBehaveLikeVesting (beneficiary) { it('check vesting schedule', async function () { - const [ fnVestedAmount, fnReleasable, ...args ] = this.token + const [ vestedAmount, releasable, ...args ] = this.token ? [ 'vestedAmount(address,uint64)', 'releasable(address)', this.token.address ] : [ 'vestedAmount(uint64)', 'releasable()' ]; @@ -18,16 +18,16 @@ function shouldBehaveLikeVesting (beneficiary) { await time.increaseTo(timestamp); const vesting = this.vestingFn(timestamp); - expect(await this.mock.methods[fnVestedAmount](...args, timestamp)) + expect(await this.mock.methods[vestedAmount](...args, timestamp)) .to.be.bignumber.equal(vesting); - expect(await this.mock.methods[fnReleasable](...args)) + expect(await this.mock.methods[releasable](...args)) .to.be.bignumber.equal(vesting); } }); it('execute vesting schedule', async function () { - const [ fnRelease, ...args ] = this.token + const [ release, ...args ] = this.token ? [ 'release(address)', this.token.address ] : [ 'release()' ]; @@ -35,7 +35,7 @@ function shouldBehaveLikeVesting (beneficiary) { const before = await this.getBalance(beneficiary); { - const receipt = await this.mock.methods[fnRelease](...args); + const receipt = await this.mock.methods[release](...args); await expectEvent.inTransaction( receipt.tx, @@ -52,7 +52,7 @@ function shouldBehaveLikeVesting (beneficiary) { await time.setNextBlockTimestamp(timestamp); const vested = this.vestingFn(timestamp); - const receipt = await this.mock.methods[fnRelease](...args); + const receipt = await this.mock.methods[release](...args); await expectEvent.inTransaction( receipt.tx, this.mock, diff --git a/test/finance/VestingWallet.test.js b/test/finance/VestingWallet.test.js index 6aa737805..81a1e228a 100644 --- a/test/finance/VestingWallet.test.js +++ b/test/finance/VestingWallet.test.js @@ -2,8 +2,8 @@ const { constants, expectEvent, expectRevert, time } = require('@openzeppelin/te const { web3 } = require('@openzeppelin/test-helpers/src/setup'); const { expect } = require('chai'); -const ERC20Mock = artifacts.require('ERC20Mock'); const VestingWallet = artifacts.require('VestingWallet'); +const ERC20 = artifacts.require('$ERC20'); const { shouldBehaveLikeVesting } = require('./VestingWallet.behavior'); @@ -51,7 +51,7 @@ contract('VestingWallet', function (accounts) { describe('ERC20 vesting', function () { beforeEach(async function () { - this.token = await ERC20Mock.new('Name', 'Symbol', this.mock.address, amount); + this.token = await ERC20.new('Name', 'Symbol'); this.getBalance = (account) => this.token.balanceOf(account); this.checkRelease = (receipt, to, value) => expectEvent.inTransaction( receipt.tx, @@ -59,6 +59,8 @@ contract('VestingWallet', function (accounts) { 'Transfer', { from: this.mock.address, to, value }, ); + + await this.token.$_mint(this.mock.address, amount); }); shouldBehaveLikeVesting(beneficiary); diff --git a/test/governance/Governor.test.js b/test/governance/Governor.test.js index b1d0b0515..e5dd04cf0 100644 --- a/test/governance/Governor.test.js +++ b/test/governance/Governor.test.js @@ -11,11 +11,11 @@ const { shouldSupportInterfaces, } = require('../utils/introspection/SupportsInterface.behavior'); -const Token = artifacts.require('ERC20VotesMock'); -const Governor = artifacts.require('GovernorMock'); +const Token = artifacts.require('$ERC20Votes'); +const Governor = artifacts.require('$GovernorMock'); const CallReceiver = artifacts.require('CallReceiverMock'); -const ERC721Mock = artifacts.require('ERC721Mock'); -const ERC1155Mock = artifacts.require('ERC1155Mock'); +const ERC721 = artifacts.require('$ERC721'); +const ERC1155 = artifacts.require('$ERC1155'); contract('Governor', function (accounts) { const [ owner, proposer, voter1, voter2, voter3, voter4 ] = accounts; @@ -32,15 +32,22 @@ contract('Governor', function (accounts) { beforeEach(async function () { this.chainId = await web3.eth.getChainId(); - this.token = await Token.new(tokenName, tokenSymbol); - this.mock = await Governor.new(name, this.token.address, votingDelay, votingPeriod, 10); + this.token = await Token.new(tokenName, tokenSymbol, tokenName); + this.mock = await Governor.new( + name, // name + votingDelay, // initialVotingDelay + votingPeriod, // initialVotingPeriod + 0, // initialProposalThreshold + this.token.address, // tokenAddress + 10, // quorumNumeratorValue + ); this.receiver = await CallReceiver.new(); this.helper = new GovernorHelper(this.mock); await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value }); - await this.token.mint(owner, tokenSupply); + await this.token.$_mint(owner, tokenSupply); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner }); @@ -585,8 +592,8 @@ contract('Governor', function (accounts) { const tokenId = new BN(1); beforeEach(async function () { - this.token = await ERC721Mock.new(name, symbol); - await this.token.mint(owner, tokenId); + this.token = await ERC721.new(name, symbol); + await this.token.$_mint(owner, tokenId); }); it('can receive an ERC721 safeTransfer', async function () { @@ -603,8 +610,8 @@ contract('Governor', function (accounts) { }; beforeEach(async function () { - this.token = await ERC1155Mock.new(uri); - await this.token.mintBatch(owner, Object.keys(tokenIds), Object.values(tokenIds), '0x'); + this.token = await ERC1155.new(uri); + await this.token.$_mintBatch(owner, Object.keys(tokenIds), Object.values(tokenIds), '0x'); }); it('can receive ERC1155 safeTransfer', async function () { diff --git a/test/governance/TimelockController.test.js b/test/governance/TimelockController.test.js index e0a32440e..3b31f8189 100644 --- a/test/governance/TimelockController.test.js +++ b/test/governance/TimelockController.test.js @@ -10,8 +10,8 @@ const { const TimelockController = artifacts.require('TimelockController'); const CallReceiverMock = artifacts.require('CallReceiverMock'); const Implementation2 = artifacts.require('Implementation2'); -const ERC721Mock = artifacts.require('ERC721Mock'); -const ERC1155Mock = artifacts.require('ERC1155Mock'); +const ERC721 = artifacts.require('$ERC721'); +const ERC1155 = artifacts.require('$ERC1155'); const MINDELAY = time.duration.days(1); @@ -1087,8 +1087,8 @@ contract('TimelockController', function (accounts) { const tokenId = new BN(1); beforeEach(async function () { - this.token = await ERC721Mock.new(name, symbol); - await this.token.mint(other, tokenId); + this.token = await ERC721.new(name, symbol); + await this.token.$_mint(other, tokenId); }); it('can receive an ERC721 safeTransfer', async function () { @@ -1105,8 +1105,8 @@ contract('TimelockController', function (accounts) { }; beforeEach(async function () { - this.token = await ERC1155Mock.new(uri); - await this.token.mintBatch(other, Object.keys(tokenIds), Object.values(tokenIds), '0x'); + this.token = await ERC1155.new(uri); + await this.token.$_mintBatch(other, Object.keys(tokenIds), Object.values(tokenIds), '0x'); }); it('can receive ERC1155 safeTransfer', async function () { diff --git a/test/governance/compatibility/GovernorCompatibilityBravo.test.js b/test/governance/compatibility/GovernorCompatibilityBravo.test.js index f46efd622..1c25be36a 100644 --- a/test/governance/compatibility/GovernorCompatibilityBravo.test.js +++ b/test/governance/compatibility/GovernorCompatibilityBravo.test.js @@ -4,9 +4,9 @@ const RLP = require('rlp'); const Enums = require('../../helpers/enums'); const { GovernorHelper } = require('../../helpers/governance'); -const Token = artifacts.require('ERC20VotesCompMock'); +const Token = artifacts.require('$ERC20VotesComp'); const Timelock = artifacts.require('CompTimelock'); -const Governor = artifacts.require('GovernorCompatibilityBravoMock'); +const Governor = artifacts.require('$GovernorCompatibilityBravoMock'); const CallReceiver = artifacts.require('CallReceiverMock'); function makeContractAddress (creator, nonce) { @@ -29,7 +29,7 @@ contract('GovernorCompatibilityBravo', function (accounts) { beforeEach(async function () { const [ deployer ] = await web3.eth.getAccounts(); - this.token = await Token.new(tokenName, tokenSymbol); + this.token = await Token.new(tokenName, tokenSymbol, tokenName); // Need to predict governance address to set it as timelock admin with a delayed transfer const nonce = await web3.eth.getTransactionCount(deployer); @@ -38,11 +38,11 @@ contract('GovernorCompatibilityBravo', function (accounts) { this.timelock = await Timelock.new(predictGovernor, 2 * 86400); this.mock = await Governor.new( name, - this.token.address, votingDelay, votingPeriod, proposalThreshold, this.timelock.address, + this.token.address, ); this.receiver = await CallReceiver.new(); @@ -50,7 +50,7 @@ contract('GovernorCompatibilityBravo', function (accounts) { await web3.eth.sendTransaction({ from: owner, to: this.timelock.address, value }); - await this.token.mint(owner, tokenSupply); + await this.token.$_mint(owner, tokenSupply); await this.helper.delegate({ token: this.token, to: proposer, value: proposalThreshold }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner }); diff --git a/test/governance/extensions/GovernorComp.test.js b/test/governance/extensions/GovernorComp.test.js index 06d2d6251..d32480ec1 100644 --- a/test/governance/extensions/GovernorComp.test.js +++ b/test/governance/extensions/GovernorComp.test.js @@ -3,8 +3,8 @@ const { expect } = require('chai'); const Enums = require('../../helpers/enums'); const { GovernorHelper } = require('../../helpers/governance'); -const Token = artifacts.require('ERC20VotesCompMock'); -const Governor = artifacts.require('GovernorCompMock'); +const Token = artifacts.require('$ERC20VotesComp'); +const Governor = artifacts.require('$GovernorCompMock'); const CallReceiver = artifacts.require('CallReceiverMock'); contract('GovernorComp', function (accounts) { @@ -21,7 +21,7 @@ contract('GovernorComp', function (accounts) { beforeEach(async function () { this.owner = owner; - this.token = await Token.new(tokenName, tokenSymbol); + this.token = await Token.new(tokenName, tokenSymbol, tokenName); this.mock = await Governor.new(name, this.token.address); this.receiver = await CallReceiver.new(); @@ -29,7 +29,7 @@ contract('GovernorComp', function (accounts) { await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value }); - await this.token.mint(owner, tokenSupply); + await this.token.$_mint(owner, tokenSupply); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner }); diff --git a/test/governance/extensions/GovernorERC721.test.js b/test/governance/extensions/GovernorERC721.test.js index 086fca4c8..4c402737b 100644 --- a/test/governance/extensions/GovernorERC721.test.js +++ b/test/governance/extensions/GovernorERC721.test.js @@ -3,11 +3,11 @@ const { expect } = require('chai'); const Enums = require('../../helpers/enums'); const { GovernorHelper } = require('../../helpers/governance'); -const Token = artifacts.require('ERC721VotesMock'); -const Governor = artifacts.require('GovernorVoteMocks'); +const Token = artifacts.require('$ERC721Votes'); +const Governor = artifacts.require('$GovernorVoteMocks'); const CallReceiver = artifacts.require('CallReceiverMock'); -contract('GovernorERC721Mock', function (accounts) { +contract('GovernorERC721', function (accounts) { const [ owner, voter1, voter2, voter3, voter4 ] = accounts; const name = 'OZ-Governor'; @@ -25,7 +25,7 @@ contract('GovernorERC721Mock', function (accounts) { beforeEach(async function () { this.owner = owner; - this.token = await Token.new(tokenName, tokenSymbol); + this.token = await Token.new(tokenName, tokenSymbol, tokenName, '1'); this.mock = await Governor.new(name, this.token.address); this.receiver = await CallReceiver.new(); @@ -33,7 +33,7 @@ contract('GovernorERC721Mock', function (accounts) { await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value }); - await Promise.all([ NFT0, NFT1, NFT2, NFT3, NFT4 ].map(tokenId => this.token.mint(owner, tokenId))); + await Promise.all([ NFT0, NFT1, NFT2, NFT3, NFT4 ].map(tokenId => this.token.$_mint(owner, tokenId))); await this.helper.delegate({ token: this.token, to: voter1, tokenId: NFT0 }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter2, tokenId: NFT1 }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter2, tokenId: NFT2 }, { from: owner }); diff --git a/test/governance/extensions/GovernorPreventLateQuorum.test.js b/test/governance/extensions/GovernorPreventLateQuorum.test.js index 6a5d644e7..b179e26f7 100644 --- a/test/governance/extensions/GovernorPreventLateQuorum.test.js +++ b/test/governance/extensions/GovernorPreventLateQuorum.test.js @@ -3,8 +3,8 @@ const { expect } = require('chai'); const Enums = require('../../helpers/enums'); const { GovernorHelper } = require('../../helpers/governance'); -const Token = artifacts.require('ERC20VotesCompMock'); -const Governor = artifacts.require('GovernorPreventLateQuorumMock'); +const Token = artifacts.require('$ERC20VotesComp'); +const Governor = artifacts.require('$GovernorPreventLateQuorumMock'); const CallReceiver = artifacts.require('CallReceiverMock'); contract('GovernorPreventLateQuorum', function (accounts) { @@ -23,14 +23,15 @@ contract('GovernorPreventLateQuorum', function (accounts) { beforeEach(async function () { this.owner = owner; - this.token = await Token.new(tokenName, tokenSymbol); + this.token = await Token.new(tokenName, tokenSymbol, tokenName); this.mock = await Governor.new( name, - this.token.address, votingDelay, votingPeriod, - quorum, + 0, + this.token.address, lateQuorumVoteExtension, + quorum, ); this.receiver = await CallReceiver.new(); @@ -38,7 +39,7 @@ contract('GovernorPreventLateQuorum', function (accounts) { await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value }); - await this.token.mint(owner, tokenSupply); + await this.token.$_mint(owner, tokenSupply); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner }); diff --git a/test/governance/extensions/GovernorTimelockCompound.test.js b/test/governance/extensions/GovernorTimelockCompound.test.js index a31df68a2..3e8e10b10 100644 --- a/test/governance/extensions/GovernorTimelockCompound.test.js +++ b/test/governance/extensions/GovernorTimelockCompound.test.js @@ -8,9 +8,9 @@ const { shouldSupportInterfaces, } = require('../../utils/introspection/SupportsInterface.behavior'); -const Token = artifacts.require('ERC20VotesMock'); +const Token = artifacts.require('$ERC20Votes'); const Timelock = artifacts.require('CompTimelock'); -const Governor = artifacts.require('GovernorTimelockCompoundMock'); +const Governor = artifacts.require('$GovernorTimelockCompoundMock'); const CallReceiver = artifacts.require('CallReceiverMock'); function makeContractAddress (creator, nonce) { @@ -32,7 +32,7 @@ contract('GovernorTimelockCompound', function (accounts) { beforeEach(async function () { const [ deployer ] = await web3.eth.getAccounts(); - this.token = await Token.new(tokenName, tokenSymbol); + this.token = await Token.new(tokenName, tokenSymbol, tokenName); // Need to predict governance address to set it as timelock admin with a delayed transfer const nonce = await web3.eth.getTransactionCount(deployer); @@ -41,10 +41,11 @@ contract('GovernorTimelockCompound', function (accounts) { this.timelock = await Timelock.new(predictGovernor, 2 * 86400); this.mock = await Governor.new( name, - this.token.address, votingDelay, votingPeriod, + 0, this.timelock.address, + this.token.address, 0, ); this.receiver = await CallReceiver.new(); @@ -53,7 +54,7 @@ contract('GovernorTimelockCompound', function (accounts) { await web3.eth.sendTransaction({ from: owner, to: this.timelock.address, value }); - await this.token.mint(owner, tokenSupply); + await this.token.$_mint(owner, tokenSupply); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner }); @@ -245,7 +246,7 @@ contract('GovernorTimelockCompound', function (accounts) { describe('onlyGovernance', function () { describe('relay', function () { beforeEach(async function () { - await this.token.mint(this.mock.address, 1); + await this.token.$_mint(this.mock.address, 1); }); it('is protected', async function () { @@ -337,8 +338,7 @@ contract('GovernorTimelockCompound', function (accounts) { }); it('can transfer timelock to new governor', async function () { - const newGovernor = await Governor.new(name, this.token.address, 8, 32, this.timelock.address, 0); - + const newGovernor = await Governor.new(name, 8, 32, 0, this.timelock.address, this.token.address, 0); this.helper.setProposal([ { target: this.timelock.address, diff --git a/test/governance/extensions/GovernorTimelockControl.test.js b/test/governance/extensions/GovernorTimelockControl.test.js index 56d3b225c..167734e9b 100644 --- a/test/governance/extensions/GovernorTimelockControl.test.js +++ b/test/governance/extensions/GovernorTimelockControl.test.js @@ -7,9 +7,9 @@ const { shouldSupportInterfaces, } = require('../../utils/introspection/SupportsInterface.behavior'); -const Token = artifacts.require('ERC20VotesMock'); +const Token = artifacts.require('$ERC20Votes'); const Timelock = artifacts.require('TimelockController'); -const Governor = artifacts.require('GovernorTimelockControlMock'); +const Governor = artifacts.require('$GovernorTimelockControlMock'); const CallReceiver = artifacts.require('CallReceiverMock'); contract('GovernorTimelockControl', function (accounts) { @@ -32,14 +32,15 @@ contract('GovernorTimelockControl', function (accounts) { beforeEach(async function () { const [ deployer ] = await web3.eth.getAccounts(); - this.token = await Token.new(tokenName, tokenSymbol); + this.token = await Token.new(tokenName, tokenSymbol, tokenName); this.timelock = await Timelock.new(3600, [], [], deployer); this.mock = await Governor.new( name, - this.token.address, votingDelay, votingPeriod, + 0, this.timelock.address, + this.token.address, 0, ); this.receiver = await CallReceiver.new(); @@ -61,7 +62,7 @@ contract('GovernorTimelockControl', function (accounts) { await this.timelock.grantRole(EXECUTOR_ROLE, constants.ZERO_ADDRESS); await this.timelock.revokeRole(TIMELOCK_ADMIN_ROLE, deployer); - await this.token.mint(owner, tokenSupply); + await this.token.$_mint(owner, tokenSupply); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner }); @@ -245,7 +246,7 @@ contract('GovernorTimelockControl', function (accounts) { describe('onlyGovernance', function () { describe('relay', function () { beforeEach(async function () { - await this.token.mint(this.mock.address, 1); + await this.token.$_mint(this.mock.address, 1); }); it('is protected', async function () { diff --git a/test/governance/extensions/GovernorVotesQuorumFraction.test.js b/test/governance/extensions/GovernorVotesQuorumFraction.test.js index 9e6b71bc0..763f03068 100644 --- a/test/governance/extensions/GovernorVotesQuorumFraction.test.js +++ b/test/governance/extensions/GovernorVotesQuorumFraction.test.js @@ -3,8 +3,8 @@ const { expect } = require('chai'); const Enums = require('../../helpers/enums'); const { GovernorHelper } = require('../../helpers/governance'); -const Token = artifacts.require('ERC20VotesMock'); -const Governor = artifacts.require('GovernorMock'); +const Token = artifacts.require('$ERC20Votes'); +const Governor = artifacts.require('$GovernorMock'); const CallReceiver = artifacts.require('CallReceiverMock'); contract('GovernorVotesQuorumFraction', function (accounts) { @@ -23,15 +23,22 @@ contract('GovernorVotesQuorumFraction', function (accounts) { beforeEach(async function () { this.owner = owner; - this.token = await Token.new(tokenName, tokenSymbol); - this.mock = await Governor.new(name, this.token.address, votingDelay, votingPeriod, ratio); + this.token = await Token.new(tokenName, tokenSymbol, tokenName); + this.mock = await Governor.new( + name, + votingDelay, + votingPeriod, + 0, + this.token.address, + ratio, + ); this.receiver = await CallReceiver.new(); this.helper = new GovernorHelper(this.mock); await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value }); - await this.token.mint(owner, tokenSupply); + await this.token.$_mint(owner, tokenSupply); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner }); diff --git a/test/governance/extensions/GovernorWithParams.test.js b/test/governance/extensions/GovernorWithParams.test.js index 875b7053a..981fe0715 100644 --- a/test/governance/extensions/GovernorWithParams.test.js +++ b/test/governance/extensions/GovernorWithParams.test.js @@ -7,8 +7,8 @@ const Enums = require('../../helpers/enums'); const { EIP712Domain } = require('../../helpers/eip712'); const { GovernorHelper } = require('../../helpers/governance'); -const Token = artifacts.require('ERC20VotesCompMock'); -const Governor = artifacts.require('GovernorWithParamsMock'); +const Token = artifacts.require('$ERC20VotesComp'); +const Governor = artifacts.require('$GovernorWithParamsMock'); const CallReceiver = artifacts.require('CallReceiverMock'); const rawParams = { @@ -35,7 +35,7 @@ contract('GovernorWithParams', function (accounts) { beforeEach(async function () { this.chainId = await web3.eth.getChainId(); - this.token = await Token.new(tokenName, tokenSymbol); + this.token = await Token.new(tokenName, tokenSymbol, tokenName); this.mock = await Governor.new(name, this.token.address); this.receiver = await CallReceiver.new(); @@ -43,7 +43,7 @@ contract('GovernorWithParams', function (accounts) { await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value }); - await this.token.mint(owner, tokenSupply); + await this.token.$_mint(owner, tokenSupply); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner }); diff --git a/test/governance/utils/Votes.behavior.js b/test/governance/utils/Votes.behavior.js index aee227bdb..fc3af64dd 100644 --- a/test/governance/utils/Votes.behavior.js +++ b/test/governance/utils/Votes.behavior.js @@ -26,7 +26,12 @@ function shouldBehaveLikeVotes () { expect( await this.votes.DOMAIN_SEPARATOR(), ).to.equal( - await domainSeparator(this.name, version, this.chainId, this.votes.address), + await domainSeparator({ + name: this.name, + version, + chainId: this.chainId, + verifyingContract: this.votes.address, + }), ); }); @@ -45,7 +50,7 @@ function shouldBehaveLikeVotes () { }); beforeEach(async function () { - await this.votes.mint(delegatorAddress, this.NFT0); + await this.votes.$_mint(delegatorAddress, this.NFT0); }); it('accept signed delegation', async function () { @@ -151,7 +156,7 @@ function shouldBehaveLikeVotes () { describe('set delegation', function () { describe('call', function () { it('delegation with tokens', async function () { - await this.votes.mint(this.account1, this.NFT0); + await this.votes.$_mint(this.account1, this.NFT0); expect(await this.votes.delegates(this.account1)).to.be.equal(ZERO_ADDRESS); const { receipt } = await this.votes.delegate(this.account1, { from: this.account1 }); @@ -192,7 +197,7 @@ function shouldBehaveLikeVotes () { describe('change delegation', function () { beforeEach(async function () { - await this.votes.mint(this.account1, this.NFT0); + await this.votes.$_mint(this.account1, this.NFT0); await this.votes.delegate(this.account1, { from: this.account1 }); }); @@ -245,7 +250,7 @@ function shouldBehaveLikeVotes () { }); it('returns the latest block if >= last checkpoint block', async function () { - const t1 = await this.votes.mint(this.account1, this.NFT0); + const t1 = await this.votes.$_mint(this.account1, this.NFT0); await time.advanceBlock(); await time.advanceBlock(); @@ -255,7 +260,7 @@ function shouldBehaveLikeVotes () { it('returns zero if < first checkpoint block', async function () { await time.advanceBlock(); - const t2 = await this.votes.mint(this.account1, this.NFT1); + const t2 = await this.votes.$_mint(this.account1, this.NFT1); await time.advanceBlock(); await time.advanceBlock(); @@ -264,19 +269,19 @@ function shouldBehaveLikeVotes () { }); it('generally returns the voting balance at the appropriate checkpoint', async function () { - const t1 = await this.votes.mint(this.account1, this.NFT1); + const t1 = await this.votes.$_mint(this.account1, this.NFT1); await time.advanceBlock(); await time.advanceBlock(); - const t2 = await this.votes.burn(this.NFT1); + const t2 = await this.votes.$_burn(this.NFT1); await time.advanceBlock(); await time.advanceBlock(); - const t3 = await this.votes.mint(this.account1, this.NFT2); + const t3 = await this.votes.$_mint(this.account1, this.NFT2); await time.advanceBlock(); await time.advanceBlock(); - const t4 = await this.votes.burn(this.NFT2); + const t4 = await this.votes.$_burn(this.NFT2); await time.advanceBlock(); await time.advanceBlock(); - const t5 = await this.votes.mint(this.account1, this.NFT3); + const t5 = await this.votes.$_mint(this.account1, this.NFT3); await time.advanceBlock(); await time.advanceBlock(); @@ -298,10 +303,10 @@ function shouldBehaveLikeVotes () { // https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js. describe('Compound test suite', function () { beforeEach(async function () { - await this.votes.mint(this.account1, this.NFT0); - await this.votes.mint(this.account1, this.NFT1); - await this.votes.mint(this.account1, this.NFT2); - await this.votes.mint(this.account1, this.NFT3); + await this.votes.$_mint(this.account1, this.NFT0); + await this.votes.$_mint(this.account1, this.NFT1); + await this.votes.$_mint(this.account1, this.NFT2); + await this.votes.$_mint(this.account1, this.NFT3); }); describe('getPastVotes', function () { diff --git a/test/governance/utils/Votes.test.js b/test/governance/utils/Votes.test.js index 32b7d1dca..e9b50b0a3 100644 --- a/test/governance/utils/Votes.test.js +++ b/test/governance/utils/Votes.test.js @@ -2,17 +2,19 @@ const { expectRevert, BN } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); +const { getChainId } = require('../../helpers/chainid'); + const { shouldBehaveLikeVotes, } = require('./Votes.behavior'); -const Votes = artifacts.require('VotesMock'); +const Votes = artifacts.require('$VotesMock'); contract('Votes', function (accounts) { const [ account1, account2, account3 ] = accounts; beforeEach(async function () { this.name = 'My Vote'; - this.votes = await Votes.new(this.name); + this.votes = await Votes.new(this.name, '1'); }); it('starts with zero votes', async function () { @@ -21,9 +23,9 @@ contract('Votes', function (accounts) { describe('performs voting operations', function () { beforeEach(async function () { - this.tx1 = await this.votes.mint(account1, 1); - this.tx2 = await this.votes.mint(account2, 1); - this.tx3 = await this.votes.mint(account3, 1); + this.tx1 = await this.votes.$_mint(account1, 1); + this.tx2 = await this.votes.$_mint(account2, 1); + this.tx3 = await this.votes.$_mint(account3, 1); }); it('reverts if block number >= current block', async function () { @@ -46,7 +48,7 @@ contract('Votes', function (accounts) { describe('performs voting workflow', function () { beforeEach(async function () { - this.chainId = await this.votes.getChainId(); + this.chainId = await getChainId(); this.account1 = account1; this.account2 = account2; this.account1Delegatee = account2; diff --git a/test/helpers/chainid.js b/test/helpers/chainid.js new file mode 100644 index 000000000..f67b91bda --- /dev/null +++ b/test/helpers/chainid.js @@ -0,0 +1,10 @@ +const hre = require('hardhat'); + +async function getChainId () { + const chainIdHex = await hre.network.provider.send('eth_chainId', []); + return new hre.web3.utils.BN(chainIdHex, 'hex'); +} + +module.exports = { + getChainId, +}; diff --git a/test/helpers/eip712.js b/test/helpers/eip712.js index 8a64b8a35..26e2218bb 100644 --- a/test/helpers/eip712.js +++ b/test/helpers/eip712.js @@ -1,4 +1,5 @@ const ethSigUtil = require('eth-sig-util'); +const keccak256 = require('keccak256'); const EIP712Domain = [ { name: 'name', type: 'string' }, @@ -15,16 +16,35 @@ const Permit = [ { name: 'deadline', type: 'uint256' }, ]; -async function domainSeparator (name, version, chainId, verifyingContract) { - return '0x' + ethSigUtil.TypedDataUtils.hashStruct( - 'EIP712Domain', - { name, version, chainId, verifyingContract }, - { EIP712Domain }, - ).toString('hex'); +function bufferToHexString (buffer) { + return '0x' + buffer.toString('hex'); +} + +function hexStringToBuffer (hexstr) { + return Buffer.from(hexstr.replace(/^0x/, ''), 'hex'); +} + +async function domainSeparator ({ name, version, chainId, verifyingContract }) { + return bufferToHexString( + ethSigUtil.TypedDataUtils.hashStruct( + 'EIP712Domain', + { name, version, chainId, verifyingContract }, + { EIP712Domain }, + ), + ); +} + +async function hashTypedData (domain, structHash) { + return domainSeparator(domain).then(separator => bufferToHexString(keccak256(Buffer.concat([ + '0x1901', + separator, + structHash, + ].map(str => hexStringToBuffer(str)))))); } module.exports = { EIP712Domain, Permit, domainSeparator, + hashTypedData, }; diff --git a/test/helpers/governance.js b/test/helpers/governance.js index c56ec4c89..66a479b52 100644 --- a/test/helpers/governance.js +++ b/test/helpers/governance.js @@ -77,7 +77,7 @@ class GovernorHelper { [ proposal.id ], opts, )) - : this.governor.methods['cancel(address[],uint256[],bytes[],bytes32)'](...concatOpts( + : this.governor.methods['$_cancel(address[],uint256[],bytes[],bytes32)'](...concatOpts( proposal.shortProposal, opts, )); diff --git a/test/helpers/map-values.js b/test/helpers/map-values.js new file mode 100644 index 000000000..d2f7b2a3f --- /dev/null +++ b/test/helpers/map-values.js @@ -0,0 +1,7 @@ +function mapValues(obj, fn) { + return Object.fromEntries([...Object.entries(obj)].map(([k, v]) => [k, fn(v)])); +} + +module.exports = { + mapValues, +}; diff --git a/test/metatx/ERC2771Context.test.js b/test/metatx/ERC2771Context.test.js index 8db92ab83..788777726 100644 --- a/test/metatx/ERC2771Context.test.js +++ b/test/metatx/ERC2771Context.test.js @@ -10,6 +10,7 @@ const MinimalForwarder = artifacts.require('MinimalForwarder'); const ContextMockCaller = artifacts.require('ContextMockCaller'); const { shouldBehaveLikeRegularContext } = require('../utils/Context.behavior'); +const { getChainId } = require('../helpers/chainid'); const name = 'MinimalForwarder'; const version = '0.0.1'; @@ -22,7 +23,7 @@ contract('ERC2771Context', function (accounts) { this.domain = { name, version, - chainId: await web3.eth.getChainId(), + chainId: await getChainId(), verifyingContract: this.forwarder.address, }; this.types = { diff --git a/test/metatx/MinimalForwarder.test.js b/test/metatx/MinimalForwarder.test.js index b8984e431..15778505e 100644 --- a/test/metatx/MinimalForwarder.test.js +++ b/test/metatx/MinimalForwarder.test.js @@ -5,6 +5,8 @@ const { EIP712Domain } = require('../helpers/eip712'); const { expectRevert, constants } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); +const { getChainId } = require('../helpers/chainid'); + const MinimalForwarder = artifacts.require('MinimalForwarder'); const CallReceiverMock = artifacts.require('CallReceiverMock'); @@ -17,7 +19,7 @@ contract('MinimalForwarder', function (accounts) { this.domain = { name, version, - chainId: await web3.eth.getChainId(), + chainId: await getChainId(), verifyingContract: this.forwarder.address, }; this.types = { diff --git a/test/proxy/Clones.test.js b/test/proxy/Clones.test.js index 0393a3331..09f719cec 100644 --- a/test/proxy/Clones.test.js +++ b/test/proxy/Clones.test.js @@ -4,14 +4,17 @@ const { expect } = require('chai'); const shouldBehaveLikeClone = require('./Clones.behaviour'); -const ClonesMock = artifacts.require('ClonesMock'); +const Clones = artifacts.require('$Clones'); + +contract('Clones', function (accounts) { + const [ deployer ] = accounts; -contract('Clones', function () { describe('clone', function () { shouldBehaveLikeClone(async (implementation, initData, opts = {}) => { - const factory = await ClonesMock.new(); - const receipt = await factory.clone(implementation, initData, { value: opts.value }); - const address = receipt.logs.find(({ event }) => event === 'NewInstance').args.instance; + const factory = await Clones.new(); + const receipt = await factory.$clone(implementation); + const address = receipt.logs.find(({ event }) => event === 'return$clone').args.instance; + await web3.eth.sendTransaction({ from: deployer, to: address, value: opts.value, data: initData }); return { address }; }); }); @@ -19,24 +22,25 @@ contract('Clones', function () { describe('cloneDeterministic', function () { shouldBehaveLikeClone(async (implementation, initData, opts = {}) => { const salt = web3.utils.randomHex(32); - const factory = await ClonesMock.new(); - const receipt = await factory.cloneDeterministic(implementation, salt, initData, { value: opts.value }); - const address = receipt.logs.find(({ event }) => event === 'NewInstance').args.instance; + const factory = await Clones.new(); + const receipt = await factory.$cloneDeterministic(implementation, salt); + const address = receipt.logs.find(({ event }) => event === 'return$cloneDeterministic').args.instance; + await web3.eth.sendTransaction({ from: deployer, to: address, value: opts.value, data: initData }); return { address }; }); it('address already used', async function () { const implementation = web3.utils.randomHex(20); const salt = web3.utils.randomHex(32); - const factory = await ClonesMock.new(); + const factory = await Clones.new(); // deploy once expectEvent( - await factory.cloneDeterministic(implementation, salt, '0x'), - 'NewInstance', + await factory.$cloneDeterministic(implementation, salt), + 'return$cloneDeterministic', ); // deploy twice await expectRevert( - factory.cloneDeterministic(implementation, salt, '0x'), + factory.$cloneDeterministic(implementation, salt), 'ERC1167: create2 failed', ); }); @@ -44,8 +48,8 @@ contract('Clones', function () { it('address prediction', async function () { const implementation = web3.utils.randomHex(20); const salt = web3.utils.randomHex(32); - const factory = await ClonesMock.new(); - const predicted = await factory.predictDeterministicAddress(implementation, salt); + const factory = await Clones.new(); + const predicted = await factory.$predictDeterministicAddress(implementation, salt); const creationCode = [ '0x3d602d80600a3d3981f3363d3d373d3d3d363d73', @@ -60,8 +64,8 @@ contract('Clones', function () { )).to.be.equal(predicted); expectEvent( - await factory.cloneDeterministic(implementation, salt, '0x'), - 'NewInstance', + await factory.$cloneDeterministic(implementation, salt), + 'return$cloneDeterministic', { instance: predicted }, ); }); diff --git a/test/proxy/utils/UUPSUpgradeable.test.js b/test/proxy/utils/UUPSUpgradeable.test.js index cd465143e..20324e67b 100644 --- a/test/proxy/utils/UUPSUpgradeable.test.js +++ b/test/proxy/utils/UUPSUpgradeable.test.js @@ -6,14 +6,14 @@ const ERC1967Proxy = artifacts.require('ERC1967Proxy'); const UUPSUpgradeableMock = artifacts.require('UUPSUpgradeableMock'); const UUPSUpgradeableUnsafeMock = artifacts.require('UUPSUpgradeableUnsafeMock'); const UUPSUpgradeableLegacyMock = artifacts.require('UUPSUpgradeableLegacyMock'); -const CountersImpl = artifacts.require('CountersImpl'); +const NonUpgradeableMock = artifacts.require('NonUpgradeableMock'); contract('UUPSUpgradeable', function () { before(async function () { this.implInitial = await UUPSUpgradeableMock.new(); this.implUpgradeOk = await UUPSUpgradeableMock.new(); this.implUpgradeUnsafe = await UUPSUpgradeableUnsafeMock.new(); - this.implUpgradeNonUUPS = await CountersImpl.new(); + this.implUpgradeNonUUPS = await NonUpgradeableMock.new(); }); beforeEach(async function () { diff --git a/test/token/ERC1155/ERC1155.behavior.js b/test/token/ERC1155/ERC1155.behavior.js index 62ba66677..37afea0aa 100644 --- a/test/token/ERC1155/ERC1155.behavior.js +++ b/test/token/ERC1155/ERC1155.behavior.js @@ -48,10 +48,10 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('when accounts own some tokens', function () { beforeEach(async function () { - await this.token.mint(firstTokenHolder, firstTokenId, firstAmount, '0x', { + await this.token.$_mint(firstTokenHolder, firstTokenId, firstAmount, '0x', { from: minter, }); - await this.token.mint( + await this.token.$_mint( secondTokenHolder, secondTokenId, secondAmount, @@ -125,10 +125,10 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('when accounts own some tokens', function () { beforeEach(async function () { - await this.token.mint(firstTokenHolder, firstTokenId, firstAmount, '0x', { + await this.token.$_mint(firstTokenHolder, firstTokenId, firstAmount, '0x', { from: minter, }); - await this.token.mint( + await this.token.$_mint( secondTokenHolder, secondTokenId, secondAmount, @@ -193,10 +193,10 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, describe('safeTransferFrom', function () { beforeEach(async function () { - await this.token.mint(multiTokenHolder, firstTokenId, firstAmount, '0x', { + await this.token.$_mint(multiTokenHolder, firstTokenId, firstAmount, '0x', { from: minter, }); - await this.token.mint( + await this.token.$_mint( multiTokenHolder, secondTokenId, secondAmount, @@ -449,10 +449,10 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, describe('safeBatchTransferFrom', function () { beforeEach(async function () { - await this.token.mint(multiTokenHolder, firstTokenId, firstAmount, '0x', { + await this.token.$_mint(multiTokenHolder, firstTokenId, firstAmount, '0x', { from: minter, }); - await this.token.mint( + await this.token.$_mint( multiTokenHolder, secondTokenId, secondAmount, diff --git a/test/token/ERC1155/ERC1155.test.js b/test/token/ERC1155/ERC1155.test.js index a0a8cf3ff..4e295d59e 100644 --- a/test/token/ERC1155/ERC1155.test.js +++ b/test/token/ERC1155/ERC1155.test.js @@ -4,7 +4,7 @@ const { ZERO_ADDRESS } = constants; const { expect } = require('chai'); const { shouldBehaveLikeERC1155 } = require('./ERC1155.behavior'); -const ERC1155Mock = artifacts.require('ERC1155Mock'); +const ERC1155Mock = artifacts.require('$ERC1155'); contract('ERC1155', function (accounts) { const [operator, tokenHolder, tokenBatchHolder, ...otherAccounts] = accounts; @@ -31,14 +31,14 @@ contract('ERC1155', function (accounts) { describe('_mint', function () { it('reverts with a zero destination address', async function () { await expectRevert( - this.token.mint(ZERO_ADDRESS, tokenId, mintAmount, data), + this.token.$_mint(ZERO_ADDRESS, tokenId, mintAmount, data), 'ERC1155: mint to the zero address', ); }); context('with minted tokens', function () { beforeEach(async function () { - (this.receipt = await this.token.mint(tokenHolder, tokenId, mintAmount, data, { from: operator })); + (this.receipt = await this.token.$_mint(tokenHolder, tokenId, mintAmount, data, { from: operator })); }); it('emits a TransferSingle event', function () { @@ -60,26 +60,26 @@ contract('ERC1155', function (accounts) { describe('_mintBatch', function () { it('reverts with a zero destination address', async function () { await expectRevert( - this.token.mintBatch(ZERO_ADDRESS, tokenBatchIds, mintAmounts, data), + this.token.$_mintBatch(ZERO_ADDRESS, tokenBatchIds, mintAmounts, data), 'ERC1155: mint to the zero address', ); }); it('reverts if length of inputs do not match', async function () { await expectRevert( - this.token.mintBatch(tokenBatchHolder, tokenBatchIds, mintAmounts.slice(1), data), + this.token.$_mintBatch(tokenBatchHolder, tokenBatchIds, mintAmounts.slice(1), data), 'ERC1155: ids and amounts length mismatch', ); await expectRevert( - this.token.mintBatch(tokenBatchHolder, tokenBatchIds.slice(1), mintAmounts, data), + this.token.$_mintBatch(tokenBatchHolder, tokenBatchIds.slice(1), mintAmounts, data), 'ERC1155: ids and amounts length mismatch', ); }); context('with minted batch of tokens', function () { beforeEach(async function () { - (this.receipt = await this.token.mintBatch( + (this.receipt = await this.token.$_mintBatch( tokenBatchHolder, tokenBatchIds, mintAmounts, @@ -112,20 +112,20 @@ contract('ERC1155', function (accounts) { describe('_burn', function () { it('reverts when burning the zero account\'s tokens', async function () { await expectRevert( - this.token.burn(ZERO_ADDRESS, tokenId, mintAmount), + this.token.$_burn(ZERO_ADDRESS, tokenId, mintAmount), 'ERC1155: burn from the zero address', ); }); it('reverts when burning a non-existent token id', async function () { await expectRevert( - this.token.burn(tokenHolder, tokenId, mintAmount), + this.token.$_burn(tokenHolder, tokenId, mintAmount), 'ERC1155: burn amount exceeds balance', ); }); it('reverts when burning more than available tokens', async function () { - await this.token.mint( + await this.token.$_mint( tokenHolder, tokenId, mintAmount, @@ -134,15 +134,15 @@ contract('ERC1155', function (accounts) { ); await expectRevert( - this.token.burn(tokenHolder, tokenId, mintAmount.addn(1)), + this.token.$_burn(tokenHolder, tokenId, mintAmount.addn(1)), 'ERC1155: burn amount exceeds balance', ); }); context('with minted-then-burnt tokens', function () { beforeEach(async function () { - await this.token.mint(tokenHolder, tokenId, mintAmount, data); - (this.receipt = await this.token.burn( + await this.token.$_mint(tokenHolder, tokenId, mintAmount, data); + (this.receipt = await this.token.$_burn( tokenHolder, tokenId, burnAmount, @@ -172,34 +172,34 @@ contract('ERC1155', function (accounts) { describe('_burnBatch', function () { it('reverts when burning the zero account\'s tokens', async function () { await expectRevert( - this.token.burnBatch(ZERO_ADDRESS, tokenBatchIds, burnAmounts), + this.token.$_burnBatch(ZERO_ADDRESS, tokenBatchIds, burnAmounts), 'ERC1155: burn from the zero address', ); }); it('reverts if length of inputs do not match', async function () { await expectRevert( - this.token.burnBatch(tokenBatchHolder, tokenBatchIds, burnAmounts.slice(1)), + this.token.$_burnBatch(tokenBatchHolder, tokenBatchIds, burnAmounts.slice(1)), 'ERC1155: ids and amounts length mismatch', ); await expectRevert( - this.token.burnBatch(tokenBatchHolder, tokenBatchIds.slice(1), burnAmounts), + this.token.$_burnBatch(tokenBatchHolder, tokenBatchIds.slice(1), burnAmounts), 'ERC1155: ids and amounts length mismatch', ); }); it('reverts when burning a non-existent token id', async function () { await expectRevert( - this.token.burnBatch(tokenBatchHolder, tokenBatchIds, burnAmounts), + this.token.$_burnBatch(tokenBatchHolder, tokenBatchIds, burnAmounts), 'ERC1155: burn amount exceeds balance', ); }); context('with minted-then-burnt tokens', function () { beforeEach(async function () { - await this.token.mintBatch(tokenBatchHolder, tokenBatchIds, mintAmounts, data); - (this.receipt = await this.token.burnBatch( + await this.token.$_mintBatch(tokenBatchHolder, tokenBatchIds, mintAmounts, data); + (this.receipt = await this.token.$_burnBatch( tokenBatchHolder, tokenBatchIds, burnAmounts, @@ -248,13 +248,13 @@ contract('ERC1155', function (accounts) { const newURI = 'https://token-cdn-domain/{locale}/{id}.json'; it('emits no URI event', async function () { - const receipt = await this.token.setURI(newURI); + const receipt = await this.token.$_setURI(newURI); expectEvent.notEmitted(receipt, 'URI'); }); it('sets the new URI for all token types', async function () { - await this.token.setURI(newURI); + await this.token.$_setURI(newURI); expect(await this.token.uri(firstTokenID)).to.be.equal(newURI); expect(await this.token.uri(secondTokenID)).to.be.equal(newURI); diff --git a/test/token/ERC1155/extensions/ERC1155Burnable.test.js b/test/token/ERC1155/extensions/ERC1155Burnable.test.js index ff6aee054..2c854e2e8 100644 --- a/test/token/ERC1155/extensions/ERC1155Burnable.test.js +++ b/test/token/ERC1155/extensions/ERC1155Burnable.test.js @@ -2,7 +2,7 @@ const { BN, expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const ERC1155BurnableMock = artifacts.require('ERC1155BurnableMock'); +const ERC1155Burnable = artifacts.require('$ERC1155Burnable'); contract('ERC1155Burnable', function (accounts) { const [ holder, operator, other ] = accounts; @@ -13,10 +13,10 @@ contract('ERC1155Burnable', function (accounts) { const amounts = [new BN('3000'), new BN('9902')]; beforeEach(async function () { - this.token = await ERC1155BurnableMock.new(uri); + this.token = await ERC1155Burnable.new(uri); - await this.token.mint(holder, tokenIds[0], amounts[0], '0x'); - await this.token.mint(holder, tokenIds[1], amounts[1], '0x'); + await this.token.$_mint(holder, tokenIds[0], amounts[0], '0x'); + await this.token.$_mint(holder, tokenIds[1], amounts[1], '0x'); }); describe('burn', function () { diff --git a/test/token/ERC1155/extensions/ERC1155Pausable.test.js b/test/token/ERC1155/extensions/ERC1155Pausable.test.js index f7c40523c..e7ace3c2c 100644 --- a/test/token/ERC1155/extensions/ERC1155Pausable.test.js +++ b/test/token/ERC1155/extensions/ERC1155Pausable.test.js @@ -2,7 +2,7 @@ const { BN, expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const ERC1155PausableMock = artifacts.require('ERC1155PausableMock'); +const ERC1155Pausable = artifacts.require('$ERC1155Pausable'); contract('ERC1155Pausable', function (accounts) { const [ holder, operator, receiver, other ] = accounts; @@ -10,7 +10,7 @@ contract('ERC1155Pausable', function (accounts) { const uri = 'https://token.com'; beforeEach(async function () { - this.token = await ERC1155PausableMock.new(uri); + this.token = await ERC1155Pausable.new(uri); }); context('when token is paused', function () { @@ -22,9 +22,9 @@ contract('ERC1155Pausable', function (accounts) { beforeEach(async function () { await this.token.setApprovalForAll(operator, true, { from: holder }); - await this.token.mint(holder, firstTokenId, firstTokenAmount, '0x'); + await this.token.$_mint(holder, firstTokenId, firstTokenAmount, '0x'); - await this.token.pause(); + await this.token.$_pause(); }); it('reverts when trying to safeTransferFrom from holder', async function () { @@ -59,28 +59,28 @@ contract('ERC1155Pausable', function (accounts) { it('reverts when trying to mint', async function () { await expectRevert( - this.token.mint(holder, secondTokenId, secondTokenAmount, '0x'), + this.token.$_mint(holder, secondTokenId, secondTokenAmount, '0x'), 'ERC1155Pausable: token transfer while paused', ); }); it('reverts when trying to mintBatch', async function () { await expectRevert( - this.token.mintBatch(holder, [secondTokenId], [secondTokenAmount], '0x'), + this.token.$_mintBatch(holder, [secondTokenId], [secondTokenAmount], '0x'), 'ERC1155Pausable: token transfer while paused', ); }); it('reverts when trying to burn', async function () { await expectRevert( - this.token.burn(holder, firstTokenId, firstTokenAmount), + this.token.$_burn(holder, firstTokenId, firstTokenAmount), 'ERC1155Pausable: token transfer while paused', ); }); it('reverts when trying to burnBatch', async function () { await expectRevert( - this.token.burnBatch(holder, [firstTokenId], [firstTokenAmount]), + this.token.$_burnBatch(holder, [firstTokenId], [firstTokenAmount]), 'ERC1155Pausable: token transfer while paused', ); }); diff --git a/test/token/ERC1155/extensions/ERC1155Supply.test.js b/test/token/ERC1155/extensions/ERC1155Supply.test.js index 1a632604d..0eb4952ab 100644 --- a/test/token/ERC1155/extensions/ERC1155Supply.test.js +++ b/test/token/ERC1155/extensions/ERC1155Supply.test.js @@ -2,7 +2,7 @@ const { BN } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const ERC1155SupplyMock = artifacts.require('ERC1155SupplyMock'); +const ERC1155Supply = artifacts.require('$ERC1155Supply'); contract('ERC1155Supply', function (accounts) { const [ holder ] = accounts; @@ -16,7 +16,7 @@ contract('ERC1155Supply', function (accounts) { const secondTokenAmount = new BN('23'); beforeEach(async function () { - this.token = await ERC1155SupplyMock.new(uri); + this.token = await ERC1155Supply.new(uri); }); context('before mint', function () { @@ -32,7 +32,7 @@ contract('ERC1155Supply', function (accounts) { context('after mint', function () { context('single', function () { beforeEach(async function () { - await this.token.mint(holder, firstTokenId, firstTokenAmount, '0x'); + await this.token.$_mint(holder, firstTokenId, firstTokenAmount, '0x'); }); it('exist', async function () { @@ -46,7 +46,7 @@ contract('ERC1155Supply', function (accounts) { context('batch', function () { beforeEach(async function () { - await this.token.mintBatch( + await this.token.$_mintBatch( holder, [ firstTokenId, secondTokenId ], [ firstTokenAmount, secondTokenAmount ], @@ -69,8 +69,8 @@ contract('ERC1155Supply', function (accounts) { context('after burn', function () { context('single', function () { beforeEach(async function () { - await this.token.mint(holder, firstTokenId, firstTokenAmount, '0x'); - await this.token.burn(holder, firstTokenId, firstTokenAmount); + await this.token.$_mint(holder, firstTokenId, firstTokenAmount, '0x'); + await this.token.$_burn(holder, firstTokenId, firstTokenAmount); }); it('exist', async function () { @@ -84,13 +84,13 @@ contract('ERC1155Supply', function (accounts) { context('batch', function () { beforeEach(async function () { - await this.token.mintBatch( + await this.token.$_mintBatch( holder, [ firstTokenId, secondTokenId ], [ firstTokenAmount, secondTokenAmount ], '0x', ); - await this.token.burnBatch( + await this.token.$_burnBatch( holder, [ firstTokenId, secondTokenId ], [ firstTokenAmount, secondTokenAmount ], diff --git a/test/token/ERC1155/extensions/ERC1155URIStorage.test.js b/test/token/ERC1155/extensions/ERC1155URIStorage.test.js index 8f20a4ced..a12a5c972 100644 --- a/test/token/ERC1155/extensions/ERC1155URIStorage.test.js +++ b/test/token/ERC1155/extensions/ERC1155URIStorage.test.js @@ -3,7 +3,7 @@ const { BN, expectEvent } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); const { artifacts } = require('hardhat'); -const ERC1155URIStorageMock = artifacts.require('ERC1155URIStorageMock'); +const ERC1155URIStorage = artifacts.require('$ERC1155URIStorage'); contract(['ERC1155URIStorage'], function (accounts) { const [ holder ] = accounts; @@ -16,10 +16,10 @@ contract(['ERC1155URIStorage'], function (accounts) { describe('with base uri set', function () { beforeEach(async function () { - this.token = await ERC1155URIStorageMock.new(erc1155Uri); - await this.token.setBaseURI(baseUri); + this.token = await ERC1155URIStorage.new(erc1155Uri); + await this.token.$_setBaseURI(baseUri); - await this.token.mint(holder, tokenId, amount, '0x'); + await this.token.$_mint(holder, tokenId, amount, '0x'); }); it('can request the token uri, returning the erc1155 uri if no token uri was set', async function () { @@ -30,7 +30,7 @@ contract(['ERC1155URIStorage'], function (accounts) { it('can request the token uri, returning the concatenated uri if a token uri was set', async function () { const tokenUri = '1234/'; - const receipt = await this.token.setURI(tokenId, tokenUri); + const receipt = await this.token.$_setURI(tokenId, tokenUri); const receivedTokenUri = await this.token.uri(tokenId); @@ -42,9 +42,9 @@ contract(['ERC1155URIStorage'], function (accounts) { describe('with base uri set to the empty string', function () { beforeEach(async function () { - this.token = await ERC1155URIStorageMock.new(''); + this.token = await ERC1155URIStorage.new(''); - await this.token.mint(holder, tokenId, amount, '0x'); + await this.token.$_mint(holder, tokenId, amount, '0x'); }); it('can request the token uri, returning an empty string if no token uri was set', async function () { @@ -55,7 +55,7 @@ contract(['ERC1155URIStorage'], function (accounts) { it('can request the token uri, returning the token uri if a token uri was set', async function () { const tokenUri = 'ipfs://1234/'; - const receipt = await this.token.setURI(tokenId, tokenUri); + const receipt = await this.token.$_setURI(tokenId, tokenUri); const receivedTokenUri = await this.token.uri(tokenId); diff --git a/test/token/ERC1155/utils/ERC1155Holder.test.js b/test/token/ERC1155/utils/ERC1155Holder.test.js index 41225c238..736925bd6 100644 --- a/test/token/ERC1155/utils/ERC1155Holder.test.js +++ b/test/token/ERC1155/utils/ERC1155Holder.test.js @@ -1,7 +1,7 @@ const { BN } = require('@openzeppelin/test-helpers'); const ERC1155Holder = artifacts.require('ERC1155Holder'); -const ERC1155Mock = artifacts.require('ERC1155Mock'); +const ERC1155 = artifacts.require('$ERC1155'); const { expect } = require('chai'); @@ -15,9 +15,9 @@ contract('ERC1155Holder', function (accounts) { const transferData = '0x12345678'; beforeEach(async function () { - this.multiToken = await ERC1155Mock.new(uri, { from: creator }); + this.multiToken = await ERC1155.new(uri); this.holder = await ERC1155Holder.new(); - await this.multiToken.mintBatch(creator, multiTokenIds, multiTokenAmounts, '0x', { from: creator }); + await this.multiToken.$_mintBatch(creator, multiTokenIds, multiTokenAmounts, '0x'); }); shouldSupportInterfaces(['ERC165', 'ERC1155Receiver']); diff --git a/test/token/ERC20/ERC20.test.js b/test/token/ERC20/ERC20.test.js index 992edf93b..10d86e4b4 100644 --- a/test/token/ERC20/ERC20.test.js +++ b/test/token/ERC20/ERC20.test.js @@ -8,8 +8,8 @@ const { shouldBehaveLikeERC20Approve, } = require('./ERC20.behavior'); -const ERC20Mock = artifacts.require('ERC20Mock'); -const ERC20DecimalsMock = artifacts.require('ERC20DecimalsMock'); +const ERC20 = artifacts.require('$ERC20'); +const ERC20Decimals = artifacts.require('$ERC20DecimalsMock'); contract('ERC20', function (accounts) { const [ initialHolder, recipient, anotherAccount ] = accounts; @@ -20,7 +20,8 @@ contract('ERC20', function (accounts) { const initialSupply = new BN(100); beforeEach(async function () { - this.token = await ERC20Mock.new(name, symbol, initialHolder, initialSupply); + this.token = await ERC20.new(name, symbol); + await this.token.$_mint(initialHolder, initialSupply); }); it('has a name', async function () { @@ -39,7 +40,7 @@ contract('ERC20', function (accounts) { const decimals = new BN(6); it('can set decimals during construction', async function () { - const token = await ERC20DecimalsMock.new(name, symbol, decimals); + const token = await ERC20Decimals.new(name, symbol, decimals); expect(await token.decimals()).to.be.bignumber.equal(decimals); }); }); @@ -203,13 +204,13 @@ contract('ERC20', function (accounts) { const amount = new BN(50); it('rejects a null account', async function () { await expectRevert( - this.token.mint(ZERO_ADDRESS, amount), 'ERC20: mint to the zero address', + this.token.$_mint(ZERO_ADDRESS, amount), 'ERC20: mint to the zero address', ); }); describe('for a non zero account', function () { beforeEach('minting', async function () { - this.receipt = await this.token.mint(recipient, amount); + this.receipt = await this.token.$_mint(recipient, amount); }); it('increments totalSupply', async function () { @@ -235,13 +236,13 @@ contract('ERC20', function (accounts) { describe('_burn', function () { it('rejects a null account', async function () { - await expectRevert(this.token.burn(ZERO_ADDRESS, new BN(1)), + await expectRevert(this.token.$_burn(ZERO_ADDRESS, new BN(1)), 'ERC20: burn from the zero address'); }); describe('for a non zero account', function () { it('rejects burning more than balance', async function () { - await expectRevert(this.token.burn( + await expectRevert(this.token.$_burn( initialHolder, initialSupply.addn(1)), 'ERC20: burn amount exceeds balance', ); }); @@ -249,7 +250,7 @@ contract('ERC20', function (accounts) { const describeBurn = function (description, amount) { describe(description, function () { beforeEach('burning', async function () { - this.receipt = await this.token.burn(initialHolder, amount); + this.receipt = await this.token.$_burn(initialHolder, amount); }); it('decrements totalSupply', async function () { @@ -281,12 +282,12 @@ contract('ERC20', function (accounts) { describe('_transfer', function () { shouldBehaveLikeERC20Transfer('ERC20', initialHolder, recipient, initialSupply, function (from, to, amount) { - return this.token.transferInternal(from, to, amount); + return this.token.$_transfer(from, to, amount); }); describe('when the sender is the zero address', function () { it('reverts', async function () { - await expectRevert(this.token.transferInternal(ZERO_ADDRESS, recipient, initialSupply), + await expectRevert(this.token.$_transfer(ZERO_ADDRESS, recipient, initialSupply), 'ERC20: transfer from the zero address', ); }); @@ -295,12 +296,12 @@ contract('ERC20', function (accounts) { describe('_approve', function () { shouldBehaveLikeERC20Approve('ERC20', initialHolder, recipient, initialSupply, function (owner, spender, amount) { - return this.token.approveInternal(owner, spender, amount); + return this.token.$_approve(owner, spender, amount); }); describe('when the owner is the zero address', function () { it('reverts', async function () { - await expectRevert(this.token.approveInternal(ZERO_ADDRESS, recipient, initialSupply), + await expectRevert(this.token.$_approve(ZERO_ADDRESS, recipient, initialSupply), 'ERC20: approve from the zero address', ); }); diff --git a/test/token/ERC20/extensions/ERC20Burnable.test.js b/test/token/ERC20/extensions/ERC20Burnable.test.js index 8aa4fb66c..45264b774 100644 --- a/test/token/ERC20/extensions/ERC20Burnable.test.js +++ b/test/token/ERC20/extensions/ERC20Burnable.test.js @@ -1,7 +1,7 @@ const { BN } = require('@openzeppelin/test-helpers'); const { shouldBehaveLikeERC20Burnable } = require('./ERC20Burnable.behavior'); -const ERC20BurnableMock = artifacts.require('ERC20BurnableMock'); +const ERC20Burnable = artifacts.require('$ERC20Burnable'); contract('ERC20Burnable', function (accounts) { const [ owner, ...otherAccounts ] = accounts; @@ -12,7 +12,8 @@ contract('ERC20Burnable', function (accounts) { const symbol = 'MTKN'; beforeEach(async function () { - this.token = await ERC20BurnableMock.new(name, symbol, owner, initialBalance, { from: owner }); + this.token = await ERC20Burnable.new(name, symbol, { from: owner }); + await this.token.$_mint(owner, initialBalance); }); shouldBehaveLikeERC20Burnable(owner, initialBalance, otherAccounts); diff --git a/test/token/ERC20/extensions/ERC20Capped.behavior.js b/test/token/ERC20/extensions/ERC20Capped.behavior.js index 4692f997f..fe8c3a4ff 100644 --- a/test/token/ERC20/extensions/ERC20Capped.behavior.js +++ b/test/token/ERC20/extensions/ERC20Capped.behavior.js @@ -2,27 +2,27 @@ const { expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -function shouldBehaveLikeERC20Capped (minter, [other], cap) { +function shouldBehaveLikeERC20Capped (accounts, cap) { describe('capped token', function () { - const from = minter; + const user = accounts[0]; it('starts with the correct cap', async function () { expect(await this.token.cap()).to.be.bignumber.equal(cap); }); it('mints when amount is less than cap', async function () { - await this.token.mint(other, cap.subn(1), { from }); + await this.token.$_mint(user, cap.subn(1)); expect(await this.token.totalSupply()).to.be.bignumber.equal(cap.subn(1)); }); it('fails to mint if the amount exceeds the cap', async function () { - await this.token.mint(other, cap.subn(1), { from }); - await expectRevert(this.token.mint(other, 2, { from }), 'ERC20Capped: cap exceeded'); + await this.token.$_mint(user, cap.subn(1)); + await expectRevert(this.token.$_mint(user, 2), 'ERC20Capped: cap exceeded'); }); it('fails to mint after cap is reached', async function () { - await this.token.mint(other, cap, { from }); - await expectRevert(this.token.mint(other, 1, { from }), 'ERC20Capped: cap exceeded'); + await this.token.$_mint(user, cap); + await expectRevert(this.token.$_mint(user, 1), 'ERC20Capped: cap exceeded'); }); }); } diff --git a/test/token/ERC20/extensions/ERC20Capped.test.js b/test/token/ERC20/extensions/ERC20Capped.test.js index 76532cefd..a86d38c1a 100644 --- a/test/token/ERC20/extensions/ERC20Capped.test.js +++ b/test/token/ERC20/extensions/ERC20Capped.test.js @@ -1,27 +1,23 @@ -const { BN, ether, expectRevert } = require('@openzeppelin/test-helpers'); +const { ether, expectRevert } = require('@openzeppelin/test-helpers'); const { shouldBehaveLikeERC20Capped } = require('./ERC20Capped.behavior'); -const ERC20Capped = artifacts.require('ERC20CappedMock'); +const ERC20Capped = artifacts.require('$ERC20Capped'); contract('ERC20Capped', function (accounts) { - const [ minter, ...otherAccounts ] = accounts; - const cap = ether('1000'); const name = 'My Token'; const symbol = 'MTKN'; it('requires a non-zero cap', async function () { - await expectRevert( - ERC20Capped.new(name, symbol, new BN(0), { from: minter }), 'ERC20Capped: cap is 0', - ); + await expectRevert(ERC20Capped.new(name, symbol, 0), 'ERC20Capped: cap is 0'); }); context('once deployed', async function () { beforeEach(async function () { - this.token = await ERC20Capped.new(name, symbol, cap, { from: minter }); + this.token = await ERC20Capped.new(name, symbol, cap); }); - shouldBehaveLikeERC20Capped(minter, otherAccounts, cap); + shouldBehaveLikeERC20Capped(accounts, cap); }); }); diff --git a/test/token/ERC20/extensions/ERC20FlashMint.test.js b/test/token/ERC20/extensions/ERC20FlashMint.test.js index 4354dd90c..86326f95d 100644 --- a/test/token/ERC20/extensions/ERC20FlashMint.test.js +++ b/test/token/ERC20/extensions/ERC20FlashMint.test.js @@ -4,7 +4,7 @@ const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test const { expect } = require('chai'); const { MAX_UINT256, ZERO_ADDRESS } = constants; -const ERC20FlashMintMock = artifacts.require('ERC20FlashMintMock'); +const ERC20FlashMintMock = artifacts.require('$ERC20FlashMintMock'); const ERC3156FlashBorrowerMock = artifacts.require('ERC3156FlashBorrowerMock'); contract('ERC20FlashMint', function (accounts) { @@ -17,7 +17,8 @@ contract('ERC20FlashMint', function (accounts) { const loanAmount = new BN(10000000000000); beforeEach(async function () { - this.token = await ERC20FlashMintMock.new(name, symbol, initialHolder, initialSupply); + this.token = await ERC20FlashMintMock.new(name, symbol); + await this.token.$_mint(initialHolder, initialSupply); }); describe('maxFlashLoan', function () { @@ -42,7 +43,7 @@ contract('ERC20FlashMint', function (accounts) { describe('flashFeeReceiver', function () { it('default receiver', async function () { - expect(await this.token.flashFeeReceiver()).to.be.eq(ZERO_ADDRESS); + expect(await this.token.$_flashFeeReceiver()).to.be.eq(ZERO_ADDRESS); }); }); @@ -99,7 +100,7 @@ contract('ERC20FlashMint', function (accounts) { beforeEach('init receiver balance & set flash fee', async function () { this.receiver = await ERC3156FlashBorrowerMock.new(true, true); - const receipt = await this.token.mint(this.receiver.address, receiverInitialBalance); + const receipt = await this.token.$_mint(this.receiver.address, receiverInitialBalance); await expectEvent(receipt, 'Transfer', { from: ZERO_ADDRESS, to: this.receiver.address, value: receiverInitialBalance }); expect(await this.token.balanceOf(this.receiver.address)).to.be.bignumber.equal(receiverInitialBalance); @@ -116,14 +117,14 @@ contract('ERC20FlashMint', function (accounts) { expect(await this.token.totalSupply()).to.be.bignumber.equal(initialSupply.add(receiverInitialBalance).sub(flashFee)); expect(await this.token.balanceOf(this.receiver.address)).to.be.bignumber.equal(receiverInitialBalance.sub(flashFee)); - expect(await this.token.balanceOf(await this.token.flashFeeReceiver())).to.be.bignumber.equal('0'); + expect(await this.token.balanceOf(await this.token.$_flashFeeReceiver())).to.be.bignumber.equal('0'); expect(await this.token.allowance(this.receiver.address, this.token.address)).to.be.bignumber.equal('0'); }); it('custom flash fee receiver', async function () { const flashFeeReceiverAddress = anotherAccount; await this.token.setFlashFeeReceiver(flashFeeReceiverAddress); - expect(await this.token.flashFeeReceiver()).to.be.eq(flashFeeReceiverAddress); + expect(await this.token.$_flashFeeReceiver()).to.be.eq(flashFeeReceiverAddress); expect(await this.token.balanceOf(flashFeeReceiverAddress)).to.be.bignumber.equal('0'); diff --git a/test/token/ERC20/extensions/ERC20Pausable.test.js b/test/token/ERC20/extensions/ERC20Pausable.test.js index 8670e2fc9..03c630451 100644 --- a/test/token/ERC20/extensions/ERC20Pausable.test.js +++ b/test/token/ERC20/extensions/ERC20Pausable.test.js @@ -2,7 +2,7 @@ const { BN, expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const ERC20PausableMock = artifacts.require('ERC20PausableMock'); +const ERC20Pausable = artifacts.require('$ERC20Pausable'); contract('ERC20Pausable', function (accounts) { const [ holder, recipient, anotherAccount ] = accounts; @@ -13,7 +13,8 @@ contract('ERC20Pausable', function (accounts) { const symbol = 'MTKN'; beforeEach(async function () { - this.token = await ERC20PausableMock.new(name, symbol, holder, initialSupply); + this.token = await ERC20Pausable.new(name, symbol); + await this.token.$_mint(holder, initialSupply); }); describe('pausable token', function () { @@ -26,8 +27,8 @@ contract('ERC20Pausable', function (accounts) { }); it('allows to transfer when paused and then unpaused', async function () { - await this.token.pause(); - await this.token.unpause(); + await this.token.$_pause(); + await this.token.$_unpause(); await this.token.transfer(recipient, initialSupply, { from: holder }); @@ -36,7 +37,7 @@ contract('ERC20Pausable', function (accounts) { }); it('reverts when trying to transfer when paused', async function () { - await this.token.pause(); + await this.token.$_pause(); await expectRevert(this.token.transfer(recipient, initialSupply, { from: holder }), 'ERC20Pausable: token transfer while paused', @@ -59,8 +60,8 @@ contract('ERC20Pausable', function (accounts) { }); it('allows to transfer when paused and then unpaused', async function () { - await this.token.pause(); - await this.token.unpause(); + await this.token.$_pause(); + await this.token.$_unpause(); await this.token.transferFrom(holder, recipient, allowance, { from: anotherAccount }); @@ -69,7 +70,7 @@ contract('ERC20Pausable', function (accounts) { }); it('reverts when trying to transfer from when paused', async function () { - await this.token.pause(); + await this.token.$_pause(); await expectRevert(this.token.transferFrom( holder, recipient, allowance, { from: anotherAccount }), 'ERC20Pausable: token transfer while paused', @@ -81,24 +82,24 @@ contract('ERC20Pausable', function (accounts) { const amount = new BN('42'); it('allows to mint when unpaused', async function () { - await this.token.mint(recipient, amount); + await this.token.$_mint(recipient, amount); expect(await this.token.balanceOf(recipient)).to.be.bignumber.equal(amount); }); it('allows to mint when paused and then unpaused', async function () { - await this.token.pause(); - await this.token.unpause(); + await this.token.$_pause(); + await this.token.$_unpause(); - await this.token.mint(recipient, amount); + await this.token.$_mint(recipient, amount); expect(await this.token.balanceOf(recipient)).to.be.bignumber.equal(amount); }); it('reverts when trying to mint when paused', async function () { - await this.token.pause(); + await this.token.$_pause(); - await expectRevert(this.token.mint(recipient, amount), + await expectRevert(this.token.$_mint(recipient, amount), 'ERC20Pausable: token transfer while paused', ); }); @@ -108,24 +109,24 @@ contract('ERC20Pausable', function (accounts) { const amount = new BN('42'); it('allows to burn when unpaused', async function () { - await this.token.burn(holder, amount); + await this.token.$_burn(holder, amount); expect(await this.token.balanceOf(holder)).to.be.bignumber.equal(initialSupply.sub(amount)); }); it('allows to burn when paused and then unpaused', async function () { - await this.token.pause(); - await this.token.unpause(); + await this.token.$_pause(); + await this.token.$_unpause(); - await this.token.burn(holder, amount); + await this.token.$_burn(holder, amount); expect(await this.token.balanceOf(holder)).to.be.bignumber.equal(initialSupply.sub(amount)); }); it('reverts when trying to burn when paused', async function () { - await this.token.pause(); + await this.token.$_pause(); - await expectRevert(this.token.burn(holder, amount), + await expectRevert(this.token.$_burn(holder, amount), 'ERC20Pausable: token transfer while paused', ); }); diff --git a/test/token/ERC20/extensions/ERC20Snapshot.test.js b/test/token/ERC20/extensions/ERC20Snapshot.test.js index 64d922706..6f7646d77 100644 --- a/test/token/ERC20/extensions/ERC20Snapshot.test.js +++ b/test/token/ERC20/extensions/ERC20Snapshot.test.js @@ -1,5 +1,5 @@ const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const ERC20SnapshotMock = artifacts.require('ERC20SnapshotMock'); +const ERC20Snapshot = artifacts.require('$ERC20Snapshot'); const { expect } = require('chai'); @@ -12,18 +12,19 @@ contract('ERC20Snapshot', function (accounts) { const symbol = 'MTKN'; beforeEach(async function () { - this.token = await ERC20SnapshotMock.new(name, symbol, initialHolder, initialSupply); + this.token = await ERC20Snapshot.new(name, symbol); + await this.token.$_mint(initialHolder, initialSupply); }); describe('snapshot', function () { it('emits a snapshot event', async function () { - const receipt = await this.token.snapshot(); + const receipt = await this.token.$_snapshot(); expectEvent(receipt, 'Snapshot'); }); it('creates increasing snapshots ids, starting from 1', async function () { for (const id of ['1', '2', '3', '4', '5']) { - const receipt = await this.token.snapshot(); + const receipt = await this.token.$_snapshot(); expectEvent(receipt, 'Snapshot', { id }); } }); @@ -42,7 +43,7 @@ contract('ERC20Snapshot', function (accounts) { beforeEach(async function () { this.initialSnapshotId = new BN('1'); - const receipt = await this.token.snapshot(); + const receipt = await this.token.$_snapshot(); expectEvent(receipt, 'Snapshot', { id: this.initialSnapshotId }); }); @@ -54,8 +55,8 @@ contract('ERC20Snapshot', function (accounts) { context('with supply changes after the snapshot', function () { beforeEach(async function () { - await this.token.mint(other, new BN('50')); - await this.token.burn(initialHolder, new BN('20')); + await this.token.$_mint(other, new BN('50')); + await this.token.$_burn(initialHolder, new BN('20')); }); it('returns the total supply before the changes', async function () { @@ -66,7 +67,7 @@ contract('ERC20Snapshot', function (accounts) { beforeEach(async function () { this.secondSnapshotId = new BN('2'); - const receipt = await this.token.snapshot(); + const receipt = await this.token.$_snapshot(); expectEvent(receipt, 'Snapshot', { id: this.secondSnapshotId }); }); @@ -84,7 +85,7 @@ contract('ERC20Snapshot', function (accounts) { this.secondSnapshotIds = ['2', '3', '4']; for (const id of this.secondSnapshotIds) { - const receipt = await this.token.snapshot(); + const receipt = await this.token.$_snapshot(); expectEvent(receipt, 'Snapshot', { id }); } }); @@ -116,7 +117,7 @@ contract('ERC20Snapshot', function (accounts) { beforeEach(async function () { this.initialSnapshotId = new BN('1'); - const receipt = await this.token.snapshot(); + const receipt = await this.token.$_snapshot(); expectEvent(receipt, 'Snapshot', { id: this.initialSnapshotId }); }); @@ -132,8 +133,8 @@ contract('ERC20Snapshot', function (accounts) { context('with balance changes after the snapshot', function () { beforeEach(async function () { await this.token.transfer(recipient, new BN('10'), { from: initialHolder }); - await this.token.mint(other, new BN('50')); - await this.token.burn(initialHolder, new BN('20')); + await this.token.$_mint(other, new BN('50')); + await this.token.$_burn(initialHolder, new BN('20')); }); it('returns the balances before the changes', async function () { @@ -147,7 +148,7 @@ contract('ERC20Snapshot', function (accounts) { beforeEach(async function () { this.secondSnapshotId = new BN('2'); - const receipt = await this.token.snapshot(); + const receipt = await this.token.$_snapshot(); expectEvent(receipt, 'Snapshot', { id: this.secondSnapshotId }); }); @@ -174,7 +175,7 @@ contract('ERC20Snapshot', function (accounts) { this.secondSnapshotIds = ['2', '3', '4']; for (const id of this.secondSnapshotIds) { - const receipt = await this.token.snapshot(); + const receipt = await this.token.$_snapshot(); expectEvent(receipt, 'Snapshot', { id }); } }); diff --git a/test/token/ERC20/extensions/ERC20Votes.test.js b/test/token/ERC20/extensions/ERC20Votes.test.js index da7b5cd47..18d3011cd 100644 --- a/test/token/ERC20/extensions/ERC20Votes.test.js +++ b/test/token/ERC20/extensions/ERC20Votes.test.js @@ -8,10 +8,11 @@ const { fromRpcSig } = require('ethereumjs-util'); const ethSigUtil = require('eth-sig-util'); const Wallet = require('ethereumjs-wallet').default; -const ERC20VotesMock = artifacts.require('ERC20VotesMock'); +const ERC20Votes = artifacts.require('$ERC20Votes'); const { batchInBlock } = require('../../../helpers/txpool'); const { EIP712Domain, domainSeparator } = require('../../../helpers/eip712'); +const { getChainId } = require('../../../helpers/chainid'); const Delegation = [ { name: 'delegatee', type: 'address' }, @@ -28,12 +29,8 @@ contract('ERC20Votes', function (accounts) { const supply = new BN('10000000000000000000000000'); beforeEach(async function () { - this.token = await ERC20VotesMock.new(name, symbol); - - // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id - // from within the EVM as from the JSON RPC interface. - // See https://github.com/trufflesuite/ganache-core/issues/515 - this.chainId = await this.token.getChainId(); + this.chainId = await getChainId(); + this.token = await ERC20Votes.new(name, symbol, name); }); it('initial nonce is 0', async function () { @@ -44,14 +41,14 @@ contract('ERC20Votes', function (accounts) { expect( await this.token.DOMAIN_SEPARATOR(), ).to.equal( - await domainSeparator(name, version, this.chainId, this.token.address), + await domainSeparator({ name, version, chainId: this.chainId, verifyingContract: this.token.address }), ); }); it('minting restriction', async function () { const amount = new BN('2').pow(new BN('224')); await expectRevert( - this.token.mint(holder, amount), + this.token.$_mint(holder, amount), 'ERC20Votes: total supply risks overflowing votes', ); }); @@ -59,7 +56,7 @@ contract('ERC20Votes', function (accounts) { it('recent checkpoints', async function () { await this.token.delegate(holder, { from: holder }); for (let i = 0; i < 6; i++) { - await this.token.mint(holder, 1); + await this.token.$_mint(holder, 1); } const block = await web3.eth.getBlockNumber(); expect(await this.token.numCheckpoints(holder)).to.be.bignumber.equal('6'); @@ -72,7 +69,7 @@ contract('ERC20Votes', function (accounts) { describe('set delegation', function () { describe('call', function () { it('delegation with balance', async function () { - await this.token.mint(holder, supply); + await this.token.$_mint(holder, supply); expect(await this.token.delegates(holder)).to.be.equal(ZERO_ADDRESS); const { receipt } = await this.token.delegate(holder, { from: holder }); @@ -123,7 +120,7 @@ contract('ERC20Votes', function (accounts) { }}); beforeEach(async function () { - await this.token.mint(delegatorAddress, supply); + await this.token.$_mint(delegatorAddress, supply); }); it('accept signed delegation', async function () { @@ -229,7 +226,7 @@ contract('ERC20Votes', function (accounts) { describe('change delegation', function () { beforeEach(async function () { - await this.token.mint(holder, supply); + await this.token.$_mint(holder, supply); await this.token.delegate(holder, { from: holder }); }); @@ -267,7 +264,7 @@ contract('ERC20Votes', function (accounts) { describe('transfers', function () { beforeEach(async function () { - await this.token.mint(holder, supply); + await this.token.$_mint(holder, supply); }); it('no delegation', async function () { @@ -338,7 +335,7 @@ contract('ERC20Votes', function (accounts) { // The following tests are a adaptation of https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js. describe('Compound test suite', function () { beforeEach(async function () { - await this.token.mint(holder, supply); + await this.token.$_mint(holder, supply); }); describe('balanceOf', function () { @@ -471,7 +468,7 @@ contract('ERC20Votes', function (accounts) { }); it('returns the latest block if >= last checkpoint block', async function () { - t1 = await this.token.mint(holder, supply); + t1 = await this.token.$_mint(holder, supply); await time.advanceBlock(); await time.advanceBlock(); @@ -482,7 +479,7 @@ contract('ERC20Votes', function (accounts) { it('returns zero if < first checkpoint block', async function () { await time.advanceBlock(); - const t1 = await this.token.mint(holder, supply); + const t1 = await this.token.$_mint(holder, supply); await time.advanceBlock(); await time.advanceBlock(); @@ -491,16 +488,16 @@ contract('ERC20Votes', function (accounts) { }); it('generally returns the voting balance at the appropriate checkpoint', async function () { - const t1 = await this.token.mint(holder, supply); + const t1 = await this.token.$_mint(holder, supply); await time.advanceBlock(); await time.advanceBlock(); - const t2 = await this.token.burn(holder, 10); + const t2 = await this.token.$_burn(holder, 10); await time.advanceBlock(); await time.advanceBlock(); - const t3 = await this.token.burn(holder, 10); + const t3 = await this.token.$_burn(holder, 10); await time.advanceBlock(); await time.advanceBlock(); - const t4 = await this.token.mint(holder, 20); + const t4 = await this.token.$_mint(holder, 20); await time.advanceBlock(); await time.advanceBlock(); diff --git a/test/token/ERC20/extensions/ERC20VotesComp.test.js b/test/token/ERC20/extensions/ERC20VotesComp.test.js index d03050951..5efaa5561 100644 --- a/test/token/ERC20/extensions/ERC20VotesComp.test.js +++ b/test/token/ERC20/extensions/ERC20VotesComp.test.js @@ -8,10 +8,11 @@ const { fromRpcSig } = require('ethereumjs-util'); const ethSigUtil = require('eth-sig-util'); const Wallet = require('ethereumjs-wallet').default; -const ERC20VotesCompMock = artifacts.require('ERC20VotesCompMock'); +const ERC20VotesComp = artifacts.require('$ERC20VotesComp'); const { batchInBlock } = require('../../../helpers/txpool'); const { EIP712Domain, domainSeparator } = require('../../../helpers/eip712'); +const { getChainId } = require('../../../helpers/chainid'); const Delegation = [ { name: 'delegatee', type: 'address' }, @@ -28,12 +29,8 @@ contract('ERC20VotesComp', function (accounts) { const supply = new BN('10000000000000000000000000'); beforeEach(async function () { - this.token = await ERC20VotesCompMock.new(name, symbol); - - // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id - // from within the EVM as from the JSON RPC interface. - // See https://github.com/trufflesuite/ganache-core/issues/515 - this.chainId = await this.token.getChainId(); + this.chainId = await getChainId(); + this.token = await ERC20VotesComp.new(name, symbol, name); }); it('initial nonce is 0', async function () { @@ -44,14 +41,14 @@ contract('ERC20VotesComp', function (accounts) { expect( await this.token.DOMAIN_SEPARATOR(), ).to.equal( - await domainSeparator(name, version, this.chainId, this.token.address), + await domainSeparator({ name, version, chainId: this.chainId, verifyingContract: this.token.address }), ); }); it('minting restriction', async function () { const amount = new BN('2').pow(new BN('96')); await expectRevert( - this.token.mint(holder, amount), + this.token.$_mint(holder, amount), 'ERC20Votes: total supply risks overflowing votes', ); }); @@ -59,7 +56,7 @@ contract('ERC20VotesComp', function (accounts) { describe('set delegation', function () { describe('call', function () { it('delegation with balance', async function () { - await this.token.mint(holder, supply); + await this.token.$_mint(holder, supply); expect(await this.token.delegates(holder)).to.be.equal(ZERO_ADDRESS); const { receipt } = await this.token.delegate(holder, { from: holder }); @@ -110,7 +107,7 @@ contract('ERC20VotesComp', function (accounts) { }}); beforeEach(async function () { - await this.token.mint(delegatorAddress, supply); + await this.token.$_mint(delegatorAddress, supply); }); it('accept signed delegation', async function () { @@ -216,7 +213,7 @@ contract('ERC20VotesComp', function (accounts) { describe('change delegation', function () { beforeEach(async function () { - await this.token.mint(holder, supply); + await this.token.$_mint(holder, supply); await this.token.delegate(holder, { from: holder }); }); @@ -254,7 +251,7 @@ contract('ERC20VotesComp', function (accounts) { describe('transfers', function () { beforeEach(async function () { - await this.token.mint(holder, supply); + await this.token.$_mint(holder, supply); }); it('no delegation', async function () { @@ -316,7 +313,7 @@ contract('ERC20VotesComp', function (accounts) { // The following tests are a adaptation of https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js. describe('Compound test suite', function () { beforeEach(async function () { - await this.token.mint(holder, supply); + await this.token.$_mint(holder, supply); }); describe('balanceOf', function () { @@ -449,7 +446,7 @@ contract('ERC20VotesComp', function (accounts) { }); it('returns the latest block if >= last checkpoint block', async function () { - t1 = await this.token.mint(holder, supply); + t1 = await this.token.$_mint(holder, supply); await time.advanceBlock(); await time.advanceBlock(); @@ -460,7 +457,7 @@ contract('ERC20VotesComp', function (accounts) { it('returns zero if < first checkpoint block', async function () { await time.advanceBlock(); - const t1 = await this.token.mint(holder, supply); + const t1 = await this.token.$_mint(holder, supply); await time.advanceBlock(); await time.advanceBlock(); @@ -469,16 +466,16 @@ contract('ERC20VotesComp', function (accounts) { }); it('generally returns the voting balance at the appropriate checkpoint', async function () { - const t1 = await this.token.mint(holder, supply); + const t1 = await this.token.$_mint(holder, supply); await time.advanceBlock(); await time.advanceBlock(); - const t2 = await this.token.burn(holder, 10); + const t2 = await this.token.$_burn(holder, 10); await time.advanceBlock(); await time.advanceBlock(); - const t3 = await this.token.burn(holder, 10); + const t3 = await this.token.$_burn(holder, 10); await time.advanceBlock(); await time.advanceBlock(); - const t4 = await this.token.mint(holder, 20); + const t4 = await this.token.$_mint(holder, 20); await time.advanceBlock(); await time.advanceBlock(); diff --git a/test/token/ERC20/extensions/ERC20Wrapper.test.js b/test/token/ERC20/extensions/ERC20Wrapper.test.js index ceb813e08..a82164cdf 100644 --- a/test/token/ERC20/extensions/ERC20Wrapper.test.js +++ b/test/token/ERC20/extensions/ERC20Wrapper.test.js @@ -5,8 +5,8 @@ const { ZERO_ADDRESS, MAX_UINT256 } = constants; const { shouldBehaveLikeERC20 } = require('../ERC20.behavior'); const NotAnERC20 = artifacts.require('CallReceiverMock'); -const ERC20Mock = artifacts.require('ERC20DecimalsMock'); -const ERC20WrapperMock = artifacts.require('ERC20WrapperMock'); +const ERC20Decimals = artifacts.require('$ERC20DecimalsMock'); +const ERC20Wrapper = artifacts.require('$ERC20Wrapper'); contract('ERC20', function (accounts) { const [ initialHolder, recipient, anotherAccount ] = accounts; @@ -17,10 +17,10 @@ contract('ERC20', function (accounts) { const initialSupply = new BN(100); beforeEach(async function () { - this.underlying = await ERC20Mock.new(name, symbol, 9); - this.token = await ERC20WrapperMock.new(this.underlying.address, `Wrapped ${name}`, `W${symbol}`); + this.underlying = await ERC20Decimals.new(name, symbol, 9); + await this.underlying.$_mint(initialHolder, initialSupply); - await this.underlying.mint(initialHolder, initialSupply); + this.token = await ERC20Wrapper.new(`Wrapped ${name}`, `W${symbol}`, this.underlying.address); }); afterEach(async function () { @@ -41,7 +41,7 @@ contract('ERC20', function (accounts) { it('decimals default back to 18 if token has no metadata', async function () { const noDecimals = await NotAnERC20.new(); - const otherToken = await ERC20WrapperMock.new(noDecimals.address, `Wrapped ${name}`, `W${symbol}`); + const otherToken = await ERC20Wrapper.new(`Wrapped ${name}`, `W${symbol}`, noDecimals.address); expect(await otherToken.decimals()).to.be.bignumber.equal('18'); }); @@ -159,7 +159,7 @@ contract('ERC20', function (accounts) { await this.underlying.approve(this.token.address, initialSupply, { from: initialHolder }); await this.token.depositFor(initialHolder, initialSupply, { from: initialHolder }); - const { tx } = await this.token.recover(anotherAccount); + const { tx } = await this.token.$_recover(anotherAccount); await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: ZERO_ADDRESS, to: anotherAccount, @@ -170,7 +170,7 @@ contract('ERC20', function (accounts) { it('something to recover', async function () { await this.underlying.transfer(this.token.address, initialSupply, { from: initialHolder }); - const { tx } = await this.token.recover(anotherAccount); + const { tx } = await this.token.$_recover(anotherAccount); await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: ZERO_ADDRESS, to: anotherAccount, diff --git a/test/token/ERC20/extensions/ERC4626.t.sol b/test/token/ERC20/extensions/ERC4626.t.sol index 0aac0d411..3d7dd4a3e 100644 --- a/test/token/ERC20/extensions/ERC4626.t.sol +++ b/test/token/ERC20/extensions/ERC4626.t.sol @@ -5,12 +5,12 @@ import "erc4626-tests/ERC4626.test.sol"; import {SafeCast} from "../../../../contracts/utils/math/SafeCast.sol"; import {ERC20Mock} from "../../../../contracts/mocks/ERC20Mock.sol"; -import {ERC4626Mock, IERC20Metadata} from "../../../../contracts/mocks/ERC4626Mock.sol"; +import {ERC4626Mock} from "../../../../contracts/mocks/ERC4626Mock.sol"; contract ERC4626StdTest is ERC4626Test { function setUp() public override { - _underlying_ = address(new ERC20Mock("MockERC20", "MockERC20", address(this), 0)); - _vault_ = address(new ERC4626Mock(IERC20Metadata(_underlying_), "MockERC4626", "MockERC4626")); + _underlying_ = address(new ERC20Mock()); + _vault_ = address(new ERC4626Mock(_underlying_)); _delta_ = 0; _vaultMayBeEmpty = false; _unlimitedAmount = true; diff --git a/test/token/ERC20/extensions/ERC4626.test.js b/test/token/ERC20/extensions/ERC4626.test.js index 4e6986c44..d095fb9d9 100644 --- a/test/token/ERC20/extensions/ERC4626.test.js +++ b/test/token/ERC20/extensions/ERC4626.test.js @@ -1,9 +1,9 @@ const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const ERC20DecimalsMock = artifacts.require('ERC20DecimalsMock'); -const ERC4626Mock = artifacts.require('ERC4626Mock'); -const ERC4626DecimalMock = artifacts.require('ERC4626DecimalMock'); +const ERC20Decimals = artifacts.require('$ERC20DecimalsMock'); +const ERC4626 = artifacts.require('$ERC4626'); +const ERC4626Decimals = artifacts.require('$ERC4626DecimalsMock'); const parseToken = (token) => (new BN(token)).mul(new BN('1000000000000')); const parseShare = (share) => (new BN(share)).mul(new BN('1000000000000000000')); @@ -15,10 +15,10 @@ contract('ERC4626', function (accounts) { const symbol = 'MTKN'; beforeEach(async function () { - this.token = await ERC20DecimalsMock.new(name, symbol, 12); - this.vault = await ERC4626DecimalMock.new(this.token.address, name + ' Vault', symbol + 'V', 18); + this.token = await ERC20Decimals.new(name, symbol, 12); + this.vault = await ERC4626Decimals.new(name + ' Vault', symbol + 'V', this.token.address, 18); - await this.token.mint(holder, web3.utils.toWei('100')); + await this.token.$_mint(holder, web3.utils.toWei('100')); await this.token.approve(this.vault.address, constants.MAX_UINT256, { from: holder }); await this.vault.approve(spender, constants.MAX_UINT256, { from: holder }); }); @@ -32,8 +32,8 @@ contract('ERC4626', function (accounts) { it('inherit decimals if from asset', async function () { for (const decimals of [ 0, 9, 12, 18, 36 ].map(web3.utils.toBN)) { - const token = await ERC20DecimalsMock.new('', '', decimals); - const vault = await ERC4626Mock.new(token.address, '', ''); + const token = await ERC20Decimals.new('', '', decimals); + const vault = await ERC4626.new('', '', token.address); expect(await vault.decimals()).to.be.bignumber.equal(decimals); } }); @@ -122,7 +122,7 @@ contract('ERC4626', function (accounts) { describe('partially empty vault: assets & no shares', function () { beforeEach(async function () { - await this.token.mint(this.vault.address, parseToken(1)); // 1 token + await this.token.$_mint(this.vault.address, parseToken(1)); // 1 token }); it('status', async function () { @@ -208,7 +208,7 @@ contract('ERC4626', function (accounts) { describe('partially empty vault: shares & no assets', function () { beforeEach(async function () { - await this.vault.mockMint(holder, parseShare(1)); // 1 share + await this.vault.$_mint(holder, parseShare(1)); // 1 share }); it('status', async function () { @@ -302,8 +302,8 @@ contract('ERC4626', function (accounts) { describe('full vault: assets & shares', function () { beforeEach(async function () { - await this.token.mint(this.vault.address, parseToken(1)); // 1 tokens - await this.vault.mockMint(holder, parseShare(100)); // 100 share + await this.token.$_mint(this.vault.address, parseToken(1)); // 1 tokens + await this.vault.$_mint(holder, parseShare(100)); // 100 share }); it('status', async function () { @@ -409,11 +409,11 @@ contract('ERC4626', function (accounts) { /// https://github.com/transmissions11/solmate/blob/main/src/test/ERC4626.t.sol it('multiple mint, deposit, redeem & withdrawal', async function () { // test designed with both asset using similar decimals - this.token = await ERC20DecimalsMock.new(name, symbol, 18); - this.vault = await ERC4626Mock.new(this.token.address, name + ' Vault', symbol + 'V'); + this.token = await ERC20Decimals.new(name, symbol, 18); + this.vault = await ERC4626.new(name + ' Vault', symbol + 'V', this.token.address); - await this.token.mint(user1, 4000); - await this.token.mint(user2, 7001); + await this.token.$_mint(user1, 4000); + await this.token.$_mint(user2, 7001); await this.token.approve(this.vault.address, 4000, { from: user1 }); await this.token.approve(this.vault.address, 7001, { from: user2 }); @@ -464,7 +464,7 @@ contract('ERC4626', function (accounts) { } // 3. Vault mutates by +3000 tokens (simulated yield returned from strategy) - await this.token.mint(this.vault.address, 3000); + await this.token.$_mint(this.vault.address, 3000); expect(await this.vault.balanceOf(user1)).to.be.bignumber.equal('2000'); expect(await this.vault.balanceOf(user2)).to.be.bignumber.equal('4000'); @@ -521,7 +521,7 @@ contract('ERC4626', function (accounts) { // 6. Vault mutates by +3000 tokens // NOTE: Vault holds 17001 tokens, but sum of assetsOf() is 17000. - await this.token.mint(this.vault.address, 3000); + await this.token.$_mint(this.vault.address, 3000); expect(await this.vault.balanceOf(user1)).to.be.bignumber.equal('3333'); expect(await this.vault.balanceOf(user2)).to.be.bignumber.equal('6000'); diff --git a/test/token/ERC20/extensions/draft-ERC20Permit.test.js b/test/token/ERC20/extensions/draft-ERC20Permit.test.js index 26d0c849c..0c6b0982d 100644 --- a/test/token/ERC20/extensions/draft-ERC20Permit.test.js +++ b/test/token/ERC20/extensions/draft-ERC20Permit.test.js @@ -8,9 +8,10 @@ const { fromRpcSig } = require('ethereumjs-util'); const ethSigUtil = require('eth-sig-util'); const Wallet = require('ethereumjs-wallet').default; -const ERC20PermitMock = artifacts.require('ERC20PermitMock'); +const ERC20Permit = artifacts.require('$ERC20Permit'); const { EIP712Domain, Permit, domainSeparator } = require('../../../helpers/eip712'); +const { getChainId } = require('../../../helpers/chainid'); contract('ERC20Permit', function (accounts) { const [ initialHolder, spender ] = accounts; @@ -22,12 +23,10 @@ contract('ERC20Permit', function (accounts) { const initialSupply = new BN(100); beforeEach(async function () { - this.token = await ERC20PermitMock.new(name, symbol, initialHolder, initialSupply); + this.chainId = await getChainId(); - // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id - // from within the EVM as from the JSON RPC interface. - // See https://github.com/trufflesuite/ganache-core/issues/515 - this.chainId = await this.token.getChainId(); + this.token = await ERC20Permit.new(name, symbol, name); + await this.token.$_mint(initialHolder, initialSupply); }); it('initial nonce is 0', async function () { @@ -38,7 +37,7 @@ contract('ERC20Permit', function (accounts) { expect( await this.token.DOMAIN_SEPARATOR(), ).to.equal( - await domainSeparator(name, version, this.chainId, this.token.address), + await domainSeparator({ name, version, chainId: this.chainId, verifyingContract: this.token.address }), ); }); diff --git a/test/token/ERC20/utils/SafeERC20.test.js b/test/token/ERC20/utils/SafeERC20.test.js index 4c54c5830..dab116131 100644 --- a/test/token/ERC20/utils/SafeERC20.test.js +++ b/test/token/ERC20/utils/SafeERC20.test.js @@ -1,12 +1,13 @@ const { constants, expectRevert } = require('@openzeppelin/test-helpers'); +const SafeERC20 = artifacts.require('$SafeERC20'); const ERC20ReturnFalseMock = artifacts.require('ERC20ReturnFalseMock'); const ERC20ReturnTrueMock = artifacts.require('ERC20ReturnTrueMock'); const ERC20NoReturnMock = artifacts.require('ERC20NoReturnMock'); const ERC20PermitNoRevertMock = artifacts.require('ERC20PermitNoRevertMock'); -const SafeERC20Wrapper = artifacts.require('SafeERC20Wrapper'); const { EIP712Domain, Permit } = require('../../../helpers/eip712'); +const { getChainId } = require('../../../helpers/chainid'); const { fromRpcSig } = require('ethereumjs-util'); const ethSigUtil = require('eth-sig-util'); @@ -15,9 +16,13 @@ const Wallet = require('ethereumjs-wallet').default; contract('SafeERC20', function (accounts) { const [ hasNoCode ] = accounts; + before(async function () { + this.mock = await SafeERC20.new(); + }); + describe('with address that has no contract code', function () { beforeEach(async function () { - this.wrapper = await SafeERC20Wrapper.new(hasNoCode); + this.token = { address: hasNoCode }; }); shouldRevertOnAllCalls('Address: call to non-contract'); @@ -25,7 +30,7 @@ contract('SafeERC20', function (accounts) { describe('with token that returns false on all calls', function () { beforeEach(async function () { - this.wrapper = await SafeERC20Wrapper.new((await ERC20ReturnFalseMock.new()).address); + this.token = await ERC20ReturnFalseMock.new(); }); shouldRevertOnAllCalls('SafeERC20: ERC20 operation did not succeed'); @@ -33,7 +38,7 @@ contract('SafeERC20', function (accounts) { describe('with token that returns true on all calls', function () { beforeEach(async function () { - this.wrapper = await SafeERC20Wrapper.new((await ERC20ReturnTrueMock.new()).address); + this.token = await ERC20ReturnTrueMock.new(); }); shouldOnlyRevertOnErrors(); @@ -41,7 +46,7 @@ contract('SafeERC20', function (accounts) { describe('with token that returns no boolean values', function () { beforeEach(async function () { - this.wrapper = await SafeERC20Wrapper.new((await ERC20NoReturnMock.new()).address); + this.token = await ERC20NoReturnMock.new(); }); shouldOnlyRevertOnErrors(); @@ -53,10 +58,9 @@ contract('SafeERC20', function (accounts) { const spender = hasNoCode; beforeEach(async function () { - this.token = await ERC20PermitNoRevertMock.new(); - this.wrapper = await SafeERC20Wrapper.new(this.token.address); + const chainId = await getChainId(); - const chainId = await this.token.getChainId(); + this.token = await ERC20PermitNoRevertMock.new(); this.data = { primaryType: 'Permit', @@ -71,7 +75,8 @@ contract('SafeERC20', function (accounts) { expect(await this.token.nonces(owner)).to.be.bignumber.equal('0'); expect(await this.token.allowance(owner, spender)).to.be.bignumber.equal('0'); - await this.wrapper.permit( + await this.mock.$safePermit( + this.token.address, this.data.message.owner, this.data.message.spender, this.data.message.value, @@ -88,7 +93,8 @@ contract('SafeERC20', function (accounts) { it('revert on reused signature', async function () { expect(await this.token.nonces(owner)).to.be.bignumber.equal('0'); // use valid signature and consume nounce - await this.wrapper.permit( + await this.mock.$safePermit( + this.token.address, this.data.message.owner, this.data.message.spender, this.data.message.value, @@ -111,7 +117,8 @@ contract('SafeERC20', function (accounts) { expect(await this.token.nonces(owner)).to.be.bignumber.equal('1'); // invalid call revert when called through the SafeERC20 library await expectRevert( - this.wrapper.permit( + this.mock.$safePermit( + this.token.address, this.data.message.owner, this.data.message.spender, this.data.message.value, @@ -146,7 +153,8 @@ contract('SafeERC20', function (accounts) { // invalid call revert when called through the SafeERC20 library await expectRevert( - this.wrapper.permit( + this.mock.$safePermit( + this.token.address, this.data.message.owner, this.data.message.spender, this.data.message.value, @@ -163,58 +171,67 @@ contract('SafeERC20', function (accounts) { function shouldRevertOnAllCalls (reason) { it('reverts on transfer', async function () { - await expectRevert(this.wrapper.transfer(), reason); + await expectRevert( + this.mock.$safeTransfer(this.token.address, constants.ZERO_ADDRESS, 0), + reason, + ); }); it('reverts on transferFrom', async function () { - await expectRevert(this.wrapper.transferFrom(), reason); + await expectRevert( + this.mock.$safeTransferFrom(this.token.address, this.mock.address, constants.ZERO_ADDRESS, 0), + reason, + ); }); it('reverts on approve', async function () { - await expectRevert(this.wrapper.approve(0), reason); + await expectRevert( + this.mock.$safeApprove(this.token.address, constants.ZERO_ADDRESS, 0), + reason, + ); }); it('reverts on increaseAllowance', async function () { // [TODO] make sure it's reverting for the right reason - await expectRevert.unspecified(this.wrapper.increaseAllowance(0)); + await expectRevert.unspecified(this.mock.$safeIncreaseAllowance(this.token.address, constants.ZERO_ADDRESS, 0)); }); it('reverts on decreaseAllowance', async function () { // [TODO] make sure it's reverting for the right reason - await expectRevert.unspecified(this.wrapper.decreaseAllowance(0)); + await expectRevert.unspecified(this.mock.$safeDecreaseAllowance(this.token.address, constants.ZERO_ADDRESS, 0)); }); } function shouldOnlyRevertOnErrors () { it('doesn\'t revert on transfer', async function () { - await this.wrapper.transfer(); + await this.mock.$safeTransfer(this.token.address, constants.ZERO_ADDRESS, 0); }); it('doesn\'t revert on transferFrom', async function () { - await this.wrapper.transferFrom(); + await this.mock.$safeTransferFrom(this.token.address, this.mock.address, constants.ZERO_ADDRESS, 0); }); describe('approvals', function () { context('with zero allowance', function () { beforeEach(async function () { - await this.wrapper.setAllowance(0); + await this.token.setAllowance(this.mock.address, 0); }); it('doesn\'t revert when approving a non-zero allowance', async function () { - await this.wrapper.approve(100); + await this.mock.$safeApprove(this.token.address, constants.ZERO_ADDRESS, 100); }); it('doesn\'t revert when approving a zero allowance', async function () { - await this.wrapper.approve(0); + await this.mock.$safeApprove(this.token.address, constants.ZERO_ADDRESS, 0); }); it('doesn\'t revert when increasing the allowance', async function () { - await this.wrapper.increaseAllowance(10); + await this.mock.$safeIncreaseAllowance(this.token.address, constants.ZERO_ADDRESS, 10); }); it('reverts when decreasing the allowance', async function () { await expectRevert( - this.wrapper.decreaseAllowance(10), + this.mock.$safeDecreaseAllowance(this.token.address, constants.ZERO_ADDRESS, 10), 'SafeERC20: decreased allowance below zero', ); }); @@ -222,31 +239,31 @@ function shouldOnlyRevertOnErrors () { context('with non-zero allowance', function () { beforeEach(async function () { - await this.wrapper.setAllowance(100); + await this.token.setAllowance(this.mock.address, 100); }); it('reverts when approving a non-zero allowance', async function () { await expectRevert( - this.wrapper.approve(20), + this.mock.$safeApprove(this.token.address, constants.ZERO_ADDRESS, 20), 'SafeERC20: approve from non-zero to non-zero allowance', ); }); it('doesn\'t revert when approving a zero allowance', async function () { - await this.wrapper.approve(0); + await this.mock.$safeApprove(this.token.address, constants.ZERO_ADDRESS, 0); }); it('doesn\'t revert when increasing the allowance', async function () { - await this.wrapper.increaseAllowance(10); + await this.mock.$safeIncreaseAllowance(this.token.address, constants.ZERO_ADDRESS, 10); }); it('doesn\'t revert when decreasing the allowance to a positive value', async function () { - await this.wrapper.decreaseAllowance(50); + await this.mock.$safeDecreaseAllowance(this.token.address, constants.ZERO_ADDRESS, 50); }); it('reverts when decreasing the allowance to a negative value', async function () { await expectRevert( - this.wrapper.decreaseAllowance(200), + this.mock.$safeDecreaseAllowance(this.token.address, constants.ZERO_ADDRESS, 200), 'SafeERC20: decreased allowance below zero', ); }); diff --git a/test/token/ERC20/utils/TokenTimelock.test.js b/test/token/ERC20/utils/TokenTimelock.test.js index e546b341e..4e0dc0a84 100644 --- a/test/token/ERC20/utils/TokenTimelock.test.js +++ b/test/token/ERC20/utils/TokenTimelock.test.js @@ -2,7 +2,7 @@ const { BN, expectRevert, time } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const ERC20Mock = artifacts.require('ERC20Mock'); +const ERC20 = artifacts.require('$ERC20'); const TokenTimelock = artifacts.require('TokenTimelock'); contract('TokenTimelock', function (accounts) { @@ -15,7 +15,7 @@ contract('TokenTimelock', function (accounts) { context('with token', function () { beforeEach(async function () { - this.token = await ERC20Mock.new(name, symbol, beneficiary, 0); // We're not using the preminted tokens + this.token = await ERC20.new(name, symbol); }); it('rejects a release time in the past', async function () { @@ -30,7 +30,7 @@ contract('TokenTimelock', function (accounts) { beforeEach(async function () { this.releaseTime = (await time.latest()).add(time.duration.years(1)); this.timelock = await TokenTimelock.new(this.token.address, beneficiary, this.releaseTime); - await this.token.mint(this.timelock.address, amount); + await this.token.$_mint(this.timelock.address, amount); }); it('can get state', async function () { diff --git a/test/token/ERC721/ERC721.behavior.js b/test/token/ERC721/ERC721.behavior.js index 7c91671df..436841a25 100644 --- a/test/token/ERC721/ERC721.behavior.js +++ b/test/token/ERC721/ERC721.behavior.js @@ -25,8 +25,8 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('with minted tokens', function () { beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - await this.token.mint(owner, secondTokenId); + await this.token.$_mint(owner, firstTokenId); + await this.token.$_mint(owner, secondTokenId); this.toWhom = other; // default to other for toWhom in context-dependent tests }); @@ -345,7 +345,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another describe('via safeMint', function () { // regular minting is tested in ERC721Mintable.test.js and others it('calls onERC721Received — with data', async function () { this.receiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.None); - const receipt = await this.token.safeMint(this.receiver.address, tokenId, data); + const receipt = await this.token.$_safeMint(this.receiver.address, tokenId, data); await expectEvent.inTransaction(receipt.tx, ERC721ReceiverMock, 'Received', { from: ZERO_ADDRESS, @@ -356,7 +356,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another it('calls onERC721Received — without data', async function () { this.receiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.None); - const receipt = await this.token.safeMint(this.receiver.address, tokenId); + const receipt = await this.token.$_safeMint(this.receiver.address, tokenId); await expectEvent.inTransaction(receipt.tx, ERC721ReceiverMock, 'Received', { from: ZERO_ADDRESS, @@ -368,7 +368,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another it('reverts', async function () { const invalidReceiver = await ERC721ReceiverMock.new('0x42', Error.None); await expectRevert( - this.token.safeMint(invalidReceiver.address, tokenId), + this.token.$_safeMint(invalidReceiver.address, tokenId), 'ERC721: transfer to non ERC721Receiver implementer', ); }); @@ -378,7 +378,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another it('reverts', async function () { const revertingReceiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.RevertWithMessage); await expectRevert( - this.token.safeMint(revertingReceiver.address, tokenId), + this.token.$_safeMint(revertingReceiver.address, tokenId), 'ERC721ReceiverMock: reverting', ); }); @@ -388,7 +388,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another it('reverts', async function () { const revertingReceiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.RevertWithoutMessage); await expectRevert( - this.token.safeMint(revertingReceiver.address, tokenId), + this.token.$_safeMint(revertingReceiver.address, tokenId), 'ERC721: transfer to non ERC721Receiver implementer', ); }); @@ -398,7 +398,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another it('reverts', async function () { const revertingReceiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.Panic); await expectRevert.unspecified( - this.token.safeMint(revertingReceiver.address, tokenId), + this.token.$_safeMint(revertingReceiver.address, tokenId), ); }); }); @@ -407,7 +407,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another it('reverts', async function () { const nonReceiver = this.token; await expectRevert( - this.token.safeMint(nonReceiver.address, tokenId), + this.token.$_safeMint(nonReceiver.address, tokenId), 'ERC721: transfer to non ERC721Receiver implementer', ); }); @@ -647,13 +647,13 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another describe('_mint(address, uint256)', function () { it('reverts with a null destination address', async function () { await expectRevert( - this.token.mint(ZERO_ADDRESS, firstTokenId), 'ERC721: mint to the zero address', + this.token.$_mint(ZERO_ADDRESS, firstTokenId), 'ERC721: mint to the zero address', ); }); context('with minted token', async function () { beforeEach(async function () { - (this.receipt = await this.token.mint(owner, firstTokenId)); + (this.receipt = await this.token.$_mint(owner, firstTokenId)); }); it('emits a Transfer event', function () { @@ -666,7 +666,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another }); it('reverts when adding a token id that already exists', async function () { - await expectRevert(this.token.mint(owner, firstTokenId), 'ERC721: token already minted'); + await expectRevert(this.token.$_mint(owner, firstTokenId), 'ERC721: token already minted'); }); }); }); @@ -674,19 +674,19 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another describe('_burn', function () { it('reverts when burning a non-existent token id', async function () { await expectRevert( - this.token.burn(nonExistentTokenId), 'ERC721: invalid token ID', + this.token.$_burn(nonExistentTokenId), 'ERC721: invalid token ID', ); }); context('with minted tokens', function () { beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - await this.token.mint(owner, secondTokenId); + await this.token.$_mint(owner, firstTokenId); + await this.token.$_mint(owner, secondTokenId); }); context('with burnt token', function () { beforeEach(async function () { - (this.receipt = await this.token.burn(firstTokenId)); + (this.receipt = await this.token.$_burn(firstTokenId)); }); it('emits a Transfer event', function () { @@ -702,7 +702,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another it('reverts when burning a token id that has been deleted', async function () { await expectRevert( - this.token.burn(firstTokenId), 'ERC721: invalid token ID', + this.token.$_burn(firstTokenId), 'ERC721: invalid token ID', ); }); }); @@ -717,8 +717,8 @@ function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approve context('with minted tokens', function () { beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - await this.token.mint(owner, secondTokenId); + await this.token.$_mint(owner, firstTokenId); + await this.token.$_mint(owner, secondTokenId); this.toWhom = other; // default to other for toWhom in context-dependent tests }); @@ -795,9 +795,9 @@ function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approve const newTokenId = new BN(300); const anotherNewTokenId = new BN(400); - await this.token.burn(tokenId); - await this.token.mint(newOwner, newTokenId); - await this.token.mint(newOwner, anotherNewTokenId); + await this.token.$_burn(tokenId); + await this.token.$_mint(newOwner, newTokenId); + await this.token.$_mint(newOwner, anotherNewTokenId); expect(await this.token.totalSupply()).to.be.bignumber.equal('3'); @@ -816,13 +816,13 @@ function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approve describe('_mint(address, uint256)', function () { it('reverts with a null destination address', async function () { await expectRevert( - this.token.mint(ZERO_ADDRESS, firstTokenId), 'ERC721: mint to the zero address', + this.token.$_mint(ZERO_ADDRESS, firstTokenId), 'ERC721: mint to the zero address', ); }); context('with minted token', async function () { beforeEach(async function () { - (this.receipt = await this.token.mint(owner, firstTokenId)); + (this.receipt = await this.token.$_mint(owner, firstTokenId)); }); it('adjusts owner tokens by index', async function () { @@ -838,19 +838,19 @@ function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approve describe('_burn', function () { it('reverts when burning a non-existent token id', async function () { await expectRevert( - this.token.burn(firstTokenId), 'ERC721: invalid token ID', + this.token.$_burn(firstTokenId), 'ERC721: invalid token ID', ); }); context('with minted tokens', function () { beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - await this.token.mint(owner, secondTokenId); + await this.token.$_mint(owner, firstTokenId); + await this.token.$_mint(owner, secondTokenId); }); context('with burnt token', function () { beforeEach(async function () { - (this.receipt = await this.token.burn(firstTokenId)); + (this.receipt = await this.token.$_burn(firstTokenId)); }); it('removes that token from the token list of the owner', async function () { @@ -862,7 +862,7 @@ function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approve }); it('burns all tokens', async function () { - await this.token.burn(secondTokenId, { from: owner }); + await this.token.$_burn(secondTokenId, { from: owner }); expect(await this.token.totalSupply()).to.be.bignumber.equal('0'); await expectRevert( this.token.tokenByIndex(0), 'ERC721Enumerable: global index out of bounds', @@ -889,7 +889,7 @@ function shouldBehaveLikeERC721Metadata (errorPrefix, name, symbol, owner) { describe('token URI', function () { beforeEach(async function () { - await this.token.mint(owner, firstTokenId); + await this.token.$_mint(owner, firstTokenId); }); it('return empty string by default', async function () { diff --git a/test/token/ERC721/ERC721.test.js b/test/token/ERC721/ERC721.test.js index 1abbd6629..6e72e02bd 100644 --- a/test/token/ERC721/ERC721.test.js +++ b/test/token/ERC721/ERC721.test.js @@ -3,14 +3,14 @@ const { shouldBehaveLikeERC721Metadata, } = require('./ERC721.behavior'); -const ERC721Mock = artifacts.require('ERC721Mock'); +const ERC721 = artifacts.require('$ERC721'); contract('ERC721', function (accounts) { const name = 'Non Fungible Token'; const symbol = 'NFT'; beforeEach(async function () { - this.token = await ERC721Mock.new(name, symbol); + this.token = await ERC721.new(name, symbol); }); shouldBehaveLikeERC721('ERC721', ...accounts); diff --git a/test/token/ERC721/ERC721Enumerable.test.js b/test/token/ERC721/ERC721Enumerable.test.js index 2c1362168..b32f22dd6 100644 --- a/test/token/ERC721/ERC721Enumerable.test.js +++ b/test/token/ERC721/ERC721Enumerable.test.js @@ -4,14 +4,14 @@ const { shouldBehaveLikeERC721Enumerable, } = require('./ERC721.behavior'); -const ERC721Mock = artifacts.require('ERC721EnumerableMock'); +const ERC721Enumerable = artifacts.require('$ERC721Enumerable'); contract('ERC721Enumerable', function (accounts) { const name = 'Non Fungible Token'; const symbol = 'NFT'; beforeEach(async function () { - this.token = await ERC721Mock.new(name, symbol); + this.token = await ERC721Enumerable.new(name, symbol); }); shouldBehaveLikeERC721('ERC721', ...accounts); diff --git a/test/token/ERC721/extensions/ERC721Burnable.test.js b/test/token/ERC721/extensions/ERC721Burnable.test.js index e8fc33494..75a5603fb 100644 --- a/test/token/ERC721/extensions/ERC721Burnable.test.js +++ b/test/token/ERC721/extensions/ERC721Burnable.test.js @@ -1,9 +1,8 @@ const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; const { expect } = require('chai'); -const ERC721BurnableMock = artifacts.require('ERC721BurnableMock'); +const ERC721Burnable = artifacts.require('$ERC721Burnable'); contract('ERC721Burnable', function (accounts) { const [owner, approved] = accounts; @@ -16,13 +15,13 @@ contract('ERC721Burnable', function (accounts) { const symbol = 'NFT'; beforeEach(async function () { - this.token = await ERC721BurnableMock.new(name, symbol); + this.token = await ERC721Burnable.new(name, symbol); }); describe('like a burnable ERC721', function () { beforeEach(async function () { - await this.token.mint(owner, firstTokenId); - await this.token.mint(owner, secondTokenId); + await this.token.$_mint(owner, firstTokenId); + await this.token.$_mint(owner, secondTokenId); }); describe('burn', function () { @@ -45,7 +44,7 @@ contract('ERC721Burnable', function (accounts) { it('emits a burn event', async function () { expectEvent(receipt, 'Transfer', { from: owner, - to: ZERO_ADDRESS, + to: constants.ZERO_ADDRESS, tokenId: tokenId, }); }); diff --git a/test/token/ERC721/extensions/ERC721Consecutive.test.js b/test/token/ERC721/extensions/ERC721Consecutive.test.js index 5e480abb8..17df12ea1 100644 --- a/test/token/ERC721/extensions/ERC721Consecutive.test.js +++ b/test/token/ERC721/extensions/ERC721Consecutive.test.js @@ -1,9 +1,9 @@ const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const ERC721ConsecutiveMock = artifacts.require('ERC721ConsecutiveMock'); -const ERC721ConsecutiveEnumerableMock = artifacts.require('ERC721ConsecutiveEnumerableMock'); -const ERC721ConsecutiveNoConstructorMintMock = artifacts.require('ERC721ConsecutiveNoConstructorMintMock'); +const ERC721ConsecutiveMock = artifacts.require('$ERC721ConsecutiveMock'); +const ERC721ConsecutiveEnumerableMock = artifacts.require('$ERC721ConsecutiveEnumerableMock'); +const ERC721ConsecutiveNoConstructorMintMock = artifacts.require('$ERC721ConsecutiveNoConstructorMintMock'); contract('ERC721Consecutive', function (accounts) { const [ user1, user2, user3, receiver ] = accounts; @@ -86,7 +86,7 @@ contract('ERC721Consecutive', function (accounts) { describe('minting after construction', function () { it('consecutive minting is not possible after construction', async function () { await expectRevert( - this.token.mintConsecutive(user1, 10), + this.token.$_mintConsecutive(user1, 10), 'ERC721Consecutive: batch minting restricted to constructor', ); }); @@ -94,10 +94,10 @@ contract('ERC721Consecutive', function (accounts) { it('simple minting is possible after construction', async function () { const tokenId = batches.reduce((acc, { amount }) => acc + amount, 0); - expect(await this.token.exists(tokenId)).to.be.equal(false); + expect(await this.token.$_exists(tokenId)).to.be.equal(false); expectEvent( - await this.token.mint(user1, tokenId), + await this.token.$_mint(user1, tokenId), 'Transfer', { from: constants.ZERO_ADDRESS, to: user1, tokenId: tokenId.toString() }, ); @@ -106,10 +106,10 @@ contract('ERC721Consecutive', function (accounts) { it('cannot mint a token that has been batched minted', async function () { const tokenId = batches.reduce((acc, { amount }) => acc + amount, 0) - 1; - expect(await this.token.exists(tokenId)).to.be.equal(true); + expect(await this.token.$_exists(tokenId)).to.be.equal(true); await expectRevert( - this.token.mint(user1, tokenId), + this.token.$_mint(user1, tokenId), 'ERC721: token already minted', ); }); @@ -124,7 +124,7 @@ contract('ERC721Consecutive', function (accounts) { it('tokens can be burned and re-minted #1', async function () { expectEvent( - await this.token.burn(1, { from: user1 }), + await this.token.$_burn(1, { from: user1 }), 'Transfer', { from: user1, to: constants.ZERO_ADDRESS, tokenId: '1' }, ); @@ -132,7 +132,7 @@ contract('ERC721Consecutive', function (accounts) { await expectRevert(this.token.ownerOf(1), 'ERC721: invalid token ID'); expectEvent( - await this.token.mint(user2, 1), + await this.token.$_mint(user2, 1), 'Transfer', { from: constants.ZERO_ADDRESS, to: user2, tokenId: '1' }, ); @@ -143,33 +143,33 @@ contract('ERC721Consecutive', function (accounts) { it('tokens can be burned and re-minted #2', async function () { const tokenId = batches.reduce((acc, { amount }) => acc.addn(amount), web3.utils.toBN(0)); - expect(await this.token.exists(tokenId)).to.be.equal(false); + expect(await this.token.$_exists(tokenId)).to.be.equal(false); await expectRevert(this.token.ownerOf(tokenId), 'ERC721: invalid token ID'); // mint - await this.token.mint(user1, tokenId); + await this.token.$_mint(user1, tokenId); - expect(await this.token.exists(tokenId)).to.be.equal(true); + expect(await this.token.$_exists(tokenId)).to.be.equal(true); expect(await this.token.ownerOf(tokenId), user1); // burn expectEvent( - await this.token.burn(tokenId, { from: user1 }), + await this.token.$_burn(tokenId, { from: user1 }), 'Transfer', { from: user1, to: constants.ZERO_ADDRESS, tokenId }, ); - expect(await this.token.exists(tokenId)).to.be.equal(false); + expect(await this.token.$_exists(tokenId)).to.be.equal(false); await expectRevert(this.token.ownerOf(tokenId), 'ERC721: invalid token ID'); // re-mint expectEvent( - await this.token.mint(user2, tokenId), + await this.token.$_mint(user2, tokenId), 'Transfer', { from: constants.ZERO_ADDRESS, to: user2, tokenId }, ); - expect(await this.token.exists(tokenId)).to.be.equal(true); + expect(await this.token.$_exists(tokenId)).to.be.equal(true); expect(await this.token.ownerOf(tokenId), user2); }); }); diff --git a/test/token/ERC721/extensions/ERC721Pausable.test.js b/test/token/ERC721/extensions/ERC721Pausable.test.js index 16847dc8d..04dd520a3 100644 --- a/test/token/ERC721/extensions/ERC721Pausable.test.js +++ b/test/token/ERC721/extensions/ERC721Pausable.test.js @@ -1,9 +1,8 @@ const { BN, constants, expectRevert } = require('@openzeppelin/test-helpers'); -const { ZERO_ADDRESS } = constants; const { expect } = require('chai'); -const ERC721PausableMock = artifacts.require('ERC721PausableMock'); +const ERC721Pausable = artifacts.require('$ERC721Pausable'); contract('ERC721Pausable', function (accounts) { const [ owner, receiver, operator ] = accounts; @@ -12,7 +11,7 @@ contract('ERC721Pausable', function (accounts) { const symbol = 'NFT'; beforeEach(async function () { - this.token = await ERC721PausableMock.new(name, symbol); + this.token = await ERC721Pausable.new(name, symbol); }); context('when token is paused', function () { @@ -22,8 +21,8 @@ contract('ERC721Pausable', function (accounts) { const mockData = '0x42'; beforeEach(async function () { - await this.token.mint(owner, firstTokenId, { from: owner }); - await this.token.pause(); + await this.token.$_mint(owner, firstTokenId, { from: owner }); + await this.token.$_pause(); }); it('reverts when trying to transferFrom', async function () { @@ -50,14 +49,14 @@ contract('ERC721Pausable', function (accounts) { it('reverts when trying to mint', async function () { await expectRevert( - this.token.mint(receiver, secondTokenId), + this.token.$_mint(receiver, secondTokenId), 'ERC721Pausable: token transfer while paused', ); }); it('reverts when trying to burn', async function () { await expectRevert( - this.token.burn(firstTokenId), + this.token.$_burn(firstTokenId), 'ERC721Pausable: token transfer while paused', ); }); @@ -65,7 +64,7 @@ contract('ERC721Pausable', function (accounts) { describe('getApproved', function () { it('returns approved address', async function () { const approvedAccount = await this.token.getApproved(firstTokenId); - expect(approvedAccount).to.equal(ZERO_ADDRESS); + expect(approvedAccount).to.equal(constants.ZERO_ADDRESS); }); }); @@ -85,7 +84,7 @@ contract('ERC721Pausable', function (accounts) { describe('exists', function () { it('returns token existence', async function () { - expect(await this.token.exists(firstTokenId)).to.equal(true); + expect(await this.token.$_exists(firstTokenId)).to.equal(true); }); }); diff --git a/test/token/ERC721/extensions/ERC721Royalty.test.js b/test/token/ERC721/extensions/ERC721Royalty.test.js index 29b28dd00..9d38071e3 100644 --- a/test/token/ERC721/extensions/ERC721Royalty.test.js +++ b/test/token/ERC721/extensions/ERC721Royalty.test.js @@ -1,9 +1,9 @@ const { BN, constants } = require('@openzeppelin/test-helpers'); -const ERC721RoyaltyMock = artifacts.require('ERC721RoyaltyMock'); -const { ZERO_ADDRESS } = constants; const { shouldBehaveLikeERC2981 } = require('../../common/ERC2981.behavior'); +const ERC721Royalty = artifacts.require('$ERC721Royalty'); + contract('ERC721Royalty', function (accounts) { const [ account1, account2 ] = accounts; const tokenId1 = new BN('1'); @@ -12,10 +12,10 @@ contract('ERC721Royalty', function (accounts) { const salePrice = new BN('1000'); beforeEach(async function () { - this.token = await ERC721RoyaltyMock.new('My Token', 'TKN'); + this.token = await ERC721Royalty.new('My Token', 'TKN'); - await this.token.mint(account1, tokenId1); - await this.token.mint(account1, tokenId2); + await this.token.$_mint(account1, tokenId1); + await this.token.$_mint(account1, tokenId2); this.account1 = account1; this.account2 = account2; this.tokenId1 = tokenId1; @@ -25,16 +25,17 @@ contract('ERC721Royalty', function (accounts) { describe('token specific functions', function () { beforeEach(async function () { - await this.token.setTokenRoyalty(tokenId1, account1, royalty); + await this.token.$_setTokenRoyalty(tokenId1, account1, royalty); }); it('removes royalty information after burn', async function () { - await this.token.burn(tokenId1); + await this.token.$_burn(tokenId1); const tokenInfo = await this.token.royaltyInfo(tokenId1, salePrice); - expect(tokenInfo[0]).to.be.equal(ZERO_ADDRESS); + expect(tokenInfo[0]).to.be.equal(constants.ZERO_ADDRESS); expect(tokenInfo[1]).to.be.bignumber.equal(new BN('0')); }); }); + shouldBehaveLikeERC2981(); }); diff --git a/test/token/ERC721/extensions/ERC721URIStorage.test.js b/test/token/ERC721/extensions/ERC721URIStorage.test.js index eeacf5ebe..a27b5f658 100644 --- a/test/token/ERC721/extensions/ERC721URIStorage.test.js +++ b/test/token/ERC721/extensions/ERC721URIStorage.test.js @@ -2,7 +2,7 @@ const { BN, expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const ERC721URIStorageMock = artifacts.require('ERC721URIStorageMock'); +const ERC721URIStorageMock = artifacts.require('$ERC721URIStorageMock'); contract('ERC721URIStorage', function (accounts) { const [ owner ] = accounts; @@ -19,7 +19,7 @@ contract('ERC721URIStorage', function (accounts) { describe('token URI', function () { beforeEach(async function () { - await this.token.mint(owner, firstTokenId); + await this.token.$_mint(owner, firstTokenId); }); const baseURI = 'https://api.example.com/v1/'; @@ -36,31 +36,31 @@ contract('ERC721URIStorage', function (accounts) { }); it('can be set for a token id', async function () { - await this.token.setTokenURI(firstTokenId, sampleUri); + await this.token.$_setTokenURI(firstTokenId, sampleUri); expect(await this.token.tokenURI(firstTokenId)).to.be.equal(sampleUri); }); it('reverts when setting for non existent token id', async function () { await expectRevert( - this.token.setTokenURI(nonExistentTokenId, sampleUri), 'ERC721URIStorage: URI set of nonexistent token', + this.token.$_setTokenURI(nonExistentTokenId, sampleUri), 'ERC721URIStorage: URI set of nonexistent token', ); }); it('base URI can be set', async function () { await this.token.setBaseURI(baseURI); - expect(await this.token.baseURI()).to.equal(baseURI); + expect(await this.token.$_baseURI()).to.equal(baseURI); }); it('base URI is added as a prefix to the token URI', async function () { await this.token.setBaseURI(baseURI); - await this.token.setTokenURI(firstTokenId, sampleUri); + await this.token.$_setTokenURI(firstTokenId, sampleUri); expect(await this.token.tokenURI(firstTokenId)).to.be.equal(baseURI + sampleUri); }); it('token URI can be changed by changing the base URI', async function () { await this.token.setBaseURI(baseURI); - await this.token.setTokenURI(firstTokenId, sampleUri); + await this.token.$_setTokenURI(firstTokenId, sampleUri); const newBaseURI = 'https://api.example.com/v2/'; await this.token.setBaseURI(newBaseURI); @@ -74,20 +74,20 @@ contract('ERC721URIStorage', function (accounts) { }); it('tokens without URI can be burnt ', async function () { - await this.token.burn(firstTokenId, { from: owner }); + await this.token.$_burn(firstTokenId, { from: owner }); - expect(await this.token.exists(firstTokenId)).to.equal(false); + expect(await this.token.$_exists(firstTokenId)).to.equal(false); await expectRevert( this.token.tokenURI(firstTokenId), 'ERC721: invalid token ID', ); }); it('tokens with URI can be burnt ', async function () { - await this.token.setTokenURI(firstTokenId, sampleUri); + await this.token.$_setTokenURI(firstTokenId, sampleUri); - await this.token.burn(firstTokenId, { from: owner }); + await this.token.$_burn(firstTokenId, { from: owner }); - expect(await this.token.exists(firstTokenId)).to.equal(false); + expect(await this.token.$_exists(firstTokenId)).to.equal(false); await expectRevert( this.token.tokenURI(firstTokenId), 'ERC721: invalid token ID', ); diff --git a/test/token/ERC721/extensions/ERC721Votes.test.js b/test/token/ERC721/extensions/ERC721Votes.test.js index 6f001f20b..8d9cb701e 100644 --- a/test/token/ERC721/extensions/ERC721Votes.test.js +++ b/test/token/ERC721/extensions/ERC721Votes.test.js @@ -3,25 +3,22 @@ const { BN, expectEvent, time } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const { promisify } = require('util'); -const queue = promisify(setImmediate); - -const ERC721VotesMock = artifacts.require('ERC721VotesMock'); +const { getChainId } = require('../../../helpers/chainid'); const { shouldBehaveLikeVotes } = require('../../../governance/utils/Votes.behavior'); +const ERC721Votes = artifacts.require('$ERC721Votes'); + contract('ERC721Votes', function (accounts) { const [ account1, account2, account1Delegatee, other1, other2 ] = accounts; - this.name = 'My Vote'; + + const name = 'My Vote'; const symbol = 'MTKN'; beforeEach(async function () { - this.votes = await ERC721VotesMock.new(name, symbol); + this.chainId = await getChainId(); - // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id - // from within the EVM as from the JSON RPC interface. - // See https://github.com/trufflesuite/ganache-core/issues/515 - this.chainId = await this.votes.getChainId(); + this.votes = await ERC721Votes.new(name, symbol, name, "1"); this.NFT0 = new BN('10000000000000000000000000'); this.NFT1 = new BN('10'); @@ -31,10 +28,10 @@ contract('ERC721Votes', function (accounts) { describe('balanceOf', function () { beforeEach(async function () { - await this.votes.mint(account1, this.NFT0); - await this.votes.mint(account1, this.NFT1); - await this.votes.mint(account1, this.NFT2); - await this.votes.mint(account1, this.NFT3); + await this.votes.$_mint(account1, this.NFT0); + await this.votes.$_mint(account1, this.NFT1); + await this.votes.$_mint(account1, this.NFT2); + await this.votes.$_mint(account1, this.NFT3); }); it('grants to initial account', async function () { @@ -44,7 +41,7 @@ contract('ERC721Votes', function (accounts) { describe('transfers', function () { beforeEach(async function () { - await this.votes.mint(account1, this.NFT0); + await this.votes.$_mint(account1, this.NFT0); }); it('no delegation', async function () { @@ -116,9 +113,9 @@ contract('ERC721Votes', function (accounts) { }); it('generally returns the voting balance at the appropriate checkpoint', async function () { - await this.votes.mint(account1, this.NFT1); - await this.votes.mint(account1, this.NFT2); - await this.votes.mint(account1, this.NFT3); + await this.votes.$_mint(account1, this.NFT1); + await this.votes.$_mint(account1, this.NFT2); + await this.votes.$_mint(account1, this.NFT3); const total = await this.votes.balanceOf(account1); diff --git a/test/token/ERC721/utils/ERC721Holder.test.js b/test/token/ERC721/utils/ERC721Holder.test.js index 2431e667c..e821f32dd 100644 --- a/test/token/ERC721/utils/ERC721Holder.test.js +++ b/test/token/ERC721/utils/ERC721Holder.test.js @@ -1,20 +1,18 @@ -const { BN } = require('@openzeppelin/test-helpers'); - const { expect } = require('chai'); const ERC721Holder = artifacts.require('ERC721Holder'); -const ERC721Mock = artifacts.require('ERC721Mock'); +const ERC721 = artifacts.require('$ERC721'); contract('ERC721Holder', function (accounts) { const [ owner ] = accounts; const name = 'Non Fungible Token'; const symbol = 'NFT'; + const tokenId = web3.utils.toBN(1); it('receives an ERC721 token', async function () { - const token = await ERC721Mock.new(name, symbol); - const tokenId = new BN(1); - await token.mint(owner, tokenId); + const token = await ERC721.new(name, symbol); + await token.$_mint(owner, tokenId); const receiver = await ERC721Holder.new(); await token.safeTransferFrom(owner, receiver.address, tokenId, { from: owner }); diff --git a/test/token/ERC777/ERC777.behavior.js b/test/token/ERC777/ERC777.behavior.js index f6af94227..be104f467 100644 --- a/test/token/ERC777/ERC777.behavior.js +++ b/test/token/ERC777/ERC777.behavior.js @@ -281,7 +281,7 @@ function shouldBehaveLikeERC777InternalMint (recipient, operator, amount, data, it('reverts when minting tokens for the zero address', async function () { await expectRevert.unspecified( - this.token.mintInternal(ZERO_ADDRESS, amount, data, operatorData, { from: operator }), + this.token.$_mint(ZERO_ADDRESS, amount, data, operatorData, true, { from: operator }), ); }); } @@ -291,7 +291,7 @@ function shouldInternalMintTokens (operator, to, amount, data, operatorData) { const initialTotalSupply = await this.token.totalSupply(); const initialToBalance = await this.token.balanceOf(to); - const receipt = await this.token.mintInternal(to, amount, data, operatorData, { from: operator }); + const receipt = await this.token.$_mint(to, amount, data, operatorData, true, { from: operator }); expectEvent(receipt, 'Minted', { operator, @@ -333,7 +333,7 @@ function shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook (operator, am it('mint (internal) reverts', async function () { await expectRevert.unspecified( - this.token.mintInternal(this.recipient, amount, data, operatorData, { from: operator }), + this.token.$_mint(this.recipient, amount, data, operatorData, true, { from: operator }), ); }); }); @@ -387,9 +387,7 @@ function shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook (operator, am }); it('TokensRecipient receives mint (internal) data and is called after state mutation', async function () { - const { tx } = await this.token.mintInternal( - this.recipient, amount, data, operatorData, { from: operator }, - ); + const { tx } = await this.token.$_mint(this.recipient, amount, data, operatorData, true, { from: operator }); const postRecipientBalance = await this.token.balanceOf(this.recipient); diff --git a/test/token/ERC777/ERC777.test.js b/test/token/ERC777/ERC777.test.js index 51da130d4..efb8eae43 100644 --- a/test/token/ERC777/ERC777.test.js +++ b/test/token/ERC777/ERC777.test.js @@ -17,8 +17,8 @@ const { shouldBehaveLikeERC20Approve, } = require('../ERC20/ERC20.behavior'); -const ERC777 = artifacts.require('ERC777Mock'); -const ERC777SenderRecipientMock = artifacts.require('ERC777SenderRecipientMock'); +const ERC777 = artifacts.require('$ERC777Mock'); +const ERC777SenderRecipientMock = artifacts.require('$ERC777SenderRecipientMock'); contract('ERC777', function (accounts) { const [ registryFunder, holder, defaultOperatorA, defaultOperatorB, newOperator, anyone ] = accounts; @@ -37,7 +37,8 @@ contract('ERC777', function (accounts) { context('with default operators', function () { beforeEach(async function () { - this.token = await ERC777.new(holder, initialSupply, name, symbol, defaultOperators); + this.token = await ERC777.new(name, symbol, defaultOperators); + await this.token.$_mint(holder, initialSupply, '0x', '0x'); }); describe('as an ERC20 token', function () { @@ -45,12 +46,12 @@ contract('ERC777', function (accounts) { describe('_approve', function () { shouldBehaveLikeERC20Approve('ERC777', holder, anyone, initialSupply, function (owner, spender, amount) { - return this.token.approveInternal(owner, spender, amount); + return this.token.$_approve(owner, spender, amount); }); describe('when the owner is the zero address', function () { it('reverts', async function () { - await expectRevert(this.token.approveInternal(ZERO_ADDRESS, anyone, initialSupply), + await expectRevert(this.token.$_approve(ZERO_ADDRESS, anyone, initialSupply), 'ERC777: approve from the zero address', ); }); @@ -184,7 +185,7 @@ contract('ERC777', function (accounts) { const operator = defaultOperatorA; it('without requireReceptionAck', async function () { - await this.token.mintInternalExtended( + await this.token.$_mint( this.recipient, amount, data, @@ -195,7 +196,7 @@ contract('ERC777', function (accounts) { }); it('with requireReceptionAck', async function () { - await this.token.mintInternalExtended( + await this.token.$_mint( this.recipient, amount, data, @@ -210,7 +211,7 @@ contract('ERC777', function (accounts) { const operator = newOperator; it('without requireReceptionAck', async function () { - await this.token.mintInternalExtended( + await this.token.$_mint( this.recipient, amount, data, @@ -221,7 +222,7 @@ contract('ERC777', function (accounts) { }); it('with requireReceptionAck', async function () { - await this.token.mintInternalExtended( + await this.token.$_mint( this.recipient, amount, data, @@ -243,7 +244,7 @@ contract('ERC777', function (accounts) { const operator = defaultOperatorA; it('without requireReceptionAck', async function () { - await this.token.mintInternalExtended( + await this.token.$_mint( this.recipient, amount, data, @@ -255,7 +256,7 @@ contract('ERC777', function (accounts) { it('with requireReceptionAck', async function () { await expectRevert( - this.token.mintInternalExtended( + this.token.$_mint( this.recipient, amount, data, @@ -272,7 +273,7 @@ contract('ERC777', function (accounts) { const operator = newOperator; it('without requireReceptionAck', async function () { - await this.token.mintInternalExtended( + await this.token.$_mint( this.recipient, amount, data, @@ -284,7 +285,7 @@ contract('ERC777', function (accounts) { it('with requireReceptionAck', async function () { await expectRevert( - this.token.mintInternalExtended( + this.token.$_mint( this.recipient, amount, data, @@ -443,7 +444,7 @@ contract('ERC777', function (accounts) { it('mint (internal) reverts', async function () { await expectRevert( - this.token.mintInternal(this.recipient, amount, data, operatorData, { from: operator }), + this.token.$_mint(this.recipient, amount, data, operatorData, true, { from: operator }), 'ERC777: token recipient contract has no implementer for ERC777TokensRecipient', ); }); @@ -567,7 +568,7 @@ contract('ERC777', function (accounts) { context('with no default operators', function () { beforeEach(async function () { - this.token = await ERC777.new(holder, initialSupply, name, symbol, []); + this.token = await ERC777.new(name, symbol, []); }); it('default operators list is empty', async function () { @@ -581,8 +582,8 @@ contract('ERC777', function (accounts) { this.sender = await ERC777SenderRecipientMock.new(); await this.sender.registerRecipient(this.sender.address); await this.sender.registerSender(this.sender.address); - this.token = await ERC777.new(holder, initialSupply, name, symbol, []); - await this.token.send(this.sender.address, 1, '0x', { from: holder }); + this.token = await ERC777.new(name, symbol, []); + await this.token.$_mint(this.sender.address, 1, '0x', '0x'); }); it('send', async function () { diff --git a/test/token/common/ERC2981.behavior.js b/test/token/common/ERC2981.behavior.js index 2fd274765..aea5e52f0 100644 --- a/test/token/common/ERC2981.behavior.js +++ b/test/token/common/ERC2981.behavior.js @@ -11,7 +11,7 @@ function shouldBehaveLikeERC2981 () { describe('default royalty', function () { beforeEach(async function () { - await this.token.setDefaultRoyalty(this.account1, royaltyFraction); + await this.token.$_setDefaultRoyalty(this.account1, royaltyFraction); }); it('checks royalty is set', async function () { @@ -27,7 +27,7 @@ function shouldBehaveLikeERC2981 () { const newPercentage = new BN('25'); // Updated royalty check - await this.token.setDefaultRoyalty(this.account1, newPercentage); + await this.token.$_setDefaultRoyalty(this.account1, newPercentage); const royalty = new BN((this.salePrice * newPercentage) / 10000); const newInfo = await this.token.royaltyInfo(this.tokenId1, this.salePrice); @@ -37,7 +37,7 @@ function shouldBehaveLikeERC2981 () { it('holds same royalty value for different tokens', async function () { const newPercentage = new BN('20'); - await this.token.setDefaultRoyalty(this.account1, newPercentage); + await this.token.$_setDefaultRoyalty(this.account1, newPercentage); const token1Info = await this.token.royaltyInfo(this.tokenId1, this.salePrice); const token2Info = await this.token.royaltyInfo(this.tokenId2, this.salePrice); @@ -47,7 +47,7 @@ function shouldBehaveLikeERC2981 () { it('Remove royalty information', async function () { const newValue = new BN('0'); - await this.token.deleteDefaultRoyalty(); + await this.token.$_deleteDefaultRoyalty(); const token1Info = await this.token.royaltyInfo(this.tokenId1, this.salePrice); const token2Info = await this.token.royaltyInfo(this.tokenId2, this.salePrice); @@ -61,12 +61,12 @@ function shouldBehaveLikeERC2981 () { it('reverts if invalid parameters', async function () { await expectRevert( - this.token.setDefaultRoyalty(ZERO_ADDRESS, royaltyFraction), + this.token.$_setDefaultRoyalty(ZERO_ADDRESS, royaltyFraction), 'ERC2981: invalid receiver', ); await expectRevert( - this.token.setDefaultRoyalty(this.account1, new BN('11000')), + this.token.$_setDefaultRoyalty(this.account1, new BN('11000')), 'ERC2981: royalty fee will exceed salePrice', ); }); @@ -74,7 +74,7 @@ function shouldBehaveLikeERC2981 () { describe('token based royalty', function () { beforeEach(async function () { - await this.token.setTokenRoyalty(this.tokenId1, this.account1, royaltyFraction); + await this.token.$_setTokenRoyalty(this.tokenId1, this.account1, royaltyFraction); }); it('updates royalty amount', async function () { @@ -87,7 +87,7 @@ function shouldBehaveLikeERC2981 () { expect(initInfo[1]).to.be.bignumber.equal(royalty); // Updated royalty check - await this.token.setTokenRoyalty(this.tokenId1, this.account1, newPercentage); + await this.token.$_setTokenRoyalty(this.tokenId1, this.account1, newPercentage); royalty = new BN((this.salePrice * newPercentage) / 10000); const newInfo = await this.token.royaltyInfo(this.tokenId1, this.salePrice); @@ -97,7 +97,7 @@ function shouldBehaveLikeERC2981 () { it('holds different values for different tokens', async function () { const newPercentage = new BN('20'); - await this.token.setTokenRoyalty(this.tokenId2, this.account1, newPercentage); + await this.token.$_setTokenRoyalty(this.tokenId2, this.account1, newPercentage); const token1Info = await this.token.royaltyInfo(this.tokenId1, this.salePrice); const token2Info = await this.token.royaltyInfo(this.tokenId2, this.salePrice); @@ -108,12 +108,12 @@ function shouldBehaveLikeERC2981 () { it('reverts if invalid parameters', async function () { await expectRevert( - this.token.setTokenRoyalty(this.tokenId1, ZERO_ADDRESS, royaltyFraction), + this.token.$_setTokenRoyalty(this.tokenId1, ZERO_ADDRESS, royaltyFraction), 'ERC2981: Invalid parameters', ); await expectRevert( - this.token.setTokenRoyalty(this.tokenId1, this.account1, new BN('11000')), + this.token.$_setTokenRoyalty(this.tokenId1, this.account1, new BN('11000')), 'ERC2981: royalty fee will exceed salePrice', ); }); @@ -121,7 +121,7 @@ function shouldBehaveLikeERC2981 () { it('can reset token after setting royalty', async function () { const newPercentage = new BN('30'); const royalty = new BN((this.salePrice * newPercentage) / 10000); - await this.token.setTokenRoyalty(this.tokenId1, this.account2, newPercentage); + await this.token.$_setTokenRoyalty(this.tokenId1, this.account2, newPercentage); const tokenInfo = await this.token.royaltyInfo(this.tokenId1, this.salePrice); @@ -129,7 +129,7 @@ function shouldBehaveLikeERC2981 () { expect(tokenInfo[1]).to.be.bignumber.equal(royalty); expect(tokenInfo[0]).to.be.equal(this.account2); - await this.token.setTokenRoyalty(this.tokenId2, this.account1, new BN('0')); + await this.token.$_setTokenRoyalty(this.tokenId2, this.account1, new BN('0')); const result = await this.token.royaltyInfo(this.tokenId2, this.salePrice); // Token must not share default information expect(result[0]).to.be.equal(this.account1); @@ -140,7 +140,7 @@ function shouldBehaveLikeERC2981 () { const newPercentage = new BN('30'); const royalty = new BN((this.salePrice * newPercentage) / 10000); - await this.token.setTokenRoyalty(this.tokenId2, this.account2, newPercentage); + await this.token.$_setTokenRoyalty(this.tokenId2, this.account2, newPercentage); const token1Info = await this.token.royaltyInfo(this.tokenId1, this.salePrice); const token2Info = await this.token.royaltyInfo(this.tokenId2, this.salePrice); diff --git a/test/utils/Address.test.js b/test/utils/Address.test.js index 1bdfad483..135a7f96d 100644 --- a/test/utils/Address.test.js +++ b/test/utils/Address.test.js @@ -1,7 +1,7 @@ -const { balance, ether, expectRevert, send, expectEvent } = require('@openzeppelin/test-helpers'); +const { balance, constants, ether, expectRevert, send, expectEvent } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const AddressImpl = artifacts.require('AddressImpl'); +const Address = artifacts.require('$Address'); const EtherReceiver = artifacts.require('EtherReceiverMock'); const CallReceiverMock = artifacts.require('CallReceiverMock'); @@ -9,17 +9,16 @@ contract('Address', function (accounts) { const [ recipient, other ] = accounts; beforeEach(async function () { - this.mock = await AddressImpl.new(); + this.mock = await Address.new(); }); describe('isContract', function () { it('returns false for account address', async function () { - expect(await this.mock.isContract(other)).to.equal(false); + expect(await this.mock.$isContract(other)).to.equal(false); }); it('returns true for contract address', async function () { - const contract = await AddressImpl.new(); - expect(await this.mock.isContract(contract.address)).to.equal(true); + expect(await this.mock.$isContract(this.mock.address)).to.equal(true); }); }); @@ -30,13 +29,16 @@ contract('Address', function (accounts) { context('when sender contract has no funds', function () { it('sends 0 wei', async function () { - await this.mock.sendValue(other, 0); + await this.mock.$sendValue(other, 0); expect(await this.recipientTracker.delta()).to.be.bignumber.equal('0'); }); it('reverts when sending non-zero amounts', async function () { - await expectRevert(this.mock.sendValue(other, 1), 'Address: insufficient balance'); + await expectRevert( + this.mock.$sendValue(other, 1), + 'Address: insufficient balance', + ); }); }); @@ -47,42 +49,46 @@ contract('Address', function (accounts) { }); it('sends 0 wei', async function () { - await this.mock.sendValue(recipient, 0); + await this.mock.$sendValue(recipient, 0); expect(await this.recipientTracker.delta()).to.be.bignumber.equal('0'); }); it('sends non-zero amounts', async function () { - await this.mock.sendValue(recipient, funds.subn(1)); + await this.mock.$sendValue(recipient, funds.subn(1)); expect(await this.recipientTracker.delta()).to.be.bignumber.equal(funds.subn(1)); }); it('sends the whole balance', async function () { - await this.mock.sendValue(recipient, funds); + await this.mock.$sendValue(recipient, funds); expect(await this.recipientTracker.delta()).to.be.bignumber.equal(funds); expect(await balance.current(this.mock.address)).to.be.bignumber.equal('0'); }); it('reverts when sending more than the balance', async function () { - await expectRevert(this.mock.sendValue(recipient, funds.addn(1)), 'Address: insufficient balance'); + await expectRevert( + this.mock.$sendValue(recipient, funds.addn(1)), + 'Address: insufficient balance', + ); }); context('with contract recipient', function () { beforeEach(async function () { - this.contractRecipient = await EtherReceiver.new(); + this.target = await EtherReceiver.new(); }); it('sends funds', async function () { - const tracker = await balance.tracker(this.contractRecipient.address); + const tracker = await balance.tracker(this.target.address); + + await this.target.setAcceptEther(true); + await this.mock.$sendValue(this.target.address, funds); - await this.contractRecipient.setAcceptEther(true); - await this.mock.sendValue(this.contractRecipient.address, funds); expect(await tracker.delta()).to.be.bignumber.equal(funds); }); it('reverts on recipient revert', async function () { - await this.contractRecipient.setAcceptEther(false); + await this.target.setAcceptEther(false); await expectRevert( - this.mock.sendValue(this.contractRecipient.address, funds), + this.mock.$sendValue(this.target.address, funds), 'Address: unable to send value, recipient may have reverted', ); }); @@ -92,71 +98,55 @@ contract('Address', function (accounts) { describe('functionCall', function () { beforeEach(async function () { - this.contractRecipient = await CallReceiverMock.new(); + this.target = await CallReceiverMock.new(); }); context('with valid contract receiver', function () { it('calls the requested function', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); - const receipt = await this.mock.functionCall(this.contractRecipient.address, abiEncodedCall); + const receipt = await this.mock.$functionCall(this.target.address, abiEncodedCall); - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); + expectEvent( + receipt, + 'return$functionCall_address_bytes', + { ret0: web3.eth.abi.encodeParameters(['string'], [ '0x1234' ]) }, + ); await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); }); it('reverts when the called function reverts with no reason', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionRevertsNoReason', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunctionRevertsNoReason().encodeABI(); await expectRevert( - this.mock.functionCall(this.contractRecipient.address, abiEncodedCall), + this.mock.$functionCall(this.target.address, abiEncodedCall), 'Address: low-level call failed', ); }); it('reverts when the called function reverts, bubbling up the revert reason', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionRevertsReason', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunctionRevertsReason().encodeABI(); await expectRevert( - this.mock.functionCall(this.contractRecipient.address, abiEncodedCall), + this.mock.$functionCall(this.target.address, abiEncodedCall), 'CallReceiverMock: reverting', ); }); it('reverts when the called function runs out of gas', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionOutOfGas', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunctionOutOfGas().encodeABI(); await expectRevert( - this.mock.functionCall(this.contractRecipient.address, abiEncodedCall, { gas: '120000' }), + this.mock.$functionCall(this.target.address, abiEncodedCall, { gas: '120000' }), 'Address: low-level call failed', ); }); it('reverts when the called function throws', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionThrows', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunctionThrows().encodeABI(); await expectRevert.unspecified( - this.mock.functionCall(this.contractRecipient.address, abiEncodedCall), + this.mock.$functionCall(this.target.address, abiEncodedCall), ); }); @@ -168,7 +158,7 @@ contract('Address', function (accounts) { }, []); await expectRevert( - this.mock.functionCall(this.contractRecipient.address, abiEncodedCall), + this.mock.$functionCall(this.target.address, abiEncodedCall), 'Address: low-level call failed', ); }); @@ -177,32 +167,31 @@ contract('Address', function (accounts) { context('with non-contract receiver', function () { it('reverts when address is not a contract', async function () { const [ recipient ] = accounts; - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); - await expectRevert(this.mock.functionCall(recipient, abiEncodedCall), 'Address: call to non-contract'); + const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); + + await expectRevert( + this.mock.$functionCall(recipient, abiEncodedCall), + 'Address: call to non-contract', + ); }); }); }); describe('functionCallWithValue', function () { beforeEach(async function () { - this.contractRecipient = await CallReceiverMock.new(); + this.target = await CallReceiverMock.new(); }); context('with zero value', function () { it('calls the requested function', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); - const receipt = await this.mock.functionCallWithValue(this.contractRecipient.address, abiEncodedCall, 0); - - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); + const receipt = await this.mock.$functionCallWithValue(this.target.address, abiEncodedCall, 0); + expectEvent( + receipt, + 'return$functionCallWithValue_address_bytes_uint256', + { ret0: web3.eth.abi.encodeParameters(['string'], [ '0x1234' ]) }, + ); await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); }); }); @@ -211,66 +200,61 @@ contract('Address', function (accounts) { const amount = ether('1.2'); it('reverts if insufficient sender balance', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); await expectRevert( - this.mock.functionCallWithValue(this.contractRecipient.address, abiEncodedCall, amount), + this.mock.$functionCallWithValue(this.target.address, abiEncodedCall, amount), 'Address: insufficient balance for call', ); }); it('calls the requested function with existing value', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); - const tracker = await balance.tracker(this.contractRecipient.address); + const tracker = await balance.tracker(this.target.address); await send.ether(other, this.mock.address, amount); - const receipt = await this.mock.functionCallWithValue(this.contractRecipient.address, abiEncodedCall, amount); + + const receipt = await this.mock.$functionCallWithValue(this.target.address, abiEncodedCall, amount); + expectEvent( + receipt, + 'return$functionCallWithValue_address_bytes_uint256', + { ret0: web3.eth.abi.encodeParameters(['string'], [ '0x1234' ]) }, + ); + await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); expect(await tracker.delta()).to.be.bignumber.equal(amount); - - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); - await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); }); it('calls the requested function with transaction funds', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); - const tracker = await balance.tracker(this.contractRecipient.address); + const tracker = await balance.tracker(this.target.address); expect(await balance.current(this.mock.address)).to.be.bignumber.equal('0'); - const receipt = await this.mock.functionCallWithValue( - this.contractRecipient.address, abiEncodedCall, amount, { from: other, value: amount }, + + const receipt = await this.mock.$functionCallWithValue( + this.target.address, + abiEncodedCall, + amount, + { from: other, value: amount }, ); + expectEvent( + receipt, + 'return$functionCallWithValue_address_bytes_uint256', + { ret0: web3.eth.abi.encodeParameters(['string'], [ '0x1234' ]) }, + ); + await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); expect(await tracker.delta()).to.be.bignumber.equal(amount); - - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); - await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); }); it('reverts when calling non-payable functions', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionNonPayable', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunctionNonPayable().encodeABI(); await send.ether(other, this.mock.address, amount); await expectRevert( - this.mock.functionCallWithValue(this.contractRecipient.address, abiEncodedCall, amount), + this.mock.$functionCallWithValue(this.target.address, abiEncodedCall, amount), 'Address: low-level call with value failed', ); }); @@ -279,56 +263,40 @@ contract('Address', function (accounts) { describe('functionStaticCall', function () { beforeEach(async function () { - this.contractRecipient = await CallReceiverMock.new(); + this.target = await CallReceiverMock.new(); }); it('calls the requested function', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockStaticFunction', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockStaticFunction().encodeABI(); - const receipt = await this.mock.functionStaticCall(this.contractRecipient.address, abiEncodedCall); - - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); + expect(await this.mock.$functionStaticCall(this.target.address, abiEncodedCall)) + .to.be.equal(web3.eth.abi.encodeParameters(['string'], [ '0x1234' ])); }); it('reverts on a non-static function', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); await expectRevert( - this.mock.functionStaticCall(this.contractRecipient.address, abiEncodedCall), + this.mock.$functionStaticCall(this.target.address, abiEncodedCall), 'Address: low-level static call failed', ); }); it('bubbles up revert reason', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionRevertsReason', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunctionRevertsReason().encodeABI(); await expectRevert( - this.mock.functionStaticCall(this.contractRecipient.address, abiEncodedCall), + this.mock.$functionStaticCall(this.target.address, abiEncodedCall), 'CallReceiverMock: reverting', ); }); it('reverts when address is not a contract', async function () { const [ recipient ] = accounts; - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); + await expectRevert( - this.mock.functionStaticCall(recipient, abiEncodedCall), + this.mock.$functionStaticCall(recipient, abiEncodedCall), 'Address: call to non-contract', ); }); @@ -336,45 +304,42 @@ contract('Address', function (accounts) { describe('functionDelegateCall', function () { beforeEach(async function () { - this.contractRecipient = await CallReceiverMock.new(); + this.target = await CallReceiverMock.new(); }); it('delegate calls the requested function', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionWritesStorage', - type: 'function', - inputs: [], - }, []); + // pseudorandom values + const slot = '0x93e4c53af435ddf777c3de84bb9a953a777788500e229a468ea1036496ab66a0'; + const value = '0x6a465d1c49869f71fb65562bcbd7e08c8044074927f0297127203f2a9924ff5b'; - const receipt = await this.mock.functionDelegateCall(this.contractRecipient.address, abiEncodedCall); + const abiEncodedCall = this.target.contract.methods.mockFunctionWritesStorage(slot, value).encodeABI(); - expectEvent(receipt, 'CallReturnValue', { data: '0x1234' }); + expect(await web3.eth.getStorageAt(this.mock.address, slot)).to.be.equal(constants.ZERO_BYTES32); - expect(await this.mock.sharedAnswer()).to.equal('42'); + expectEvent( + await this.mock.$functionDelegateCall(this.target.address, abiEncodedCall), + 'return$functionDelegateCall_address_bytes', + { ret0: web3.eth.abi.encodeParameters(['string'], [ '0x1234' ]) }, + ); + + expect(await web3.eth.getStorageAt(this.mock.address, slot)).to.be.equal(value); }); it('bubbles up revert reason', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionRevertsReason', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunctionRevertsReason().encodeABI(); await expectRevert( - this.mock.functionDelegateCall(this.contractRecipient.address, abiEncodedCall), + this.mock.$functionDelegateCall(this.target.address, abiEncodedCall), 'CallReceiverMock: reverting', ); }); it('reverts when address is not a contract', async function () { const [ recipient ] = accounts; - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunction', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); + await expectRevert( - this.mock.functionDelegateCall(recipient, abiEncodedCall), + this.mock.$functionDelegateCall(recipient, abiEncodedCall), 'Address: call to non-contract', ); }); diff --git a/test/utils/Base64.test.js b/test/utils/Base64.test.js index b6ee6579e..dfff0b0d0 100644 --- a/test/utils/Base64.test.js +++ b/test/utils/Base64.test.js @@ -1,33 +1,33 @@ const { expect } = require('chai'); -const Base64Mock = artifacts.require('Base64Mock'); +const Base64 = artifacts.require('$Base64'); contract('Strings', function () { beforeEach(async function () { - this.base64 = await Base64Mock.new(); + this.base64 = await Base64.new(); }); describe('from bytes - base64', function () { it('converts to base64 encoded string with double padding', async function () { const TEST_MESSAGE = 'test'; const input = web3.utils.asciiToHex(TEST_MESSAGE); - expect(await this.base64.encode(input)).to.equal('dGVzdA=='); + expect(await this.base64.$encode(input)).to.equal('dGVzdA=='); }); it('converts to base64 encoded string with single padding', async function () { const TEST_MESSAGE = 'test1'; const input = web3.utils.asciiToHex(TEST_MESSAGE); - expect(await this.base64.encode(input)).to.equal('dGVzdDE='); + expect(await this.base64.$encode(input)).to.equal('dGVzdDE='); }); it('converts to base64 encoded string without padding', async function () { const TEST_MESSAGE = 'test12'; const input = web3.utils.asciiToHex(TEST_MESSAGE); - expect(await this.base64.encode(input)).to.equal('dGVzdDEy'); + expect(await this.base64.$encode(input)).to.equal('dGVzdDEy'); }); it('empty bytes', async function () { - expect(await this.base64.encode([])).to.equal(''); + expect(await this.base64.$encode([])).to.equal(''); }); }); }); diff --git a/test/utils/Checkpoints.test.js b/test/utils/Checkpoints.test.js index abc5c9b36..520cf4fd0 100644 --- a/test/utils/Checkpoints.test.js +++ b/test/utils/Checkpoints.test.js @@ -4,22 +4,35 @@ const { expect } = require('chai'); const { batchInBlock } = require('../helpers/txpool'); -const CheckpointsMock = artifacts.require('CheckpointsMock'); +const $Checkpoints = artifacts.require('$Checkpoints'); const first = (array) => array.length ? array[0] : undefined; const last = (array) => array.length ? array[array.length - 1] : undefined; contract('Checkpoints', function () { + beforeEach(async function () { + this.mock = await $Checkpoints.new(); + }); + describe('History checkpoints', function () { - beforeEach(async function () { - this.checkpoint = await CheckpointsMock.new(); - }); + const latest = (self, ...args) => + self.methods['$latest_Checkpoints_History(uint256)'](0, ...args); + const latestCheckpoint = (self, ...args) => + self.methods['$latestCheckpoint_Checkpoints_History(uint256)'](0, ...args); + const push = (self, ...args) => + self.methods['$push(uint256,uint256)'](0, ...args); + const getAtBlock = (self, ...args) => + self.methods['$getAtBlock(uint256,uint256)'](0, ...args); + const getAtRecentBlock = (self, ...args) => + self.methods['$getAtProbablyRecentBlock(uint256,uint256)'](0, ...args); + const getLength = (self, ...args) => + self.methods['$length_Checkpoints_History(uint256)'](0, ...args); describe('without checkpoints', function () { it('returns zero as latest value', async function () { - expect(await this.checkpoint.latest()).to.be.bignumber.equal('0'); + expect(await latest(this.mock)).to.be.bignumber.equal('0'); - const ckpt = await this.checkpoint.latestCheckpoint(); + const ckpt = await latestCheckpoint(this.mock); expect(ckpt[0]).to.be.equal(false); expect(ckpt[1]).to.be.bignumber.equal('0'); expect(ckpt[2]).to.be.bignumber.equal('0'); @@ -27,51 +40,49 @@ contract('Checkpoints', function () { it('returns zero as past value', async function () { await time.advanceBlock(); - expect(await this.checkpoint.getAtBlock(await web3.eth.getBlockNumber() - 1)) - .to.be.bignumber.equal('0'); - expect(await this.checkpoint.getAtProbablyRecentBlock(await web3.eth.getBlockNumber() - 1)) - .to.be.bignumber.equal('0'); + expect(await getAtBlock(this.mock, await web3.eth.getBlockNumber() - 1)).to.be.bignumber.equal('0'); + expect(await getAtRecentBlock(this.mock, await web3.eth.getBlockNumber() - 1)).to.be.bignumber.equal('0'); }); }); describe('with checkpoints', function () { beforeEach('pushing checkpoints', async function () { - this.tx1 = await this.checkpoint.push(1); - this.tx2 = await this.checkpoint.push(2); + this.tx1 = await push(this.mock, 1); + this.tx2 = await push(this.mock, 2); await time.advanceBlock(); - this.tx3 = await this.checkpoint.push(3); + this.tx3 = await push(this.mock, 3); await time.advanceBlock(); await time.advanceBlock(); }); it('returns latest value', async function () { - expect(await this.checkpoint.latest()).to.be.bignumber.equal('3'); + expect(await latest(this.mock)).to.be.bignumber.equal('3'); - const ckpt = await this.checkpoint.latestCheckpoint(); + const ckpt = await latestCheckpoint(this.mock); expect(ckpt[0]).to.be.equal(true); expect(ckpt[1]).to.be.bignumber.equal(web3.utils.toBN(this.tx3.receipt.blockNumber)); expect(ckpt[2]).to.be.bignumber.equal(web3.utils.toBN('3')); }); - for (const fn of [ 'getAtBlock(uint256)', 'getAtProbablyRecentBlock(uint256)' ]) { - describe(`lookup: ${fn}`, function () { + for (const getAtBlockVariant of [ getAtBlock, getAtRecentBlock ]) { + describe(`lookup: ${getAtBlockVariant}`, function () { it('returns past values', async function () { - expect(await this.checkpoint.methods[fn](this.tx1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.checkpoint.methods[fn](this.tx1.receipt.blockNumber)).to.be.bignumber.equal('1'); - expect(await this.checkpoint.methods[fn](this.tx2.receipt.blockNumber)).to.be.bignumber.equal('2'); + expect(await getAtBlockVariant(this.mock, this.tx1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); + expect(await getAtBlockVariant(this.mock, this.tx1.receipt.blockNumber)).to.be.bignumber.equal('1'); + expect(await getAtBlockVariant(this.mock, this.tx2.receipt.blockNumber)).to.be.bignumber.equal('2'); // Block with no new checkpoints - expect(await this.checkpoint.methods[fn](this.tx2.receipt.blockNumber + 1)).to.be.bignumber.equal('2'); - expect(await this.checkpoint.methods[fn](this.tx3.receipt.blockNumber)).to.be.bignumber.equal('3'); - expect(await this.checkpoint.methods[fn](this.tx3.receipt.blockNumber + 1)).to.be.bignumber.equal('3'); + expect(await getAtBlockVariant(this.mock, this.tx2.receipt.blockNumber + 1)).to.be.bignumber.equal('2'); + expect(await getAtBlockVariant(this.mock, this.tx3.receipt.blockNumber)).to.be.bignumber.equal('3'); + expect(await getAtBlockVariant(this.mock, this.tx3.receipt.blockNumber + 1)).to.be.bignumber.equal('3'); }); it('reverts if block number >= current block', async function () { await expectRevert( - this.checkpoint.methods[fn](await web3.eth.getBlockNumber()), + getAtBlockVariant(this.mock, await web3.eth.getBlockNumber()), 'Checkpoints: block not yet mined', ); await expectRevert( - this.checkpoint.methods[fn](await web3.eth.getBlockNumber() + 1), + getAtBlockVariant(this.mock, await web3.eth.getBlockNumber() + 1), 'Checkpoints: block not yet mined', ); }); @@ -79,51 +90,60 @@ contract('Checkpoints', function () { } it('multiple checkpoints in the same block', async function () { - const lengthBefore = await this.checkpoint.length(); + const lengthBefore = await getLength(this.mock); await batchInBlock([ - () => this.checkpoint.push(8, { gas: 100000 }), - () => this.checkpoint.push(9, { gas: 100000 }), - () => this.checkpoint.push(10, { gas: 100000 }), + () => push(this.mock, 8, { gas: 100000 }), + () => push(this.mock, 9, { gas: 100000 }), + () => push(this.mock, 10, { gas: 100000 }), ]); - expect(await this.checkpoint.length()).to.be.bignumber.equal(lengthBefore.addn(1)); - expect(await this.checkpoint.latest()).to.be.bignumber.equal('10'); + expect(await getLength(this.mock)).to.be.bignumber.equal(lengthBefore.addn(1)); + expect(await latest(this.mock)).to.be.bignumber.equal('10'); }); it('more than 5 checkpoints', async function () { for (let i = 4; i <= 6; i++) { - await this.checkpoint.push(i); + await push(this.mock, i); } - expect(await this.checkpoint.length()).to.be.bignumber.equal('6'); + expect(await getLength(this.mock)).to.be.bignumber.equal('6'); const block = await web3.eth.getBlockNumber(); // recent - expect(await this.checkpoint.getAtProbablyRecentBlock(block - 1)).to.be.bignumber.equal('5'); + expect(await getAtRecentBlock(this.mock, block - 1)).to.be.bignumber.equal('5'); // non-recent - expect(await this.checkpoint.getAtProbablyRecentBlock(block - 9)).to.be.bignumber.equal('0'); + expect(await getAtRecentBlock(this.mock, block - 9)).to.be.bignumber.equal('0'); }); }); }); for (const length of [160, 224]) { describe(`Trace${length}`, function () { - beforeEach(async function () { - this.contract = await artifacts.require(`Checkpoints${length}Mock`).new(); - }); + const latest = (self, ...args) => + self.methods[`$latest_Checkpoints_Trace${length}(uint256)`](0, ...args); + const latestCheckpoint = (self, ...args) => + self.methods[`$latestCheckpoint_Checkpoints_Trace${length}(uint256)`](0, ...args); + const push = (self, ...args) => + self.methods[`$push(uint256,uint${256 - length},uint${length})`](0, ...args); + const upperLookup = (self, ...args) => + self.methods[`$upperLookup(uint256,uint${256 - length})`](0, ...args); + const lowerLookup = (self, ...args) => + self.methods[`$lowerLookup(uint256,uint${256 - length})`](0, ...args); + const getLength = (self, ...args) => + self.methods[`$length_Checkpoints_Trace${length}(uint256)`](0, ...args); describe('without checkpoints', function () { it('returns zero as latest value', async function () { - expect(await this.contract.latest()).to.be.bignumber.equal('0'); + expect(await latest(this.mock)).to.be.bignumber.equal('0'); - const ckpt = await this.contract.latestCheckpoint(); + const ckpt = await latestCheckpoint(this.mock); expect(ckpt[0]).to.be.equal(false); expect(ckpt[1]).to.be.bignumber.equal('0'); expect(ckpt[2]).to.be.bignumber.equal('0'); }); it('lookup returns 0', async function () { - expect(await this.contract.lowerLookup(0)).to.be.bignumber.equal('0'); - expect(await this.contract.upperLookup(0)).to.be.bignumber.equal('0'); + expect(await lowerLookup(this.mock, 0)).to.be.bignumber.equal('0'); + expect(await upperLookup(this.mock, 0)).to.be.bignumber.equal('0'); }); }); @@ -137,42 +157,47 @@ contract('Checkpoints', function () { { key: '11', value: '99' }, ]; for (const { key, value } of this.checkpoints) { - await this.contract.push(key, value); + await push(this.mock, key, value); } }); - it('returns latest value', async function () { - expect(await this.contract.latest()).to.be.bignumber.equal(last(this.checkpoints).value); + it('length', async function () { + expect(await getLength(this.mock)) + .to.be.bignumber.equal(this.checkpoints.length.toString()); + }); - const ckpt = await this.contract.latestCheckpoint(); + it('returns latest value', async function () { + expect(await latest(this.mock)).to.be.bignumber.equal(last(this.checkpoints).value); + + const ckpt = await latestCheckpoint(this.mock); expect(ckpt[0]).to.be.equal(true); expect(ckpt[1]).to.be.bignumber.equal(last(this.checkpoints).key); expect(ckpt[2]).to.be.bignumber.equal(last(this.checkpoints).value); }); it('cannot push values in the past', async function () { - await expectRevert(this.contract.push(last(this.checkpoints).key - 1, '0'), 'Checkpoint: decreasing keys'); + await expectRevert(push(this.mock, last(this.checkpoints).key - 1, '0'), 'Checkpoint: decreasing keys'); }); it('can update last value', async function () { const newValue = '42'; // check length before the update - expect(await this.contract.length()).to.be.bignumber.equal(this.checkpoints.length.toString()); + expect(await getLength(this.mock)).to.be.bignumber.equal(this.checkpoints.length.toString()); // update last key - await this.contract.push(last(this.checkpoints).key, newValue); - expect(await this.contract.latest()).to.be.bignumber.equal(newValue); + await push(this.mock, last(this.checkpoints).key, newValue); + expect(await latest(this.mock)).to.be.bignumber.equal(newValue); // check that length did not change - expect(await this.contract.length()).to.be.bignumber.equal(this.checkpoints.length.toString()); + expect(await getLength(this.mock)).to.be.bignumber.equal(this.checkpoints.length.toString()); }); it('lower lookup', async function () { for (let i = 0; i < 14; ++i) { const value = first(this.checkpoints.filter(x => i <= x.key))?.value || '0'; - expect(await this.contract.lowerLookup(i)).to.be.bignumber.equal(value); + expect(await lowerLookup(this.mock, i)).to.be.bignumber.equal(value); } }); @@ -180,7 +205,7 @@ contract('Checkpoints', function () { for (let i = 0; i < 14; ++i) { const value = last(this.checkpoints.filter(x => i >= x.key))?.value || '0'; - expect(await this.contract.upperLookup(i)).to.be.bignumber.equal(value); + expect(await upperLookup(this.mock, i)).to.be.bignumber.equal(value); } }); }); diff --git a/test/utils/Counters.test.js b/test/utils/Counters.test.js index 2159fd08d..6fb89922d 100644 --- a/test/utils/Counters.test.js +++ b/test/utils/Counters.test.js @@ -2,62 +2,62 @@ const { expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const CountersImpl = artifacts.require('CountersImpl'); +const Counters = artifacts.require('$Counters'); contract('Counters', function () { beforeEach(async function () { - this.counter = await CountersImpl.new(); + this.counter = await Counters.new(); }); it('starts at zero', async function () { - expect(await this.counter.current()).to.be.bignumber.equal('0'); + expect(await this.counter.$current(0)).to.be.bignumber.equal('0'); }); describe('increment', function () { context('starting from 0', function () { it('increments the current value by one', async function () { - await this.counter.increment(); - expect(await this.counter.current()).to.be.bignumber.equal('1'); + await this.counter.$increment(0); + expect(await this.counter.$current(0)).to.be.bignumber.equal('1'); }); it('can be called multiple times', async function () { - await this.counter.increment(); - await this.counter.increment(); - await this.counter.increment(); + await this.counter.$increment(0); + await this.counter.$increment(0); + await this.counter.$increment(0); - expect(await this.counter.current()).to.be.bignumber.equal('3'); + expect(await this.counter.$current(0)).to.be.bignumber.equal('3'); }); }); }); describe('decrement', function () { beforeEach(async function () { - await this.counter.increment(); - expect(await this.counter.current()).to.be.bignumber.equal('1'); + await this.counter.$increment(0); + expect(await this.counter.$current(0)).to.be.bignumber.equal('1'); }); context('starting from 1', function () { it('decrements the current value by one', async function () { - await this.counter.decrement(); - expect(await this.counter.current()).to.be.bignumber.equal('0'); + await this.counter.$decrement(0); + expect(await this.counter.$current(0)).to.be.bignumber.equal('0'); }); it('reverts if the current value is 0', async function () { - await this.counter.decrement(); - await expectRevert(this.counter.decrement(), 'Counter: decrement overflow'); + await this.counter.$decrement(0); + await expectRevert(this.counter.$decrement(0), 'Counter: decrement overflow'); }); }); context('after incremented to 3', function () { it('can be called multiple times', async function () { - await this.counter.increment(); - await this.counter.increment(); + await this.counter.$increment(0); + await this.counter.$increment(0); - expect(await this.counter.current()).to.be.bignumber.equal('3'); + expect(await this.counter.$current(0)).to.be.bignumber.equal('3'); - await this.counter.decrement(); - await this.counter.decrement(); - await this.counter.decrement(); + await this.counter.$decrement(0); + await this.counter.$decrement(0); + await this.counter.$decrement(0); - expect(await this.counter.current()).to.be.bignumber.equal('0'); + expect(await this.counter.$current(0)).to.be.bignumber.equal('0'); }); }); }); @@ -65,19 +65,19 @@ contract('Counters', function () { describe('reset', function () { context('null counter', function () { it('does not throw', async function () { - await this.counter.reset(); - expect(await this.counter.current()).to.be.bignumber.equal('0'); + await this.counter.$reset(0); + expect(await this.counter.$current(0)).to.be.bignumber.equal('0'); }); }); context('non null counter', function () { beforeEach(async function () { - await this.counter.increment(); - expect(await this.counter.current()).to.be.bignumber.equal('1'); + await this.counter.$increment(0); + expect(await this.counter.$current(0)).to.be.bignumber.equal('1'); }); it('reset to 0', async function () { - await this.counter.reset(); - expect(await this.counter.current()).to.be.bignumber.equal('0'); + await this.counter.$reset(0); + expect(await this.counter.$current(0)).to.be.bignumber.equal('0'); }); }); }); diff --git a/test/utils/Create2.test.js b/test/utils/Create2.test.js index b57e06366..121630265 100644 --- a/test/utils/Create2.test.js +++ b/test/utils/Create2.test.js @@ -1,39 +1,39 @@ -const { balance, BN, ether, expectRevert, send } = require('@openzeppelin/test-helpers'); +const { balance, ether, expectEvent, expectRevert, send } = require('@openzeppelin/test-helpers'); const { computeCreate2Address } = require('../helpers/create2'); const { expect } = require('chai'); -const Create2Impl = artifacts.require('Create2Impl'); -const ERC20Mock = artifacts.require('ERC20Mock'); -const ERC1820Implementer = artifacts.require('ERC1820Implementer'); +const Create2 = artifacts.require('$Create2'); +const VestingWallet = artifacts.require('VestingWallet'); +const ERC1820Implementer = artifacts.require('$ERC1820Implementer'); contract('Create2', function (accounts) { - const [deployerAccount] = accounts; + const [ deployerAccount, other ] = accounts; const salt = 'salt message'; const saltHex = web3.utils.soliditySha3(salt); const encodedParams = web3.eth.abi.encodeParameters( - ['string', 'string', 'address', 'uint256'], - ['MyToken', 'MTKN', deployerAccount, 100], + [ 'address', 'uint64', 'uint64' ], + [ other, 0, 0 ], ).slice(2); - const constructorByteCode = `${ERC20Mock.bytecode}${encodedParams}`; + const constructorByteCode = `${VestingWallet.bytecode}${encodedParams}`; beforeEach(async function () { - this.factory = await Create2Impl.new(); + this.factory = await Create2.new(); }); describe('computeAddress', function () { it('computes the correct contract address', async function () { - const onChainComputed = await this.factory - .computeAddress(saltHex, web3.utils.keccak256(constructorByteCode)); + const onChainComputed = + await this.factory.$computeAddress(saltHex, web3.utils.keccak256(constructorByteCode)); const offChainComputed = computeCreate2Address(saltHex, constructorByteCode, this.factory.address); expect(onChainComputed).to.equal(offChainComputed); }); it('computes the correct contract address with deployer', async function () { - const onChainComputed = await this.factory - .computeAddressWithDeployer(saltHex, web3.utils.keccak256(constructorByteCode), deployerAccount); + const onChainComputed = + await this.factory.$computeAddress(saltHex, web3.utils.keccak256(constructorByteCode), deployerAccount); const offChainComputed = computeCreate2Address(saltHex, constructorByteCode, deployerAccount); expect(onChainComputed).to.equal(offChainComputed); @@ -42,19 +42,27 @@ contract('Create2', function (accounts) { describe('deploy', function () { it('deploys a ERC1820Implementer from inline assembly code', async function () { - const offChainComputed = - computeCreate2Address(saltHex, ERC1820Implementer.bytecode, this.factory.address); - await this.factory.deployERC1820Implementer(0, saltHex); + const offChainComputed = computeCreate2Address(saltHex, ERC1820Implementer.bytecode, this.factory.address); + + expectEvent( + await this.factory.$deploy(0, saltHex, ERC1820Implementer.bytecode), + 'return$deploy', + { addr: offChainComputed }, + ); + expect(ERC1820Implementer.bytecode).to.include((await web3.eth.getCode(offChainComputed)).slice(2)); }); - it('deploys a ERC20Mock with correct balances', async function () { + it('deploys a contract with constructor arguments', async function () { const offChainComputed = computeCreate2Address(saltHex, constructorByteCode, this.factory.address); - await this.factory.deploy(0, saltHex, constructorByteCode); + expectEvent( + await this.factory.$deploy(0, saltHex, constructorByteCode), + 'return$deploy', + { addr: offChainComputed }, + ); - const erc20 = await ERC20Mock.at(offChainComputed); - expect(await erc20.balanceOf(deployerAccount)).to.be.bignumber.equal(new BN(100)); + expect(await VestingWallet.at(offChainComputed).then(instance => instance.beneficiary())).to.be.equal(other); }); it('deploys a contract with funds deposited in the factory', async function () { @@ -62,29 +70,39 @@ contract('Create2', function (accounts) { await send.ether(deployerAccount, this.factory.address, deposit); expect(await balance.current(this.factory.address)).to.be.bignumber.equal(deposit); - const onChainComputed = await this.factory - .computeAddressWithDeployer(saltHex, web3.utils.keccak256(constructorByteCode), this.factory.address); + const offChainComputed = computeCreate2Address(saltHex, constructorByteCode, this.factory.address); - await this.factory.deploy(deposit, saltHex, constructorByteCode); - expect(await balance.current(onChainComputed)).to.be.bignumber.equal(deposit); + expectEvent( + await this.factory.$deploy(deposit, saltHex, constructorByteCode), + 'return$deploy', + { addr: offChainComputed }, + ); + + expect(await balance.current(offChainComputed)).to.be.bignumber.equal(deposit); }); it('fails deploying a contract in an existent address', async function () { - await this.factory.deploy(0, saltHex, constructorByteCode, { from: deployerAccount }); + expectEvent( + await this.factory.$deploy(0, saltHex, constructorByteCode), + 'return$deploy', + ); + await expectRevert( - this.factory.deploy(0, saltHex, constructorByteCode, { from: deployerAccount }), 'Create2: Failed on deploy', + this.factory.$deploy(0, saltHex, constructorByteCode), + 'Create2: Failed on deploy', ); }); it('fails deploying a contract if the bytecode length is zero', async function () { await expectRevert( - this.factory.deploy(0, saltHex, '0x', { from: deployerAccount }), 'Create2: bytecode length is zero', + this.factory.$deploy(0, saltHex, '0x'), + 'Create2: bytecode length is zero', ); }); it('fails deploying a contract if factory contract does not have sufficient balance', async function () { await expectRevert( - this.factory.deploy(1, saltHex, constructorByteCode, { from: deployerAccount }), + this.factory.$deploy(1, saltHex, constructorByteCode), 'Create2: insufficient balance', ); }); diff --git a/test/utils/Multicall.test.js b/test/utils/Multicall.test.js index 61c26344c..95cdddc92 100644 --- a/test/utils/Multicall.test.js +++ b/test/utils/Multicall.test.js @@ -1,12 +1,14 @@ const { BN, expectRevert } = require('@openzeppelin/test-helpers'); -const MulticallTokenMock = artifacts.require('MulticallTokenMock'); -contract('MulticallToken', function (accounts) { - const [deployer, alice, bob] = accounts; +const ERC20MulticallMock = artifacts.require('$ERC20MulticallMock'); + +contract('Multicall', function (accounts) { + const [ deployer, alice, bob ] = accounts; const amount = 12000; beforeEach(async function () { - this.multicallToken = await MulticallTokenMock.new(new BN(amount), { from: deployer }); + this.multicallToken = await ERC20MulticallMock.new('name', 'symbol'); + await this.multicallToken.$_mint(deployer, amount); }); it('batches function calls', async function () { diff --git a/test/utils/Strings.test.js b/test/utils/Strings.test.js index 6d8e3aa3c..11f3e7270 100644 --- a/test/utils/Strings.test.js +++ b/test/utils/Strings.test.js @@ -2,11 +2,11 @@ const { BN, constants, expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const StringsMock = artifacts.require('StringsMock'); +const Strings = artifacts.require('$Strings'); contract('Strings', function () { before(async function () { - this.strings = await StringsMock.new(); + this.strings = await Strings.new(); }); describe('toString', function () { @@ -34,12 +34,12 @@ contract('Strings', function () { describe('uint256', function () { it('converts MAX_UINT256', async function () { const value = constants.MAX_UINT256; - expect(await this.strings.methods['toString(uint256)'](value)).to.equal(value.toString(10)); + expect(await this.strings.methods['$toString(uint256)'](value)).to.equal(value.toString(10)); }); for (const value of values) { it(`converts ${value}`, async function () { - expect(await this.strings.methods['toString(uint256)'](value)).to.equal(value); + expect(await this.strings.methods['$toString(uint256)'](value)).to.equal(value); }); } }); @@ -47,22 +47,22 @@ contract('Strings', function () { describe('int256', function () { it('converts MAX_INT256', async function () { const value = constants.MAX_INT256; - expect(await this.strings.methods['toString(int256)'](value)).to.equal(value.toString(10)); + expect(await this.strings.methods['$toString(int256)'](value)).to.equal(value.toString(10)); }); it('converts MIN_INT256', async function () { const value = constants.MIN_INT256; - expect(await this.strings.methods['toString(int256)'](value)).to.equal(value.toString(10)); + expect(await this.strings.methods['$toString(int256)'](value)).to.equal(value.toString(10)); }); for (const value of values) { it(`convert ${value}`, async function () { - expect(await this.strings.methods['toString(int256)'](value)).to.equal(value); + expect(await this.strings.methods['$toString(int256)'](value)).to.equal(value); }); it(`convert negative ${value}`, async function () { const negated = new BN(value).neg(); - expect(await this.strings.methods['toString(int256)'](negated)).to.equal(negated.toString(10)); + expect(await this.strings.methods['$toString(int256)'](negated)).to.equal(negated.toString(10)); }); } }); @@ -70,34 +70,34 @@ contract('Strings', function () { describe('toHexString', function () { it('converts 0', async function () { - expect(await this.strings.methods['toHexString(uint256)'](0)).to.equal('0x00'); + expect(await this.strings.methods['$toHexString(uint256)'](0)).to.equal('0x00'); }); it('converts a positive number', async function () { - expect(await this.strings.methods['toHexString(uint256)'](0x4132)).to.equal('0x4132'); + expect(await this.strings.methods['$toHexString(uint256)'](0x4132)).to.equal('0x4132'); }); it('converts MAX_UINT256', async function () { - expect(await this.strings.methods['toHexString(uint256)'](constants.MAX_UINT256)) + expect(await this.strings.methods['$toHexString(uint256)'](constants.MAX_UINT256)) .to.equal(web3.utils.toHex(constants.MAX_UINT256)); }); }); describe('toHexString fixed', function () { it('converts a positive number (long)', async function () { - expect(await this.strings.methods['toHexString(uint256,uint256)'](0x4132, 32)) + expect(await this.strings.methods['$toHexString(uint256,uint256)'](0x4132, 32)) .to.equal('0x0000000000000000000000000000000000000000000000000000000000004132'); }); it('converts a positive number (short)', async function () { await expectRevert( - this.strings.methods['toHexString(uint256,uint256)'](0x4132, 1), + this.strings.methods['$toHexString(uint256,uint256)'](0x4132, 1), 'Strings: hex length insufficient', ); }); it('converts MAX_UINT256', async function () { - expect(await this.strings.methods['toHexString(uint256,uint256)'](constants.MAX_UINT256, 32)) + expect(await this.strings.methods['$toHexString(uint256,uint256)'](constants.MAX_UINT256, 32)) .to.equal(web3.utils.toHex(constants.MAX_UINT256)); }); }); @@ -105,43 +105,43 @@ contract('Strings', function () { describe('toHexString address', function () { it('converts a random address', async function () { const addr = '0xa9036907dccae6a1e0033479b12e837e5cf5a02f'; - expect(await this.strings.methods['toHexString(address)'](addr)).to.equal(addr); + expect(await this.strings.methods['$toHexString(address)'](addr)).to.equal(addr); }); it('converts an address with leading zeros', async function () { const addr = '0x0000e0ca771e21bd00057f54a68c30d400000000'; - expect(await this.strings.methods['toHexString(address)'](addr)).to.equal(addr); + expect(await this.strings.methods['$toHexString(address)'](addr)).to.equal(addr); }); }); describe('equal', function () { it('compares two empty strings', async function () { - expect(await this.strings.methods['equal(string,string)']('', '')).to.equal(true); + expect(await this.strings.methods['$equal(string,string)']('', '')).to.equal(true); }); it('compares two equal strings', async function () { - expect(await this.strings.methods['equal(string,string)']('a', 'a')).to.equal(true); + expect(await this.strings.methods['$equal(string,string)']('a', 'a')).to.equal(true); }); it('compares two different strings', async function () { - expect(await this.strings.methods['equal(string,string)']('a', 'b')).to.equal(false); + expect(await this.strings.methods['$equal(string,string)']('a', 'b')).to.equal(false); }); it('compares two different strings of different lengths', async function () { - expect(await this.strings.methods['equal(string,string)']('a', 'aa')).to.equal(false); - expect(await this.strings.methods['equal(string,string)']('aa', 'a')).to.equal(false); + expect(await this.strings.methods['$equal(string,string)']('a', 'aa')).to.equal(false); + expect(await this.strings.methods['$equal(string,string)']('aa', 'a')).to.equal(false); }); it('compares two different large strings', async function () { const str1 = 'a'.repeat(201); const str2 = 'a'.repeat(200) + 'b'; - expect(await this.strings.methods['equal(string,string)'](str1, str2)).to.equal(false); + expect(await this.strings.methods['$equal(string,string)'](str1, str2)).to.equal(false); }); it('compares two equal large strings', async function () { const str1 = 'a'.repeat(201); const str2 = 'a'.repeat(201); - expect(await this.strings.methods['equal(string,string)'](str1, str2)).to.equal(true); + expect(await this.strings.methods['$equal(string,string)'](str1, str2)).to.equal(true); }); }); }); diff --git a/test/utils/cryptography/ECDSA.test.js b/test/utils/cryptography/ECDSA.test.js index 04374c4fe..fc3df0db4 100644 --- a/test/utils/cryptography/ECDSA.test.js +++ b/test/utils/cryptography/ECDSA.test.js @@ -3,7 +3,7 @@ const { toEthSignedMessageHash } = require('../../helpers/sign'); const { expect } = require('chai'); -const ECDSAMock = artifacts.require('ECDSAMock'); +const ECDSA = artifacts.require('$ECDSA'); const TEST_MESSAGE = web3.utils.sha3('OpenZeppelin'); const WRONG_MESSAGE = web3.utils.sha3('Nope'); @@ -45,18 +45,18 @@ contract('ECDSA', function (accounts) { const [ other ] = accounts; beforeEach(async function () { - this.ecdsa = await ECDSAMock.new(); + this.ecdsa = await ECDSA.new(); }); context('recover with invalid signature', function () { it('with short signature', async function () { - await expectRevert(this.ecdsa.recover(TEST_MESSAGE, '0x1234'), 'ECDSA: invalid signature length'); + await expectRevert(this.ecdsa.$recover(TEST_MESSAGE, '0x1234'), 'ECDSA: invalid signature length'); }); it('with long signature', async function () { await expectRevert( // eslint-disable-next-line max-len - this.ecdsa.recover(TEST_MESSAGE, '0x01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'), + this.ecdsa.$recover(TEST_MESSAGE, '0x01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'), 'ECDSA: invalid signature length', ); }); @@ -69,7 +69,7 @@ contract('ECDSA', function (accounts) { const signature = await web3.eth.sign(TEST_MESSAGE, other); // Recover the signer address from the generated message and signature. - expect(await this.ecdsa.recover( + expect(await this.ecdsa.$recover( toEthSignedMessageHash(TEST_MESSAGE), signature, )).to.equal(other); @@ -80,7 +80,7 @@ contract('ECDSA', function (accounts) { const signature = await web3.eth.sign(NON_HASH_MESSAGE, other); // Recover the signer address from the generated message and signature. - expect(await this.ecdsa.recover( + expect(await this.ecdsa.$recover( toEthSignedMessageHash(NON_HASH_MESSAGE), signature, )).to.equal(other); @@ -88,13 +88,13 @@ contract('ECDSA', function (accounts) { it('returns a different address', async function () { const signature = await web3.eth.sign(TEST_MESSAGE, other); - expect(await this.ecdsa.recover(WRONG_MESSAGE, signature)).to.not.equal(other); + expect(await this.ecdsa.$recover(WRONG_MESSAGE, signature)).to.not.equal(other); }); it('reverts with invalid signature', async function () { // eslint-disable-next-line max-len const signature = '0x332ce75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e01c'; - await expectRevert(this.ecdsa.recover(TEST_MESSAGE, signature), 'ECDSA: invalid signature'); + await expectRevert(this.ecdsa.$recover(TEST_MESSAGE, signature), 'ECDSA: invalid signature'); }); }); @@ -107,24 +107,53 @@ contract('ECDSA', function (accounts) { it('works with correct v value', async function () { const v = '1b'; // 27 = 1b. const signature = signatureWithoutV + v; - expect(await this.ecdsa.recover(TEST_MESSAGE, signature)).to.equal(signer); - expect(await this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature))).to.equal(signer); - expect(await this.ecdsa.recover_r_vs(TEST_MESSAGE, ...split(to2098Format(signature)))).to.equal(signer); + expect(await this.ecdsa.$recover( + TEST_MESSAGE, + signature, + )).to.equal(signer); + + expect(await this.ecdsa.methods['$recover(bytes32,uint8,bytes32,bytes32)']( + TEST_MESSAGE, + ...split(signature), + )).to.equal(signer); + + expect(await this.ecdsa.methods['$recover(bytes32,bytes32,bytes32)']( + TEST_MESSAGE, + ...split(to2098Format(signature)), + )).to.equal(signer); }); it('rejects incorrect v value', async function () { const v = '1c'; // 28 = 1c. const signature = signatureWithoutV + v; - expect(await this.ecdsa.recover(TEST_MESSAGE, signature)).to.not.equal(signer); - expect(await this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature))).to.not.equal(signer); - expect(await this.ecdsa.recover_r_vs(TEST_MESSAGE, ...split(to2098Format(signature)))).to.not.equal(signer); + expect(await this.ecdsa.$recover( + TEST_MESSAGE, + signature, + )).to.not.equal(signer); + + expect(await this.ecdsa.methods['$recover(bytes32,uint8,bytes32,bytes32)']( + TEST_MESSAGE, + ...split(signature), + )).to.not.equal(signer); + + expect(await this.ecdsa.methods['$recover(bytes32,bytes32,bytes32)']( + TEST_MESSAGE, + ...split(to2098Format(signature)), + )).to.not.equal(signer); }); it('reverts wrong v values', async function () { for (const v of ['00', '01']) { const signature = signatureWithoutV + v; - await expectRevert(this.ecdsa.recover(TEST_MESSAGE, signature), 'ECDSA: invalid signature'); - await expectRevert(this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature)), 'ECDSA: invalid signature'); + await expectRevert( + this.ecdsa.$recover(TEST_MESSAGE, signature), + 'ECDSA: invalid signature', + ); + + await expectRevert( + this.ecdsa.methods['$recover(bytes32,uint8,bytes32,bytes32)'](TEST_MESSAGE, ...split(signature)), + 'ECDSA: invalid signature', + ); } }); @@ -132,7 +161,7 @@ contract('ECDSA', function (accounts) { const v = '1b'; // 27 = 1b. const signature = signatureWithoutV + v; await expectRevert( - this.ecdsa.recover(TEST_MESSAGE, to2098Format(signature)), + this.ecdsa.$recover(TEST_MESSAGE, to2098Format(signature)), 'ECDSA: invalid signature length', ); }); @@ -146,24 +175,53 @@ contract('ECDSA', function (accounts) { it('works with correct v value', async function () { const v = '1c'; // 28 = 1c. const signature = signatureWithoutV + v; - expect(await this.ecdsa.recover(TEST_MESSAGE, signature)).to.equal(signer); - expect(await this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature))).to.equal(signer); - expect(await this.ecdsa.recover_r_vs(TEST_MESSAGE, ...split(to2098Format(signature)))).to.equal(signer); + expect(await this.ecdsa.$recover( + TEST_MESSAGE, + signature, + )).to.equal(signer); + + expect(await this.ecdsa.methods['$recover(bytes32,uint8,bytes32,bytes32)']( + TEST_MESSAGE, + ...split(signature), + )).to.equal(signer); + + expect(await this.ecdsa.methods['$recover(bytes32,bytes32,bytes32)']( + TEST_MESSAGE, + ...split(to2098Format(signature)), + )).to.equal(signer); }); it('rejects incorrect v value', async function () { const v = '1b'; // 27 = 1b. const signature = signatureWithoutV + v; - expect(await this.ecdsa.recover(TEST_MESSAGE, signature)).to.not.equal(signer); - expect(await this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature))).to.not.equal(signer); - expect(await this.ecdsa.recover_r_vs(TEST_MESSAGE, ...split(to2098Format(signature)))).to.not.equal(signer); + expect(await this.ecdsa.$recover( + TEST_MESSAGE, + signature, + )).to.not.equal(signer); + + expect(await this.ecdsa.methods['$recover(bytes32,uint8,bytes32,bytes32)']( + TEST_MESSAGE, + ...split(signature), + )).to.not.equal(signer); + + expect(await this.ecdsa.methods['$recover(bytes32,bytes32,bytes32)']( + TEST_MESSAGE, + ...split(to2098Format(signature)), + )).to.not.equal(signer); }); it('reverts invalid v values', async function () { for (const v of ['00', '01']) { const signature = signatureWithoutV + v; - await expectRevert(this.ecdsa.recover(TEST_MESSAGE, signature), 'ECDSA: invalid signature'); - await expectRevert(this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(signature)), 'ECDSA: invalid signature'); + await expectRevert( + this.ecdsa.$recover(TEST_MESSAGE, signature), + 'ECDSA: invalid signature', + ); + + await expectRevert( + this.ecdsa.methods['$recover(bytes32,uint8,bytes32,bytes32)'](TEST_MESSAGE, ...split(signature)), + 'ECDSA: invalid signature', + ); } }); @@ -171,7 +229,7 @@ contract('ECDSA', function (accounts) { const v = '1c'; // 27 = 1b. const signature = signatureWithoutV + v; await expectRevert( - this.ecdsa.recover(TEST_MESSAGE, to2098Format(signature)), + this.ecdsa.$recover(TEST_MESSAGE, to2098Format(signature)), 'ECDSA: invalid signature length', ); }); @@ -181,9 +239,9 @@ contract('ECDSA', function (accounts) { const message = '0xb94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'; // eslint-disable-next-line max-len const highSSignature = '0xe742ff452d41413616a5bf43fe15dd88294e983d3d36206c2712f39083d638bde0a0fc89be718fbc1033e1d30d78be1c68081562ed2e97af876f286f3453231d1b'; - await expectRevert(this.ecdsa.recover(message, highSSignature), 'ECDSA: invalid signature \'s\' value'); + await expectRevert(this.ecdsa.$recover(message, highSSignature), 'ECDSA: invalid signature \'s\' value'); await expectRevert( - this.ecdsa.recover_v_r_s(TEST_MESSAGE, ...split(highSSignature)), + this.ecdsa.methods['$recover(bytes32,uint8,bytes32,bytes32)'](TEST_MESSAGE, ...split(highSSignature)), 'ECDSA: invalid signature \'s\' value', ); expect(() => to2098Format(highSSignature)).to.throw('invalid signature \'s\' value'); @@ -192,12 +250,12 @@ contract('ECDSA', function (accounts) { context('toEthSignedMessageHash', function () { it('prefixes bytes32 data correctly', async function () { - expect(await this.ecdsa.methods['toEthSignedMessageHash(bytes32)'](TEST_MESSAGE)) + expect(await this.ecdsa.methods['$toEthSignedMessageHash(bytes32)'](TEST_MESSAGE)) .to.equal(toEthSignedMessageHash(TEST_MESSAGE)); }); it('prefixes dynamic length data correctly', async function () { - expect(await this.ecdsa.methods['toEthSignedMessageHash(bytes)'](NON_HASH_MESSAGE)) + expect(await this.ecdsa.methods['$toEthSignedMessageHash(bytes)'](NON_HASH_MESSAGE)) .to.equal(toEthSignedMessageHash(NON_HASH_MESSAGE)); }); }); diff --git a/test/utils/cryptography/EIP712.test.js b/test/utils/cryptography/EIP712.test.js index 9e26a87c6..8c20b91ba 100644 --- a/test/utils/cryptography/EIP712.test.js +++ b/test/utils/cryptography/EIP712.test.js @@ -1,9 +1,10 @@ const ethSigUtil = require('eth-sig-util'); const Wallet = require('ethereumjs-wallet').default; -const { EIP712Domain, domainSeparator } = require('../../helpers/eip712'); +const { EIP712Domain, domainSeparator, hashTypedData } = require('../../helpers/eip712'); +const { getChainId } = require('../../helpers/chainid'); -const EIP712 = artifacts.require('EIP712External'); +const EIP712Verifier = artifacts.require('$EIP712Verifier'); contract('EIP712', function (accounts) { const [mailTo] = accounts; @@ -12,25 +13,30 @@ contract('EIP712', function (accounts) { const version = '1'; beforeEach('deploying', async function () { - this.eip712 = await EIP712.new(name, version); + this.eip712 = await EIP712Verifier.new(name, version); - // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id - // from within the EVM as from the JSON RPC interface. - // See https://github.com/trufflesuite/ganache-core/issues/515 - this.chainId = await this.eip712.getChainId(); + this.domain = { + name, + version, + chainId: await getChainId(), + verifyingContract: this.eip712.address, + }; }); it('domain separator', async function () { - expect( - await this.eip712.domainSeparator(), - ).to.equal( - await domainSeparator(name, version, this.chainId, this.eip712.address), - ); + const expected = await domainSeparator(this.domain); + + expect(await this.eip712.$_domainSeparatorV4()).to.equal(expected); + }); + + it('hash digest', async function () { + const structhash = web3.utils.randomHex(32); + const expected = await hashTypedData(this.domain, structhash); + + expect(await this.eip712.$_hashTypedDataV4(structhash)).to.be.equal(expected); }); it('digest', async function () { - const chainId = this.chainId; - const verifyingContract = this.eip712.address; const message = { to: mailTo, contents: 'very interesting', @@ -44,7 +50,7 @@ contract('EIP712', function (accounts) { { name: 'contents', type: 'string' }, ], }, - domain: { name, version, chainId, verifyingContract }, + domain: this.domain, primaryType: 'Mail', message, }; diff --git a/test/utils/cryptography/MerkleProof.test.js b/test/utils/cryptography/MerkleProof.test.js index 7af3d38d7..70271eea1 100644 --- a/test/utils/cryptography/MerkleProof.test.js +++ b/test/utils/cryptography/MerkleProof.test.js @@ -6,11 +6,11 @@ const keccak256 = require('keccak256'); const { expect } = require('chai'); -const MerkleProofWrapper = artifacts.require('MerkleProofWrapper'); +const MerkleProof = artifacts.require('$MerkleProof'); contract('MerkleProof', function () { beforeEach(async function () { - this.merkleProof = await MerkleProofWrapper.new(); + this.merkleProof = await MerkleProof.new(); }); describe('verify', function () { @@ -24,15 +24,15 @@ contract('MerkleProof', function () { const proof = merkleTree.getHexProof(leaf); - expect(await this.merkleProof.verify(proof, root, leaf)).to.equal(true); - expect(await this.merkleProof.verifyCalldata(proof, root, leaf)).to.equal(true); + expect(await this.merkleProof.$verify(proof, root, leaf)).to.equal(true); + expect(await this.merkleProof.$verifyCalldata(proof, root, leaf)).to.equal(true); // For demonstration, it is also possible to create valid proofs for certain 64-byte values *not* in elements: const noSuchLeaf = keccak256( Buffer.concat([keccak256(elements[0]), keccak256(elements[1])].sort(Buffer.compare)), ); - expect(await this.merkleProof.verify(proof.slice(1), root, noSuchLeaf)).to.equal(true); - expect(await this.merkleProof.verifyCalldata(proof.slice(1), root, noSuchLeaf)).to.equal(true); + expect(await this.merkleProof.$verify(proof.slice(1), root, noSuchLeaf)).to.equal(true); + expect(await this.merkleProof.$verifyCalldata(proof.slice(1), root, noSuchLeaf)).to.equal(true); }); it('returns false for an invalid Merkle proof', async function () { @@ -48,8 +48,8 @@ contract('MerkleProof', function () { const badProof = badMerkleTree.getHexProof(badElements[0]); - expect(await this.merkleProof.verify(badProof, correctRoot, correctLeaf)).to.equal(false); - expect(await this.merkleProof.verifyCalldata(badProof, correctRoot, correctLeaf)).to.equal(false); + expect(await this.merkleProof.$verify(badProof, correctRoot, correctLeaf)).to.equal(false); + expect(await this.merkleProof.$verifyCalldata(badProof, correctRoot, correctLeaf)).to.equal(false); }); it('returns false for a Merkle proof of invalid length', async function () { @@ -63,8 +63,8 @@ contract('MerkleProof', function () { const proof = merkleTree.getHexProof(leaf); const badProof = proof.slice(0, proof.length - 5); - expect(await this.merkleProof.verify(badProof, root, leaf)).to.equal(false); - expect(await this.merkleProof.verifyCalldata(badProof, root, leaf)).to.equal(false); + expect(await this.merkleProof.$verify(badProof, root, leaf)).to.equal(false); + expect(await this.merkleProof.$verifyCalldata(badProof, root, leaf)).to.equal(false); }); }); @@ -78,8 +78,8 @@ contract('MerkleProof', function () { const proof = merkleTree.getMultiProof(proofLeaves); const proofFlags = merkleTree.getProofFlags(proofLeaves, proof); - expect(await this.merkleProof.multiProofVerify(proof, proofFlags, root, proofLeaves)).to.equal(true); - expect(await this.merkleProof.multiProofVerifyCalldata(proof, proofFlags, root, proofLeaves)).to.equal(true); + expect(await this.merkleProof.$multiProofVerify(proof, proofFlags, root, proofLeaves)).to.equal(true); + expect(await this.merkleProof.$multiProofVerifyCalldata(proof, proofFlags, root, proofLeaves)).to.equal(true); }); it('returns false for an invalid Merkle multi proof', async function () { @@ -92,9 +92,9 @@ contract('MerkleProof', function () { const badProof = badMerkleTree.getMultiProof(badProofLeaves); const badProofFlags = badMerkleTree.getProofFlags(badProofLeaves, badProof); - expect(await this.merkleProof.multiProofVerify(badProof, badProofFlags, root, badProofLeaves)) + expect(await this.merkleProof.$multiProofVerify(badProof, badProofFlags, root, badProofLeaves)) .to.equal(false); - expect(await this.merkleProof.multiProofVerifyCalldata(badProof, badProofFlags, root, badProofLeaves)) + expect(await this.merkleProof.$multiProofVerifyCalldata(badProof, badProofFlags, root, badProofLeaves)) .to.equal(false); }); @@ -107,7 +107,7 @@ contract('MerkleProof', function () { const root = merkleTree.getRoot(); await expectRevert( - this.merkleProof.multiProofVerify( + this.merkleProof.$multiProofVerify( [ leaves[1], fill, merkleTree.layers[1][1] ], [ false, false, false ], root, @@ -116,7 +116,7 @@ contract('MerkleProof', function () { 'MerkleProof: invalid multiproof', ); await expectRevert( - this.merkleProof.multiProofVerifyCalldata( + this.merkleProof.$multiProofVerifyCalldata( [ leaves[1], fill, merkleTree.layers[1][1] ], [ false, false, false ], root, @@ -135,7 +135,7 @@ contract('MerkleProof', function () { const root = merkleTree.getRoot(); await expectRevert( - this.merkleProof.multiProofVerify( + this.merkleProof.$multiProofVerify( [ leaves[1], fill, merkleTree.layers[1][1] ], [ false, false, false, false ], root, @@ -143,8 +143,9 @@ contract('MerkleProof', function () { ), 'reverted with panic code 0x32', ); + await expectRevert( - this.merkleProof.multiProofVerifyCalldata( + this.merkleProof.$multiProofVerifyCalldata( [ leaves[1], fill, merkleTree.layers[1][1] ], [ false, false, false, false ], root, @@ -163,8 +164,8 @@ contract('MerkleProof', function () { const proof = merkleTree.getMultiProof(proofLeaves); const proofFlags = merkleTree.getProofFlags(proofLeaves, proof); - expect(await this.merkleProof.multiProofVerify(proof, proofFlags, root, proofLeaves)).to.equal(true); - expect(await this.merkleProof.multiProofVerifyCalldata(proof, proofFlags, root, proofLeaves)).to.equal(true); + expect(await this.merkleProof.$multiProofVerify(proof, proofFlags, root, proofLeaves)).to.equal(true); + expect(await this.merkleProof.$multiProofVerifyCalldata(proof, proofFlags, root, proofLeaves)).to.equal(true); }); it('limit case: can prove empty leaves', async function () { @@ -172,8 +173,8 @@ contract('MerkleProof', function () { const merkleTree = new MerkleTree(leaves, keccak256, { sort: true }); const root = merkleTree.getRoot(); - expect(await this.merkleProof.multiProofVerify([ root ], [], root, [])).to.equal(true); - expect(await this.merkleProof.multiProofVerifyCalldata([ root ], [], root, [])).to.equal(true); + expect(await this.merkleProof.$multiProofVerify([ root ], [], root, [])).to.equal(true); + expect(await this.merkleProof.$multiProofVerifyCalldata([ root ], [], root, [])).to.equal(true); }); }); }); diff --git a/test/utils/cryptography/SignatureChecker.test.js b/test/utils/cryptography/SignatureChecker.test.js index 801377a95..55ba75af0 100644 --- a/test/utils/cryptography/SignatureChecker.test.js +++ b/test/utils/cryptography/SignatureChecker.test.js @@ -2,7 +2,7 @@ const { toEthSignedMessageHash } = require('../../helpers/sign'); const { expect } = require('chai'); -const SignatureCheckerMock = artifacts.require('SignatureCheckerMock'); +const SignatureChecker = artifacts.require('$SignatureChecker'); const ERC1271WalletMock = artifacts.require('ERC1271WalletMock'); const ERC1271MaliciousMock = artifacts.require('ERC1271MaliciousMock'); @@ -13,7 +13,7 @@ contract('SignatureChecker (ERC1271)', function (accounts) { const [signer, other] = accounts; before('deploying', async function () { - this.signaturechecker = await SignatureCheckerMock.new(); + this.signaturechecker = await SignatureChecker.new(); this.wallet = await ERC1271WalletMock.new(signer); this.malicious = await ERC1271MaliciousMock.new(); this.signature = await web3.eth.sign(TEST_MESSAGE, signer); @@ -21,7 +21,7 @@ contract('SignatureChecker (ERC1271)', function (accounts) { context('EOA account', function () { it('with matching signer and signature', async function () { - expect(await this.signaturechecker.isValidSignatureNow( + expect(await this.signaturechecker.$isValidSignatureNow( signer, toEthSignedMessageHash(TEST_MESSAGE), this.signature, @@ -29,7 +29,7 @@ contract('SignatureChecker (ERC1271)', function (accounts) { }); it('with invalid signer', async function () { - expect(await this.signaturechecker.isValidSignatureNow( + expect(await this.signaturechecker.$isValidSignatureNow( other, toEthSignedMessageHash(TEST_MESSAGE), this.signature, @@ -37,7 +37,7 @@ contract('SignatureChecker (ERC1271)', function (accounts) { }); it('with invalid signature', async function () { - expect(await this.signaturechecker.isValidSignatureNow( + expect(await this.signaturechecker.$isValidSignatureNow( signer, toEthSignedMessageHash(WRONG_MESSAGE), this.signature, @@ -47,7 +47,7 @@ contract('SignatureChecker (ERC1271)', function (accounts) { context('ERC1271 wallet', function () { it('with matching signer and signature', async function () { - expect(await this.signaturechecker.isValidSignatureNow( + expect(await this.signaturechecker.$isValidSignatureNow( this.wallet.address, toEthSignedMessageHash(TEST_MESSAGE), this.signature, @@ -55,7 +55,7 @@ contract('SignatureChecker (ERC1271)', function (accounts) { }); it('with invalid signer', async function () { - expect(await this.signaturechecker.isValidSignatureNow( + expect(await this.signaturechecker.$isValidSignatureNow( this.signaturechecker.address, toEthSignedMessageHash(TEST_MESSAGE), this.signature, @@ -63,7 +63,7 @@ contract('SignatureChecker (ERC1271)', function (accounts) { }); it('with invalid signature', async function () { - expect(await this.signaturechecker.isValidSignatureNow( + expect(await this.signaturechecker.$isValidSignatureNow( this.wallet.address, toEthSignedMessageHash(WRONG_MESSAGE), this.signature, @@ -71,7 +71,7 @@ contract('SignatureChecker (ERC1271)', function (accounts) { }); it('with malicious wallet', async function () { - expect(await this.signaturechecker.isValidSignatureNow( + expect(await this.signaturechecker.$isValidSignatureNow( this.malicious.address, toEthSignedMessageHash(TEST_MESSAGE), this.signature, diff --git a/test/utils/introspection/ERC165.test.js b/test/utils/introspection/ERC165.test.js index fabad8cdc..c1db67768 100644 --- a/test/utils/introspection/ERC165.test.js +++ b/test/utils/introspection/ERC165.test.js @@ -1,10 +1,10 @@ const { shouldSupportInterfaces } = require('./SupportsInterface.behavior'); -const ERC165Mock = artifacts.require('ERC165Mock'); +const ERC165 = artifacts.require('$ERC165'); contract('ERC165', function () { beforeEach(async function () { - this.mock = await ERC165Mock.new(); + this.mock = await ERC165.new(); }); shouldSupportInterfaces([ diff --git a/test/utils/introspection/ERC165Checker.test.js b/test/utils/introspection/ERC165Checker.test.js index f4abf44f8..baa344a7f 100644 --- a/test/utils/introspection/ERC165Checker.test.js +++ b/test/utils/introspection/ERC165Checker.test.js @@ -2,11 +2,11 @@ require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const ERC165CheckerMock = artifacts.require('ERC165CheckerMock'); +const ERC165Checker = artifacts.require('$ERC165Checker'); +const ERC165Storage = artifacts.require('$ERC165Storage'); const ERC165MissingData = artifacts.require('ERC165MissingData'); const ERC165MaliciousData = artifacts.require('ERC165MaliciousData'); const ERC165NotSupported = artifacts.require('ERC165NotSupported'); -const ERC165InterfacesSupported = artifacts.require('ERC165InterfacesSupported'); const ERC165ReturnBombMock = artifacts.require('ERC165ReturnBombMock'); const DUMMY_ID = '0xdeadbeef'; @@ -18,7 +18,7 @@ const DUMMY_ACCOUNT = '0x1111111111111111111111111111111111111111'; contract('ERC165Checker', function () { beforeEach(async function () { - this.mock = await ERC165CheckerMock.new(); + this.mock = await ERC165Checker.new(); }); context('ERC165 missing return data', function () { @@ -27,28 +27,28 @@ contract('ERC165Checker', function () { }); it('does not support ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); + const supported = await this.mock.$supportsERC165(this.target.address); expect(supported).to.equal(false); }); it('does not support mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(this.target.address, DUMMY_ID); + const supported = await this.mock.$supportsInterface(this.target.address, DUMMY_ID); expect(supported).to.equal(false); }); it('does not support mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, [DUMMY_ID]); + const supported = await this.mock.$supportsAllInterfaces(this.target.address, [DUMMY_ID]); expect(supported).to.equal(false); }); it('does not support mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, [DUMMY_ID]); + const supported = await this.mock.$getSupportedInterfaces(this.target.address, [DUMMY_ID]); expect(supported.length).to.equal(1); expect(supported[0]).to.equal(false); }); it('does not support mock interface via supportsERC165InterfaceUnchecked', async function () { - const supported = await this.mock.supportsERC165InterfaceUnchecked(this.target.address, DUMMY_ID); + const supported = await this.mock.$supportsERC165InterfaceUnchecked(this.target.address, DUMMY_ID); expect(supported).to.equal(false); }); }); @@ -59,28 +59,28 @@ contract('ERC165Checker', function () { }); it('does not support ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); + const supported = await this.mock.$supportsERC165(this.target.address); expect(supported).to.equal(false); }); it('does not support mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(this.target.address, DUMMY_ID); + const supported = await this.mock.$supportsInterface(this.target.address, DUMMY_ID); expect(supported).to.equal(false); }); it('does not support mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, [DUMMY_ID]); + const supported = await this.mock.$supportsAllInterfaces(this.target.address, [DUMMY_ID]); expect(supported).to.equal(false); }); it('does not support mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, [DUMMY_ID]); + const supported = await this.mock.$getSupportedInterfaces(this.target.address, [DUMMY_ID]); expect(supported.length).to.equal(1); expect(supported[0]).to.equal(false); }); it('does not support mock interface via supportsERC165InterfaceUnchecked', async function () { - const supported = await this.mock.supportsERC165InterfaceUnchecked(this.target.address, DUMMY_ID); + const supported = await this.mock.$supportsERC165InterfaceUnchecked(this.target.address, DUMMY_ID); expect(supported).to.equal(true); }); }); @@ -91,135 +91,137 @@ contract('ERC165Checker', function () { }); it('does not support ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); + const supported = await this.mock.$supportsERC165(this.target.address); expect(supported).to.equal(false); }); it('does not support mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(this.target.address, DUMMY_ID); + const supported = await this.mock.$supportsInterface(this.target.address, DUMMY_ID); expect(supported).to.equal(false); }); it('does not support mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, [DUMMY_ID]); + const supported = await this.mock.$supportsAllInterfaces(this.target.address, [DUMMY_ID]); expect(supported).to.equal(false); }); it('does not support mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, [DUMMY_ID]); + const supported = await this.mock.$getSupportedInterfaces(this.target.address, [DUMMY_ID]); expect(supported.length).to.equal(1); expect(supported[0]).to.equal(false); }); it('does not support mock interface via supportsERC165InterfaceUnchecked', async function () { - const supported = await this.mock.supportsERC165InterfaceUnchecked(this.target.address, DUMMY_ID); + const supported = await this.mock.$supportsERC165InterfaceUnchecked(this.target.address, DUMMY_ID); expect(supported).to.equal(false); }); }); context('ERC165 supported', function () { beforeEach(async function () { - this.target = await ERC165InterfacesSupported.new([]); + this.target = await ERC165Storage.new(); }); it('supports ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); + const supported = await this.mock.$supportsERC165(this.target.address); expect(supported).to.equal(true); }); it('does not support mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(this.target.address, DUMMY_ID); + const supported = await this.mock.$supportsInterface(this.target.address, DUMMY_ID); expect(supported).to.equal(false); }); it('does not support mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, [DUMMY_ID]); + const supported = await this.mock.$supportsAllInterfaces(this.target.address, [DUMMY_ID]); expect(supported).to.equal(false); }); it('does not support mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, [DUMMY_ID]); + const supported = await this.mock.$getSupportedInterfaces(this.target.address, [DUMMY_ID]); expect(supported.length).to.equal(1); expect(supported[0]).to.equal(false); }); it('does not support mock interface via supportsERC165InterfaceUnchecked', async function () { - const supported = await this.mock.supportsERC165InterfaceUnchecked(this.target.address, DUMMY_ID); + const supported = await this.mock.$supportsERC165InterfaceUnchecked(this.target.address, DUMMY_ID); expect(supported).to.equal(false); }); }); context('ERC165 and single interface supported', function () { beforeEach(async function () { - this.target = await ERC165InterfacesSupported.new([DUMMY_ID]); + this.target = await ERC165Storage.new(); + await this.target.$_registerInterface(DUMMY_ID); }); it('supports ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); + const supported = await this.mock.$supportsERC165(this.target.address); expect(supported).to.equal(true); }); it('supports mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(this.target.address, DUMMY_ID); + const supported = await this.mock.$supportsInterface(this.target.address, DUMMY_ID); expect(supported).to.equal(true); }); it('supports mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, [DUMMY_ID]); + const supported = await this.mock.$supportsAllInterfaces(this.target.address, [DUMMY_ID]); expect(supported).to.equal(true); }); it('supports mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, [DUMMY_ID]); + const supported = await this.mock.$getSupportedInterfaces(this.target.address, [DUMMY_ID]); expect(supported.length).to.equal(1); expect(supported[0]).to.equal(true); }); it('supports mock interface via supportsERC165InterfaceUnchecked', async function () { - const supported = await this.mock.supportsERC165InterfaceUnchecked(this.target.address, DUMMY_ID); + const supported = await this.mock.$supportsERC165InterfaceUnchecked(this.target.address, DUMMY_ID); expect(supported).to.equal(true); }); }); context('ERC165 and many interfaces supported', function () { beforeEach(async function () { - this.supportedInterfaces = [DUMMY_ID, DUMMY_ID_2, DUMMY_ID_3]; - this.target = await ERC165InterfacesSupported.new(this.supportedInterfaces); + this.supportedInterfaces = [ DUMMY_ID, DUMMY_ID_2, DUMMY_ID_3 ]; + this.target = await ERC165Storage.new(); + await Promise.all(this.supportedInterfaces.map(interfaceId => this.target.$_registerInterface(interfaceId))); }); it('supports ERC165', async function () { - const supported = await this.mock.supportsERC165(this.target.address); + const supported = await this.mock.$supportsERC165(this.target.address); expect(supported).to.equal(true); }); it('supports each interfaceId via supportsInterface', async function () { for (const interfaceId of this.supportedInterfaces) { - const supported = await this.mock.supportsInterface(this.target.address, interfaceId); + const supported = await this.mock.$supportsInterface(this.target.address, interfaceId); expect(supported).to.equal(true); }; }); it('supports all interfaceIds via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(this.target.address, this.supportedInterfaces); + const supported = await this.mock.$supportsAllInterfaces(this.target.address, this.supportedInterfaces); expect(supported).to.equal(true); }); it('supports none of the interfaces queried via supportsAllInterfaces', async function () { const interfaceIdsToTest = [DUMMY_UNSUPPORTED_ID, DUMMY_UNSUPPORTED_ID_2]; - const supported = await this.mock.supportsAllInterfaces(this.target.address, interfaceIdsToTest); + const supported = await this.mock.$supportsAllInterfaces(this.target.address, interfaceIdsToTest); expect(supported).to.equal(false); }); it('supports not all of the interfaces queried via supportsAllInterfaces', async function () { const interfaceIdsToTest = [...this.supportedInterfaces, DUMMY_UNSUPPORTED_ID]; - const supported = await this.mock.supportsAllInterfaces(this.target.address, interfaceIdsToTest); + const supported = await this.mock.$supportsAllInterfaces(this.target.address, interfaceIdsToTest); expect(supported).to.equal(false); }); it('supports all interfaceIds via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(this.target.address, this.supportedInterfaces); + const supported = await this.mock.$getSupportedInterfaces(this.target.address, this.supportedInterfaces); expect(supported.length).to.equal(3); expect(supported[0]).to.equal(true); expect(supported[1]).to.equal(true); @@ -229,7 +231,7 @@ contract('ERC165Checker', function () { it('supports none of the interfaces queried via getSupportedInterfaces', async function () { const interfaceIdsToTest = [DUMMY_UNSUPPORTED_ID, DUMMY_UNSUPPORTED_ID_2]; - const supported = await this.mock.getSupportedInterfaces(this.target.address, interfaceIdsToTest); + const supported = await this.mock.$getSupportedInterfaces(this.target.address, interfaceIdsToTest); expect(supported.length).to.equal(2); expect(supported[0]).to.equal(false); expect(supported[1]).to.equal(false); @@ -238,7 +240,7 @@ contract('ERC165Checker', function () { it('supports not all of the interfaces queried via getSupportedInterfaces', async function () { const interfaceIdsToTest = [...this.supportedInterfaces, DUMMY_UNSUPPORTED_ID]; - const supported = await this.mock.getSupportedInterfaces(this.target.address, interfaceIdsToTest); + const supported = await this.mock.$getSupportedInterfaces(this.target.address, interfaceIdsToTest); expect(supported.length).to.equal(4); expect(supported[0]).to.equal(true); expect(supported[1]).to.equal(true); @@ -248,7 +250,7 @@ contract('ERC165Checker', function () { it('supports each interfaceId via supportsERC165InterfaceUnchecked', async function () { for (const interfaceId of this.supportedInterfaces) { - const supported = await this.mock.supportsERC165InterfaceUnchecked(this.target.address, interfaceId); + const supported = await this.mock.$supportsERC165InterfaceUnchecked(this.target.address, interfaceId); expect(supported).to.equal(true); }; }); @@ -256,28 +258,28 @@ contract('ERC165Checker', function () { context('account address does not support ERC165', function () { it('does not support ERC165', async function () { - const supported = await this.mock.supportsERC165(DUMMY_ACCOUNT); + const supported = await this.mock.$supportsERC165(DUMMY_ACCOUNT); expect(supported).to.equal(false); }); it('does not support mock interface via supportsInterface', async function () { - const supported = await this.mock.supportsInterface(DUMMY_ACCOUNT, DUMMY_ID); + const supported = await this.mock.$supportsInterface(DUMMY_ACCOUNT, DUMMY_ID); expect(supported).to.equal(false); }); it('does not support mock interface via supportsAllInterfaces', async function () { - const supported = await this.mock.supportsAllInterfaces(DUMMY_ACCOUNT, [DUMMY_ID]); + const supported = await this.mock.$supportsAllInterfaces(DUMMY_ACCOUNT, [DUMMY_ID]); expect(supported).to.equal(false); }); it('does not support mock interface via getSupportedInterfaces', async function () { - const supported = await this.mock.getSupportedInterfaces(DUMMY_ACCOUNT, [DUMMY_ID]); + const supported = await this.mock.$getSupportedInterfaces(DUMMY_ACCOUNT, [DUMMY_ID]); expect(supported.length).to.equal(1); expect(supported[0]).to.equal(false); }); it('does not support mock interface via supportsERC165InterfaceUnchecked', async function () { - const supported = await this.mock.supportsERC165InterfaceUnchecked(DUMMY_ACCOUNT, DUMMY_ID); + const supported = await this.mock.$supportsERC165InterfaceUnchecked(DUMMY_ACCOUNT, DUMMY_ID); expect(supported).to.equal(false); }); }); @@ -285,10 +287,10 @@ contract('ERC165Checker', function () { it('Return bomb resistance', async function () { this.target = await ERC165ReturnBombMock.new(); - const tx1 = await this.mock.supportsInterface.sendTransaction(this.target.address, DUMMY_ID); + const tx1 = await this.mock.$supportsInterface.sendTransaction(this.target.address, DUMMY_ID); expect(tx1.receipt.gasUsed).to.be.lessThan(120000); // 3*30k + 21k + some margin - const tx2 = await this.mock.getSupportedInterfaces.sendTransaction( + const tx2 = await this.mock.$getSupportedInterfaces.sendTransaction( this.target.address, [ DUMMY_ID, diff --git a/test/utils/introspection/ERC165Storage.test.js b/test/utils/introspection/ERC165Storage.test.js index 9c2792de8..278f4ae18 100644 --- a/test/utils/introspection/ERC165Storage.test.js +++ b/test/utils/introspection/ERC165Storage.test.js @@ -2,21 +2,21 @@ const { expectRevert } = require('@openzeppelin/test-helpers'); const { shouldSupportInterfaces } = require('./SupportsInterface.behavior'); -const ERC165Mock = artifacts.require('ERC165StorageMock'); +const ERC165Storage = artifacts.require('$ERC165Storage'); contract('ERC165Storage', function () { beforeEach(async function () { - this.mock = await ERC165Mock.new(); + this.mock = await ERC165Storage.new(); }); it('register interface', async function () { expect(await this.mock.supportsInterface('0x00000001')).to.be.equal(false); - await this.mock.registerInterface('0x00000001'); + await this.mock.$_registerInterface('0x00000001'); expect(await this.mock.supportsInterface('0x00000001')).to.be.equal(true); }); it('does not allow 0xffffffff', async function () { - await expectRevert(this.mock.registerInterface('0xffffffff'), 'ERC165: invalid interface id'); + await expectRevert(this.mock.$_registerInterface('0xffffffff'), 'ERC165: invalid interface id'); }); shouldSupportInterfaces([ diff --git a/test/utils/introspection/ERC1820Implementer.test.js b/test/utils/introspection/ERC1820Implementer.test.js index 8d9fe5634..ba0304625 100644 --- a/test/utils/introspection/ERC1820Implementer.test.js +++ b/test/utils/introspection/ERC1820Implementer.test.js @@ -3,7 +3,7 @@ const { bufferToHex, keccakFromString } = require('ethereumjs-util'); const { expect } = require('chai'); -const ERC1820ImplementerMock = artifacts.require('ERC1820ImplementerMock'); +const ERC1820Implementer = artifacts.require('$ERC1820Implementer'); contract('ERC1820Implementer', function (accounts) { const [ registryFunder, implementee, other ] = accounts; @@ -11,7 +11,7 @@ contract('ERC1820Implementer', function (accounts) { const ERC1820_ACCEPT_MAGIC = bufferToHex(keccakFromString('ERC1820_ACCEPT_MAGIC')); beforeEach(async function () { - this.implementer = await ERC1820ImplementerMock.new(); + this.implementer = await ERC1820Implementer.new(); this.registry = await singletons.ERC1820Registry(registryFunder); this.interfaceA = bufferToHex(keccakFromString('interfaceA')); @@ -36,7 +36,7 @@ contract('ERC1820Implementer', function (accounts) { context('with registered interfaces', function () { beforeEach(async function () { - await this.implementer.registerInterfaceForAddress(this.interfaceA, implementee); + await this.implementer.$_registerInterfaceForAddress(this.interfaceA, implementee); }); it('returns true when interface implementation is queried', async function () { diff --git a/test/utils/math/Math.test.js b/test/utils/math/Math.test.js index 51df28d12..63cfa186c 100644 --- a/test/utils/math/Math.test.js +++ b/test/utils/math/Math.test.js @@ -3,7 +3,7 @@ const { expect } = require('chai'); const { MAX_UINT256 } = constants; const { Rounding } = require('../../helpers/enums.js'); -const MathMock = artifacts.require('MathMock'); +const Math = artifacts.require('$Math'); contract('Math', function () { const min = new BN('1234'); @@ -12,26 +12,26 @@ contract('Math', function () { const MAX_UINT256_SUB2 = MAX_UINT256.sub(new BN('2')); beforeEach(async function () { - this.math = await MathMock.new(); + this.math = await Math.new(); }); describe('max', function () { it('is correctly detected in first argument position', async function () { - expect(await this.math.max(max, min)).to.be.bignumber.equal(max); + expect(await this.math.$max(max, min)).to.be.bignumber.equal(max); }); it('is correctly detected in second argument position', async function () { - expect(await this.math.max(min, max)).to.be.bignumber.equal(max); + expect(await this.math.$max(min, max)).to.be.bignumber.equal(max); }); }); describe('min', function () { it('is correctly detected in first argument position', async function () { - expect(await this.math.min(min, max)).to.be.bignumber.equal(min); + expect(await this.math.$min(min, max)).to.be.bignumber.equal(min); }); it('is correctly detected in second argument position', async function () { - expect(await this.math.min(max, min)).to.be.bignumber.equal(min); + expect(await this.math.$min(max, min)).to.be.bignumber.equal(min); }); }); @@ -43,24 +43,24 @@ contract('Math', function () { it('is correctly calculated with two odd numbers', async function () { const a = new BN('57417'); const b = new BN('95431'); - expect(await this.math.average(a, b)).to.be.bignumber.equal(bnAverage(a, b)); + expect(await this.math.$average(a, b)).to.be.bignumber.equal(bnAverage(a, b)); }); it('is correctly calculated with two even numbers', async function () { const a = new BN('42304'); const b = new BN('84346'); - expect(await this.math.average(a, b)).to.be.bignumber.equal(bnAverage(a, b)); + expect(await this.math.$average(a, b)).to.be.bignumber.equal(bnAverage(a, b)); }); it('is correctly calculated with one even and one odd number', async function () { const a = new BN('57417'); const b = new BN('84346'); - expect(await this.math.average(a, b)).to.be.bignumber.equal(bnAverage(a, b)); + expect(await this.math.$average(a, b)).to.be.bignumber.equal(bnAverage(a, b)); }); it('is correctly calculated with two max uint256 numbers', async function () { const a = MAX_UINT256; - expect(await this.math.average(a, a)).to.be.bignumber.equal(bnAverage(a, a)); + expect(await this.math.$average(a, a)).to.be.bignumber.equal(bnAverage(a, a)); }); }); @@ -68,68 +68,68 @@ contract('Math', function () { it('does not round up on exact division', async function () { const a = new BN('10'); const b = new BN('5'); - expect(await this.math.ceilDiv(a, b)).to.be.bignumber.equal('2'); + expect(await this.math.$ceilDiv(a, b)).to.be.bignumber.equal('2'); }); it('rounds up on division with remainders', async function () { const a = new BN('42'); const b = new BN('13'); - expect(await this.math.ceilDiv(a, b)).to.be.bignumber.equal('4'); + expect(await this.math.$ceilDiv(a, b)).to.be.bignumber.equal('4'); }); it('does not overflow', async function () { const b = new BN('2'); const result = new BN('1').shln(255); - expect(await this.math.ceilDiv(MAX_UINT256, b)).to.be.bignumber.equal(result); + expect(await this.math.$ceilDiv(MAX_UINT256, b)).to.be.bignumber.equal(result); }); it('correctly computes max uint256 divided by 1', async function () { const b = new BN('1'); - expect(await this.math.ceilDiv(MAX_UINT256, b)).to.be.bignumber.equal(MAX_UINT256); + expect(await this.math.$ceilDiv(MAX_UINT256, b)).to.be.bignumber.equal(MAX_UINT256); }); }); describe('muldiv', function () { it('divide by 0', async function () { - await expectRevert.unspecified(this.math.mulDiv(1, 1, 0, Rounding.Down)); + await expectRevert.unspecified(this.math.$mulDiv(1, 1, 0, Rounding.Down)); }); describe('does round down', async function () { it('small values', async function () { - expect(await this.math.mulDiv('3', '4', '5', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.mulDiv('3', '5', '5', Rounding.Down)).to.be.bignumber.equal('3'); + expect(await this.math.$mulDiv('3', '4', '5', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.$mulDiv('3', '5', '5', Rounding.Down)).to.be.bignumber.equal('3'); }); it('large values', async function () { - expect(await this.math.mulDiv( + expect(await this.math.$mulDiv( new BN('42'), MAX_UINT256_SUB1, MAX_UINT256, Rounding.Down, )).to.be.bignumber.equal(new BN('41')); - expect(await this.math.mulDiv( + expect(await this.math.$mulDiv( new BN('17'), MAX_UINT256, MAX_UINT256, Rounding.Down, )).to.be.bignumber.equal(new BN('17')); - expect(await this.math.mulDiv( + expect(await this.math.$mulDiv( MAX_UINT256_SUB1, MAX_UINT256_SUB1, MAX_UINT256, Rounding.Down, )).to.be.bignumber.equal(MAX_UINT256_SUB2); - expect(await this.math.mulDiv( + expect(await this.math.$mulDiv( MAX_UINT256, MAX_UINT256_SUB1, MAX_UINT256, Rounding.Down, )).to.be.bignumber.equal(MAX_UINT256_SUB1); - expect(await this.math.mulDiv( + expect(await this.math.$mulDiv( MAX_UINT256, MAX_UINT256, MAX_UINT256, @@ -140,40 +140,40 @@ contract('Math', function () { describe('does round up', async function () { it('small values', async function () { - expect(await this.math.mulDiv('3', '4', '5', Rounding.Up)).to.be.bignumber.equal('3'); - expect(await this.math.mulDiv('3', '5', '5', Rounding.Up)).to.be.bignumber.equal('3'); + expect(await this.math.$mulDiv('3', '4', '5', Rounding.Up)).to.be.bignumber.equal('3'); + expect(await this.math.$mulDiv('3', '5', '5', Rounding.Up)).to.be.bignumber.equal('3'); }); it('large values', async function () { - expect(await this.math.mulDiv( + expect(await this.math.$mulDiv( new BN('42'), MAX_UINT256_SUB1, MAX_UINT256, Rounding.Up, )).to.be.bignumber.equal(new BN('42')); - expect(await this.math.mulDiv( + expect(await this.math.$mulDiv( new BN('17'), MAX_UINT256, MAX_UINT256, Rounding.Up, )).to.be.bignumber.equal(new BN('17')); - expect(await this.math.mulDiv( + expect(await this.math.$mulDiv( MAX_UINT256_SUB1, MAX_UINT256_SUB1, MAX_UINT256, Rounding.Up, )).to.be.bignumber.equal(MAX_UINT256_SUB1); - expect(await this.math.mulDiv( + expect(await this.math.$mulDiv( MAX_UINT256, MAX_UINT256_SUB1, MAX_UINT256, Rounding.Up, )).to.be.bignumber.equal(MAX_UINT256_SUB1); - expect(await this.math.mulDiv( + expect(await this.math.$mulDiv( MAX_UINT256, MAX_UINT256, MAX_UINT256, @@ -185,34 +185,34 @@ contract('Math', function () { describe('sqrt', function () { it('rounds down', async function () { - expect(await this.math.sqrt('0', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.sqrt('1', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.sqrt('2', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.sqrt('3', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.sqrt('4', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.sqrt('144', Rounding.Down)).to.be.bignumber.equal('12'); - expect(await this.math.sqrt('999999', Rounding.Down)).to.be.bignumber.equal('999'); - expect(await this.math.sqrt('1000000', Rounding.Down)).to.be.bignumber.equal('1000'); - expect(await this.math.sqrt('1000001', Rounding.Down)).to.be.bignumber.equal('1000'); - expect(await this.math.sqrt('1002000', Rounding.Down)).to.be.bignumber.equal('1000'); - expect(await this.math.sqrt('1002001', Rounding.Down)).to.be.bignumber.equal('1001'); - expect(await this.math.sqrt(MAX_UINT256, Rounding.Down)) + expect(await this.math.$sqrt('0', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.$sqrt('1', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.$sqrt('2', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.$sqrt('3', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.$sqrt('4', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.$sqrt('144', Rounding.Down)).to.be.bignumber.equal('12'); + expect(await this.math.$sqrt('999999', Rounding.Down)).to.be.bignumber.equal('999'); + expect(await this.math.$sqrt('1000000', Rounding.Down)).to.be.bignumber.equal('1000'); + expect(await this.math.$sqrt('1000001', Rounding.Down)).to.be.bignumber.equal('1000'); + expect(await this.math.$sqrt('1002000', Rounding.Down)).to.be.bignumber.equal('1000'); + expect(await this.math.$sqrt('1002001', Rounding.Down)).to.be.bignumber.equal('1001'); + expect(await this.math.$sqrt(MAX_UINT256, Rounding.Down)) .to.be.bignumber.equal('340282366920938463463374607431768211455'); }); it('rounds up', async function () { - expect(await this.math.sqrt('0', Rounding.Up)).to.be.bignumber.equal('0'); - expect(await this.math.sqrt('1', Rounding.Up)).to.be.bignumber.equal('1'); - expect(await this.math.sqrt('2', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.sqrt('3', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.sqrt('4', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.sqrt('144', Rounding.Up)).to.be.bignumber.equal('12'); - expect(await this.math.sqrt('999999', Rounding.Up)).to.be.bignumber.equal('1000'); - expect(await this.math.sqrt('1000000', Rounding.Up)).to.be.bignumber.equal('1000'); - expect(await this.math.sqrt('1000001', Rounding.Up)).to.be.bignumber.equal('1001'); - expect(await this.math.sqrt('1002000', Rounding.Up)).to.be.bignumber.equal('1001'); - expect(await this.math.sqrt('1002001', Rounding.Up)).to.be.bignumber.equal('1001'); - expect(await this.math.sqrt(MAX_UINT256, Rounding.Up)) + expect(await this.math.$sqrt('0', Rounding.Up)).to.be.bignumber.equal('0'); + expect(await this.math.$sqrt('1', Rounding.Up)).to.be.bignumber.equal('1'); + expect(await this.math.$sqrt('2', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.$sqrt('3', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.$sqrt('4', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.$sqrt('144', Rounding.Up)).to.be.bignumber.equal('12'); + expect(await this.math.$sqrt('999999', Rounding.Up)).to.be.bignumber.equal('1000'); + expect(await this.math.$sqrt('1000000', Rounding.Up)).to.be.bignumber.equal('1000'); + expect(await this.math.$sqrt('1000001', Rounding.Up)).to.be.bignumber.equal('1001'); + expect(await this.math.$sqrt('1002000', Rounding.Up)).to.be.bignumber.equal('1001'); + expect(await this.math.$sqrt('1002001', Rounding.Up)).to.be.bignumber.equal('1001'); + expect(await this.math.$sqrt(MAX_UINT256, Rounding.Up)) .to.be.bignumber.equal('340282366920938463463374607431768211456'); }); }); @@ -220,92 +220,97 @@ contract('Math', function () { describe('log', function () { describe('log2', function () { it('rounds down', async function () { - expect(await this.math.log2('0', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.log2('1', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.log2('2', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.log2('3', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.log2('4', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.log2('5', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.log2('6', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.log2('7', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.log2('8', Rounding.Down)).to.be.bignumber.equal('3'); - expect(await this.math.log2('9', Rounding.Down)).to.be.bignumber.equal('3'); - expect(await this.math.log2(MAX_UINT256, Rounding.Down)).to.be.bignumber.equal('255'); + // For some reason calling .$log2() directly fails + expect(await this.math.methods['$log2(uint256,uint8)']('0', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.methods['$log2(uint256,uint8)']('1', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.methods['$log2(uint256,uint8)']('2', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.methods['$log2(uint256,uint8)']('3', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.methods['$log2(uint256,uint8)']('4', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.methods['$log2(uint256,uint8)']('5', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.methods['$log2(uint256,uint8)']('6', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.methods['$log2(uint256,uint8)']('7', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.methods['$log2(uint256,uint8)']('8', Rounding.Down)).to.be.bignumber.equal('3'); + expect(await this.math.methods['$log2(uint256,uint8)']('9', Rounding.Down)).to.be.bignumber.equal('3'); + expect(await this.math.methods['$log2(uint256,uint8)'](MAX_UINT256, Rounding.Down)) + .to.be.bignumber.equal('255'); }); it('rounds up', async function () { - expect(await this.math.log2('0', Rounding.Up)).to.be.bignumber.equal('0'); - expect(await this.math.log2('1', Rounding.Up)).to.be.bignumber.equal('0'); - expect(await this.math.log2('2', Rounding.Up)).to.be.bignumber.equal('1'); - expect(await this.math.log2('3', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.log2('4', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.log2('5', Rounding.Up)).to.be.bignumber.equal('3'); - expect(await this.math.log2('6', Rounding.Up)).to.be.bignumber.equal('3'); - expect(await this.math.log2('7', Rounding.Up)).to.be.bignumber.equal('3'); - expect(await this.math.log2('8', Rounding.Up)).to.be.bignumber.equal('3'); - expect(await this.math.log2(MAX_UINT256, Rounding.Up)).to.be.bignumber.equal('256'); + // For some reason calling .$log2() directly fails + expect(await this.math.methods['$log2(uint256,uint8)']('0', Rounding.Up)).to.be.bignumber.equal('0'); + expect(await this.math.methods['$log2(uint256,uint8)']('1', Rounding.Up)).to.be.bignumber.equal('0'); + expect(await this.math.methods['$log2(uint256,uint8)']('2', Rounding.Up)).to.be.bignumber.equal('1'); + expect(await this.math.methods['$log2(uint256,uint8)']('3', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.methods['$log2(uint256,uint8)']('4', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.methods['$log2(uint256,uint8)']('5', Rounding.Up)).to.be.bignumber.equal('3'); + expect(await this.math.methods['$log2(uint256,uint8)']('6', Rounding.Up)).to.be.bignumber.equal('3'); + expect(await this.math.methods['$log2(uint256,uint8)']('7', Rounding.Up)).to.be.bignumber.equal('3'); + expect(await this.math.methods['$log2(uint256,uint8)']('8', Rounding.Up)).to.be.bignumber.equal('3'); + expect(await this.math.methods['$log2(uint256,uint8)']('9', Rounding.Up)).to.be.bignumber.equal('4'); + expect(await this.math.methods['$log2(uint256,uint8)'](MAX_UINT256, Rounding.Up)) + .to.be.bignumber.equal('256'); }); }); describe('log10', function () { it('rounds down', async function () { - expect(await this.math.log10('0', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.log10('1', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.log10('2', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.log10('9', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.log10('10', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.log10('11', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.log10('99', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.log10('100', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.log10('101', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.log10('999', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.log10('1000', Rounding.Down)).to.be.bignumber.equal('3'); - expect(await this.math.log10('1001', Rounding.Down)).to.be.bignumber.equal('3'); - expect(await this.math.log10(MAX_UINT256, Rounding.Down)).to.be.bignumber.equal('77'); + expect(await this.math.$log10('0', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.$log10('1', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.$log10('2', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.$log10('9', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.$log10('10', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.$log10('11', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.$log10('99', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.$log10('100', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.$log10('101', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.$log10('999', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.$log10('1000', Rounding.Down)).to.be.bignumber.equal('3'); + expect(await this.math.$log10('1001', Rounding.Down)).to.be.bignumber.equal('3'); + expect(await this.math.$log10(MAX_UINT256, Rounding.Down)).to.be.bignumber.equal('77'); }); it('rounds up', async function () { - expect(await this.math.log10('0', Rounding.Up)).to.be.bignumber.equal('0'); - expect(await this.math.log10('1', Rounding.Up)).to.be.bignumber.equal('0'); - expect(await this.math.log10('2', Rounding.Up)).to.be.bignumber.equal('1'); - expect(await this.math.log10('9', Rounding.Up)).to.be.bignumber.equal('1'); - expect(await this.math.log10('10', Rounding.Up)).to.be.bignumber.equal('1'); - expect(await this.math.log10('11', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.log10('99', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.log10('100', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.log10('101', Rounding.Up)).to.be.bignumber.equal('3'); - expect(await this.math.log10('999', Rounding.Up)).to.be.bignumber.equal('3'); - expect(await this.math.log10('1000', Rounding.Up)).to.be.bignumber.equal('3'); - expect(await this.math.log10('1001', Rounding.Up)).to.be.bignumber.equal('4'); - expect(await this.math.log10(MAX_UINT256, Rounding.Up)).to.be.bignumber.equal('78'); + expect(await this.math.$log10('0', Rounding.Up)).to.be.bignumber.equal('0'); + expect(await this.math.$log10('1', Rounding.Up)).to.be.bignumber.equal('0'); + expect(await this.math.$log10('2', Rounding.Up)).to.be.bignumber.equal('1'); + expect(await this.math.$log10('9', Rounding.Up)).to.be.bignumber.equal('1'); + expect(await this.math.$log10('10', Rounding.Up)).to.be.bignumber.equal('1'); + expect(await this.math.$log10('11', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.$log10('99', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.$log10('100', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.$log10('101', Rounding.Up)).to.be.bignumber.equal('3'); + expect(await this.math.$log10('999', Rounding.Up)).to.be.bignumber.equal('3'); + expect(await this.math.$log10('1000', Rounding.Up)).to.be.bignumber.equal('3'); + expect(await this.math.$log10('1001', Rounding.Up)).to.be.bignumber.equal('4'); + expect(await this.math.$log10(MAX_UINT256, Rounding.Up)).to.be.bignumber.equal('78'); }); }); describe('log256', function () { it('rounds down', async function () { - expect(await this.math.log256('0', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.log256('1', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.log256('2', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.log256('255', Rounding.Down)).to.be.bignumber.equal('0'); - expect(await this.math.log256('256', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.log256('257', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.log256('65535', Rounding.Down)).to.be.bignumber.equal('1'); - expect(await this.math.log256('65536', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.log256('65537', Rounding.Down)).to.be.bignumber.equal('2'); - expect(await this.math.log256(MAX_UINT256, Rounding.Down)).to.be.bignumber.equal('31'); + expect(await this.math.$log256('0', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.$log256('1', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.$log256('2', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.$log256('255', Rounding.Down)).to.be.bignumber.equal('0'); + expect(await this.math.$log256('256', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.$log256('257', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.$log256('65535', Rounding.Down)).to.be.bignumber.equal('1'); + expect(await this.math.$log256('65536', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.$log256('65537', Rounding.Down)).to.be.bignumber.equal('2'); + expect(await this.math.$log256(MAX_UINT256, Rounding.Down)).to.be.bignumber.equal('31'); }); it('rounds up', async function () { - expect(await this.math.log256('0', Rounding.Up)).to.be.bignumber.equal('0'); - expect(await this.math.log256('1', Rounding.Up)).to.be.bignumber.equal('0'); - expect(await this.math.log256('2', Rounding.Up)).to.be.bignumber.equal('1'); - expect(await this.math.log256('255', Rounding.Up)).to.be.bignumber.equal('1'); - expect(await this.math.log256('256', Rounding.Up)).to.be.bignumber.equal('1'); - expect(await this.math.log256('257', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.log256('65535', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.log256('65536', Rounding.Up)).to.be.bignumber.equal('2'); - expect(await this.math.log256('65537', Rounding.Up)).to.be.bignumber.equal('3'); - expect(await this.math.log256(MAX_UINT256, Rounding.Up)).to.be.bignumber.equal('32'); + expect(await this.math.$log256('0', Rounding.Up)).to.be.bignumber.equal('0'); + expect(await this.math.$log256('1', Rounding.Up)).to.be.bignumber.equal('0'); + expect(await this.math.$log256('2', Rounding.Up)).to.be.bignumber.equal('1'); + expect(await this.math.$log256('255', Rounding.Up)).to.be.bignumber.equal('1'); + expect(await this.math.$log256('256', Rounding.Up)).to.be.bignumber.equal('1'); + expect(await this.math.$log256('257', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.$log256('65535', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.$log256('65536', Rounding.Up)).to.be.bignumber.equal('2'); + expect(await this.math.$log256('65537', Rounding.Up)).to.be.bignumber.equal('3'); + expect(await this.math.$log256(MAX_UINT256, Rounding.Up)).to.be.bignumber.equal('32'); }); }); }); diff --git a/test/utils/math/SafeCast.test.js b/test/utils/math/SafeCast.test.js index 1399350a5..38374e500 100644 --- a/test/utils/math/SafeCast.test.js +++ b/test/utils/math/SafeCast.test.js @@ -2,11 +2,11 @@ const { BN, expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); const { range } = require('../../../scripts/helpers'); -const SafeCastMock = artifacts.require('SafeCastMock'); +const SafeCast = artifacts.require('$SafeCast'); contract('SafeCast', async function () { beforeEach(async function () { - this.safeCast = await SafeCastMock.new(); + this.safeCast = await SafeCast.new(); }); function testToUint (bits) { @@ -14,27 +14,27 @@ contract('SafeCast', async function () { const maxValue = new BN('2').pow(new BN(bits)).subn(1); it('downcasts 0', async function () { - expect(await this.safeCast[`toUint${bits}`](0)).to.be.bignumber.equal('0'); + expect(await this.safeCast[`$toUint${bits}`](0)).to.be.bignumber.equal('0'); }); it('downcasts 1', async function () { - expect(await this.safeCast[`toUint${bits}`](1)).to.be.bignumber.equal('1'); + expect(await this.safeCast[`$toUint${bits}`](1)).to.be.bignumber.equal('1'); }); it(`downcasts 2^${bits} - 1 (${maxValue})`, async function () { - expect(await this.safeCast[`toUint${bits}`](maxValue)).to.be.bignumber.equal(maxValue); + expect(await this.safeCast[`$toUint${bits}`](maxValue)).to.be.bignumber.equal(maxValue); }); it(`reverts when downcasting 2^${bits} (${maxValue.addn(1)})`, async function () { await expectRevert( - this.safeCast[`toUint${bits}`](maxValue.addn(1)), + this.safeCast[`$toUint${bits}`](maxValue.addn(1)), `SafeCast: value doesn't fit in ${bits} bits`, ); }); it(`reverts when downcasting 2^${bits} + 1 (${maxValue.addn(2)})`, async function () { await expectRevert( - this.safeCast[`toUint${bits}`](maxValue.addn(2)), + this.safeCast[`$toUint${bits}`](maxValue.addn(2)), `SafeCast: value doesn't fit in ${bits} bits`, ); }); @@ -48,27 +48,27 @@ contract('SafeCast', async function () { const minInt256 = new BN('2').pow(new BN(255)).neg(); it('casts 0', async function () { - expect(await this.safeCast.toUint256(0)).to.be.bignumber.equal('0'); + expect(await this.safeCast.$toUint256(0)).to.be.bignumber.equal('0'); }); it('casts 1', async function () { - expect(await this.safeCast.toUint256(1)).to.be.bignumber.equal('1'); + expect(await this.safeCast.$toUint256(1)).to.be.bignumber.equal('1'); }); it(`casts INT256_MAX (${maxInt256})`, async function () { - expect(await this.safeCast.toUint256(maxInt256)).to.be.bignumber.equal(maxInt256); + expect(await this.safeCast.$toUint256(maxInt256)).to.be.bignumber.equal(maxInt256); }); it('reverts when casting -1', async function () { await expectRevert( - this.safeCast.toUint256(-1), + this.safeCast.$toUint256(-1), 'SafeCast: value must be positive', ); }); it(`reverts when casting INT256_MIN (${minInt256})`, async function () { await expectRevert( - this.safeCast.toUint256(minInt256), + this.safeCast.$toUint256(minInt256), 'SafeCast: value must be positive', ); }); @@ -80,49 +80,49 @@ contract('SafeCast', async function () { const maxValue = new BN('2').pow(new BN(bits - 1)).subn(1); it('downcasts 0', async function () { - expect(await this.safeCast[`toInt${bits}`](0)).to.be.bignumber.equal('0'); + expect(await this.safeCast[`$toInt${bits}`](0)).to.be.bignumber.equal('0'); }); it('downcasts 1', async function () { - expect(await this.safeCast[`toInt${bits}`](1)).to.be.bignumber.equal('1'); + expect(await this.safeCast[`$toInt${bits}`](1)).to.be.bignumber.equal('1'); }); it('downcasts -1', async function () { - expect(await this.safeCast[`toInt${bits}`](-1)).to.be.bignumber.equal('-1'); + expect(await this.safeCast[`$toInt${bits}`](-1)).to.be.bignumber.equal('-1'); }); it(`downcasts -2^${bits - 1} (${minValue})`, async function () { - expect(await this.safeCast[`toInt${bits}`](minValue)).to.be.bignumber.equal(minValue); + expect(await this.safeCast[`$toInt${bits}`](minValue)).to.be.bignumber.equal(minValue); }); it(`downcasts 2^${bits - 1} - 1 (${maxValue})`, async function () { - expect(await this.safeCast[`toInt${bits}`](maxValue)).to.be.bignumber.equal(maxValue); + expect(await this.safeCast[`$toInt${bits}`](maxValue)).to.be.bignumber.equal(maxValue); }); it(`reverts when downcasting -2^${bits - 1} - 1 (${minValue.subn(1)})`, async function () { await expectRevert( - this.safeCast[`toInt${bits}`](minValue.subn(1)), + this.safeCast[`$toInt${bits}`](minValue.subn(1)), `SafeCast: value doesn't fit in ${bits} bits`, ); }); it(`reverts when downcasting -2^${bits - 1} - 2 (${minValue.subn(2)})`, async function () { await expectRevert( - this.safeCast[`toInt${bits}`](minValue.subn(2)), + this.safeCast[`$toInt${bits}`](minValue.subn(2)), `SafeCast: value doesn't fit in ${bits} bits`, ); }); it(`reverts when downcasting 2^${bits - 1} (${maxValue.addn(1)})`, async function () { await expectRevert( - this.safeCast[`toInt${bits}`](maxValue.addn(1)), + this.safeCast[`$toInt${bits}`](maxValue.addn(1)), `SafeCast: value doesn't fit in ${bits} bits`, ); }); it(`reverts when downcasting 2^${bits - 1} + 1 (${maxValue.addn(2)})`, async function () { await expectRevert( - this.safeCast[`toInt${bits}`](maxValue.addn(2)), + this.safeCast[`$toInt${bits}`](maxValue.addn(2)), `SafeCast: value doesn't fit in ${bits} bits`, ); }); @@ -136,27 +136,27 @@ contract('SafeCast', async function () { const maxInt256 = new BN('2').pow(new BN(255)).subn(1); it('casts 0', async function () { - expect(await this.safeCast.toInt256(0)).to.be.bignumber.equal('0'); + expect(await this.safeCast.$toInt256(0)).to.be.bignumber.equal('0'); }); it('casts 1', async function () { - expect(await this.safeCast.toInt256(1)).to.be.bignumber.equal('1'); + expect(await this.safeCast.$toInt256(1)).to.be.bignumber.equal('1'); }); it(`casts INT256_MAX (${maxInt256})`, async function () { - expect(await this.safeCast.toInt256(maxInt256)).to.be.bignumber.equal(maxInt256); + expect(await this.safeCast.$toInt256(maxInt256)).to.be.bignumber.equal(maxInt256); }); it(`reverts when casting INT256_MAX + 1 (${maxInt256.addn(1)})`, async function () { await expectRevert( - this.safeCast.toInt256(maxInt256.addn(1)), + this.safeCast.$toInt256(maxInt256.addn(1)), 'SafeCast: value doesn\'t fit in an int256', ); }); it(`reverts when casting UINT256_MAX (${maxUint256})`, async function () { await expectRevert( - this.safeCast.toInt256(maxUint256), + this.safeCast.$toInt256(maxUint256), 'SafeCast: value doesn\'t fit in an int256', ); }); diff --git a/test/utils/math/SafeMath.test.js b/test/utils/math/SafeMath.test.js index 4c2cfe551..a74d7fb96 100644 --- a/test/utils/math/SafeMath.test.js +++ b/test/utils/math/SafeMath.test.js @@ -3,7 +3,8 @@ const { MAX_UINT256 } = constants; const { expect } = require('chai'); -const SafeMathMock = artifacts.require('SafeMathMock'); +const SafeMath = artifacts.require('$SafeMath'); +const SafeMathMemoryCheck = artifacts.require('$SafeMathMemoryCheck'); function expectStruct (value, expected) { for (const key in expected) { @@ -17,7 +18,7 @@ function expectStruct (value, expected) { contract('SafeMath', function () { beforeEach(async function () { - this.safeMath = await SafeMathMock.new(); + this.safeMath = await SafeMath.new(); }); async function testCommutative (fn, lhs, rhs, expected, ...extra) { @@ -46,14 +47,14 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('1234'); - testCommutativeIterable(this.safeMath.tryAdd, a, b, { flag: true, value: a.add(b) }); + testCommutativeIterable(this.safeMath.$tryAdd, a, b, [ true, a.add(b) ]); }); it('reverts on addition overflow', async function () { const a = MAX_UINT256; const b = new BN('1'); - testCommutativeIterable(this.safeMath.tryAdd, a, b, { flag: false, value: '0' }); + testCommutativeIterable(this.safeMath.$tryAdd, a, b, [ false, '0' ]); }); }); @@ -62,14 +63,14 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('1234'); - expectStruct(await this.safeMath.trySub(a, b), { flag: true, value: a.sub(b) }); + expectStruct(await this.safeMath.$trySub(a, b), [ true, a.sub(b) ]); }); it('reverts if subtraction result would be negative', async function () { const a = new BN('1234'); const b = new BN('5678'); - expectStruct(await this.safeMath.trySub(a, b), { flag: false, value: '0' }); + expectStruct(await this.safeMath.$trySub(a, b), [ false, '0' ]); }); }); @@ -78,21 +79,21 @@ contract('SafeMath', function () { const a = new BN('1234'); const b = new BN('5678'); - testCommutativeIterable(this.safeMath.tryMul, a, b, { flag: true, value: a.mul(b) }); + testCommutativeIterable(this.safeMath.$tryMul, a, b, [ true, a.mul(b) ]); }); it('multiplies by zero correctly', async function () { const a = new BN('0'); const b = new BN('5678'); - testCommutativeIterable(this.safeMath.tryMul, a, b, { flag: true, value: a.mul(b) }); + testCommutativeIterable(this.safeMath.$tryMul, a, b, [ true, a.mul(b) ]); }); it('reverts on multiplication overflow', async function () { const a = MAX_UINT256; const b = new BN('2'); - testCommutativeIterable(this.safeMath.tryMul, a, b, { flag: false, value: '0' }); + testCommutativeIterable(this.safeMath.$tryMul, a, b, [ false, '0' ]); }); }); @@ -101,28 +102,28 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('5678'); - expectStruct(await this.safeMath.tryDiv(a, b), { flag: true, value: a.div(b) }); + expectStruct(await this.safeMath.$tryDiv(a, b), [ true, a.div(b) ]); }); it('divides zero correctly', async function () { const a = new BN('0'); const b = new BN('5678'); - expectStruct(await this.safeMath.tryDiv(a, b), { flag: true, value: a.div(b) }); + expectStruct(await this.safeMath.$tryDiv(a, b), [ true, a.div(b) ]); }); it('returns complete number result on non-even division', async function () { const a = new BN('7000'); const b = new BN('5678'); - expectStruct(await this.safeMath.tryDiv(a, b), { flag: true, value: a.div(b) }); + expectStruct(await this.safeMath.$tryDiv(a, b), [ true, a.div(b) ]); }); it('reverts on division by zero', async function () { const a = new BN('5678'); const b = new BN('0'); - expectStruct(await this.safeMath.tryDiv(a, b), { flag: false, value: '0' }); + expectStruct(await this.safeMath.$tryDiv(a, b), [ false, '0' ]); }); }); @@ -132,28 +133,28 @@ contract('SafeMath', function () { const a = new BN('284'); const b = new BN('5678'); - expectStruct(await this.safeMath.tryMod(a, b), { flag: true, value: a.mod(b) }); + expectStruct(await this.safeMath.$tryMod(a, b), [ true, a.mod(b) ]); }); it('when the dividend is equal to the divisor', async function () { const a = new BN('5678'); const b = new BN('5678'); - expectStruct(await this.safeMath.tryMod(a, b), { flag: true, value: a.mod(b) }); + expectStruct(await this.safeMath.$tryMod(a, b), [ true, a.mod(b) ]); }); it('when the dividend is larger than the divisor', async function () { const a = new BN('7000'); const b = new BN('5678'); - expectStruct(await this.safeMath.tryMod(a, b), { flag: true, value: a.mod(b) }); + expectStruct(await this.safeMath.$tryMod(a, b), [ true, a.mod(b) ]); }); it('when the dividend is a multiple of the divisor', async function () { const a = new BN('17034'); // 17034 == 5678 * 3 const b = new BN('5678'); - expectStruct(await this.safeMath.tryMod(a, b), { flag: true, value: a.mod(b) }); + expectStruct(await this.safeMath.$tryMod(a, b), [ true, a.mod(b) ]); }); }); @@ -161,7 +162,7 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('0'); - expectStruct(await this.safeMath.tryMod(a, b), { flag: false, value: '0' }); + expectStruct(await this.safeMath.$tryMod(a, b), [ false, '0' ]); }); }); }); @@ -172,14 +173,14 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('1234'); - await testCommutative(this.safeMath.doAdd, a, b, a.add(b)); + await testCommutative(this.safeMath.$add, a, b, a.add(b)); }); it('reverts on addition overflow', async function () { const a = MAX_UINT256; const b = new BN('1'); - await testFailsCommutative(this.safeMath.doAdd, a, b, undefined); + await testFailsCommutative(this.safeMath.$add, a, b, undefined); }); }); @@ -188,14 +189,14 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('1234'); - expect(await this.safeMath.doSub(a, b)).to.be.bignumber.equal(a.sub(b)); + expect(await this.safeMath.$sub(a, b)).to.be.bignumber.equal(a.sub(b)); }); it('reverts if subtraction result would be negative', async function () { const a = new BN('1234'); const b = new BN('5678'); - await expectRevert.unspecified(this.safeMath.doSub(a, b)); + await expectRevert.unspecified(this.safeMath.$sub(a, b)); }); }); @@ -204,21 +205,21 @@ contract('SafeMath', function () { const a = new BN('1234'); const b = new BN('5678'); - await testCommutative(this.safeMath.doMul, a, b, a.mul(b)); + await testCommutative(this.safeMath.$mul, a, b, a.mul(b)); }); it('multiplies by zero correctly', async function () { const a = new BN('0'); const b = new BN('5678'); - await testCommutative(this.safeMath.doMul, a, b, '0'); + await testCommutative(this.safeMath.$mul, a, b, '0'); }); it('reverts on multiplication overflow', async function () { const a = MAX_UINT256; const b = new BN('2'); - await testFailsCommutative(this.safeMath.doMul, a, b, undefined); + await testFailsCommutative(this.safeMath.$mul, a, b, undefined); }); }); @@ -227,28 +228,28 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('5678'); - expect(await this.safeMath.doDiv(a, b)).to.be.bignumber.equal(a.div(b)); + expect(await this.safeMath.$div(a, b)).to.be.bignumber.equal(a.div(b)); }); it('divides zero correctly', async function () { const a = new BN('0'); const b = new BN('5678'); - expect(await this.safeMath.doDiv(a, b)).to.be.bignumber.equal('0'); + expect(await this.safeMath.$div(a, b)).to.be.bignumber.equal('0'); }); it('returns complete number result on non-even division', async function () { const a = new BN('7000'); const b = new BN('5678'); - expect(await this.safeMath.doDiv(a, b)).to.be.bignumber.equal('1'); + expect(await this.safeMath.$div(a, b)).to.be.bignumber.equal('1'); }); it('reverts on division by zero', async function () { const a = new BN('5678'); const b = new BN('0'); - await expectRevert.unspecified(this.safeMath.doDiv(a, b)); + await expectRevert.unspecified(this.safeMath.$div(a, b)); }); }); @@ -258,28 +259,28 @@ contract('SafeMath', function () { const a = new BN('284'); const b = new BN('5678'); - expect(await this.safeMath.doMod(a, b)).to.be.bignumber.equal(a.mod(b)); + expect(await this.safeMath.$mod(a, b)).to.be.bignumber.equal(a.mod(b)); }); it('when the dividend is equal to the divisor', async function () { const a = new BN('5678'); const b = new BN('5678'); - expect(await this.safeMath.doMod(a, b)).to.be.bignumber.equal(a.mod(b)); + expect(await this.safeMath.$mod(a, b)).to.be.bignumber.equal(a.mod(b)); }); it('when the dividend is larger than the divisor', async function () { const a = new BN('7000'); const b = new BN('5678'); - expect(await this.safeMath.doMod(a, b)).to.be.bignumber.equal(a.mod(b)); + expect(await this.safeMath.$mod(a, b)).to.be.bignumber.equal(a.mod(b)); }); it('when the dividend is a multiple of the divisor', async function () { const a = new BN('17034'); // 17034 == 5678 * 3 const b = new BN('5678'); - expect(await this.safeMath.doMod(a, b)).to.be.bignumber.equal(a.mod(b)); + expect(await this.safeMath.$mod(a, b)).to.be.bignumber.equal(a.mod(b)); }); }); @@ -287,7 +288,7 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('0'); - await expectRevert.unspecified(this.safeMath.doMod(a, b)); + await expectRevert.unspecified(this.safeMath.$mod(a, b)); }); }); }); @@ -298,14 +299,18 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('1234'); - expect(await this.safeMath.subWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.sub(b)); + expect(await this.safeMath.methods['$sub(uint256,uint256,string)'](a, b, 'MyErrorMessage')) + .to.be.bignumber.equal(a.sub(b)); }); it('reverts if subtraction result would be negative', async function () { const a = new BN('1234'); const b = new BN('5678'); - await expectRevert(this.safeMath.subWithMessage(a, b, 'MyErrorMessage'), 'MyErrorMessage'); + await expectRevert( + this.safeMath.methods['$sub(uint256,uint256,string)'](a, b, 'MyErrorMessage'), + 'MyErrorMessage', + ); }); }); @@ -314,28 +319,34 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('5678'); - expect(await this.safeMath.divWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.div(b)); + expect(await this.safeMath.methods['$div(uint256,uint256,string)'](a, b, 'MyErrorMessage')) + .to.be.bignumber.equal(a.div(b)); }); it('divides zero correctly', async function () { const a = new BN('0'); const b = new BN('5678'); - expect(await this.safeMath.divWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal('0'); + expect(await this.safeMath.methods['$div(uint256,uint256,string)'](a, b, 'MyErrorMessage')) + .to.be.bignumber.equal('0'); }); it('returns complete number result on non-even division', async function () { const a = new BN('7000'); const b = new BN('5678'); - expect(await this.safeMath.divWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal('1'); + expect(await this.safeMath.methods['$div(uint256,uint256,string)'](a, b, 'MyErrorMessage')) + .to.be.bignumber.equal('1'); }); it('reverts on division by zero', async function () { const a = new BN('5678'); const b = new BN('0'); - await expectRevert(this.safeMath.divWithMessage(a, b, 'MyErrorMessage'), 'MyErrorMessage'); + await expectRevert( + this.safeMath.methods['$div(uint256,uint256,string)'](a, b, 'MyErrorMessage'), + 'MyErrorMessage', + ); }); }); @@ -345,28 +356,32 @@ contract('SafeMath', function () { const a = new BN('284'); const b = new BN('5678'); - expect(await this.safeMath.modWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.mod(b)); + expect(await this.safeMath.methods['$mod(uint256,uint256,string)'](a, b, 'MyErrorMessage')) + .to.be.bignumber.equal(a.mod(b)); }); it('when the dividend is equal to the divisor', async function () { const a = new BN('5678'); const b = new BN('5678'); - expect(await this.safeMath.modWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.mod(b)); + expect(await this.safeMath.methods['$mod(uint256,uint256,string)'](a, b, 'MyErrorMessage')) + .to.be.bignumber.equal(a.mod(b)); }); it('when the dividend is larger than the divisor', async function () { const a = new BN('7000'); const b = new BN('5678'); - expect(await this.safeMath.modWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.mod(b)); + expect(await this.safeMath.methods['$mod(uint256,uint256,string)'](a, b, 'MyErrorMessage')) + .to.be.bignumber.equal(a.mod(b)); }); it('when the dividend is a multiple of the divisor', async function () { const a = new BN('17034'); // 17034 == 5678 * 3 const b = new BN('5678'); - expect(await this.safeMath.modWithMessage(a, b, 'MyErrorMessage')).to.be.bignumber.equal(a.mod(b)); + expect(await this.safeMath.methods['$mod(uint256,uint256,string)'](a, b, 'MyErrorMessage')) + .to.be.bignumber.equal(a.mod(b)); }); }); @@ -374,30 +389,37 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('0'); - await expectRevert(this.safeMath.modWithMessage(a, b, 'MyErrorMessage'), 'MyErrorMessage'); + await expectRevert( + this.safeMath.methods['$mod(uint256,uint256,string)'](a, b, 'MyErrorMessage'), + 'MyErrorMessage', + ); }); }); }); describe('memory leakage', function () { + beforeEach(async function () { + this.safeMathMemoryCheck = await SafeMathMemoryCheck.new(); + }); + it('add', async function () { - expect(await this.safeMath.addMemoryCheck()).to.be.bignumber.equal('0'); + expect(await this.safeMathMemoryCheck.$addMemoryCheck()).to.be.bignumber.equal('0'); }); it('sub', async function () { - expect(await this.safeMath.subMemoryCheck()).to.be.bignumber.equal('0'); + expect(await this.safeMathMemoryCheck.$subMemoryCheck()).to.be.bignumber.equal('0'); }); it('mul', async function () { - expect(await this.safeMath.mulMemoryCheck()).to.be.bignumber.equal('0'); + expect(await this.safeMathMemoryCheck.$mulMemoryCheck()).to.be.bignumber.equal('0'); }); it('div', async function () { - expect(await this.safeMath.divMemoryCheck()).to.be.bignumber.equal('0'); + expect(await this.safeMathMemoryCheck.$divMemoryCheck()).to.be.bignumber.equal('0'); }); it('mod', async function () { - expect(await this.safeMath.modMemoryCheck()).to.be.bignumber.equal('0'); + expect(await this.safeMathMemoryCheck.$modMemoryCheck()).to.be.bignumber.equal('0'); }); }); }); diff --git a/test/utils/math/SignedMath.test.js b/test/utils/math/SignedMath.test.js index f1bcc18b3..bbf492b20 100644 --- a/test/utils/math/SignedMath.test.js +++ b/test/utils/math/SignedMath.test.js @@ -2,33 +2,33 @@ const { BN, constants } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); const { MIN_INT256, MAX_INT256 } = constants; -const SignedMathMock = artifacts.require('SignedMathMock'); +const SignedMath = artifacts.require('$SignedMath'); contract('SignedMath', function () { const min = new BN('-1234'); const max = new BN('5678'); beforeEach(async function () { - this.math = await SignedMathMock.new(); + this.math = await SignedMath.new(); }); describe('max', function () { it('is correctly detected in first argument position', async function () { - expect(await this.math.max(max, min)).to.be.bignumber.equal(max); + expect(await this.math.$max(max, min)).to.be.bignumber.equal(max); }); it('is correctly detected in second argument position', async function () { - expect(await this.math.max(min, max)).to.be.bignumber.equal(max); + expect(await this.math.$max(min, max)).to.be.bignumber.equal(max); }); }); describe('min', function () { it('is correctly detected in first argument position', async function () { - expect(await this.math.min(min, max)).to.be.bignumber.equal(min); + expect(await this.math.$min(min, max)).to.be.bignumber.equal(min); }); it('is correctly detected in second argument position', async function () { - expect(await this.math.min(max, min)).to.be.bignumber.equal(min); + expect(await this.math.$min(max, min)).to.be.bignumber.equal(min); }); }); @@ -68,7 +68,7 @@ contract('SignedMath', function () { for (const x of valuesX) { for (const y of valuesY) { - expect(await this.math.average(x, y)) + expect(await this.math.$average(x, y)) .to.be.bignumber.equal(bnAverage(x, y), `Bad result for average(${x}, ${y})`); } } @@ -86,7 +86,7 @@ contract('SignedMath', function () { MAX_INT256, ]) { it(`correctly computes the absolute value of ${n}`, async function () { - expect(await this.math.abs(n)).to.be.bignumber.equal(n.abs()); + expect(await this.math.$abs(n)).to.be.bignumber.equal(n.abs()); }); } }); diff --git a/test/utils/math/SignedSafeMath.test.js b/test/utils/math/SignedSafeMath.test.js index c14d40be0..5702a4330 100644 --- a/test/utils/math/SignedSafeMath.test.js +++ b/test/utils/math/SignedSafeMath.test.js @@ -3,11 +3,11 @@ const { MAX_INT256, MIN_INT256 } = constants; const { expect } = require('chai'); -const SignedSafeMathMock = artifacts.require('SignedSafeMathMock'); +const SignedSafeMath = artifacts.require('$SignedSafeMath'); contract('SignedSafeMath', function () { beforeEach(async function () { - this.safeMath = await SignedSafeMathMock.new(); + this.safeMath = await SignedSafeMath.new(); }); async function testCommutative (fn, lhs, rhs, expected) { @@ -25,28 +25,28 @@ contract('SignedSafeMath', function () { const a = new BN('1234'); const b = new BN('5678'); - await testCommutative(this.safeMath.add, a, b, a.add(b)); + await testCommutative(this.safeMath.$add, a, b, a.add(b)); }); it('adds correctly if it does not overflow and the result is negative', async function () { const a = MAX_INT256; const b = MIN_INT256; - await testCommutative(this.safeMath.add, a, b, a.add(b)); + await testCommutative(this.safeMath.$add, a, b, a.add(b)); }); it('reverts on positive addition overflow', async function () { const a = MAX_INT256; const b = new BN('1'); - await testFailsCommutative(this.safeMath.add, a, b); + await testFailsCommutative(this.safeMath.$add, a, b); }); it('reverts on negative addition overflow', async function () { const a = MIN_INT256; const b = new BN('-1'); - await testFailsCommutative(this.safeMath.add, a, b); + await testFailsCommutative(this.safeMath.$add, a, b); }); }); @@ -55,7 +55,7 @@ contract('SignedSafeMath', function () { const a = new BN('5678'); const b = new BN('1234'); - const result = await this.safeMath.sub(a, b); + const result = await this.safeMath.$sub(a, b); expect(result).to.be.bignumber.equal(a.sub(b)); }); @@ -63,7 +63,7 @@ contract('SignedSafeMath', function () { const a = new BN('1234'); const b = new BN('5678'); - const result = await this.safeMath.sub(a, b); + const result = await this.safeMath.$sub(a, b); expect(result).to.be.bignumber.equal(a.sub(b)); }); @@ -71,14 +71,14 @@ contract('SignedSafeMath', function () { const a = MAX_INT256; const b = new BN('-1'); - await expectRevert.unspecified(this.safeMath.sub(a, b)); + await expectRevert.unspecified(this.safeMath.$sub(a, b)); }); it('reverts on negative subtraction overflow', async function () { const a = MIN_INT256; const b = new BN('1'); - await expectRevert.unspecified(this.safeMath.sub(a, b)); + await expectRevert.unspecified(this.safeMath.$sub(a, b)); }); }); @@ -87,28 +87,28 @@ contract('SignedSafeMath', function () { const a = new BN('5678'); const b = new BN('-1234'); - await testCommutative(this.safeMath.mul, a, b, a.mul(b)); + await testCommutative(this.safeMath.$mul, a, b, a.mul(b)); }); it('multiplies by zero correctly', async function () { const a = new BN('0'); const b = new BN('5678'); - await testCommutative(this.safeMath.mul, a, b, '0'); + await testCommutative(this.safeMath.$mul, a, b, '0'); }); it('reverts on multiplication overflow, positive operands', async function () { const a = MAX_INT256; const b = new BN('2'); - await testFailsCommutative(this.safeMath.mul, a, b); + await testFailsCommutative(this.safeMath.$mul, a, b); }); it('reverts when minimum integer is multiplied by -1', async function () { const a = MIN_INT256; const b = new BN('-1'); - await testFailsCommutative(this.safeMath.mul, a, b); + await testFailsCommutative(this.safeMath.$mul, a, b); }); }); @@ -117,7 +117,7 @@ contract('SignedSafeMath', function () { const a = new BN('-5678'); const b = new BN('5678'); - const result = await this.safeMath.div(a, b); + const result = await this.safeMath.$div(a, b); expect(result).to.be.bignumber.equal(a.div(b)); }); @@ -125,28 +125,28 @@ contract('SignedSafeMath', function () { const a = new BN('0'); const b = new BN('5678'); - expect(await this.safeMath.div(a, b)).to.be.bignumber.equal('0'); + expect(await this.safeMath.$div(a, b)).to.be.bignumber.equal('0'); }); it('returns complete number result on non-even division', async function () { const a = new BN('7000'); const b = new BN('5678'); - expect(await this.safeMath.div(a, b)).to.be.bignumber.equal('1'); + expect(await this.safeMath.$div(a, b)).to.be.bignumber.equal('1'); }); it('reverts on division by zero', async function () { const a = new BN('-5678'); const b = new BN('0'); - await expectRevert.unspecified(this.safeMath.div(a, b)); + await expectRevert.unspecified(this.safeMath.$div(a, b)); }); it('reverts on overflow, negative second', async function () { const a = new BN(MIN_INT256); const b = new BN('-1'); - await expectRevert.unspecified(this.safeMath.div(a, b)); + await expectRevert.unspecified(this.safeMath.$div(a, b)); }); }); }); diff --git a/test/utils/structs/BitMap.test.js b/test/utils/structs/BitMap.test.js index 4d85bcfbf..8a1470c5c 100644 --- a/test/utils/structs/BitMap.test.js +++ b/test/utils/structs/BitMap.test.js @@ -1,7 +1,7 @@ const { BN } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -const BitMap = artifacts.require('BitMapMock'); +const BitMap = artifacts.require('$BitMaps'); contract('BitMap', function () { const keyA = new BN('7891'); @@ -13,133 +13,133 @@ contract('BitMap', function () { }); it('starts empty', async function () { - expect(await this.bitmap.get(keyA)).to.equal(false); - expect(await this.bitmap.get(keyB)).to.equal(false); - expect(await this.bitmap.get(keyC)).to.equal(false); + expect(await this.bitmap.$get(0, keyA)).to.equal(false); + expect(await this.bitmap.$get(0, keyB)).to.equal(false); + expect(await this.bitmap.$get(0, keyC)).to.equal(false); }); describe('setTo', function () { it('set a key to true', async function () { - await this.bitmap.setTo(keyA, true); - expect(await this.bitmap.get(keyA)).to.equal(true); - expect(await this.bitmap.get(keyB)).to.equal(false); - expect(await this.bitmap.get(keyC)).to.equal(false); + await this.bitmap.$setTo(0, keyA, true); + expect(await this.bitmap.$get(0, keyA)).to.equal(true); + expect(await this.bitmap.$get(0, keyB)).to.equal(false); + expect(await this.bitmap.$get(0, keyC)).to.equal(false); }); it('set a key to false', async function () { - await this.bitmap.setTo(keyA, true); - await this.bitmap.setTo(keyA, false); - expect(await this.bitmap.get(keyA)).to.equal(false); - expect(await this.bitmap.get(keyB)).to.equal(false); - expect(await this.bitmap.get(keyC)).to.equal(false); + await this.bitmap.$setTo(0, keyA, true); + await this.bitmap.$setTo(0, keyA, false); + expect(await this.bitmap.$get(0, keyA)).to.equal(false); + expect(await this.bitmap.$get(0, keyB)).to.equal(false); + expect(await this.bitmap.$get(0, keyC)).to.equal(false); }); it('set several consecutive keys', async function () { - await this.bitmap.setTo(keyA.addn(0), true); - await this.bitmap.setTo(keyA.addn(1), true); - await this.bitmap.setTo(keyA.addn(2), true); - await this.bitmap.setTo(keyA.addn(3), true); - await this.bitmap.setTo(keyA.addn(4), true); - await this.bitmap.setTo(keyA.addn(2), false); - await this.bitmap.setTo(keyA.addn(4), false); - expect(await this.bitmap.get(keyA.addn(0))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(1))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(2))).to.equal(false); - expect(await this.bitmap.get(keyA.addn(3))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(4))).to.equal(false); + await this.bitmap.$setTo(0, keyA.addn(0), true); + await this.bitmap.$setTo(0, keyA.addn(1), true); + await this.bitmap.$setTo(0, keyA.addn(2), true); + await this.bitmap.$setTo(0, keyA.addn(3), true); + await this.bitmap.$setTo(0, keyA.addn(4), true); + await this.bitmap.$setTo(0, keyA.addn(2), false); + await this.bitmap.$setTo(0, keyA.addn(4), false); + expect(await this.bitmap.$get(0, keyA.addn(0))).to.equal(true); + expect(await this.bitmap.$get(0, keyA.addn(1))).to.equal(true); + expect(await this.bitmap.$get(0, keyA.addn(2))).to.equal(false); + expect(await this.bitmap.$get(0, keyA.addn(3))).to.equal(true); + expect(await this.bitmap.$get(0, keyA.addn(4))).to.equal(false); }); }); describe('set', function () { it('adds a key', async function () { - await this.bitmap.set(keyA); - expect(await this.bitmap.get(keyA)).to.equal(true); - expect(await this.bitmap.get(keyB)).to.equal(false); - expect(await this.bitmap.get(keyC)).to.equal(false); + await this.bitmap.$set(0, keyA); + expect(await this.bitmap.$get(0, keyA)).to.equal(true); + expect(await this.bitmap.$get(0, keyB)).to.equal(false); + expect(await this.bitmap.$get(0, keyC)).to.equal(false); }); it('adds several keys', async function () { - await this.bitmap.set(keyA); - await this.bitmap.set(keyB); - expect(await this.bitmap.get(keyA)).to.equal(true); - expect(await this.bitmap.get(keyB)).to.equal(true); - expect(await this.bitmap.get(keyC)).to.equal(false); + await this.bitmap.$set(0, keyA); + await this.bitmap.$set(0, keyB); + expect(await this.bitmap.$get(0, keyA)).to.equal(true); + expect(await this.bitmap.$get(0, keyB)).to.equal(true); + expect(await this.bitmap.$get(0, keyC)).to.equal(false); }); it('adds several consecutive keys', async function () { - await this.bitmap.set(keyA.addn(0)); - await this.bitmap.set(keyA.addn(1)); - await this.bitmap.set(keyA.addn(3)); - expect(await this.bitmap.get(keyA.addn(0))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(1))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(2))).to.equal(false); - expect(await this.bitmap.get(keyA.addn(3))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(4))).to.equal(false); + await this.bitmap.$set(0, keyA.addn(0)); + await this.bitmap.$set(0, keyA.addn(1)); + await this.bitmap.$set(0, keyA.addn(3)); + expect(await this.bitmap.$get(0, keyA.addn(0))).to.equal(true); + expect(await this.bitmap.$get(0, keyA.addn(1))).to.equal(true); + expect(await this.bitmap.$get(0, keyA.addn(2))).to.equal(false); + expect(await this.bitmap.$get(0, keyA.addn(3))).to.equal(true); + expect(await this.bitmap.$get(0, keyA.addn(4))).to.equal(false); }); }); describe('unset', function () { it('removes added keys', async function () { - await this.bitmap.set(keyA); - await this.bitmap.set(keyB); - await this.bitmap.unset(keyA); - expect(await this.bitmap.get(keyA)).to.equal(false); - expect(await this.bitmap.get(keyB)).to.equal(true); - expect(await this.bitmap.get(keyC)).to.equal(false); + await this.bitmap.$set(0, keyA); + await this.bitmap.$set(0, keyB); + await this.bitmap.$unset(0, keyA); + expect(await this.bitmap.$get(0, keyA)).to.equal(false); + expect(await this.bitmap.$get(0, keyB)).to.equal(true); + expect(await this.bitmap.$get(0, keyC)).to.equal(false); }); it('removes consecutive added keys', async function () { - await this.bitmap.set(keyA.addn(0)); - await this.bitmap.set(keyA.addn(1)); - await this.bitmap.set(keyA.addn(3)); - await this.bitmap.unset(keyA.addn(1)); - expect(await this.bitmap.get(keyA.addn(0))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(1))).to.equal(false); - expect(await this.bitmap.get(keyA.addn(2))).to.equal(false); - expect(await this.bitmap.get(keyA.addn(3))).to.equal(true); - expect(await this.bitmap.get(keyA.addn(4))).to.equal(false); + await this.bitmap.$set(0, keyA.addn(0)); + await this.bitmap.$set(0, keyA.addn(1)); + await this.bitmap.$set(0, keyA.addn(3)); + await this.bitmap.$unset(0, keyA.addn(1)); + expect(await this.bitmap.$get(0, keyA.addn(0))).to.equal(true); + expect(await this.bitmap.$get(0, keyA.addn(1))).to.equal(false); + expect(await this.bitmap.$get(0, keyA.addn(2))).to.equal(false); + expect(await this.bitmap.$get(0, keyA.addn(3))).to.equal(true); + expect(await this.bitmap.$get(0, keyA.addn(4))).to.equal(false); }); it('adds and removes multiple keys', async function () { // [] - await this.bitmap.set(keyA); - await this.bitmap.set(keyC); + await this.bitmap.$set(0, keyA); + await this.bitmap.$set(0, keyC); // [A, C] - await this.bitmap.unset(keyA); - await this.bitmap.unset(keyB); + await this.bitmap.$unset(0, keyA); + await this.bitmap.$unset(0, keyB); // [C] - await this.bitmap.set(keyB); + await this.bitmap.$set(0, keyB); // [C, B] - await this.bitmap.set(keyA); - await this.bitmap.unset(keyC); + await this.bitmap.$set(0, keyA); + await this.bitmap.$unset(0, keyC); // [A, B] - await this.bitmap.set(keyA); - await this.bitmap.set(keyB); + await this.bitmap.$set(0, keyA); + await this.bitmap.$set(0, keyB); // [A, B] - await this.bitmap.set(keyC); - await this.bitmap.unset(keyA); + await this.bitmap.$set(0, keyC); + await this.bitmap.$unset(0, keyA); // [B, C] - await this.bitmap.set(keyA); - await this.bitmap.unset(keyB); + await this.bitmap.$set(0, keyA); + await this.bitmap.$unset(0, keyB); // [A, C] - expect(await this.bitmap.get(keyA)).to.equal(true); - expect(await this.bitmap.get(keyB)).to.equal(false); - expect(await this.bitmap.get(keyC)).to.equal(true); + expect(await this.bitmap.$get(0, keyA)).to.equal(true); + expect(await this.bitmap.$get(0, keyB)).to.equal(false); + expect(await this.bitmap.$get(0, keyC)).to.equal(true); }); }); }); diff --git a/test/utils/structs/DoubleEndedQueue.test.js b/test/utils/structs/DoubleEndedQueue.test.js index 667df77ca..8900663d8 100644 --- a/test/utils/structs/DoubleEndedQueue.test.js +++ b/test/utils/structs/DoubleEndedQueue.test.js @@ -1,14 +1,12 @@ const { expectEvent } = require('@openzeppelin/test-helpers'); const { expectRevertCustomError } = require('../../helpers/customError'); -const Bytes32DequeMock = artifacts.require('Bytes32DequeMock'); +const DoubleEndedQueue = artifacts.require('$DoubleEndedQueue'); /** Rebuild the content of the deque as a JS array. */ -async function getContent (deque) { - const length = await deque.length().then(bn => bn.toNumber()); - const values = await Promise.all(Array(length).fill().map((_, i) => deque.at(i))); - return values; -} +const getContent = (deque) => deque.$length(0).then(bn => + Promise.all(Array(bn.toNumber()).fill().map((_, i) => deque.$at(0, i))), +); contract('DoubleEndedQueue', function () { const bytesA = '0xdeadbeef'.padEnd(66, '0'); @@ -17,53 +15,53 @@ contract('DoubleEndedQueue', function () { const bytesD = '0x171717'.padEnd(66, '0'); beforeEach(async function () { - this.deque = await Bytes32DequeMock.new(); + this.deque = await DoubleEndedQueue.new(); }); describe('when empty', function () { it('getters', async function () { - expect(await this.deque.empty()).to.be.equal(true); + expect(await this.deque.$empty(0)).to.be.equal(true); expect(await getContent(this.deque)).to.have.ordered.members([]); }); it('reverts on accesses', async function () { - await expectRevertCustomError(this.deque.popBack(), 'Empty()'); - await expectRevertCustomError(this.deque.popFront(), 'Empty()'); - await expectRevertCustomError(this.deque.back(), 'Empty()'); - await expectRevertCustomError(this.deque.front(), 'Empty()'); + await expectRevertCustomError(this.deque.$popBack(0), 'Empty()'); + await expectRevertCustomError(this.deque.$popFront(0), 'Empty()'); + await expectRevertCustomError(this.deque.$back(0), 'Empty()'); + await expectRevertCustomError(this.deque.$front(0), 'Empty()'); }); }); describe('when not empty', function () { beforeEach(async function () { - await this.deque.pushBack(bytesB); - await this.deque.pushFront(bytesA); - await this.deque.pushBack(bytesC); + await this.deque.$pushBack(0, bytesB); + await this.deque.$pushFront(0, bytesA); + await this.deque.$pushBack(0, bytesC); this.content = [ bytesA, bytesB, bytesC ]; }); it('getters', async function () { - expect(await this.deque.empty()).to.be.equal(false); - expect(await this.deque.length()).to.be.bignumber.equal(this.content.length.toString()); - expect(await this.deque.front()).to.be.equal(this.content[0]); - expect(await this.deque.back()).to.be.equal(this.content[this.content.length - 1]); + expect(await this.deque.$empty(0)).to.be.equal(false); + expect(await this.deque.$length(0)).to.be.bignumber.equal(this.content.length.toString()); + expect(await this.deque.$front(0)).to.be.equal(this.content[0]); + expect(await this.deque.$back(0)).to.be.equal(this.content[this.content.length - 1]); expect(await getContent(this.deque)).to.have.ordered.members(this.content); }); it('out of bounds access', async function () { - await expectRevertCustomError(this.deque.at(this.content.length), 'OutOfBounds()'); + await expectRevertCustomError(this.deque.$at(0, this.content.length), 'OutOfBounds()'); }); describe('push', function () { it('front', async function () { - await this.deque.pushFront(bytesD); + await this.deque.$pushFront(0, bytesD); this.content.unshift(bytesD); // add element at the beginning expect(await getContent(this.deque)).to.have.ordered.members(this.content); }); it('back', async function () { - await this.deque.pushBack(bytesD); + await this.deque.$pushBack(0, bytesD); this.content.push(bytesD); // add element at the end expect(await getContent(this.deque)).to.have.ordered.members(this.content); @@ -73,23 +71,23 @@ contract('DoubleEndedQueue', function () { describe('pop', function () { it('front', async function () { const value = this.content.shift(); // remove first element - expectEvent(await this.deque.popFront(), 'OperationResult', { value }); + expectEvent(await this.deque.$popFront(0), 'return$popFront', { value }); expect(await getContent(this.deque)).to.have.ordered.members(this.content); }); it('back', async function () { const value = this.content.pop(); // remove last element - expectEvent(await this.deque.popBack(), 'OperationResult', { value }); + expectEvent(await this.deque.$popBack(0), 'return$popBack', { value }); expect(await getContent(this.deque)).to.have.ordered.members(this.content); }); }); it('clear', async function () { - await this.deque.clear(); + await this.deque.$clear(0); - expect(await this.deque.empty()).to.be.equal(true); + expect(await this.deque.$empty(0)).to.be.equal(true); expect(await getContent(this.deque)).to.have.ordered.members([]); }); }); diff --git a/test/utils/structs/EnumerableMap.behavior.js b/test/utils/structs/EnumerableMap.behavior.js index b1d0d0dce..4d698f334 100644 --- a/test/utils/structs/EnumerableMap.behavior.js +++ b/test/utils/structs/EnumerableMap.behavior.js @@ -3,21 +3,27 @@ const { expect } = require('chai'); const zip = require('lodash.zip'); -function shouldBehaveLikeMap (keys, values, zeroValue) { - const [keyA, keyB, keyC] = keys; - const [valueA, valueB, valueC] = values; +function shouldBehaveLikeMap ( + keys, + values, + zeroValue, + methods, + events, +) { + const [ keyA, keyB, keyC ] = keys; + const [ valueA, valueB, valueC ] = values; async function expectMembersMatch (map, keys, values) { expect(keys.length).to.equal(values.length); await Promise.all(keys.map(async key => - expect(await map.contains(key)).to.equal(true), + expect(await methods.contains(map, key)).to.equal(true), )); - expect(await map.length()).to.bignumber.equal(keys.length.toString()); + expect(await methods.length(map)).to.bignumber.equal(keys.length.toString()); expect( - (await Promise.all(keys.map(key => map.get(key)))).map(k => k.toString()), + (await Promise.all(keys.map(key => methods.get(map, key)))).map(k => k.toString()), ).to.have.same.members( values.map(value => value.toString()), ); @@ -25,48 +31,47 @@ function shouldBehaveLikeMap (keys, values, zeroValue) { // To compare key-value pairs, we zip keys and values, and convert BNs to // strings to workaround Chai limitations when dealing with nested arrays expect(await Promise.all([...Array(keys.length).keys()].map(async (index) => { - const entry = await map.at(index); - return [entry.key.toString(), entry.value.toString()]; + const entry = await methods.at(map, index); + return [ entry[0].toString(), entry[1].toString() ]; }))).to.have.same.deep.members( zip(keys.map(k => k.toString()), values.map(v => v.toString())), ); } it('starts empty', async function () { - expect(await this.map.contains(keyA)).to.equal(false); + expect(await methods.contains(this.map, keyA)).to.equal(false); await expectMembersMatch(this.map, [], []); }); describe('set', function () { it('adds a key', async function () { - const receipt = await this.map.set(keyA, valueA); - expectEvent(receipt, 'OperationResult', { result: true }); + const receipt = await methods.set(this.map, keyA, valueA); + expectEvent(receipt, events.setReturn, { ret0: true }); await expectMembersMatch(this.map, [keyA], [valueA]); }); it('adds several keys', async function () { - await this.map.set(keyA, valueA); - await this.map.set(keyB, valueB); + await methods.set(this.map, keyA, valueA); + await methods.set(this.map, keyB, valueB); await expectMembersMatch(this.map, [keyA, keyB], [valueA, valueB]); - expect(await this.map.contains(keyC)).to.equal(false); + expect(await methods.contains(this.map, keyC)).to.equal(false); }); it('returns false when adding keys already in the set', async function () { - await this.map.set(keyA, valueA); + await methods.set(this.map, keyA, valueA); - const receipt = (await this.map.set(keyA, valueA)); - expectEvent(receipt, 'OperationResult', { result: false }); + const receipt = await methods.set(this.map, keyA, valueA); + expectEvent(receipt, events.setReturn, { ret0: false }); await expectMembersMatch(this.map, [keyA], [valueA]); }); it('updates values for keys already in the set', async function () { - await this.map.set(keyA, valueA); - - await this.map.set(keyA, valueB); + await methods.set(this.map, keyA, valueA); + await methods.set(this.map, keyA, valueB); await expectMembersMatch(this.map, [keyA], [valueB]); }); @@ -74,101 +79,108 @@ function shouldBehaveLikeMap (keys, values, zeroValue) { describe('remove', function () { it('removes added keys', async function () { - await this.map.set(keyA, valueA); + await methods.set(this.map, keyA, valueA); - const receipt = await this.map.remove(keyA); - expectEvent(receipt, 'OperationResult', { result: true }); + const receipt = await methods.remove(this.map, keyA); + expectEvent(receipt, events.removeReturn, { ret0: true }); - expect(await this.map.contains(keyA)).to.equal(false); + expect(await methods.contains(this.map, keyA)).to.equal(false); await expectMembersMatch(this.map, [], []); }); it('returns false when removing keys not in the set', async function () { - const receipt = await this.map.remove(keyA); - expectEvent(receipt, 'OperationResult', { result: false }); + const receipt = await methods.remove(this.map, keyA); + expectEvent(receipt, events.removeReturn, { ret0: false }); - expect(await this.map.contains(keyA)).to.equal(false); + expect(await methods.contains(this.map, keyA)).to.equal(false); }); it('adds and removes multiple keys', async function () { // [] - await this.map.set(keyA, valueA); - await this.map.set(keyC, valueC); + await methods.set(this.map, keyA, valueA); + await methods.set(this.map, keyC, valueC); // [A, C] - await this.map.remove(keyA); - await this.map.remove(keyB); + await methods.remove(this.map, keyA); + await methods.remove(this.map, keyB); // [C] - await this.map.set(keyB, valueB); + await methods.set(this.map, keyB, valueB); // [C, B] - await this.map.set(keyA, valueA); - await this.map.remove(keyC); + await methods.set(this.map, keyA, valueA); + await methods.remove(this.map, keyC); // [A, B] - await this.map.set(keyA, valueA); - await this.map.set(keyB, valueB); + await methods.set(this.map, keyA, valueA); + await methods.set(this.map, keyB, valueB); // [A, B] - await this.map.set(keyC, valueC); - await this.map.remove(keyA); + await methods.set(this.map, keyC, valueC); + await methods.remove(this.map, keyA); // [B, C] - await this.map.set(keyA, valueA); - await this.map.remove(keyB); + await methods.set(this.map, keyA, valueA); + await methods.remove(this.map, keyB); // [A, C] await expectMembersMatch(this.map, [keyA, keyC], [valueA, valueC]); - expect(await this.map.contains(keyB)).to.equal(false); + expect(await methods.contains(this.map, keyA)).to.equal(true); + expect(await methods.contains(this.map, keyB)).to.equal(false); + expect(await methods.contains(this.map, keyC)).to.equal(true); }); }); describe('read', function () { beforeEach(async function () { - await this.map.set(keyA, valueA); + await methods.set(this.map, keyA, valueA); }); describe('get', function () { it('existing value', async function () { expect( - (await this.map.get(keyA)).toString(), + await methods.get(this.map, keyA).then(r => r.toString()), ).to.be.equal(valueA.toString()); }); it('missing value', async function () { - await expectRevert(this.map.get(keyB), 'EnumerableMap: nonexistent key'); + await expectRevert( + methods.get(this.map, keyB), + 'EnumerableMap: nonexistent key', + ); }); }); describe('get with message', function () { it('existing value', async function () { expect( - (await this.map.getWithMessage(keyA, 'custom error string')) - .toString(), + await methods.getWithMessage(this.map, keyA, 'custom error string').then(r => r.toString()), ).to.be.equal(valueA.toString()); }); it('missing value', async function () { - await expectRevert(this.map.getWithMessage(keyB, 'custom error string'), 'custom error string'); + await expectRevert( + methods.getWithMessage(this.map, keyB, 'custom error string'), + 'custom error string', + ); }); }); describe('tryGet', function () { it('existing value', async function () { - const result = await this.map.tryGet(keyA); + const result = await methods.tryGet(this.map, keyA); expect(result['0']).to.be.equal(true); expect(result['1'].toString()).to.be.equal(valueA.toString()); }); it('missing value', async function () { - const result = await this.map.tryGet(keyB); + const result = await methods.tryGet(this.map, keyB); expect(result['0']).to.be.equal(false); expect(result['1'].toString()).to.be.equal(zeroValue.toString()); }); diff --git a/test/utils/structs/EnumerableMap.test.js b/test/utils/structs/EnumerableMap.test.js index 58f4eb861..2587f7595 100644 --- a/test/utils/structs/EnumerableMap.test.js +++ b/test/utils/structs/EnumerableMap.test.js @@ -1,13 +1,14 @@ const { BN, constants } = require('@openzeppelin/test-helpers'); +const { mapValues } = require('../../helpers/map-values'); -const AddressToUintMapMock = artifacts.require('AddressToUintMapMock'); -const UintToAddressMapMock = artifacts.require('UintToAddressMapMock'); -const Bytes32ToBytes32MapMock = artifacts.require('Bytes32ToBytes32MapMock'); -const UintToUintMapMock = artifacts.require('UintToUintMapMock'); -const Bytes32ToUintMapMock = artifacts.require('Bytes32ToUintMapMock'); +const EnumerableMap = artifacts.require('$EnumerableMap'); const { shouldBehaveLikeMap } = require('./EnumerableMap.behavior'); +const getMethods = (ms) => { + return mapValues(ms, m => (self, ...args) => self.methods[m](0, ...args)); +}; + contract('EnumerableMap', function (accounts) { const [ accountA, accountB, accountC ] = accounts; @@ -19,68 +20,122 @@ contract('EnumerableMap', function (accounts) { const bytesB = '0x0123456789'.padEnd(66, '0'); const bytesC = '0x42424242'.padEnd(66, '0'); + beforeEach(async function () { + this.map = await EnumerableMap.new(); + }); + // AddressToUintMap describe('AddressToUintMap', function () { - beforeEach(async function () { - this.map = await AddressToUintMapMock.new(); - }); - shouldBehaveLikeMap( [ accountA, accountB, accountC ], [ keyA, keyB, keyC ], new BN('0'), + getMethods({ + set: '$set(uint256,address,uint256)', + get: '$get(uint256,address)', + getWithMessage: '$get(uint256,address,string)', + tryGet: '$tryGet(uint256,address)', + remove: '$remove(uint256,address)', + length: '$length_EnumerableMap_AddressToUintMap(uint256)', + at: '$at_EnumerableMap_AddressToUintMap(uint256,uint256)', + contains: '$contains(uint256,address)', + }), + { + setReturn: 'return$set_EnumerableMap_AddressToUintMap_address_uint256', + removeReturn: 'return$remove_EnumerableMap_AddressToUintMap_address', + }, ); }); // UintToAddressMap describe('UintToAddressMap', function () { - beforeEach(async function () { - this.map = await UintToAddressMapMock.new(); - }); - shouldBehaveLikeMap( [ keyA, keyB, keyC ], [ accountA, accountB, accountC ], constants.ZERO_ADDRESS, + getMethods({ + set: '$set(uint256,uint256,address)', + get: '$get_EnumerableMap_UintToAddressMap(uint256,uint256)', + getWithMessage: '$get_EnumerableMap_UintToAddressMap(uint256,uint256,string)', + tryGet: '$tryGet_EnumerableMap_UintToAddressMap(uint256,uint256)', + remove: '$remove_EnumerableMap_UintToAddressMap(uint256,uint256)', + length: '$length_EnumerableMap_UintToAddressMap(uint256)', + at: '$at_EnumerableMap_UintToAddressMap(uint256,uint256)', + contains: '$contains_EnumerableMap_UintToAddressMap(uint256,uint256)', + }), + { + setReturn: 'return$set_EnumerableMap_UintToAddressMap_uint256_address', + removeReturn: 'return$remove_EnumerableMap_UintToAddressMap_uint256', + }, ); }); // Bytes32ToBytes32Map describe('Bytes32ToBytes32Map', function () { - beforeEach(async function () { - this.map = await Bytes32ToBytes32MapMock.new(); - }); - shouldBehaveLikeMap( [ keyA, keyB, keyC ].map(k => '0x' + k.toString(16).padEnd(64, '0')), [ bytesA, bytesB, bytesC ], constants.ZERO_BYTES32, + getMethods({ + set: '$set(uint256,bytes32,bytes32)', + get: '$get_EnumerableMap_Bytes32ToBytes32Map(uint256,bytes32)', + getWithMessage: '$get_EnumerableMap_Bytes32ToBytes32Map(uint256,bytes32,string)', + tryGet: '$tryGet_EnumerableMap_Bytes32ToBytes32Map(uint256,bytes32)', + remove: '$remove_EnumerableMap_Bytes32ToBytes32Map(uint256,bytes32)', + length: '$length_EnumerableMap_Bytes32ToBytes32Map(uint256)', + at: '$at_EnumerableMap_Bytes32ToBytes32Map(uint256,uint256)', + contains: '$contains_EnumerableMap_Bytes32ToBytes32Map(uint256,bytes32)', + }), + { + setReturn: 'return$set_EnumerableMap_Bytes32ToBytes32Map_bytes32_bytes32', + removeReturn: 'return$remove_EnumerableMap_Bytes32ToBytes32Map_bytes32', + }, ); }); // UintToUintMap describe('UintToUintMap', function () { - beforeEach(async function () { - this.map = await UintToUintMapMock.new(); - }); - shouldBehaveLikeMap( [ keyA, keyB, keyC ], [ keyA, keyB, keyC ].map(k => k.add(new BN('1332'))), new BN('0'), + getMethods({ + set: '$set(uint256,uint256,uint256)', + get: '$get_EnumerableMap_UintToUintMap(uint256,uint256)', + getWithMessage: '$get_EnumerableMap_UintToUintMap(uint256,uint256,string)', + tryGet: '$tryGet_EnumerableMap_UintToUintMap(uint256,uint256)', + remove: '$remove_EnumerableMap_UintToUintMap(uint256,uint256)', + length: '$length_EnumerableMap_UintToUintMap(uint256)', + at: '$at_EnumerableMap_UintToUintMap(uint256,uint256)', + contains: '$contains_EnumerableMap_UintToUintMap(uint256,uint256)', + }), + { + setReturn: 'return$set_EnumerableMap_UintToUintMap_uint256_uint256', + removeReturn: 'return$remove_EnumerableMap_UintToUintMap_uint256', + }, ); }); // Bytes32ToUintMap describe('Bytes32ToUintMap', function () { - beforeEach(async function () { - this.map = await Bytes32ToUintMapMock.new(); - }); - shouldBehaveLikeMap( [ bytesA, bytesB, bytesC ], [ keyA, keyB, keyC ], new BN('0'), + getMethods({ + set: '$set(uint256,bytes32,uint256)', + get: '$get_EnumerableMap_Bytes32ToUintMap(uint256,bytes32)', + getWithMessage: '$get_EnumerableMap_Bytes32ToUintMap(uint256,bytes32,string)', + tryGet: '$tryGet_EnumerableMap_Bytes32ToUintMap(uint256,bytes32)', + remove: '$remove_EnumerableMap_Bytes32ToUintMap(uint256,bytes32)', + length: '$length_EnumerableMap_Bytes32ToUintMap(uint256)', + at: '$at_EnumerableMap_Bytes32ToUintMap(uint256,uint256)', + contains: '$contains_EnumerableMap_Bytes32ToUintMap(uint256,bytes32)', + }), + { + setReturn: 'return$set_EnumerableMap_Bytes32ToUintMap_bytes32_uint256', + removeReturn: 'return$remove_EnumerableMap_Bytes32ToUintMap_bytes32', + }, ); }); }); diff --git a/test/utils/structs/EnumerableSet.behavior.js b/test/utils/structs/EnumerableSet.behavior.js index 17e086671..db56a2eca 100644 --- a/test/utils/structs/EnumerableSet.behavior.js +++ b/test/utils/structs/EnumerableSet.behavior.js @@ -1,24 +1,30 @@ const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -function shouldBehaveLikeSet (valueA, valueB, valueC) { +function shouldBehaveLikeSet ( + values, + methods, + events, +) { + const [ valueA, valueB, valueC ] = values; + async function expectMembersMatch (set, values) { - const contains = await Promise.all(values.map(value => set.contains(value))); + const contains = await Promise.all(values.map(value => methods.contains(set, value))); expect(contains.every(Boolean)).to.be.equal(true); - const length = await set.length(); + const length = await methods.length(set); expect(length).to.bignumber.equal(values.length.toString()); // To compare values we convert to strings to workaround Chai // limitations when dealing with nested arrays (required for BNs) - const indexedValues = await Promise.all(Array(values.length).fill().map((_, index) => set.at(index))); + const indexedValues = await Promise.all(Array(values.length).fill().map((_, index) => methods.at(set, index))); expect( indexedValues.map(v => v.toString()), ).to.have.same.members( values.map(v => v.toString()), ); - const returnedValues = await set.values(); + const returnedValues = await methods.values(set); expect( returnedValues.map(v => v.toString()), ).to.have.same.members( @@ -27,32 +33,32 @@ function shouldBehaveLikeSet (valueA, valueB, valueC) { } it('starts empty', async function () { - expect(await this.set.contains(valueA)).to.equal(false); + expect(await methods.contains(this.set, valueA)).to.equal(false); await expectMembersMatch(this.set, []); }); describe('add', function () { it('adds a value', async function () { - const receipt = await this.set.add(valueA); - expectEvent(receipt, 'OperationResult', { result: true }); + const receipt = await methods.add(this.set, valueA); + expectEvent(receipt, events.addReturn, { ret0: true }); await expectMembersMatch(this.set, [valueA]); }); it('adds several values', async function () { - await this.set.add(valueA); - await this.set.add(valueB); + await methods.add(this.set, valueA); + await methods.add(this.set, valueB); await expectMembersMatch(this.set, [valueA, valueB]); - expect(await this.set.contains(valueC)).to.equal(false); + expect(await methods.contains(this.set, valueC)).to.equal(false); }); it('returns false when adding values already in the set', async function () { - await this.set.add(valueA); + await methods.add(this.set, valueA); - const receipt = (await this.set.add(valueA)); - expectEvent(receipt, 'OperationResult', { result: false }); + const receipt = await methods.add(this.set, valueA); + expectEvent(receipt, events.addReturn, { ret0: false }); await expectMembersMatch(this.set, [valueA]); }); @@ -60,68 +66,68 @@ function shouldBehaveLikeSet (valueA, valueB, valueC) { describe('at', function () { it('reverts when retrieving non-existent elements', async function () { - await expectRevert.unspecified(this.set.at(0)); + await expectRevert.unspecified(methods.at(this.set, 0)); }); }); describe('remove', function () { it('removes added values', async function () { - await this.set.add(valueA); + await methods.add(this.set, valueA); - const receipt = await this.set.remove(valueA); - expectEvent(receipt, 'OperationResult', { result: true }); + const receipt = await methods.remove(this.set, valueA); + expectEvent(receipt, events.removeReturn, { ret0: true }); - expect(await this.set.contains(valueA)).to.equal(false); + expect(await methods.contains(this.set, valueA)).to.equal(false); await expectMembersMatch(this.set, []); }); it('returns false when removing values not in the set', async function () { - const receipt = await this.set.remove(valueA); - expectEvent(receipt, 'OperationResult', { result: false }); + const receipt = await methods.remove(this.set, valueA); + expectEvent(receipt, events.removeReturn, { ret0: false }); - expect(await this.set.contains(valueA)).to.equal(false); + expect(await methods.contains(this.set, valueA)).to.equal(false); }); it('adds and removes multiple values', async function () { // [] - await this.set.add(valueA); - await this.set.add(valueC); + await methods.add(this.set, valueA); + await methods.add(this.set, valueC); // [A, C] - await this.set.remove(valueA); - await this.set.remove(valueB); + await methods.remove(this.set, valueA); + await methods.remove(this.set, valueB); // [C] - await this.set.add(valueB); + await methods.add(this.set, valueB); // [C, B] - await this.set.add(valueA); - await this.set.remove(valueC); + await methods.add(this.set, valueA); + await methods.remove(this.set, valueC); // [A, B] - await this.set.add(valueA); - await this.set.add(valueB); + await methods.add(this.set, valueA); + await methods.add(this.set, valueB); // [A, B] - await this.set.add(valueC); - await this.set.remove(valueA); + await methods.add(this.set, valueC); + await methods.remove(this.set, valueA); // [B, C] - await this.set.add(valueA); - await this.set.remove(valueB); + await methods.add(this.set, valueA); + await methods.remove(this.set, valueB); // [A, C] await expectMembersMatch(this.set, [valueA, valueC]); - expect(await this.set.contains(valueB)).to.equal(false); + expect(await methods.contains(this.set, valueB)).to.equal(false); }); }); } diff --git a/test/utils/structs/EnumerableSet.test.js b/test/utils/structs/EnumerableSet.test.js index 2b7d0a3d6..27f1c731e 100644 --- a/test/utils/structs/EnumerableSet.test.js +++ b/test/utils/structs/EnumerableSet.test.js @@ -1,46 +1,71 @@ -const { BN } = require('@openzeppelin/test-helpers'); - -const EnumerableBytes32SetMock = artifacts.require('EnumerableBytes32SetMock'); -const EnumerableAddressSetMock = artifacts.require('EnumerableAddressSetMock'); -const EnumerableUintSetMock = artifacts.require('EnumerableUintSetMock'); +const EnumerableSet = artifacts.require('$EnumerableSet'); +const { mapValues } = require('../../helpers/map-values'); const { shouldBehaveLikeSet } = require('./EnumerableSet.behavior'); +const getMethods = (ms) => { + return mapValues(ms, m => (self, ...args) => self.methods[m](0, ...args)); +}; + contract('EnumerableSet', function (accounts) { + beforeEach(async function () { + this.set = await EnumerableSet.new(); + }); + // Bytes32Set describe('EnumerableBytes32Set', function () { - const bytesA = '0xdeadbeef'.padEnd(66, '0'); - const bytesB = '0x0123456789'.padEnd(66, '0'); - const bytesC = '0x42424242'.padEnd(66, '0'); - - beforeEach(async function () { - this.set = await EnumerableBytes32SetMock.new(); - }); - - shouldBehaveLikeSet(bytesA, bytesB, bytesC); + shouldBehaveLikeSet( + [ '0xdeadbeef', '0x0123456789', '0x42424242' ].map(e => e.padEnd(66, '0')), + getMethods({ + add: '$add(uint256,bytes32)', + remove: '$remove(uint256,bytes32)', + contains: '$contains(uint256,bytes32)', + length: '$length_EnumerableSet_Bytes32Set(uint256)', + at: '$at_EnumerableSet_Bytes32Set(uint256,uint256)', + values: '$values_EnumerableSet_Bytes32Set(uint256)', + }), + { + addReturn: 'return$add_EnumerableSet_Bytes32Set_bytes32', + removeReturn: 'return$remove_EnumerableSet_Bytes32Set_bytes32', + }, + ); }); // AddressSet describe('EnumerableAddressSet', function () { - const [accountA, accountB, accountC] = accounts; - - beforeEach(async function () { - this.set = await EnumerableAddressSetMock.new(); - }); - - shouldBehaveLikeSet(accountA, accountB, accountC); + shouldBehaveLikeSet( + accounts, + getMethods({ + add: '$add(uint256,address)', + remove: '$remove(uint256,address)', + contains: '$contains(uint256,address)', + length: '$length_EnumerableSet_AddressSet(uint256)', + at: '$at_EnumerableSet_AddressSet(uint256,uint256)', + values: '$values_EnumerableSet_AddressSet(uint256)', + }), + { + addReturn: 'return$add_EnumerableSet_AddressSet_address', + removeReturn: 'return$remove_EnumerableSet_AddressSet_address', + }, + ); }); // UintSet describe('EnumerableUintSet', function () { - const uintA = new BN('1234'); - const uintB = new BN('5678'); - const uintC = new BN('9101112'); - - beforeEach(async function () { - this.set = await EnumerableUintSetMock.new(); - }); - - shouldBehaveLikeSet(uintA, uintB, uintC); + shouldBehaveLikeSet( + [ 1234, 5678, 9101112 ].map(e => web3.utils.toBN(e)), + getMethods({ + add: '$add(uint256,uint256)', + remove: '$remove(uint256,uint256)', + contains: '$contains(uint256,uint256)', + length: '$length_EnumerableSet_UintSet(uint256)', + at: '$at_EnumerableSet_UintSet(uint256,uint256)', + values: '$values_EnumerableSet_UintSet(uint256)', + }), + { + addReturn: 'return$add_EnumerableSet_UintSet_uint256', + removeReturn: 'return$remove_EnumerableSet_UintSet_uint256', + }, + ); }); });