From f799475d930b4e26477b7c09140e9859177fcda3 Mon Sep 17 00:00:00 2001 From: Francisco Date: Wed, 28 Dec 2022 17:02:40 -0300 Subject: [PATCH 01/29] Fix links to Wizard (#3901) --- docs/modules/ROOT/pages/erc1155.adoc | 2 +- docs/modules/ROOT/pages/erc20.adoc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/modules/ROOT/pages/erc1155.adoc b/docs/modules/ROOT/pages/erc1155.adoc index 0ca933865..b47d7a072 100644 --- a/docs/modules/ROOT/pages/erc1155.adoc +++ b/docs/modules/ROOT/pages/erc1155.adoc @@ -150,4 +150,4 @@ A preset ERC1155 is available, https://github.com/OpenZeppelin/openzeppelin-cont This contract is ready to deploy without having to write any Solidity code. It can be used as-is for quick prototyping and testing, but is also suitable for production environments. -NOTE: Contract presets are now deprecated in favor of https://wizard.openzeppelin.com[Contracts Wizard] as a more powerful alternative. +NOTE: Contract presets are now deprecated in favor of https://wizard.openzeppelin.com[Contracts Wizard] as a more powerful alternative. diff --git a/docs/modules/ROOT/pages/erc20.adoc b/docs/modules/ROOT/pages/erc20.adoc index bcb510c51..168b02493 100644 --- a/docs/modules/ROOT/pages/erc20.adoc +++ b/docs/modules/ROOT/pages/erc20.adoc @@ -82,4 +82,4 @@ A preset ERC20 is available, https://github.com/OpenZeppelin/openzeppelin-contra This contract is ready to deploy without having to write any Solidity code. It can be used as-is for quick prototyping and testing, but is also suitable for production environments. -NOTE: Contract presets are now deprecated in favor of https://wizard.openzeppelin.com[Contracts Wizard] as a more powerful alternative. +NOTE: Contract presets are now deprecated in favor of https://wizard.openzeppelin.com[Contracts Wizard] as a more powerful alternative. From 7a6a9d1516218739b0159cd88d6ce3a287052f0b Mon Sep 17 00:00:00 2001 From: Matteo Casonato Date: Wed, 28 Dec 2022 22:23:24 +0100 Subject: [PATCH 02/29] Add Strings.equal (#3774) Co-authored-by: Francisco --- CHANGELOG.md | 1 + contracts/mocks/StringsMock.sol | 4 ++++ contracts/utils/Strings.sol | 7 +++++++ test/utils/Strings.test.js | 25 +++++++++++++++++++++++++ 4 files changed, 37 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d95b79934..58bec1469 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ * `ERC20Votes`: optimize by using unchecked arithmetic. ([#3748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3748)) * `Initializable`: optimize `_disableInitializers` by using `!=` instead of `<`. ([#3787](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3787)) * `Math`: optimize `log256` rounding check. ([#3745](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3745)) + * `Strings`: add `equal` method. ([#3774](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3774)) ### Deprecations diff --git a/contracts/mocks/StringsMock.sol b/contracts/mocks/StringsMock.sol index 90a6c94b3..81389fad4 100644 --- a/contracts/mocks/StringsMock.sol +++ b/contracts/mocks/StringsMock.sol @@ -20,4 +20,8 @@ contract StringsMock { 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/utils/Strings.sol b/contracts/utils/Strings.sol index 76aa3640a..e7597f12e 100644 --- a/contracts/utils/Strings.sol +++ b/contracts/utils/Strings.sol @@ -67,4 +67,11 @@ library Strings { function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } + + /** + * @dev Returns true if the two strings are equal. + */ + function equal(string memory a, string memory b) internal pure returns (bool) { + return keccak256(bytes(a)) == keccak256(bytes(b)); + } } diff --git a/test/utils/Strings.test.js b/test/utils/Strings.test.js index 7abc859ff..db9e25438 100644 --- a/test/utils/Strings.test.js +++ b/test/utils/Strings.test.js @@ -83,4 +83,29 @@ contract('Strings', function (accounts) { 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); + }); + + it('compares two equal strings', async function () { + 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); + }); + + 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); + }); + + it('compares two different strings of different (big) lengths', 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); + }); + }); }); From 96ff934ad099505bfe985e2175b7b2637f06f900 Mon Sep 17 00:00:00 2001 From: Pascal Marco Caversaccio Date: Wed, 28 Dec 2022 23:34:44 +0100 Subject: [PATCH 03/29] Update `forge-std` submodule to `v1.2.0` (#3885) Signed-off-by: Pascal Marco Caversaccio --- lib/forge-std | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/forge-std b/lib/forge-std index ca8d6e00e..eb980e1d4 160000 --- a/lib/forge-std +++ b/lib/forge-std @@ -1 +1 @@ -Subproject commit ca8d6e00ea9cb035f6856ff732203c9a3c48b966 +Subproject commit eb980e1d4f0e8173ec27da77297ae411840c8ccb From 8335676b0e99944eef6a742e16dcd9ff6e68e609 Mon Sep 17 00:00:00 2001 From: ganone <89295500+galadd@users.noreply.github.com> Date: Wed, 28 Dec 2022 14:46:52 -0800 Subject: [PATCH 04/29] Add Strings.toString for signed integers (#3773) Co-authored-by: Hadrien Croubois Co-authored-by: Gbolahan <89295500+GbolahanAnon@users.noreply.github.com> Co-authored-by: Francisco Giordano --- CHANGELOG.md | 1 + contracts/mocks/StringsMock.sol | 4 ++++ contracts/utils/Strings.sol | 8 +++++++ test/utils/Strings.test.js | 42 ++++++++++++++++++++++++++++----- 4 files changed, 49 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58bec1469..5549260a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ * `Initializable`: optimize `_disableInitializers` by using `!=` instead of `<`. ([#3787](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3787)) * `Math`: optimize `log256` rounding check. ([#3745](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3745)) * `Strings`: add `equal` method. ([#3774](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3774)) + * `Strings`: add `toString` method for signed integers. ([#3773](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3773)) ### Deprecations diff --git a/contracts/mocks/StringsMock.sol b/contracts/mocks/StringsMock.sol index 81389fad4..9f98e2778 100644 --- a/contracts/mocks/StringsMock.sol +++ b/contracts/mocks/StringsMock.sol @@ -9,6 +9,10 @@ contract StringsMock { 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); } diff --git a/contracts/utils/Strings.sol b/contracts/utils/Strings.sol index e7597f12e..3a037f477 100644 --- a/contracts/utils/Strings.sol +++ b/contracts/utils/Strings.sol @@ -4,6 +4,7 @@ pragma solidity ^0.8.0; import "./math/Math.sol"; +import "./math/SignedMath.sol"; /** * @dev String operations. @@ -37,6 +38,13 @@ library Strings { } } + /** + * @dev Converts a `int256` to its ASCII `string` decimal representation. + */ + function toString(int256 value) internal pure returns (string memory) { + return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value)))); + } + /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ diff --git a/test/utils/Strings.test.js b/test/utils/Strings.test.js index db9e25438..67e414e44 100644 --- a/test/utils/Strings.test.js +++ b/test/utils/Strings.test.js @@ -10,7 +10,7 @@ contract('Strings', function (accounts) { }); describe('toString', function () { - for (const [ key, value ] of Object.entries([ + const values = [ '0', '7', '10', @@ -29,13 +29,43 @@ contract('Strings', function (accounts) { '12345678901234567890123456789012345678901234567890', '123456789012345678901234567890123456789012345678901234567890', '1234567890123456789012345678901234567890123456789012345678901234567890', - ].reduce((acc, value) => Object.assign(acc, { [value]: new BN(value) }), { - MAX_UINT256: constants.MAX_UINT256.toString(), - }))) { - it(`converts ${key}`, async 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)); }); - } + + for (const value of values) { + it(`converts ${value}`, async function () { + expect(await this.strings.methods['toString(uint256)'](value)).to.equal(value); + }); + } + }); + + 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)); + }); + + it('converts MIN_INT256', async function () { + const value = constants.MIN_INT256; + 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); + }); + + 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)); + }); + } + }); }); describe('toHexString', function () { From cafe5eb985cee6d4c51a40957c8b0e945dbd4136 Mon Sep 17 00:00:00 2001 From: robriks <80549215+robriks@users.noreply.github.com> Date: Wed, 28 Dec 2022 18:07:29 -0500 Subject: [PATCH 05/29] Update blurb on GovernorVotes compatibility (#3764) --- contracts/governance/README.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts/governance/README.adoc b/contracts/governance/README.adoc index f711c63cf..9bfa64fea 100644 --- a/contracts/governance/README.adoc +++ b/contracts/governance/README.adoc @@ -20,7 +20,7 @@ For a written walkthrough, check out our guide on xref:ROOT:governance.adoc[How Votes modules determine the source of voting power, and sometimes quorum number. -* {GovernorVotes}: Extracts voting weight from an {ERC20Votes} token. +* {GovernorVotes}: Extracts voting weight from an {ERC20Votes}, or since v4.5 an {ERC721Votes} token. * {GovernorVotesComp}: Extracts voting weight from a COMP-like or {ERC20VotesComp} token. From b0db207e4e542ac6bc868ec25a99938ea8d88883 Mon Sep 17 00:00:00 2001 From: Pierre Grimaud Date: Thu, 29 Dec 2022 00:16:56 +0100 Subject: [PATCH 06/29] Fix typos in testing files (#3899) --- contracts/mocks/MultipleInheritanceInitializableMocks.sol | 8 ++++---- test/governance/Governor.test.js | 6 +++--- .../compatibility/GovernorCompatibilityBravo.test.js | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/contracts/mocks/MultipleInheritanceInitializableMocks.sol b/contracts/mocks/MultipleInheritanceInitializableMocks.sol index b8cf9d9d5..e79cd92c8 100644 --- a/contracts/mocks/MultipleInheritanceInitializableMocks.sol +++ b/contracts/mocks/MultipleInheritanceInitializableMocks.sol @@ -16,7 +16,7 @@ import "../proxy/utils/Initializable.sol"; // -- Child -- /** - * Sample base intializable contract that is a human + * Sample base initializable contract that is a human */ contract SampleHuman is Initializable { bool public isHuman; @@ -37,7 +37,7 @@ contract SampleHuman is Initializable { } /** - * Sample base intializable contract that defines a field mother + * Sample base initializable contract that defines a field mother */ contract SampleMother is Initializable, SampleHuman { uint256 public mother; @@ -59,7 +59,7 @@ contract SampleMother is Initializable, SampleHuman { } /** - * Sample base intializable contract that defines a field gramps + * Sample base initializable contract that defines a field gramps */ contract SampleGramps is Initializable, SampleHuman { string public gramps; @@ -81,7 +81,7 @@ contract SampleGramps is Initializable, SampleHuman { } /** - * Sample base intializable contract that defines a field father and extends from gramps + * Sample base initializable contract that defines a field father and extends from gramps */ contract SampleFather is Initializable, SampleGramps { uint256 public father; diff --git a/test/governance/Governor.test.js b/test/governance/Governor.test.js index bd10dcd68..b1d0b0515 100644 --- a/test/governance/Governor.test.js +++ b/test/governance/Governor.test.js @@ -454,7 +454,7 @@ contract('Governor', function (accounts) { await expectRevert(this.helper.propose(), 'Governor: empty proposal'); }); - it('missmatch #1', async function () { + it('mismatch #1', async function () { this.helper.setProposal({ targets: [ ], values: [ web3.utils.toWei('0') ], @@ -463,7 +463,7 @@ contract('Governor', function (accounts) { await expectRevert(this.helper.propose(), 'Governor: invalid proposal length'); }); - it('missmatch #2', async function () { + it('mismatch #2', async function () { this.helper.setProposal({ targets: [ this.receiver.address ], values: [ ], @@ -472,7 +472,7 @@ contract('Governor', function (accounts) { await expectRevert(this.helper.propose(), 'Governor: invalid proposal length'); }); - it('missmatch #3', async function () { + it('mismatch #3', async function () { this.helper.setProposal({ targets: [ this.receiver.address ], values: [ web3.utils.toWei('0') ], diff --git a/test/governance/compatibility/GovernorCompatibilityBravo.test.js b/test/governance/compatibility/GovernorCompatibilityBravo.test.js index 79950474c..f46efd622 100644 --- a/test/governance/compatibility/GovernorCompatibilityBravo.test.js +++ b/test/governance/compatibility/GovernorCompatibilityBravo.test.js @@ -168,7 +168,7 @@ contract('GovernorCompatibilityBravo', function (accounts) { ); }); - it('double voting is forbiden', async function () { + it('double voting is forbidden', async function () { await this.helper.propose({ from: proposer }); await this.helper.waitForSnapshot(); await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }); From bc50d373e37a6250f931a5dba3847bc88e46797e Mon Sep 17 00:00:00 2001 From: Paul Razvan Berg Date: Thu, 29 Dec 2022 01:32:50 +0200 Subject: [PATCH 07/29] Rename approved parameter in IERC721 (#3900) Co-authored-by: Francisco --- contracts/token/ERC721/IERC721.sol | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts/token/ERC721/IERC721.sol b/contracts/token/ERC721/IERC721.sol index 646530aa5..7b60a9f51 100644 --- a/contracts/token/ERC721/IERC721.sol +++ b/contracts/token/ERC721/IERC721.sol @@ -112,7 +112,7 @@ interface IERC721 is IERC165 { * * Emits an {ApprovalForAll} event. */ - function setApprovalForAll(address operator, bool _approved) external; + function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns the account approved for `tokenId` token. From cc27aed3910f3c3c67fa5ee7ababeac06e6e48a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ernesto=20Garc=C3=ADa?= Date: Thu, 29 Dec 2022 13:11:15 -0600 Subject: [PATCH 08/29] Improve Strings `equal` tests (#3902) Co-authored-by: Francisco --- test/utils/Strings.test.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/test/utils/Strings.test.js b/test/utils/Strings.test.js index 67e414e44..6c4c3423b 100644 --- a/test/utils/Strings.test.js +++ b/test/utils/Strings.test.js @@ -132,10 +132,16 @@ contract('Strings', function (accounts) { expect(await this.strings.methods['equal(string,string)']('aa', 'a')).to.equal(false); }); - it('compares two different strings of different (big) lengths', async function () { + 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); }); + + 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); + }); }); }); From 2336bd3e8e050d0e81caf30e89dcc9a9106e1a1f Mon Sep 17 00:00:00 2001 From: Francisco Date: Thu, 29 Dec 2022 17:08:12 -0300 Subject: [PATCH 09/29] Simplify ESLint config (#3903) --- .eslintrc | 66 +- package-lock.json | 1477 ++++++----------- package.json | 8 +- test/access/AccessControl.behavior.js | 2 +- test/proxy/Clones.test.js | 2 +- test/proxy/utils/Initializable.test.js | 2 +- test/proxy/utils/UUPSUpgradeable.test.js | 2 +- test/security/ReentrancyGuard.test.js | 2 +- test/token/ERC721/ERC721.behavior.js | 2 +- test/utils/Arrays.test.js | 2 +- test/utils/Checkpoints.test.js | 2 +- test/utils/Counters.test.js | 2 +- test/utils/Strings.test.js | 2 +- test/utils/TimersBlockNumberImpl.test.js | 2 +- test/utils/TimersTimestamp.test.js | 2 +- test/utils/cryptography/MerkleProof.test.js | 2 +- test/utils/introspection/ERC165.test.js | 2 +- .../utils/introspection/ERC165Checker.test.js | 2 +- .../utils/introspection/ERC165Storage.test.js | 2 +- test/utils/math/Math.test.js | 2 +- test/utils/math/SafeCast.test.js | 2 +- test/utils/math/SafeMath.test.js | 2 +- test/utils/math/SignedMath.test.js | 2 +- test/utils/math/SignedSafeMath.test.js | 2 +- test/utils/structs/BitMap.test.js | 2 +- test/utils/structs/DoubleEndedQueue.test.js | 2 +- 26 files changed, 515 insertions(+), 1082 deletions(-) diff --git a/.eslintrc b/.eslintrc index 095d2754d..a5418c5e4 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,62 +1,20 @@ { + "root": true, "extends" : [ - "standard" - ], - "plugins": [ - "mocha" + "eslint:recommended", + "prettier", ], "env": { - "browser" : true, - "node" : true, - "mocha" : true, - "jest" : true, + "es2022": true, + "browser": true, + "node": true, + "mocha": true, }, "globals" : { - "artifacts": false, - "contract": false, - "assert": false, - "web3": false, - "usePlugin": false, - "extendEnvironment": false, - }, - "rules": { - - // Strict mode - "strict": ["error", "global"], - - // Code style - "array-bracket-spacing": ["off"], - "camelcase": ["error", {"properties": "always"}], - "comma-dangle": ["error", "always-multiline"], - "comma-spacing": ["error", {"before": false, "after": true}], - "dot-notation": ["error", {"allowKeywords": true, "allowPattern": ""}], - "eol-last": ["error", "always"], - "eqeqeq": ["error", "smart"], - "generator-star-spacing": ["error", "before"], - "indent": ["error", 2], - "linebreak-style": ["error", "unix"], - "max-len": ["error", 120, 2], - "no-debugger": "off", - "no-dupe-args": "error", - "no-dupe-keys": "error", - "no-mixed-spaces-and-tabs": ["error", "smart-tabs"], - "no-redeclare": ["error", {"builtinGlobals": true}], - "no-trailing-spaces": ["error", { "skipBlankLines": false }], - "no-undef": "error", - "no-use-before-define": "off", - "no-var": "error", - "object-curly-spacing": ["error", "always"], - "prefer-const": "error", - "quotes": ["error", "single"], - "semi": ["error", "always"], - "space-before-function-paren": ["error", "always"], - - "mocha/no-exclusive-tests": ["error"], - - "promise/always-return": "off", - "promise/avoid-new": "off", - }, - "parserOptions": { - "ecmaVersion": 2020 + "artifacts": "readonly", + "contract": "readonly", + "web3": "readonly", + "extendEnvironment": "readonly", + "expect": "readonly", } } diff --git a/package-lock.json b/package-lock.json index 8d8a2ca16..9473a1be3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,12 +18,8 @@ "@openzeppelin/docs-utils": "^0.1.3", "@openzeppelin/test-helpers": "^0.5.13", "chai": "^4.2.0", - "eslint": "^7.32.0", - "eslint-config-standard": "^16.0.3", - "eslint-plugin-import": "^2.25.4", - "eslint-plugin-mocha": "^10.0.3", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^5.2.0", + "eslint": "^8.30.0", + "eslint-config-prettier": "^8.5.0", "eth-sig-util": "^3.0.0", "ethereumjs-util": "^7.0.7", "ethereumjs-wallet": "^1.0.1", @@ -265,23 +261,53 @@ "dev": true }, "node_modules/@eslint/eslintrc": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", - "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.4.0.tgz", + "integrity": "sha512-7yfvXy6MWLgWSFsLhz5yH3iQ52St8cdUY6FoGieKkRDVxuxmrNuUetIuu6cmjNWwniUHiWXjxCr5tTXDrbYS5A==", "dev": true, "dependencies": { "ajv": "^6.12.4", - "debug": "^4.1.1", - "espree": "^7.3.0", - "globals": "^13.9.0", - "ignore": "^4.0.6", + "debug": "^4.3.2", + "espree": "^9.4.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", "import-fresh": "^3.2.1", - "js-yaml": "^3.13.1", - "minimatch": "^3.0.4", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, + "node_modules/@eslint/eslintrc/node_modules/ignore": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/@eslint/eslintrc/node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" } }, "node_modules/@ethereumjs/common": { @@ -1055,19 +1081,32 @@ } }, "node_modules/@humanwhocodes/config-array": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", - "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", + "version": "0.11.8", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.8.tgz", + "integrity": "sha512-UybHIJzJnR5Qc/MsD9Kr+RpO2h+/P1GhOwdiLPXK5TWk5sgTdu88bTD9UP+CKbPPh5Rni1u0GjAdYQLemG8g+g==", "dev": true, "dependencies": { - "@humanwhocodes/object-schema": "^1.2.0", + "@humanwhocodes/object-schema": "^1.2.1", "debug": "^4.1.1", - "minimatch": "^3.0.4" + "minimatch": "^3.0.5" }, "engines": { "node": ">=10.10.0" } }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, "node_modules/@humanwhocodes/object-schema": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz", @@ -2250,12 +2289,6 @@ "integrity": "sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ==", "dev": true }, - "node_modules/@types/json5": { - "version": "0.0.29", - "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", - "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", - "dev": true - }, "node_modules/@types/keyv": { "version": "3.1.4", "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz", @@ -2396,9 +2429,9 @@ } }, "node_modules/acorn": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", - "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", + "version": "8.8.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.1.tgz", + "integrity": "sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA==", "dev": true, "bin": { "acorn": "bin/acorn" @@ -2591,25 +2624,6 @@ "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", "dev": true }, - "node_modules/array-includes": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.6.tgz", - "integrity": "sha512-sgTbLvL6cNnw24FnbaDyjmvddQ2ML8arZsgaJhoABMoplz/4QRhtrYS+alr1BUM1Bwp6dhx8vVCBSLG+StwOFw==", - "dev": true, - "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4", - "get-intrinsic": "^1.1.3", - "is-string": "^1.0.7" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/array-union": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", @@ -2628,24 +2642,6 @@ "node": ">=0.10.0" } }, - "node_modules/array.prototype.flat": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.1.tgz", - "integrity": "sha512-roTU0KWIOmJ4DRLmwKd19Otg0/mT3qPNt0Qb3GWW8iObuZXxrjB/pzn0R3hqpRSWg4HCwqx+0vwOnWnvlOyeIA==", - "dev": true, - "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4", - "es-shim-unscopables": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/array.prototype.reduce": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/array.prototype.reduce/-/array.prototype.reduce-1.0.5.tgz", @@ -2716,15 +2712,6 @@ "integrity": "sha512-XHusKxKz3zoYk1ic8Un640joHbFMhbqneyoZfoKnEGtf2ey9Uh/IdpcQplODdO/kENaMIWsD0nJm4+wX3UNLHA==", "dev": true }, - "node_modules/astral-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", - "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/async": { "version": "2.6.4", "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", @@ -4547,15 +4534,6 @@ "integrity": "sha512-wd6JXUmyHmt8T5a2xreUwKcGPq6f1f+WwIJkijUqiGcJz1qqnZgP6XIK+QyIWU5lT7imeNxUll48bziG+TSYcA==", "dev": true }, - "node_modules/es-shim-unscopables": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.0.tgz", - "integrity": "sha512-Jm6GPcCdC30eMLbZ2x8z2WuRwAws3zTBBKuusffYVUrNj/GVSUAZ+xKMaUpfNDR5IbyNA5LJbaecoUVbmUcB1w==", - "dev": true, - "dependencies": { - "has": "^1.0.3" - } - }, "node_modules/es-to-primitive": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", @@ -4738,334 +4716,93 @@ } }, "node_modules/eslint": { - "version": "7.32.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", - "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", + "version": "8.30.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.30.0.tgz", + "integrity": "sha512-MGADB39QqYuzEGov+F/qb18r4i7DohCDOfatHaxI2iGlPuC65bwG2gxgO+7DkyL38dRFaRH7RaRAgU6JKL9rMQ==", "dev": true, "dependencies": { - "@babel/code-frame": "7.12.11", - "@eslint/eslintrc": "^0.4.3", - "@humanwhocodes/config-array": "^0.5.0", + "@eslint/eslintrc": "^1.4.0", + "@humanwhocodes/config-array": "^0.11.8", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", "ajv": "^6.10.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", - "debug": "^4.0.1", + "debug": "^4.3.2", "doctrine": "^3.0.0", - "enquirer": "^2.3.5", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^2.1.0", - "eslint-visitor-keys": "^2.0.0", - "espree": "^7.3.1", + "eslint-scope": "^7.1.1", + "eslint-utils": "^3.0.0", + "eslint-visitor-keys": "^3.3.0", + "espree": "^9.4.0", "esquery": "^1.4.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^6.0.1", - "functional-red-black-tree": "^1.0.1", - "glob-parent": "^5.1.2", - "globals": "^13.6.0", - "ignore": "^4.0.6", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "grapheme-splitter": "^1.0.4", + "ignore": "^5.2.0", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", - "js-yaml": "^3.13.1", + "is-path-inside": "^3.0.3", + "js-sdsl": "^4.1.4", + "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.2", "natural-compare": "^1.4.0", "optionator": "^0.9.1", - "progress": "^2.0.0", - "regexpp": "^3.1.0", - "semver": "^7.2.1", - "strip-ansi": "^6.0.0", + "regexpp": "^3.2.0", + "strip-ansi": "^6.0.1", "strip-json-comments": "^3.1.0", - "table": "^6.0.9", - "text-table": "^0.2.0", - "v8-compile-cache": "^2.0.3" + "text-table": "^0.2.0" }, "bin": { "eslint": "bin/eslint.js" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "url": "https://opencollective.com/eslint" } }, - "node_modules/eslint-config-standard": { - "version": "16.0.3", - "resolved": "https://registry.npmjs.org/eslint-config-standard/-/eslint-config-standard-16.0.3.tgz", - "integrity": "sha512-x4fmJL5hGqNJKGHSjnLdgA6U6h1YW/G2dW9fA+cyVur4SK6lyue8+UgNKWlZtUDTXvgKDD/Oa3GQjmB5kjtVvg==", + "node_modules/eslint-config-prettier": { + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.5.0.tgz", + "integrity": "sha512-obmWKLUNCnhtQRKc+tmnYuQl0pFU1ibYJQ5BGhTVB08bHe9wC8qUeG7c08dj9XX+AuPj1YSGSQIHl1pnDHZR0Q==", "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "peerDependencies": { - "eslint": "^7.12.1", - "eslint-plugin-import": "^2.22.1", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^4.2.1 || ^5.0.0" - } - }, - "node_modules/eslint-import-resolver-node": { - "version": "0.3.6", - "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.6.tgz", - "integrity": "sha512-0En0w03NRVMn9Uiyn8YRPDKvWjxCWkslUEhGNTdGx15RvPJYQ+lbOlqrlNI2vEAs4pDYK4f/HN2TbDmk5TP0iw==", - "dev": true, - "dependencies": { - "debug": "^3.2.7", - "resolve": "^1.20.0" - } - }, - "node_modules/eslint-import-resolver-node/node_modules/debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dev": true, - "dependencies": { - "ms": "^2.1.1" - } - }, - "node_modules/eslint-module-utils": { - "version": "2.7.4", - "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.7.4.tgz", - "integrity": "sha512-j4GT+rqzCoRKHwURX7pddtIPGySnX9Si/cgMI5ztrcqOPtk5dDEeZ34CQVPphnqkJytlc97Vuk05Um2mJ3gEQA==", - "dev": true, - "dependencies": { - "debug": "^3.2.7" - }, - "engines": { - "node": ">=4" - }, - "peerDependenciesMeta": { - "eslint": { - "optional": true - } - } - }, - "node_modules/eslint-module-utils/node_modules/debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dev": true, - "dependencies": { - "ms": "^2.1.1" - } - }, - "node_modules/eslint-plugin-es": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz", - "integrity": "sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ==", - "dev": true, - "dependencies": { - "eslint-utils": "^2.0.0", - "regexpp": "^3.0.0" - }, - "engines": { - "node": ">=8.10.0" - }, - "funding": { - "url": "https://github.com/sponsors/mysticatea" - }, - "peerDependencies": { - "eslint": ">=4.19.1" - } - }, - "node_modules/eslint-plugin-import": { - "version": "2.26.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.26.0.tgz", - "integrity": "sha512-hYfi3FXaM8WPLf4S1cikh/r4IxnO6zrhZbEGz2b660EJRbuxgpDS5gkCuYgGWg2xxh2rBuIr4Pvhve/7c31koA==", - "dev": true, - "dependencies": { - "array-includes": "^3.1.4", - "array.prototype.flat": "^1.2.5", - "debug": "^2.6.9", - "doctrine": "^2.1.0", - "eslint-import-resolver-node": "^0.3.6", - "eslint-module-utils": "^2.7.3", - "has": "^1.0.3", - "is-core-module": "^2.8.1", - "is-glob": "^4.0.3", - "minimatch": "^3.1.2", - "object.values": "^1.1.5", - "resolve": "^1.22.0", - "tsconfig-paths": "^3.14.1" - }, - "engines": { - "node": ">=4" - }, - "peerDependencies": { - "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8" - } - }, - "node_modules/eslint-plugin-import/node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/eslint-plugin-import/node_modules/doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", - "dev": true, - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/eslint-plugin-import/node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", - "dev": true - }, - "node_modules/eslint-plugin-mocha": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-mocha/-/eslint-plugin-mocha-10.1.0.tgz", - "integrity": "sha512-xLqqWUF17llsogVOC+8C6/jvQ+4IoOREbN7ZCHuOHuD6cT5cDD4h7f2LgsZuzMAiwswWE21tO7ExaknHVDrSkw==", - "dev": true, - "dependencies": { - "eslint-utils": "^3.0.0", - "rambda": "^7.1.0" - }, - "engines": { - "node": ">=14.0.0" + "bin": { + "eslint-config-prettier": "bin/cli.js" }, "peerDependencies": { "eslint": ">=7.0.0" } }, - "node_modules/eslint-plugin-mocha/node_modules/eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "dependencies": { - "eslint-visitor-keys": "^2.0.0" - }, - "engines": { - "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/mysticatea" - }, - "peerDependencies": { - "eslint": ">=5" - } - }, - "node_modules/eslint-plugin-node": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz", - "integrity": "sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g==", - "dev": true, - "dependencies": { - "eslint-plugin-es": "^3.0.0", - "eslint-utils": "^2.0.0", - "ignore": "^5.1.1", - "minimatch": "^3.0.4", - "resolve": "^1.10.1", - "semver": "^6.1.0" - }, - "engines": { - "node": ">=8.10.0" - }, - "peerDependencies": { - "eslint": ">=5.16.0" - } - }, - "node_modules/eslint-plugin-node/node_modules/ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true, - "engines": { - "node": ">= 4" - } - }, - "node_modules/eslint-plugin-node/node_modules/semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/eslint-plugin-promise": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-promise/-/eslint-plugin-promise-5.2.0.tgz", - "integrity": "sha512-SftLb1pUG01QYq2A/hGAWfDRXqYD82zE7j7TopDOyNdU+7SvvoXREls/+PRTY17vUXzXnZA/zfnyKgRH6x4JJw==", - "dev": true, - "engines": { - "node": "^10.12.0 || >=12.0.0" - }, - "peerDependencies": { - "eslint": "^7.0.0" - } - }, "node_modules/eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.1.1.tgz", + "integrity": "sha512-QKQM/UXpIiHcLqJ5AOyIW7XZmzjkzQXYE54n1++wb0u9V/abW3l9uQnxX8Z5Xd18xyKIMTUAyQ0k1e8pz6LUrw==", "dev": true, "dependencies": { "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" + "estraverse": "^5.2.0" }, "engines": { - "node": ">=8.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, - "node_modules/eslint-utils": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", - "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", - "dev": true, - "dependencies": { - "eslint-visitor-keys": "^1.1.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/mysticatea" - } - }, - "node_modules/eslint-utils/node_modules/eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "node_modules/eslint-scope/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true, "engines": { - "node": ">=4" - } - }, - "node_modules/eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true, - "engines": { - "node": ">=10" + "node": ">=4.0" } }, "node_modules/eslint/node_modules/ansi-regex": { @@ -5077,6 +4814,12 @@ "node": ">=8" } }, + "node_modules/eslint/node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, "node_modules/eslint/node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -5093,6 +4836,136 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/eslint/node_modules/eslint-utils": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", + "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^2.0.0" + }, + "engines": { + "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" + }, + "peerDependencies": { + "eslint": ">=5" + } + }, + "node_modules/eslint/node_modules/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", + "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", + "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/eslint/node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/eslint/node_modules/ignore": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/eslint/node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/eslint/node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/eslint/node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -5106,26 +4979,29 @@ } }, "node_modules/espree": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", - "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", + "version": "9.4.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.4.1.tgz", + "integrity": "sha512-XwctdmTO6SIvCzd9810yyNzIrOrqNYV9Koizx4C/mRhf9uq0o4yHoCEU/670pOxOL/MSraektvSAji79kX90Vg==", "dev": true, "dependencies": { - "acorn": "^7.4.0", - "acorn-jsx": "^5.3.1", - "eslint-visitor-keys": "^1.3.0" + "acorn": "^8.8.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.3.0" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, "node_modules/espree/node_modules/eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", + "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", "dev": true, "engines": { - "node": ">=4" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, "node_modules/esprima": { @@ -6930,6 +6806,12 @@ "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", "dev": true }, + "node_modules/grapheme-splitter": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz", + "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", + "dev": true + }, "node_modules/graphlib": { "version": "2.1.8", "resolved": "https://registry.npmjs.org/graphlib/-/graphlib-2.1.8.tgz", @@ -8192,6 +8074,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, "node_modules/is-plain-obj": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz", @@ -8350,6 +8241,16 @@ "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==", "dev": true }, + "node_modules/js-sdsl": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.2.0.tgz", + "integrity": "sha512-dyBIzQBDkCqCu+0upx25Y2jGdbTGxE9fshMsCdK0ViOongpV+n5tXRcZY9v7CaVQ79AGS9KA1KHtojxiM7aXSQ==", + "dev": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, "node_modules/js-sha3": { "version": "0.8.0", "resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz", @@ -8417,18 +8318,6 @@ "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", "dev": true }, - "node_modules/json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", - "dev": true, - "dependencies": { - "minimist": "^1.2.0" - }, - "bin": { - "json5": "lib/cli.js" - } - }, "node_modules/jsonfile": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", @@ -8724,12 +8613,6 @@ "integrity": "sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg==", "dev": true }, - "node_modules/lodash.truncate": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", - "integrity": "sha512-jttmRe7bRse52OsWIMDLaXxWqRAmtIUccAQ3garviCqJjafXOfNMO0yMfNpdD6zbGaTU0P5Nz7e7gAT6cKmJRw==", - "dev": true - }, "node_modules/lodash.zip": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/lodash.zip/-/lodash.zip-4.2.0.tgz", @@ -9774,23 +9657,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/object.values": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.6.tgz", - "integrity": "sha512-FVVTkD1vENCsAcwNs9k6jea2uHC/X0+JcjG8YA60FN5CMaJmG95wT9jek/xX9nornqGRrBkKtzuAu2wuHpKqvw==", - "dev": true, - "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/obliterator": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.4.tgz", @@ -10438,12 +10304,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/rambda": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/rambda/-/rambda-7.4.0.tgz", - "integrity": "sha512-A9hihu7dUTLOUCM+I8E61V4kRXnN4DwYeK0DwCBydC1MqNI1PidyAtbtpsJlBBzK4icSctEcCQ1bGcLpBuETUQ==", - "dev": true - }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -11510,32 +11370,6 @@ "node": ">=8" } }, - "node_modules/slice-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", - "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/slice-ansi?sponsor=1" - } - }, - "node_modules/slice-ansi/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/snake-case": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/snake-case/-/snake-case-2.1.0.tgz", @@ -13271,15 +13105,6 @@ "node": ">=4" } }, - "node_modules/strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/strip-hex-prefix": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/strip-hex-prefix/-/strip-hex-prefix-1.0.0.tgz", @@ -13478,103 +13303,6 @@ "get-port": "^3.1.0" } }, - "node_modules/table": { - "version": "6.8.1", - "resolved": "https://registry.npmjs.org/table/-/table-6.8.1.tgz", - "integrity": "sha512-Y4X9zqrCftUhMeH2EptSSERdVKt/nEdijTOacGD/97EKjhQ/Qs8RTlEGABSJNNN8lac9kheH+af7yAkEWlgneA==", - "dev": true, - "dependencies": { - "ajv": "^8.0.1", - "lodash.truncate": "^4.4.2", - "slice-ansi": "^4.0.0", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/table/node_modules/ajv": { - "version": "8.11.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.2.tgz", - "integrity": "sha512-E4bfmKAhGiSTvMfL1Myyycaub+cUEU2/IvpylXkUu7CHBkBj1f/ikdzbD7YQ6FKUbixDxeYvB/xY4fvyroDlQg==", - "dev": true, - "dependencies": { - "fast-deep-equal": "^3.1.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/table/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/table/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/table/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/table/node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true - }, - "node_modules/table/node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/table/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/table/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/tar": { "version": "4.4.19", "resolved": "https://registry.npmjs.org/tar/-/tar-4.4.19.tgz", @@ -13729,18 +13457,6 @@ "node": ">=0.6" } }, - "node_modules/tsconfig-paths": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.14.1.tgz", - "integrity": "sha512-fxDhWnFSLt3VuTwtvJt5fpwxBHg5AdKWMsgcPOOIilyjymcYVZoCQF8fvFRezCNfblEXmi+PcM1eYHeOAgXCOQ==", - "dev": true, - "dependencies": { - "@types/json5": "^0.0.29", - "json5": "^1.0.1", - "minimist": "^1.2.6", - "strip-bom": "^3.0.0" - } - }, "node_modules/tslib": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", @@ -14000,12 +13716,6 @@ "uuid": "dist/bin/uuid" } }, - "node_modules/v8-compile-cache": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", - "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==", - "dev": true - }, "node_modules/validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", @@ -15084,20 +14794,43 @@ "dev": true }, "@eslint/eslintrc": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", - "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.4.0.tgz", + "integrity": "sha512-7yfvXy6MWLgWSFsLhz5yH3iQ52St8cdUY6FoGieKkRDVxuxmrNuUetIuu6cmjNWwniUHiWXjxCr5tTXDrbYS5A==", "dev": true, "requires": { "ajv": "^6.12.4", - "debug": "^4.1.1", - "espree": "^7.3.0", - "globals": "^13.9.0", - "ignore": "^4.0.6", + "debug": "^4.3.2", + "espree": "^9.4.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", "import-fresh": "^3.2.1", - "js-yaml": "^3.13.1", - "minimatch": "^3.0.4", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", "strip-json-comments": "^3.1.1" + }, + "dependencies": { + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, + "ignore": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", + "dev": true + }, + "js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "requires": { + "argparse": "^2.0.1" + } + } } }, "@ethereumjs/common": { @@ -15561,16 +15294,22 @@ "dev": true }, "@humanwhocodes/config-array": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", - "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", + "version": "0.11.8", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.8.tgz", + "integrity": "sha512-UybHIJzJnR5Qc/MsD9Kr+RpO2h+/P1GhOwdiLPXK5TWk5sgTdu88bTD9UP+CKbPPh5Rni1u0GjAdYQLemG8g+g==", "dev": true, "requires": { - "@humanwhocodes/object-schema": "^1.2.0", + "@humanwhocodes/object-schema": "^1.2.1", "debug": "^4.1.1", - "minimatch": "^3.0.4" + "minimatch": "^3.0.5" } }, + "@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true + }, "@humanwhocodes/object-schema": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz", @@ -16504,12 +16243,6 @@ "integrity": "sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ==", "dev": true }, - "@types/json5": { - "version": "0.0.29", - "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", - "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", - "dev": true - }, "@types/keyv": { "version": "3.1.4", "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz", @@ -16629,9 +16362,9 @@ } }, "acorn": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", - "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", + "version": "8.8.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.1.tgz", + "integrity": "sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA==", "dev": true }, "acorn-jsx": { @@ -16772,19 +16505,6 @@ "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", "dev": true }, - "array-includes": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.6.tgz", - "integrity": "sha512-sgTbLvL6cNnw24FnbaDyjmvddQ2ML8arZsgaJhoABMoplz/4QRhtrYS+alr1BUM1Bwp6dhx8vVCBSLG+StwOFw==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4", - "get-intrinsic": "^1.1.3", - "is-string": "^1.0.7" - } - }, "array-union": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", @@ -16797,18 +16517,6 @@ "integrity": "sha512-MNha4BWQ6JbwhFhj03YK552f7cb3AzoE8SzeljgChvL1dl3IcvggXVz1DilzySZkCja+CXuZbdW7yATchWn8/Q==", "dev": true }, - "array.prototype.flat": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.1.tgz", - "integrity": "sha512-roTU0KWIOmJ4DRLmwKd19Otg0/mT3qPNt0Qb3GWW8iObuZXxrjB/pzn0R3hqpRSWg4HCwqx+0vwOnWnvlOyeIA==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4", - "es-shim-unscopables": "^1.0.0" - } - }, "array.prototype.reduce": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/array.prototype.reduce/-/array.prototype.reduce-1.0.5.tgz", @@ -16867,12 +16575,6 @@ "integrity": "sha512-XHusKxKz3zoYk1ic8Un640joHbFMhbqneyoZfoKnEGtf2ey9Uh/IdpcQplODdO/kENaMIWsD0nJm4+wX3UNLHA==", "dev": true }, - "astral-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", - "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", - "dev": true - }, "async": { "version": "2.6.4", "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", @@ -18354,15 +18056,6 @@ "integrity": "sha512-wd6JXUmyHmt8T5a2xreUwKcGPq6f1f+WwIJkijUqiGcJz1qqnZgP6XIK+QyIWU5lT7imeNxUll48bziG+TSYcA==", "dev": true }, - "es-shim-unscopables": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.0.tgz", - "integrity": "sha512-Jm6GPcCdC30eMLbZ2x8z2WuRwAws3zTBBKuusffYVUrNj/GVSUAZ+xKMaUpfNDR5IbyNA5LJbaecoUVbmUcB1w==", - "dev": true, - "requires": { - "has": "^1.0.3" - } - }, "es-to-primitive": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", @@ -18497,51 +18190,50 @@ } }, "eslint": { - "version": "7.32.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", - "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", + "version": "8.30.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.30.0.tgz", + "integrity": "sha512-MGADB39QqYuzEGov+F/qb18r4i7DohCDOfatHaxI2iGlPuC65bwG2gxgO+7DkyL38dRFaRH7RaRAgU6JKL9rMQ==", "dev": true, "requires": { - "@babel/code-frame": "7.12.11", - "@eslint/eslintrc": "^0.4.3", - "@humanwhocodes/config-array": "^0.5.0", + "@eslint/eslintrc": "^1.4.0", + "@humanwhocodes/config-array": "^0.11.8", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", "ajv": "^6.10.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", - "debug": "^4.0.1", + "debug": "^4.3.2", "doctrine": "^3.0.0", - "enquirer": "^2.3.5", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^2.1.0", - "eslint-visitor-keys": "^2.0.0", - "espree": "^7.3.1", + "eslint-scope": "^7.1.1", + "eslint-utils": "^3.0.0", + "eslint-visitor-keys": "^3.3.0", + "espree": "^9.4.0", "esquery": "^1.4.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^6.0.1", - "functional-red-black-tree": "^1.0.1", - "glob-parent": "^5.1.2", - "globals": "^13.6.0", - "ignore": "^4.0.6", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "grapheme-splitter": "^1.0.4", + "ignore": "^5.2.0", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", - "js-yaml": "^3.13.1", + "is-path-inside": "^3.0.3", + "js-sdsl": "^4.1.4", + "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.2", "natural-compare": "^1.4.0", "optionator": "^0.9.1", - "progress": "^2.0.0", - "regexpp": "^3.1.0", - "semver": "^7.2.1", - "strip-ansi": "^6.0.0", + "regexpp": "^3.2.0", + "strip-ansi": "^6.0.1", "strip-json-comments": "^3.1.0", - "table": "^6.0.9", - "text-table": "^0.2.0", - "v8-compile-cache": "^2.0.3" + "text-table": "^0.2.0" }, "dependencies": { "ansi-regex": { @@ -18550,6 +18242,12 @@ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, "chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -18560,6 +18258,90 @@ "supports-color": "^7.1.0" } }, + "eslint-utils": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", + "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", + "dev": true, + "requires": { + "eslint-visitor-keys": "^2.0.0" + }, + "dependencies": { + "eslint-visitor-keys": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", + "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", + "dev": true + } + } + }, + "eslint-visitor-keys": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", + "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", + "dev": true + }, + "find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "requires": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + } + }, + "glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "requires": { + "is-glob": "^4.0.3" + } + }, + "ignore": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", + "dev": true + }, + "js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "requires": { + "argparse": "^2.0.1" + } + }, + "locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "requires": { + "p-locate": "^5.0.0" + } + }, + "p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "requires": { + "yocto-queue": "^0.1.0" + } + }, + "p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "requires": { + "p-limit": "^3.0.2" + } + }, "strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -18571,215 +18353,46 @@ } } }, - "eslint-config-standard": { - "version": "16.0.3", - "resolved": "https://registry.npmjs.org/eslint-config-standard/-/eslint-config-standard-16.0.3.tgz", - "integrity": "sha512-x4fmJL5hGqNJKGHSjnLdgA6U6h1YW/G2dW9fA+cyVur4SK6lyue8+UgNKWlZtUDTXvgKDD/Oa3GQjmB5kjtVvg==", - "dev": true, - "requires": {} - }, - "eslint-import-resolver-node": { - "version": "0.3.6", - "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.6.tgz", - "integrity": "sha512-0En0w03NRVMn9Uiyn8YRPDKvWjxCWkslUEhGNTdGx15RvPJYQ+lbOlqrlNI2vEAs4pDYK4f/HN2TbDmk5TP0iw==", - "dev": true, - "requires": { - "debug": "^3.2.7", - "resolve": "^1.20.0" - }, - "dependencies": { - "debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - } - } - }, - "eslint-module-utils": { - "version": "2.7.4", - "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.7.4.tgz", - "integrity": "sha512-j4GT+rqzCoRKHwURX7pddtIPGySnX9Si/cgMI5ztrcqOPtk5dDEeZ34CQVPphnqkJytlc97Vuk05Um2mJ3gEQA==", - "dev": true, - "requires": { - "debug": "^3.2.7" - }, - "dependencies": { - "debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - } - } - }, - "eslint-plugin-es": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz", - "integrity": "sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ==", - "dev": true, - "requires": { - "eslint-utils": "^2.0.0", - "regexpp": "^3.0.0" - } - }, - "eslint-plugin-import": { - "version": "2.26.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.26.0.tgz", - "integrity": "sha512-hYfi3FXaM8WPLf4S1cikh/r4IxnO6zrhZbEGz2b660EJRbuxgpDS5gkCuYgGWg2xxh2rBuIr4Pvhve/7c31koA==", - "dev": true, - "requires": { - "array-includes": "^3.1.4", - "array.prototype.flat": "^1.2.5", - "debug": "^2.6.9", - "doctrine": "^2.1.0", - "eslint-import-resolver-node": "^0.3.6", - "eslint-module-utils": "^2.7.3", - "has": "^1.0.3", - "is-core-module": "^2.8.1", - "is-glob": "^4.0.3", - "minimatch": "^3.1.2", - "object.values": "^1.1.5", - "resolve": "^1.22.0", - "tsconfig-paths": "^3.14.1" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", - "dev": true, - "requires": { - "esutils": "^2.0.2" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", - "dev": true - } - } - }, - "eslint-plugin-mocha": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-mocha/-/eslint-plugin-mocha-10.1.0.tgz", - "integrity": "sha512-xLqqWUF17llsogVOC+8C6/jvQ+4IoOREbN7ZCHuOHuD6cT5cDD4h7f2LgsZuzMAiwswWE21tO7ExaknHVDrSkw==", - "dev": true, - "requires": { - "eslint-utils": "^3.0.0", - "rambda": "^7.1.0" - }, - "dependencies": { - "eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "requires": { - "eslint-visitor-keys": "^2.0.0" - } - } - } - }, - "eslint-plugin-node": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz", - "integrity": "sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g==", - "dev": true, - "requires": { - "eslint-plugin-es": "^3.0.0", - "eslint-utils": "^2.0.0", - "ignore": "^5.1.1", - "minimatch": "^3.0.4", - "resolve": "^1.10.1", - "semver": "^6.1.0" - }, - "dependencies": { - "ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true - }, - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, - "eslint-plugin-promise": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-promise/-/eslint-plugin-promise-5.2.0.tgz", - "integrity": "sha512-SftLb1pUG01QYq2A/hGAWfDRXqYD82zE7j7TopDOyNdU+7SvvoXREls/+PRTY17vUXzXnZA/zfnyKgRH6x4JJw==", + "eslint-config-prettier": { + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.5.0.tgz", + "integrity": "sha512-obmWKLUNCnhtQRKc+tmnYuQl0pFU1ibYJQ5BGhTVB08bHe9wC8qUeG7c08dj9XX+AuPj1YSGSQIHl1pnDHZR0Q==", "dev": true, "requires": {} }, "eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.1.1.tgz", + "integrity": "sha512-QKQM/UXpIiHcLqJ5AOyIW7XZmzjkzQXYE54n1++wb0u9V/abW3l9uQnxX8Z5Xd18xyKIMTUAyQ0k1e8pz6LUrw==", "dev": true, "requires": { "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" - } - }, - "eslint-utils": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", - "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", - "dev": true, - "requires": { - "eslint-visitor-keys": "^1.1.0" + "estraverse": "^5.2.0" }, "dependencies": { - "eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true } } }, - "eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true - }, "espree": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", - "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", + "version": "9.4.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.4.1.tgz", + "integrity": "sha512-XwctdmTO6SIvCzd9810yyNzIrOrqNYV9Koizx4C/mRhf9uq0o4yHoCEU/670pOxOL/MSraektvSAji79kX90Vg==", "dev": true, "requires": { - "acorn": "^7.4.0", - "acorn-jsx": "^5.3.1", - "eslint-visitor-keys": "^1.3.0" + "acorn": "^8.8.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.3.0" }, "dependencies": { "eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", + "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", "dev": true } } @@ -20279,6 +19892,12 @@ "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", "dev": true }, + "grapheme-splitter": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz", + "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", + "dev": true + }, "graphlib": { "version": "2.1.8", "resolved": "https://registry.npmjs.org/graphlib/-/graphlib-2.1.8.tgz", @@ -21231,6 +20850,12 @@ "has-tostringtag": "^1.0.0" } }, + "is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true + }, "is-plain-obj": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz", @@ -21347,6 +20972,12 @@ "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==", "dev": true }, + "js-sdsl": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.2.0.tgz", + "integrity": "sha512-dyBIzQBDkCqCu+0upx25Y2jGdbTGxE9fshMsCdK0ViOongpV+n5tXRcZY9v7CaVQ79AGS9KA1KHtojxiM7aXSQ==", + "dev": true + }, "js-sha3": { "version": "0.8.0", "resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz", @@ -21411,15 +21042,6 @@ "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", "dev": true }, - "json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", - "dev": true, - "requires": { - "minimist": "^1.2.0" - } - }, "jsonfile": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", @@ -21646,12 +21268,6 @@ "integrity": "sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg==", "dev": true }, - "lodash.truncate": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", - "integrity": "sha512-jttmRe7bRse52OsWIMDLaXxWqRAmtIUccAQ3garviCqJjafXOfNMO0yMfNpdD6zbGaTU0P5Nz7e7gAT6cKmJRw==", - "dev": true - }, "lodash.zip": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/lodash.zip/-/lodash.zip-4.2.0.tgz", @@ -22472,17 +22088,6 @@ "es-abstract": "^1.20.4" } }, - "object.values": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.6.tgz", - "integrity": "sha512-FVVTkD1vENCsAcwNs9k6jea2uHC/X0+JcjG8YA60FN5CMaJmG95wT9jek/xX9nornqGRrBkKtzuAu2wuHpKqvw==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4" - } - }, "obliterator": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.4.tgz", @@ -22969,12 +22574,6 @@ "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==", "dev": true }, - "rambda": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/rambda/-/rambda-7.4.0.tgz", - "integrity": "sha512-A9hihu7dUTLOUCM+I8E61V4kRXnN4DwYeK0DwCBydC1MqNI1PidyAtbtpsJlBBzK4icSctEcCQ1bGcLpBuETUQ==", - "dev": true - }, "randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -23786,25 +23385,6 @@ "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true }, - "slice-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", - "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", - "dev": true, - "requires": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" - }, - "dependencies": { - "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 - } - } - }, "snake-case": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/snake-case/-/snake-case-2.1.0.tgz", @@ -25135,12 +24715,6 @@ "ansi-regex": "^3.0.0" } }, - "strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", - "dev": true - }, "strip-hex-prefix": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/strip-hex-prefix/-/strip-hex-prefix-1.0.0.tgz", @@ -25295,83 +24869,6 @@ "get-port": "^3.1.0" } }, - "table": { - "version": "6.8.1", - "resolved": "https://registry.npmjs.org/table/-/table-6.8.1.tgz", - "integrity": "sha512-Y4X9zqrCftUhMeH2EptSSERdVKt/nEdijTOacGD/97EKjhQ/Qs8RTlEGABSJNNN8lac9kheH+af7yAkEWlgneA==", - "dev": true, - "requires": { - "ajv": "^8.0.1", - "lodash.truncate": "^4.4.2", - "slice-ansi": "^4.0.0", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1" - }, - "dependencies": { - "ajv": { - "version": "8.11.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.2.tgz", - "integrity": "sha512-E4bfmKAhGiSTvMfL1Myyycaub+cUEU2/IvpylXkUu7CHBkBj1f/ikdzbD7YQ6FKUbixDxeYvB/xY4fvyroDlQg==", - "dev": true, - "requires": { - "fast-deep-equal": "^3.1.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.2.2" - } - }, - "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 - }, - "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 - }, - "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 - }, - "json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true - }, - "require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true - }, - "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" - } - }, - "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" - } - } - } - }, "tar": { "version": "4.4.19", "resolved": "https://registry.npmjs.org/tar/-/tar-4.4.19.tgz", @@ -25502,18 +24999,6 @@ "integrity": "sha512-1m4RA7xVAJrSGrrXGs0L3YTwyvBs2S8PbRHaLZAkFw7JR8oIFwYtysxlBZhYIa7xSyiYJKZ3iGrrk55cGA3i9A==", "dev": true }, - "tsconfig-paths": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.14.1.tgz", - "integrity": "sha512-fxDhWnFSLt3VuTwtvJt5fpwxBHg5AdKWMsgcPOOIilyjymcYVZoCQF8fvFRezCNfblEXmi+PcM1eYHeOAgXCOQ==", - "dev": true, - "requires": { - "@types/json5": "^0.0.29", - "json5": "^1.0.1", - "minimist": "^1.2.6", - "strip-bom": "^3.0.0" - } - }, "tslib": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", @@ -25727,12 +25212,6 @@ "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", "dev": true }, - "v8-compile-cache": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", - "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==", - "dev": true - }, "validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", diff --git a/package.json b/package.json index 4bc8f6e25..c20e7f883 100644 --- a/package.json +++ b/package.json @@ -59,12 +59,8 @@ "@openzeppelin/docs-utils": "^0.1.3", "@openzeppelin/test-helpers": "^0.5.13", "chai": "^4.2.0", - "eslint": "^7.32.0", - "eslint-config-standard": "^16.0.3", - "eslint-plugin-import": "^2.25.4", - "eslint-plugin-mocha": "^10.0.3", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^5.2.0", + "eslint": "^8.30.0", + "eslint-config-prettier": "^8.5.0", "eth-sig-util": "^3.0.0", "ethereumjs-util": "^7.0.7", "ethereumjs-wallet": "^1.0.1", diff --git a/test/access/AccessControl.behavior.js b/test/access/AccessControl.behavior.js index 53dfa3ddb..2edd3fd4a 100644 --- a/test/access/AccessControl.behavior.js +++ b/test/access/AccessControl.behavior.js @@ -7,7 +7,7 @@ const DEFAULT_ADMIN_ROLE = '0x00000000000000000000000000000000000000000000000000 const ROLE = web3.utils.soliditySha3('ROLE'); const OTHER_ROLE = web3.utils.soliditySha3('OTHER_ROLE'); -function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, otherAdmin, otherAuthorized) { +function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, otherAdmin) { shouldSupportInterfaces(['AccessControl']); describe('default admin', function () { diff --git a/test/proxy/Clones.test.js b/test/proxy/Clones.test.js index 65e5ac11b..0393a3331 100644 --- a/test/proxy/Clones.test.js +++ b/test/proxy/Clones.test.js @@ -6,7 +6,7 @@ const shouldBehaveLikeClone = require('./Clones.behaviour'); const ClonesMock = artifacts.require('ClonesMock'); -contract('Clones', function (accounts) { +contract('Clones', function () { describe('clone', function () { shouldBehaveLikeClone(async (implementation, initData, opts = {}) => { const factory = await ClonesMock.new(); diff --git a/test/proxy/utils/Initializable.test.js b/test/proxy/utils/Initializable.test.js index 2c0c147f6..39c820b9d 100644 --- a/test/proxy/utils/Initializable.test.js +++ b/test/proxy/utils/Initializable.test.js @@ -10,7 +10,7 @@ const DisableBad1 = artifacts.require('DisableBad1'); const DisableBad2 = artifacts.require('DisableBad2'); const DisableOk = artifacts.require('DisableOk'); -contract('Initializable', function (accounts) { +contract('Initializable', function () { describe('basic testing without inheritance', function () { beforeEach('deploying', async function () { this.contract = await InitializableMock.new(); diff --git a/test/proxy/utils/UUPSUpgradeable.test.js b/test/proxy/utils/UUPSUpgradeable.test.js index 466081d20..cd465143e 100644 --- a/test/proxy/utils/UUPSUpgradeable.test.js +++ b/test/proxy/utils/UUPSUpgradeable.test.js @@ -8,7 +8,7 @@ const UUPSUpgradeableUnsafeMock = artifacts.require('UUPSUpgradeableUnsafeMock') const UUPSUpgradeableLegacyMock = artifacts.require('UUPSUpgradeableLegacyMock'); const CountersImpl = artifacts.require('CountersImpl'); -contract('UUPSUpgradeable', function (accounts) { +contract('UUPSUpgradeable', function () { before(async function () { this.implInitial = await UUPSUpgradeableMock.new(); this.implUpgradeOk = await UUPSUpgradeableMock.new(); diff --git a/test/security/ReentrancyGuard.test.js b/test/security/ReentrancyGuard.test.js index c7f7d4697..172a29b1f 100644 --- a/test/security/ReentrancyGuard.test.js +++ b/test/security/ReentrancyGuard.test.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const ReentrancyMock = artifacts.require('ReentrancyMock'); const ReentrancyAttack = artifacts.require('ReentrancyAttack'); -contract('ReentrancyGuard', function (accounts) { +contract('ReentrancyGuard', function () { beforeEach(async function () { this.reentrancyMock = await ReentrancyMock.new(); expect(await this.reentrancyMock.counter()).to.be.bignumber.equal('0'); diff --git a/test/token/ERC721/ERC721.behavior.js b/test/token/ERC721/ERC721.behavior.js index 021398449..7c91671df 100644 --- a/test/token/ERC721/ERC721.behavior.js +++ b/test/token/ERC721/ERC721.behavior.js @@ -83,7 +83,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another await this.token.setApprovalForAll(operator, true, { from: owner }); }); - const transferWasSuccessful = function ({ owner, tokenId, approved }) { + const transferWasSuccessful = function ({ owner, tokenId }) { it('transfers the ownership of the given token ID to the given address', async function () { expect(await this.token.ownerOf(tokenId)).to.be.equal(this.toWhom); }); diff --git a/test/utils/Arrays.test.js b/test/utils/Arrays.test.js index 8c287ccff..5d32e510a 100644 --- a/test/utils/Arrays.test.js +++ b/test/utils/Arrays.test.js @@ -6,7 +6,7 @@ const AddressArraysMock = artifacts.require('AddressArraysMock'); const Bytes32ArraysMock = artifacts.require('Bytes32ArraysMock'); const Uint256ArraysMock = artifacts.require('Uint256ArraysMock'); -contract('Arrays', function (accounts) { +contract('Arrays', function () { describe('findUpperBound', function () { context('Even number of elements', function () { const EVEN_ELEMENTS_ARRAY = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; diff --git a/test/utils/Checkpoints.test.js b/test/utils/Checkpoints.test.js index 87335da9b..abc5c9b36 100644 --- a/test/utils/Checkpoints.test.js +++ b/test/utils/Checkpoints.test.js @@ -9,7 +9,7 @@ const CheckpointsMock = artifacts.require('CheckpointsMock'); const first = (array) => array.length ? array[0] : undefined; const last = (array) => array.length ? array[array.length - 1] : undefined; -contract('Checkpoints', function (accounts) { +contract('Checkpoints', function () { describe('History checkpoints', function () { beforeEach(async function () { this.checkpoint = await CheckpointsMock.new(); diff --git a/test/utils/Counters.test.js b/test/utils/Counters.test.js index 04be4c0c8..2159fd08d 100644 --- a/test/utils/Counters.test.js +++ b/test/utils/Counters.test.js @@ -4,7 +4,7 @@ const { expect } = require('chai'); const CountersImpl = artifacts.require('CountersImpl'); -contract('Counters', function (accounts) { +contract('Counters', function () { beforeEach(async function () { this.counter = await CountersImpl.new(); }); diff --git a/test/utils/Strings.test.js b/test/utils/Strings.test.js index 6c4c3423b..6d8e3aa3c 100644 --- a/test/utils/Strings.test.js +++ b/test/utils/Strings.test.js @@ -4,7 +4,7 @@ const { expect } = require('chai'); const StringsMock = artifacts.require('StringsMock'); -contract('Strings', function (accounts) { +contract('Strings', function () { before(async function () { this.strings = await StringsMock.new(); }); diff --git a/test/utils/TimersBlockNumberImpl.test.js b/test/utils/TimersBlockNumberImpl.test.js index d9f83d933..ee0d54bfb 100644 --- a/test/utils/TimersBlockNumberImpl.test.js +++ b/test/utils/TimersBlockNumberImpl.test.js @@ -3,7 +3,7 @@ const { expect } = require('chai'); const TimersBlockNumberImpl = artifacts.require('TimersBlockNumberImpl'); -contract('TimersBlockNumber', function (accounts) { +contract('TimersBlockNumber', function () { beforeEach(async function () { this.instance = await TimersBlockNumberImpl.new(); this.now = await web3.eth.getBlock('latest').then(({ number }) => number); diff --git a/test/utils/TimersTimestamp.test.js b/test/utils/TimersTimestamp.test.js index b08118d4f..fc32de7d0 100644 --- a/test/utils/TimersTimestamp.test.js +++ b/test/utils/TimersTimestamp.test.js @@ -3,7 +3,7 @@ const { expect } = require('chai'); const TimersTimestampImpl = artifacts.require('TimersTimestampImpl'); -contract('TimersTimestamp', function (accounts) { +contract('TimersTimestamp', function () { beforeEach(async function () { this.instance = await TimersTimestampImpl.new(); this.now = await web3.eth.getBlock('latest').then(({ timestamp }) => timestamp); diff --git a/test/utils/cryptography/MerkleProof.test.js b/test/utils/cryptography/MerkleProof.test.js index 2d4aacdac..7af3d38d7 100644 --- a/test/utils/cryptography/MerkleProof.test.js +++ b/test/utils/cryptography/MerkleProof.test.js @@ -8,7 +8,7 @@ const { expect } = require('chai'); const MerkleProofWrapper = artifacts.require('MerkleProofWrapper'); -contract('MerkleProof', function (accounts) { +contract('MerkleProof', function () { beforeEach(async function () { this.merkleProof = await MerkleProofWrapper.new(); }); diff --git a/test/utils/introspection/ERC165.test.js b/test/utils/introspection/ERC165.test.js index c891500e3..fabad8cdc 100644 --- a/test/utils/introspection/ERC165.test.js +++ b/test/utils/introspection/ERC165.test.js @@ -2,7 +2,7 @@ const { shouldSupportInterfaces } = require('./SupportsInterface.behavior'); const ERC165Mock = artifacts.require('ERC165Mock'); -contract('ERC165', function (accounts) { +contract('ERC165', function () { beforeEach(async function () { this.mock = await ERC165Mock.new(); }); diff --git a/test/utils/introspection/ERC165Checker.test.js b/test/utils/introspection/ERC165Checker.test.js index 90409a899..f4abf44f8 100644 --- a/test/utils/introspection/ERC165Checker.test.js +++ b/test/utils/introspection/ERC165Checker.test.js @@ -16,7 +16,7 @@ const DUMMY_UNSUPPORTED_ID = '0xbaddcafe'; const DUMMY_UNSUPPORTED_ID_2 = '0xbaadcafe'; const DUMMY_ACCOUNT = '0x1111111111111111111111111111111111111111'; -contract('ERC165Checker', function (accounts) { +contract('ERC165Checker', function () { beforeEach(async function () { this.mock = await ERC165CheckerMock.new(); }); diff --git a/test/utils/introspection/ERC165Storage.test.js b/test/utils/introspection/ERC165Storage.test.js index 568d64576..9c2792de8 100644 --- a/test/utils/introspection/ERC165Storage.test.js +++ b/test/utils/introspection/ERC165Storage.test.js @@ -4,7 +4,7 @@ const { shouldSupportInterfaces } = require('./SupportsInterface.behavior'); const ERC165Mock = artifacts.require('ERC165StorageMock'); -contract('ERC165Storage', function (accounts) { +contract('ERC165Storage', function () { beforeEach(async function () { this.mock = await ERC165Mock.new(); }); diff --git a/test/utils/math/Math.test.js b/test/utils/math/Math.test.js index 2b5448b54..51df28d12 100644 --- a/test/utils/math/Math.test.js +++ b/test/utils/math/Math.test.js @@ -5,7 +5,7 @@ const { Rounding } = require('../../helpers/enums.js'); const MathMock = artifacts.require('MathMock'); -contract('Math', function (accounts) { +contract('Math', function () { const min = new BN('1234'); const max = new BN('5678'); const MAX_UINT256_SUB1 = MAX_UINT256.sub(new BN('1')); diff --git a/test/utils/math/SafeCast.test.js b/test/utils/math/SafeCast.test.js index 97fc22e92..1399350a5 100644 --- a/test/utils/math/SafeCast.test.js +++ b/test/utils/math/SafeCast.test.js @@ -4,7 +4,7 @@ const { range } = require('../../../scripts/helpers'); const SafeCastMock = artifacts.require('SafeCastMock'); -contract('SafeCast', async (accounts) => { +contract('SafeCast', async function () { beforeEach(async function () { this.safeCast = await SafeCastMock.new(); }); diff --git a/test/utils/math/SafeMath.test.js b/test/utils/math/SafeMath.test.js index 7c9b937a8..4c2cfe551 100644 --- a/test/utils/math/SafeMath.test.js +++ b/test/utils/math/SafeMath.test.js @@ -15,7 +15,7 @@ function expectStruct (value, expected) { } } -contract('SafeMath', function (accounts) { +contract('SafeMath', function () { beforeEach(async function () { this.safeMath = await SafeMathMock.new(); }); diff --git a/test/utils/math/SignedMath.test.js b/test/utils/math/SignedMath.test.js index 8e9826f02..f1bcc18b3 100644 --- a/test/utils/math/SignedMath.test.js +++ b/test/utils/math/SignedMath.test.js @@ -4,7 +4,7 @@ const { MIN_INT256, MAX_INT256 } = constants; const SignedMathMock = artifacts.require('SignedMathMock'); -contract('SignedMath', function (accounts) { +contract('SignedMath', function () { const min = new BN('-1234'); const max = new BN('5678'); diff --git a/test/utils/math/SignedSafeMath.test.js b/test/utils/math/SignedSafeMath.test.js index c6aa15ed9..c14d40be0 100644 --- a/test/utils/math/SignedSafeMath.test.js +++ b/test/utils/math/SignedSafeMath.test.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const SignedSafeMathMock = artifacts.require('SignedSafeMathMock'); -contract('SignedSafeMath', function (accounts) { +contract('SignedSafeMath', function () { beforeEach(async function () { this.safeMath = await SignedSafeMathMock.new(); }); diff --git a/test/utils/structs/BitMap.test.js b/test/utils/structs/BitMap.test.js index 58d70ca8f..4d85bcfbf 100644 --- a/test/utils/structs/BitMap.test.js +++ b/test/utils/structs/BitMap.test.js @@ -3,7 +3,7 @@ const { expect } = require('chai'); const BitMap = artifacts.require('BitMapMock'); -contract('BitMap', function (accounts) { +contract('BitMap', function () { const keyA = new BN('7891'); const keyB = new BN('451'); const keyC = new BN('9592328'); diff --git a/test/utils/structs/DoubleEndedQueue.test.js b/test/utils/structs/DoubleEndedQueue.test.js index 545c82a72..667df77ca 100644 --- a/test/utils/structs/DoubleEndedQueue.test.js +++ b/test/utils/structs/DoubleEndedQueue.test.js @@ -10,7 +10,7 @@ async function getContent (deque) { return values; } -contract('DoubleEndedQueue', function (accounts) { +contract('DoubleEndedQueue', function () { const bytesA = '0xdeadbeef'.padEnd(66, '0'); const bytesB = '0x0123456789'.padEnd(66, '0'); const bytesC = '0x42424242'.padEnd(66, '0'); From ccc175a9ed6afff646d7777bb57598fac6f7787b Mon Sep 17 00:00:00 2001 From: Francisco Date: Fri, 30 Dec 2022 16:51:22 -0300 Subject: [PATCH 10/29] Add /out to .gitignore (#3908) --- .gitignore | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index c60c5d945..2f5220de1 100644 --- a/.gitignore +++ b/.gitignore @@ -54,9 +54,12 @@ allFiredEvents .coverage_cache .coverage_contracts -# hardhat -cache -artifacts +# Hardhat +/cache +/artifacts + +# Foundry +/out # Certora .certora* From a4596cab053d46e0bf2957e2ed490cb3921539ee Mon Sep 17 00:00:00 2001 From: Pascal Marco Caversaccio Date: Fri, 30 Dec 2022 23:00:53 +0100 Subject: [PATCH 11/29] Add warning on `SELFDESTRUCT` usage with `isContract` (#3875) Co-authored-by: Francisco --- contracts/utils/Address.sol | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/contracts/utils/Address.sol b/contracts/utils/Address.sol index 70d03e3d2..433a866d7 100644 --- a/contracts/utils/Address.sol +++ b/contracts/utils/Address.sol @@ -22,6 +22,10 @@ library Address { * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed + * + * Furthermore, `isContract` will also return true if the target contract within + * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, + * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] From 0892f877b885d63bc3aed4a36a795f2004f16b15 Mon Sep 17 00:00:00 2001 From: Francisco Giordano Date: Mon, 2 Jan 2023 17:45:42 -0300 Subject: [PATCH 12/29] Fix base for Renovate config --- renovate.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/renovate.json b/renovate.json index 0ec3e857e..f6df03630 100644 --- a/renovate.json +++ b/renovate.json @@ -1,6 +1,6 @@ { "extends": [ - "github>OpenZeppelin/code-style" + "github>OpenZeppelin/configs" ], "packageRules": [ { From 4fc19ddb8dd1de3b828c32942896d527cf0e8eda Mon Sep 17 00:00:00 2001 From: Francisco Giordano Date: Mon, 2 Jan 2023 18:03:24 -0300 Subject: [PATCH 13/29] Add label to Renovate PRs --- renovate.json | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/renovate.json b/renovate.json index f6df03630..875bf6ec4 100644 --- a/renovate.json +++ b/renovate.json @@ -1,11 +1,4 @@ { - "extends": [ - "github>OpenZeppelin/configs" - ], - "packageRules": [ - { - "extends": ["packages:eslint"], - "enabled": false - } - ] + "extends": ["github>OpenZeppelin/configs"], + "labels": ["ignore-changelog"] } From 276b32a5ecbab5c52fe6dfd450108d7964df0843 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 2 Jan 2023 21:42:08 +0000 Subject: [PATCH 14/29] Update lockfile (#3909) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- package-lock.json | 1151 +++++++++++++++++---------------------------- 1 file changed, 443 insertions(+), 708 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9473a1be3..5524f8a12 100644 --- a/package-lock.json +++ b/package-lock.json @@ -46,12 +46,15 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", - "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", + "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", "dev": true, "dependencies": { - "@babel/highlight": "^7.10.4" + "@babel/highlight": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { @@ -261,9 +264,9 @@ "dev": true }, "node_modules/@eslint/eslintrc": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.4.0.tgz", - "integrity": "sha512-7yfvXy6MWLgWSFsLhz5yH3iQ52St8cdUY6FoGieKkRDVxuxmrNuUetIuu6cmjNWwniUHiWXjxCr5tTXDrbYS5A==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.4.1.tgz", + "integrity": "sha512-XXrH9Uarn0stsyldqDYq8r++mROmWRI1xKMXa640Bb//SY1+ECYX6VzT6Lcx5frD0V30XieqJ0oX9I2Xj5aoMA==", "dev": true, "dependencies": { "ajv": "^6.12.4", @@ -289,15 +292,6 @@ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true }, - "node_modules/@eslint/eslintrc/node_modules/ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true, - "engines": { - "node": ">= 4" - } - }, "node_modules/@eslint/eslintrc/node_modules/js-yaml": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", @@ -2311,9 +2305,9 @@ "dev": true }, "node_modules/@types/node": { - "version": "18.11.17", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.17.tgz", - "integrity": "sha512-HJSUJmni4BeDHhfzn6nF0sVmd1SMezP7/4F0Lq+aXzmp2xm9O7WXrUtHW/CHlYVtZUbByEvWidHqRtcJXGF2Ng==", + "version": "18.11.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz", + "integrity": "sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==", "dev": true }, "node_modules/@types/pbkdf2": { @@ -2712,6 +2706,15 @@ "integrity": "sha512-XHusKxKz3zoYk1ic8Un640joHbFMhbqneyoZfoKnEGtf2ey9Uh/IdpcQplODdO/kENaMIWsD0nJm4+wX3UNLHA==", "dev": true }, + "node_modules/astral-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", + "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", + "dev": true, + "engines": { + "node": ">=4" + } + }, "node_modules/async": { "version": "2.6.4", "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", @@ -3631,12 +3634,6 @@ "node": ">=8" } }, - "node_modules/cliui/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/cliui/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", @@ -4415,9 +4412,9 @@ } }, "node_modules/emoji-regex": { - "version": "10.2.1", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.2.1.tgz", - "integrity": "sha512-97g6QgOk8zlDRdgq1WxwgTMgEWGVAQvB5Fdpgc1MkNy56la5SKP9GsMXKDOdqwn90/41a8yPwIGk1Y6WVbeMQA==", + "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/encodeurl": { @@ -4528,6 +4525,24 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/es-abstract/node_modules/object.assign": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", + "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/es-array-method-boxes-properly": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/es-array-method-boxes-properly/-/es-array-method-boxes-properly-1.0.0.tgz", @@ -4716,12 +4731,12 @@ } }, "node_modules/eslint": { - "version": "8.30.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.30.0.tgz", - "integrity": "sha512-MGADB39QqYuzEGov+F/qb18r4i7DohCDOfatHaxI2iGlPuC65bwG2gxgO+7DkyL38dRFaRH7RaRAgU6JKL9rMQ==", + "version": "8.31.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.31.0.tgz", + "integrity": "sha512-0tQQEVdmPZ1UtUKXjX7EMm9BlgJ08G90IhWh0PKDCb3ZLsgAOHI8fYSIzYVZej92zsgq+ft0FGsxhJ3xo2tbuA==", "dev": true, "dependencies": { - "@eslint/eslintrc": "^1.4.0", + "@eslint/eslintrc": "^1.4.1", "@humanwhocodes/config-array": "^0.11.8", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", @@ -4772,9 +4787,9 @@ } }, "node_modules/eslint-config-prettier": { - "version": "8.5.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.5.0.tgz", - "integrity": "sha512-obmWKLUNCnhtQRKc+tmnYuQl0pFU1ibYJQ5BGhTVB08bHe9wC8qUeG7c08dj9XX+AuPj1YSGSQIHl1pnDHZR0Q==", + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.6.0.tgz", + "integrity": "sha512-bAF0eLpLVqP5oEVUFKpMA+NnRFICwn9X8B5jrR9FcqnYBuPbqWEjTEspPWMj5ye6czoSLDweCzSo3Ko7gGrZaA==", "dev": true, "bin": { "eslint-config-prettier": "bin/cli.js" @@ -4796,13 +4811,40 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, - "node_modules/eslint-scope/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "node_modules/eslint-utils": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", + "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^2.0.0" + }, + "engines": { + "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" + }, + "peerDependencies": { + "eslint": ">=5" + } + }, + "node_modules/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", + "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", "dev": true, "engines": { - "node": ">=4.0" + "node": ">=10" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", + "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, "node_modules/eslint/node_modules/ansi-regex": { @@ -4836,42 +4878,6 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/eslint/node_modules/eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "dependencies": { - "eslint-visitor-keys": "^2.0.0" - }, - "engines": { - "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/mysticatea" - }, - "peerDependencies": { - "eslint": ">=5" - } - }, - "node_modules/eslint/node_modules/eslint-utils/node_modules/eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/eslint/node_modules/eslint-visitor-keys": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", - "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", - "dev": true, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, "node_modules/eslint/node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -4900,15 +4906,6 @@ "node": ">=10.13.0" } }, - "node_modules/eslint/node_modules/ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true, - "engines": { - "node": ">= 4" - } - }, "node_modules/eslint/node_modules/js-yaml": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", @@ -4995,15 +4992,6 @@ "url": "https://opencollective.com/eslint" } }, - "node_modules/espree/node_modules/eslint-visitor-keys": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", - "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", - "dev": true, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, "node_modules/esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", @@ -5029,15 +5017,6 @@ "node": ">=0.10" } }, - "node_modules/esquery/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "engines": { - "node": ">=4.0" - } - }, "node_modules/esrecurse": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", @@ -5050,7 +5029,7 @@ "node": ">=4.0" } }, - "node_modules/esrecurse/node_modules/estraverse": { + "node_modules/estraverse": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", @@ -5059,15 +5038,6 @@ "node": ">=4.0" } }, - "node_modules/estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true, - "engines": { - "node": ">=4.0" - } - }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -5476,21 +5446,6 @@ "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", "dev": true }, - "node_modules/eth-gas-reporter/node_modules/object.assign": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", - "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", - "dev": true, - "dependencies": { - "define-properties": "^1.1.2", - "function-bind": "^1.1.1", - "has-symbols": "^1.0.0", - "object-keys": "^1.0.11" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/eth-gas-reporter/node_modules/p-locate": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", @@ -6139,9 +6094,9 @@ "dev": true }, "node_modules/fastq": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.14.0.tgz", - "integrity": "sha512-eR2D+V9/ExcbF9ls441yIuN6TI2ED1Y2ZcA5BmMtJsOkWOFRJQ0Jt0g1UwqXJJVAb+V+umH5Dfr8oh4EVP7VVg==", + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz", + "integrity": "sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw==", "dev": true, "dependencies": { "reusify": "^1.0.4" @@ -6752,15 +6707,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/globby/node_modules/ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true, - "engines": { - "node": ">= 4" - } - }, "node_modules/gopd": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", @@ -6884,9 +6830,9 @@ } }, "node_modules/hardhat": { - "version": "2.12.4", - "resolved": "https://registry.npmjs.org/hardhat/-/hardhat-2.12.4.tgz", - "integrity": "sha512-rc9S2U/4M+77LxW1Kg7oqMMmjl81tzn5rNFARhbXKUA1am/nhfMJEujOjuKvt+ZGMiZ11PYSe8gyIpB/aRNDgw==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/hardhat/-/hardhat-2.12.5.tgz", + "integrity": "sha512-f/t7+hLlhsnQZ6LDXyV+8rHGRZFZY1sgFvgrwr9fBjMdGp1Bu6hHq1KXS4/VFZfZcVdL1DAWWEkryinZhqce+A==", "dev": true, "dependencies": { "@ethersproject/abi": "^5.1.2", @@ -7187,18 +7133,6 @@ "node": ">=0.10.0" } }, - "node_modules/hardhat/node_modules/resolve": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", - "integrity": "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w==", - "dev": true, - "dependencies": { - "path-parse": "^1.0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/hardhat/node_modules/rimraf": { "version": "2.7.1", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", @@ -7590,9 +7524,9 @@ ] }, "node_modules/ignore": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", - "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", "dev": true, "engines": { "node": ">= 4" @@ -7932,18 +7866,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-core-module": { - "version": "2.11.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", - "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", - "dev": true, - "dependencies": { - "has": "^1.0.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/is-date-object": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", @@ -8352,9 +8274,9 @@ } }, "node_modules/keccak": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/keccak/-/keccak-3.0.2.tgz", - "integrity": "sha512-PyKKjkH53wDMLGrvmRGSNWgmSxZOUqbnXwKL9tmgbFYA1iAYqW21kfR7mZXV0MlESiefxQQE9X9fTa3X+2MPDQ==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/keccak/-/keccak-3.0.3.tgz", + "integrity": "sha512-JZrLIAJWuZxKbCilMpNz5Vj7Vtb4scDG3dMXLOsbzBmQGyjwE61BbW7bJkfKKCShXiQZt3T6sBgALRtmd+nZaQ==", "dev": true, "hasInstallScript": true, "dependencies": { @@ -8559,18 +8481,6 @@ "node": ">=0.10.0" } }, - "node_modules/load-json-file/node_modules/strip-bom": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", - "integrity": "sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==", - "dev": true, - "dependencies": { - "is-utf8": "^0.2.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", @@ -9056,12 +8966,6 @@ "wrap-ansi": "^7.0.0" } }, - "node_modules/mocha/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/mocha/node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -9622,21 +9526,18 @@ } }, "node_modules/object.assign": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", - "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", + "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", "dev": true, "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "has-symbols": "^1.0.3", - "object-keys": "^1.1.1" + "define-properties": "^1.1.2", + "function-bind": "^1.1.1", + "has-symbols": "^1.0.0", + "object-keys": "^1.0.11" }, "engines": { "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, "node_modules/object.getownpropertydescriptors": { @@ -10073,73 +9974,20 @@ } }, "node_modules/prettier-plugin-solidity": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/prettier-plugin-solidity/-/prettier-plugin-solidity-1.1.0.tgz", - "integrity": "sha512-5gq0T49ifvXH/6x1STuKyWjTUgi6ICoV65yNtKlg/vZEvocFtSpByJOJICBfqPwNsnv4vhhWIqkLGSUJmWum2w==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/prettier-plugin-solidity/-/prettier-plugin-solidity-1.1.1.tgz", + "integrity": "sha512-uD24KO26tAHF+zMN2nt1OUzfknzza5AgxjogQQrMLZc7j8xiQrDoNWNeOlfFC0YLTwo12CLD10b9niLyP6AqXg==", "dev": true, "dependencies": { "@solidity-parser/parser": "^0.14.5", - "emoji-regex": "^10.2.1", - "escape-string-regexp": "^4.0.0", "semver": "^7.3.8", - "solidity-comments-extractor": "^0.0.7", - "string-width": "^4.2.3" + "solidity-comments-extractor": "^0.0.7" }, "engines": { "node": ">=12" }, "peerDependencies": { - "prettier": "^2.3.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/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" + "prettier": ">=2.3.0 || >=3.0.0-alpha.0" } }, "node_modules/process": { @@ -10649,17 +10497,12 @@ "dev": true }, "node_modules/resolve": { - "version": "1.22.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", - "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", + "integrity": "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w==", "dev": true, "dependencies": { - "is-core-module": "^2.9.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" + "path-parse": "^1.0.6" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -11370,6 +11213,47 @@ "node": ">=8" } }, + "node_modules/slice-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", + "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.0", + "astral-regex": "^1.0.0", + "is-fullwidth-code-point": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/slice-ansi/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/slice-ansi/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/slice-ansi/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + }, "node_modules/snake-case": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/snake-case/-/snake-case-2.1.0.tgz", @@ -11643,15 +11527,6 @@ "node": ">=0.4.0" } }, - "node_modules/solhint/node_modules/ansi-regex": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", - "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", - "dev": true, - "engines": { - "node": ">=6" - } - }, "node_modules/solhint/node_modules/ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", @@ -11664,15 +11539,6 @@ "node": ">=4" } }, - "node_modules/solhint/node_modules/astral-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", - "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/solhint/node_modules/chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", @@ -11727,12 +11593,6 @@ "semver": "bin/semver" } }, - "node_modules/solhint/node_modules/emoji-regex": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", - "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", - "dev": true - }, "node_modules/solhint/node_modules/escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -11849,6 +11709,15 @@ "node": ">=6.0.0" } }, + "node_modules/solhint/node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, "node_modules/solhint/node_modules/file-entry-cache": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-5.0.1.tgz", @@ -11919,6 +11788,15 @@ "node": ">=4" } }, + "node_modules/solhint/node_modules/ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, "node_modules/solhint/node_modules/levn": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", @@ -12031,46 +11909,6 @@ "node": ">=0.10.0" } }, - "node_modules/solhint/node_modules/slice-ansi": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", - "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^3.2.0", - "astral-regex": "^1.0.0", - "is-fullwidth-code-point": "^2.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/solhint/node_modules/string-width": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", - "dev": true, - "dependencies": { - "emoji-regex": "^7.0.1", - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^5.1.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/solhint/node_modules/string-width/node_modules/strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "dev": true, - "dependencies": { - "ansi-regex": "^4.1.0" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/solhint/node_modules/strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", @@ -12092,21 +11930,6 @@ "node": ">=4" } }, - "node_modules/solhint/node_modules/table": { - "version": "5.4.6", - "resolved": "https://registry.npmjs.org/table/-/table-5.4.6.tgz", - "integrity": "sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug==", - "dev": true, - "dependencies": { - "ajv": "^6.10.2", - "lodash": "^4.17.14", - "slice-ansi": "^2.1.0", - "string-width": "^3.0.0" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/solhint/node_modules/type-check": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", @@ -12132,9 +11955,9 @@ } }, "node_modules/solidity-ast": { - "version": "0.4.39", - "resolved": "https://registry.npmjs.org/solidity-ast/-/solidity-ast-0.4.39.tgz", - "integrity": "sha512-91d4HMzV9x3ZG1fXRtAFFq2UjJrQXkyWdrmzXqBlueOSGB+v+0+iiLfZIPnTE0apndG2zm23qkZQJf8IbRrf7w==", + "version": "0.4.40", + "resolved": "https://registry.npmjs.org/solidity-ast/-/solidity-ast-0.4.40.tgz", + "integrity": "sha512-M8uLBT2jgFB7B0iVAC5a2l71J8vim7aEm03AZkaHbDqyrl1pE+i5PriMEw6WlwGfHp3/Ym7cn9BqvVLQgRk+Yw==", "dev": true }, "node_modules/solidity-comments": { @@ -12703,21 +12526,6 @@ "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", "dev": true }, - "node_modules/solidity-coverage/node_modules/object.assign": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", - "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", - "dev": true, - "dependencies": { - "define-properties": "^1.1.2", - "function-bind": "^1.1.1", - "has-symbols": "^1.0.0", - "object-keys": "^1.0.11" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/solidity-coverage/node_modules/p-locate": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", @@ -12873,9 +12681,9 @@ } }, "node_modules/solidity-docgen": { - "version": "0.6.0-beta.32", - "resolved": "https://registry.npmjs.org/solidity-docgen/-/solidity-docgen-0.6.0-beta.32.tgz", - "integrity": "sha512-LGcosbgqxrqTo9winVq3+Xz1shS9k4p+RKwqPVPI0HtjfsKF9Mc5GzBzOUhce9uwzy0yJfhf832whfY1UKt4Aw==", + "version": "0.6.0-beta.34", + "resolved": "https://registry.npmjs.org/solidity-docgen/-/solidity-docgen-0.6.0-beta.34.tgz", + "integrity": "sha512-igdGrkg8gT1jn+B2NwzjEtSf+7NTrSi/jz88zO7MZWgETmcWbXaxgAsQP4BQeC4YFeH0Pie1NsLP7+9qDgvFtA==", "dev": true, "dependencies": { "handlebars": "^4.7.7", @@ -13105,6 +12913,18 @@ "node": ">=4" } }, + "node_modules/strip-bom": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", + "integrity": "sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==", + "dev": true, + "dependencies": { + "is-utf8": "^0.2.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/strip-hex-prefix": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/strip-hex-prefix/-/strip-hex-prefix-1.0.0.tgz", @@ -13151,18 +12971,6 @@ "node": ">=8" } }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/swap-case": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/swap-case/-/swap-case-1.1.2.tgz", @@ -13303,6 +13111,62 @@ "get-port": "^3.1.0" } }, + "node_modules/table": { + "version": "5.4.6", + "resolved": "https://registry.npmjs.org/table/-/table-5.4.6.tgz", + "integrity": "sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug==", + "dev": true, + "dependencies": { + "ajv": "^6.10.2", + "lodash": "^4.17.14", + "slice-ansi": "^2.1.0", + "string-width": "^3.0.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/table/node_modules/ansi-regex": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/table/node_modules/emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "node_modules/table/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/table/node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/tar": { "version": "4.4.19", "resolved": "https://registry.npmjs.org/tar/-/tar-4.4.19.tgz", @@ -14325,12 +14189,6 @@ "node": ">=8" } }, - "node_modules/wrap-ansi/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/wrap-ansi/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", @@ -14546,12 +14404,6 @@ "node": ">=8" } }, - "node_modules/yargs/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/yargs/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", @@ -14611,12 +14463,12 @@ }, "dependencies": { "@babel/code-frame": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", - "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", + "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", "dev": true, "requires": { - "@babel/highlight": "^7.10.4" + "@babel/highlight": "^7.18.6" } }, "@babel/helper-validator-identifier": { @@ -14794,9 +14646,9 @@ "dev": true }, "@eslint/eslintrc": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.4.0.tgz", - "integrity": "sha512-7yfvXy6MWLgWSFsLhz5yH3iQ52St8cdUY6FoGieKkRDVxuxmrNuUetIuu6cmjNWwniUHiWXjxCr5tTXDrbYS5A==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.4.1.tgz", + "integrity": "sha512-XXrH9Uarn0stsyldqDYq8r++mROmWRI1xKMXa640Bb//SY1+ECYX6VzT6Lcx5frD0V30XieqJ0oX9I2Xj5aoMA==", "dev": true, "requires": { "ajv": "^6.12.4", @@ -14816,12 +14668,6 @@ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true }, - "ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true - }, "js-yaml": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", @@ -16265,9 +16111,9 @@ "dev": true }, "@types/node": { - "version": "18.11.17", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.17.tgz", - "integrity": "sha512-HJSUJmni4BeDHhfzn6nF0sVmd1SMezP7/4F0Lq+aXzmp2xm9O7WXrUtHW/CHlYVtZUbByEvWidHqRtcJXGF2Ng==", + "version": "18.11.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz", + "integrity": "sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==", "dev": true }, "@types/pbkdf2": { @@ -16575,6 +16421,12 @@ "integrity": "sha512-XHusKxKz3zoYk1ic8Un640joHbFMhbqneyoZfoKnEGtf2ey9Uh/IdpcQplODdO/kENaMIWsD0nJm4+wX3UNLHA==", "dev": true }, + "astral-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", + "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", + "dev": true + }, "async": { "version": "2.6.4", "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", @@ -17330,12 +17182,6 @@ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, - "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 - }, "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", @@ -17959,9 +17805,9 @@ } }, "emoji-regex": { - "version": "10.2.1", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.2.1.tgz", - "integrity": "sha512-97g6QgOk8zlDRdgq1WxwgTMgEWGVAQvB5Fdpgc1MkNy56la5SKP9GsMXKDOdqwn90/41a8yPwIGk1Y6WVbeMQA==", + "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 }, "encodeurl": { @@ -18048,6 +17894,20 @@ "string.prototype.trimend": "^1.0.6", "string.prototype.trimstart": "^1.0.6", "unbox-primitive": "^1.0.2" + }, + "dependencies": { + "object.assign": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", + "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.4", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + } + } } }, "es-array-method-boxes-properly": { @@ -18190,12 +18050,12 @@ } }, "eslint": { - "version": "8.30.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.30.0.tgz", - "integrity": "sha512-MGADB39QqYuzEGov+F/qb18r4i7DohCDOfatHaxI2iGlPuC65bwG2gxgO+7DkyL38dRFaRH7RaRAgU6JKL9rMQ==", + "version": "8.31.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.31.0.tgz", + "integrity": "sha512-0tQQEVdmPZ1UtUKXjX7EMm9BlgJ08G90IhWh0PKDCb3ZLsgAOHI8fYSIzYVZej92zsgq+ft0FGsxhJ3xo2tbuA==", "dev": true, "requires": { - "@eslint/eslintrc": "^1.4.0", + "@eslint/eslintrc": "^1.4.1", "@humanwhocodes/config-array": "^0.11.8", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", @@ -18258,29 +18118,6 @@ "supports-color": "^7.1.0" } }, - "eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "requires": { - "eslint-visitor-keys": "^2.0.0" - }, - "dependencies": { - "eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true - } - } - }, - "eslint-visitor-keys": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", - "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", - "dev": true - }, "find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -18300,12 +18137,6 @@ "is-glob": "^4.0.3" } }, - "ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true - }, "js-yaml": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", @@ -18354,9 +18185,9 @@ } }, "eslint-config-prettier": { - "version": "8.5.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.5.0.tgz", - "integrity": "sha512-obmWKLUNCnhtQRKc+tmnYuQl0pFU1ibYJQ5BGhTVB08bHe9wC8qUeG7c08dj9XX+AuPj1YSGSQIHl1pnDHZR0Q==", + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.6.0.tgz", + "integrity": "sha512-bAF0eLpLVqP5oEVUFKpMA+NnRFICwn9X8B5jrR9FcqnYBuPbqWEjTEspPWMj5ye6czoSLDweCzSo3Ko7gGrZaA==", "dev": true, "requires": {} }, @@ -18368,16 +18199,31 @@ "requires": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" + } + }, + "eslint-utils": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", + "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", + "dev": true, + "requires": { + "eslint-visitor-keys": "^2.0.0" }, "dependencies": { - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "eslint-visitor-keys": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", + "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", "dev": true } } }, + "eslint-visitor-keys": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", + "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", + "dev": true + }, "espree": { "version": "9.4.1", "resolved": "https://registry.npmjs.org/espree/-/espree-9.4.1.tgz", @@ -18387,14 +18233,6 @@ "acorn": "^8.8.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^3.3.0" - }, - "dependencies": { - "eslint-visitor-keys": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", - "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", - "dev": true - } } }, "esprima": { @@ -18410,14 +18248,6 @@ "dev": true, "requires": { "estraverse": "^5.1.0" - }, - "dependencies": { - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - } } }, "esrecurse": { @@ -18427,20 +18257,12 @@ "dev": true, "requires": { "estraverse": "^5.2.0" - }, - "dependencies": { - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - } } }, "estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true }, "esutils": { @@ -18762,18 +18584,6 @@ "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", "dev": true }, - "object.assign": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", - "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", - "dev": true, - "requires": { - "define-properties": "^1.1.2", - "function-bind": "^1.1.1", - "has-symbols": "^1.0.0", - "object-keys": "^1.0.11" - } - }, "p-locate": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", @@ -19372,9 +19182,9 @@ "dev": true }, "fastq": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.14.0.tgz", - "integrity": "sha512-eR2D+V9/ExcbF9ls441yIuN6TI2ED1Y2ZcA5BmMtJsOkWOFRJQ0Jt0g1UwqXJJVAb+V+umH5Dfr8oh4EVP7VVg==", + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz", + "integrity": "sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw==", "dev": true, "requires": { "reusify": "^1.0.4" @@ -19847,12 +19657,6 @@ "once": "^1.3.0", "path-is-absolute": "^1.0.0" } - }, - "ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true } } }, @@ -19951,9 +19755,9 @@ } }, "hardhat": { - "version": "2.12.4", - "resolved": "https://registry.npmjs.org/hardhat/-/hardhat-2.12.4.tgz", - "integrity": "sha512-rc9S2U/4M+77LxW1Kg7oqMMmjl81tzn5rNFARhbXKUA1am/nhfMJEujOjuKvt+ZGMiZ11PYSe8gyIpB/aRNDgw==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/hardhat/-/hardhat-2.12.5.tgz", + "integrity": "sha512-f/t7+hLlhsnQZ6LDXyV+8rHGRZFZY1sgFvgrwr9fBjMdGp1Bu6hHq1KXS4/VFZfZcVdL1DAWWEkryinZhqce+A==", "dev": true, "requires": { "@ethersproject/abi": "^5.1.2", @@ -20151,15 +19955,6 @@ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", "dev": true }, - "resolve": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", - "integrity": "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w==", - "dev": true, - "requires": { - "path-parse": "^1.0.6" - } - }, "rimraf": { "version": "2.7.1", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", @@ -20505,9 +20300,9 @@ "dev": true }, "ignore": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", - "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", + "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", "dev": true }, "immutable": { @@ -20754,15 +20549,6 @@ "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", "dev": true }, - "is-core-module": { - "version": "2.11.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", - "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", - "dev": true, - "requires": { - "has": "^1.0.3" - } - }, "is-date-object": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", @@ -21070,9 +20856,9 @@ } }, "keccak": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/keccak/-/keccak-3.0.2.tgz", - "integrity": "sha512-PyKKjkH53wDMLGrvmRGSNWgmSxZOUqbnXwKL9tmgbFYA1iAYqW21kfR7mZXV0MlESiefxQQE9X9fTa3X+2MPDQ==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/keccak/-/keccak-3.0.3.tgz", + "integrity": "sha512-JZrLIAJWuZxKbCilMpNz5Vj7Vtb4scDG3dMXLOsbzBmQGyjwE61BbW7bJkfKKCShXiQZt3T6sBgALRtmd+nZaQ==", "dev": true, "requires": { "node-addon-api": "^2.0.0", @@ -21217,15 +21003,6 @@ "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", "dev": true - }, - "strip-bom": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", - "integrity": "sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==", - "dev": true, - "requires": { - "is-utf8": "^0.2.0" - } } } }, @@ -21619,12 +21396,6 @@ "wrap-ansi": "^7.0.0" } }, - "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 - }, "find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -22065,15 +21836,15 @@ "dev": true }, "object.assign": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", - "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", + "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", "dev": true, "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "has-symbols": "^1.0.3", - "object-keys": "^1.1.1" + "define-properties": "^1.1.2", + "function-bind": "^1.1.1", + "has-symbols": "^1.0.0", + "object-keys": "^1.0.11" } }, "object.getownpropertydescriptors": { @@ -22408,59 +22179,14 @@ "dev": true }, "prettier-plugin-solidity": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/prettier-plugin-solidity/-/prettier-plugin-solidity-1.1.0.tgz", - "integrity": "sha512-5gq0T49ifvXH/6x1STuKyWjTUgi6ICoV65yNtKlg/vZEvocFtSpByJOJICBfqPwNsnv4vhhWIqkLGSUJmWum2w==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/prettier-plugin-solidity/-/prettier-plugin-solidity-1.1.1.tgz", + "integrity": "sha512-uD24KO26tAHF+zMN2nt1OUzfknzza5AgxjogQQrMLZc7j8xiQrDoNWNeOlfFC0YLTwo12CLD10b9niLyP6AqXg==", "dev": true, "requires": { "@solidity-parser/parser": "^0.14.5", - "emoji-regex": "^10.2.1", - "escape-string-regexp": "^4.0.0", "semver": "^7.3.8", - "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 - }, - "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" - } - } + "solidity-comments-extractor": "^0.0.7" } }, "process": { @@ -22840,14 +22566,12 @@ "dev": true }, "resolve": { - "version": "1.22.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", - "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", + "integrity": "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w==", "dev": true, "requires": { - "is-core-module": "^2.9.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" + "path-parse": "^1.0.6" } }, "resolve-alpn": { @@ -23385,6 +23109,43 @@ "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true }, + "slice-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", + "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "astral-regex": "^1.0.0", + "is-fullwidth-code-point": "^2.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true + } + } + }, "snake-case": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/snake-case/-/snake-case-2.1.0.tgz", @@ -23613,12 +23374,6 @@ "integrity": "sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==", "dev": true }, - "ansi-regex": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", - "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", - "dev": true - }, "ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", @@ -23628,12 +23383,6 @@ "color-convert": "^1.9.0" } }, - "astral-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", - "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", - "dev": true - }, "chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", @@ -23681,12 +23430,6 @@ } } }, - "emoji-regex": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", - "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", - "dev": true - }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -23781,6 +23524,12 @@ "eslint-visitor-keys": "^1.0.0" } }, + "estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true + }, "file-entry-cache": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-5.0.1.tgz", @@ -23833,6 +23582,12 @@ "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", "dev": true }, + "ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "dev": true + }, "levn": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", @@ -23912,39 +23667,6 @@ "integrity": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==", "dev": true }, - "slice-ansi": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", - "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.0", - "astral-regex": "^1.0.0", - "is-fullwidth-code-point": "^2.0.0" - } - }, - "string-width": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", - "dev": true, - "requires": { - "emoji-regex": "^7.0.1", - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^5.1.0" - }, - "dependencies": { - "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "dev": true, - "requires": { - "ansi-regex": "^4.1.0" - } - } - } - }, "strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", @@ -23960,18 +23682,6 @@ "has-flag": "^3.0.0" } }, - "table": { - "version": "5.4.6", - "resolved": "https://registry.npmjs.org/table/-/table-5.4.6.tgz", - "integrity": "sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug==", - "dev": true, - "requires": { - "ajv": "^6.10.2", - "lodash": "^4.17.14", - "slice-ansi": "^2.1.0", - "string-width": "^3.0.0" - } - }, "type-check": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", @@ -23993,9 +23703,9 @@ } }, "solidity-ast": { - "version": "0.4.39", - "resolved": "https://registry.npmjs.org/solidity-ast/-/solidity-ast-0.4.39.tgz", - "integrity": "sha512-91d4HMzV9x3ZG1fXRtAFFq2UjJrQXkyWdrmzXqBlueOSGB+v+0+iiLfZIPnTE0apndG2zm23qkZQJf8IbRrf7w==", + "version": "0.4.40", + "resolved": "https://registry.npmjs.org/solidity-ast/-/solidity-ast-0.4.40.tgz", + "integrity": "sha512-M8uLBT2jgFB7B0iVAC5a2l71J8vim7aEm03AZkaHbDqyrl1pE+i5PriMEw6WlwGfHp3/Ym7cn9BqvVLQgRk+Yw==", "dev": true }, "solidity-comments": { @@ -24385,18 +24095,6 @@ "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", "dev": true }, - "object.assign": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", - "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", - "dev": true, - "requires": { - "define-properties": "^1.1.2", - "function-bind": "^1.1.1", - "has-symbols": "^1.0.0", - "object-keys": "^1.0.11" - } - }, "p-locate": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", @@ -24524,9 +24222,9 @@ } }, "solidity-docgen": { - "version": "0.6.0-beta.32", - "resolved": "https://registry.npmjs.org/solidity-docgen/-/solidity-docgen-0.6.0-beta.32.tgz", - "integrity": "sha512-LGcosbgqxrqTo9winVq3+Xz1shS9k4p+RKwqPVPI0HtjfsKF9Mc5GzBzOUhce9uwzy0yJfhf832whfY1UKt4Aw==", + "version": "0.6.0-beta.34", + "resolved": "https://registry.npmjs.org/solidity-docgen/-/solidity-docgen-0.6.0-beta.34.tgz", + "integrity": "sha512-igdGrkg8gT1jn+B2NwzjEtSf+7NTrSi/jz88zO7MZWgETmcWbXaxgAsQP4BQeC4YFeH0Pie1NsLP7+9qDgvFtA==", "dev": true, "requires": { "handlebars": "^4.7.7", @@ -24715,6 +24413,15 @@ "ansi-regex": "^3.0.0" } }, + "strip-bom": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", + "integrity": "sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==", + "dev": true, + "requires": { + "is-utf8": "^0.2.0" + } + }, "strip-hex-prefix": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/strip-hex-prefix/-/strip-hex-prefix-1.0.0.tgz", @@ -24745,12 +24452,6 @@ "has-flag": "^4.0.0" } }, - "supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true - }, "swap-case": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/swap-case/-/swap-case-1.1.2.tgz", @@ -24869,6 +24570,52 @@ "get-port": "^3.1.0" } }, + "table": { + "version": "5.4.6", + "resolved": "https://registry.npmjs.org/table/-/table-5.4.6.tgz", + "integrity": "sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug==", + "dev": true, + "requires": { + "ajv": "^6.10.2", + "lodash": "^4.17.14", + "slice-ansi": "^2.1.0", + "string-width": "^3.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", + "dev": true + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, "tar": { "version": "4.4.19", "resolved": "https://registry.npmjs.org/tar/-/tar-4.4.19.tgz", @@ -25721,12 +25468,6 @@ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, - "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 - }, "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", @@ -25864,12 +25605,6 @@ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, - "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 - }, "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", From a81b0d0b2136a0cca6029048be25c4e2bb230d49 Mon Sep 17 00:00:00 2001 From: Pascal Marco Caversaccio Date: Tue, 3 Jan 2023 02:04:49 +0100 Subject: [PATCH 15/29] Use unchecked in MerkleProof.processMultiProof (#3869) Signed-off-by: Pascal Marco Caversaccio Co-authored-by: Francisco --- CHANGELOG.md | 1 + contracts/utils/cryptography/MerkleProof.sol | 12 ++++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5549260a5..58f21d999 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ * `Math`: optimize `log256` rounding check. ([#3745](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3745)) * `Strings`: add `equal` method. ([#3774](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3774)) * `Strings`: add `toString` method for signed integers. ([#3773](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3773)) + * `MerkleProof`: optimize by using unchecked arithmetic. ([#3745](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3745)) ### Deprecations diff --git a/contracts/utils/cryptography/MerkleProof.sol b/contracts/utils/cryptography/MerkleProof.sol index 0ce87faf2..3862fdbfe 100644 --- a/contracts/utils/cryptography/MerkleProof.sol +++ b/contracts/utils/cryptography/MerkleProof.sol @@ -135,7 +135,7 @@ library MerkleProof { // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. - // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the + // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; @@ -146,7 +146,9 @@ library MerkleProof { } if (totalHashes > 0) { - return hashes[totalHashes - 1]; + unchecked { + return hashes[totalHashes - 1]; + } } else if (leavesLen > 0) { return leaves[0]; } else { @@ -185,7 +187,7 @@ library MerkleProof { // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. - // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the + // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; @@ -196,7 +198,9 @@ library MerkleProof { } if (totalHashes > 0) { - return hashes[totalHashes - 1]; + unchecked { + return hashes[totalHashes - 1]; + } } else if (leavesLen > 0) { return leaves[0]; } else { From c1d9da4052a75232dca1fafac80c4a2cb82fe518 Mon Sep 17 00:00:00 2001 From: Hadrien Croubois Date: Tue, 3 Jan 2023 15:38:13 +0100 Subject: [PATCH 16/29] 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', + }, + ); }); }); From 3a3c87b1a676f277c17a4601de56ddfc432d427d Mon Sep 17 00:00:00 2001 From: Saint Rat Wrongtail <36714477+saint-rat@users.noreply.github.com> Date: Wed, 4 Jan 2023 00:52:53 +1000 Subject: [PATCH 17/29] Fix docs for Math.log256 (#3916) --- contracts/utils/math/Math.sol | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts/utils/math/Math.sol b/contracts/utils/math/Math.sol index f3a83b0ff..8400d0669 100644 --- a/contracts/utils/math/Math.sol +++ b/contracts/utils/math/Math.sol @@ -324,7 +324,7 @@ library Math { } /** - * @dev Return the log in base 10, following the selected rounding direction, of a positive value. + * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { From 2fc24fc8d4c3998de71d9d2319dd07db442d28eb Mon Sep 17 00:00:00 2001 From: Benjamin Date: Tue, 3 Jan 2023 16:30:51 +0100 Subject: [PATCH 18/29] Rename param to match the interface (#3917) --- contracts/token/common/ERC2981.sol | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/token/common/ERC2981.sol b/contracts/token/common/ERC2981.sol index 84cb6b8de..f49cc8d98 100644 --- a/contracts/token/common/ERC2981.sol +++ b/contracts/token/common/ERC2981.sol @@ -40,14 +40,14 @@ abstract contract ERC2981 is IERC2981, ERC165 { /** * @inheritdoc IERC2981 */ - function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) { - RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; + function royaltyInfo(uint256 tokenId, uint256 salePrice) public view virtual override returns (address, uint256) { + RoyaltyInfo memory royalty = _tokenRoyaltyInfo[tokenId]; if (royalty.receiver == address(0)) { royalty = _defaultRoyaltyInfo; } - uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); + uint256 royaltyAmount = (salePrice * royalty.royaltyFraction) / _feeDenominator(); return (royalty.receiver, royaltyAmount); } From 88754d0b36cde4e6b1daab591058eaef449f5adb Mon Sep 17 00:00:00 2001 From: Hadrien Croubois Date: Tue, 3 Jan 2023 22:25:37 +0100 Subject: [PATCH 19/29] Add keys() accessor to EnumerableMaps (#3920) Co-authored-by: Francisco Giordano --- CHANGELOG.md | 1 + contracts/utils/structs/EnumerableMap.sol | 108 +++++++++++++++++-- scripts/generate/templates/EnumerableMap.js | 36 ++++++- test/utils/structs/EnumerableMap.behavior.js | 7 ++ test/utils/structs/EnumerableMap.test.js | 5 + 5 files changed, 147 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58f21d999..7f6a9be40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ * `Strings`: add `equal` method. ([#3774](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3774)) * `Strings`: add `toString` method for signed integers. ([#3773](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3773)) * `MerkleProof`: optimize by using unchecked arithmetic. ([#3745](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3745)) + * `EnumerableMap`: add a `keys()` function that returns an array containing all the keys. ([#3920](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3920)) ### Deprecations diff --git a/contracts/utils/structs/EnumerableMap.sol b/contracts/utils/structs/EnumerableMap.sol index d359671f4..8b188c734 100644 --- a/contracts/utils/structs/EnumerableMap.sol +++ b/contracts/utils/structs/EnumerableMap.sol @@ -156,6 +156,18 @@ library EnumerableMap { return value; } + /** + * @dev Return the an array containing all the keys + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function keys(Bytes32ToBytes32Map storage map) internal view returns (bytes32[] memory) { + return map._keys.values(); + } + // UintToUintMap struct UintToUintMap { @@ -174,7 +186,7 @@ library EnumerableMap { } /** - * @dev Removes a value from a set. O(1). + * @dev Removes a value from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ @@ -197,7 +209,7 @@ library EnumerableMap { } /** - * @dev Returns the element stored at position `index` in the set. O(1). + * @dev Returns the element stored at position `index` in the map. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * @@ -240,6 +252,26 @@ library EnumerableMap { return uint256(get(map._inner, bytes32(key), errorMessage)); } + /** + * @dev Return the an array containing all the keys + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function keys(UintToUintMap storage map) internal view returns (uint256[] memory) { + bytes32[] memory store = keys(map._inner); + uint256[] memory result; + + /// @solidity memory-safe-assembly + assembly { + result := store + } + + return result; + } + // UintToAddressMap struct UintToAddressMap { @@ -258,7 +290,7 @@ library EnumerableMap { } /** - * @dev Removes a value from a set. O(1). + * @dev Removes a value from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ @@ -281,7 +313,7 @@ library EnumerableMap { } /** - * @dev Returns the element stored at position `index` in the set. O(1). + * @dev Returns the element stored at position `index` in the map. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * @@ -328,6 +360,26 @@ library EnumerableMap { return address(uint160(uint256(get(map._inner, bytes32(key), errorMessage)))); } + /** + * @dev Return the an array containing all the keys + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function keys(UintToAddressMap storage map) internal view returns (uint256[] memory) { + bytes32[] memory store = keys(map._inner); + uint256[] memory result; + + /// @solidity memory-safe-assembly + assembly { + result := store + } + + return result; + } + // AddressToUintMap struct AddressToUintMap { @@ -346,7 +398,7 @@ library EnumerableMap { } /** - * @dev Removes a value from a set. O(1). + * @dev Removes a value from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ @@ -369,7 +421,7 @@ library EnumerableMap { } /** - * @dev Returns the element stored at position `index` in the set. O(1). + * @dev Returns the element stored at position `index` in the map. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * @@ -416,6 +468,26 @@ library EnumerableMap { return uint256(get(map._inner, bytes32(uint256(uint160(key))), errorMessage)); } + /** + * @dev Return the an array containing all the keys + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function keys(AddressToUintMap storage map) internal view returns (address[] memory) { + bytes32[] memory store = keys(map._inner); + address[] memory result; + + /// @solidity memory-safe-assembly + assembly { + result := store + } + + return result; + } + // Bytes32ToUintMap struct Bytes32ToUintMap { @@ -434,7 +506,7 @@ library EnumerableMap { } /** - * @dev Removes a value from a set. O(1). + * @dev Removes a value from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ @@ -457,7 +529,7 @@ library EnumerableMap { } /** - * @dev Returns the element stored at position `index` in the set. O(1). + * @dev Returns the element stored at position `index` in the map. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * @@ -503,4 +575,24 @@ library EnumerableMap { ) internal view returns (uint256) { return uint256(get(map._inner, key, errorMessage)); } + + /** + * @dev Return the an array containing all the keys + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function keys(Bytes32ToUintMap storage map) internal view returns (bytes32[] memory) { + bytes32[] memory store = keys(map._inner); + bytes32[] memory result; + + /// @solidity memory-safe-assembly + assembly { + result := store + } + + return result; + } } diff --git a/scripts/generate/templates/EnumerableMap.js b/scripts/generate/templates/EnumerableMap.js index ca8e0e77d..dbd502a0b 100644 --- a/scripts/generate/templates/EnumerableMap.js +++ b/scripts/generate/templates/EnumerableMap.js @@ -168,6 +168,18 @@ function get( require(value != 0 || contains(map, key), errorMessage); return value; } + +/** + * @dev Return the an array containing all the keys + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block. + */ +function keys(Bytes32ToBytes32Map storage map) internal view returns (bytes32[] memory) { + return map._keys.values(); +} `; const customMap = ({ name, keyType, valueType }) => `\ @@ -193,7 +205,7 @@ function set( } /** - * @dev Removes a value from a set. O(1). + * @dev Removes a value from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ @@ -216,7 +228,7 @@ function length(${name} storage map) internal view returns (uint256) { } /** - * @dev Returns the element stored at position \`index\` in the set. O(1). + * @dev Returns the element stored at position \`index\` in the map. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * @@ -262,6 +274,26 @@ function get( ) internal view returns (${valueType}) { return ${fromBytes32(valueType, `get(map._inner, ${toBytes32(keyType, 'key')}, errorMessage)`)}; } + +/** + * @dev Return the an array containing all the keys + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block. + */ +function keys(${name} storage map) internal view returns (${keyType}[] memory) { + bytes32[] memory store = keys(map._inner); + ${keyType}[] memory result; + + /// @solidity memory-safe-assembly + assembly { + result := store + } + + return result; +} `; // GENERATE diff --git a/test/utils/structs/EnumerableMap.behavior.js b/test/utils/structs/EnumerableMap.behavior.js index 4d698f334..25ae84215 100644 --- a/test/utils/structs/EnumerableMap.behavior.js +++ b/test/utils/structs/EnumerableMap.behavior.js @@ -36,6 +36,13 @@ function shouldBehaveLikeMap ( }))).to.have.same.deep.members( zip(keys.map(k => k.toString()), values.map(v => v.toString())), ); + + // This also checks that both arrays have the same length + expect( + (await methods.keys(map)).map(k => k.toString()), + ).to.have.same.members( + keys.map(key => key.toString()), + ); } it('starts empty', async function () { diff --git a/test/utils/structs/EnumerableMap.test.js b/test/utils/structs/EnumerableMap.test.js index 2587f7595..14f31b429 100644 --- a/test/utils/structs/EnumerableMap.test.js +++ b/test/utils/structs/EnumerableMap.test.js @@ -39,6 +39,7 @@ contract('EnumerableMap', function (accounts) { length: '$length_EnumerableMap_AddressToUintMap(uint256)', at: '$at_EnumerableMap_AddressToUintMap(uint256,uint256)', contains: '$contains(uint256,address)', + keys: '$keys_EnumerableMap_AddressToUintMap(uint256)', }), { setReturn: 'return$set_EnumerableMap_AddressToUintMap_address_uint256', @@ -62,6 +63,7 @@ contract('EnumerableMap', function (accounts) { length: '$length_EnumerableMap_UintToAddressMap(uint256)', at: '$at_EnumerableMap_UintToAddressMap(uint256,uint256)', contains: '$contains_EnumerableMap_UintToAddressMap(uint256,uint256)', + keys: '$keys_EnumerableMap_UintToAddressMap(uint256)', }), { setReturn: 'return$set_EnumerableMap_UintToAddressMap_uint256_address', @@ -85,6 +87,7 @@ contract('EnumerableMap', function (accounts) { length: '$length_EnumerableMap_Bytes32ToBytes32Map(uint256)', at: '$at_EnumerableMap_Bytes32ToBytes32Map(uint256,uint256)', contains: '$contains_EnumerableMap_Bytes32ToBytes32Map(uint256,bytes32)', + keys: '$keys_EnumerableMap_Bytes32ToBytes32Map(uint256)', }), { setReturn: 'return$set_EnumerableMap_Bytes32ToBytes32Map_bytes32_bytes32', @@ -108,6 +111,7 @@ contract('EnumerableMap', function (accounts) { length: '$length_EnumerableMap_UintToUintMap(uint256)', at: '$at_EnumerableMap_UintToUintMap(uint256,uint256)', contains: '$contains_EnumerableMap_UintToUintMap(uint256,uint256)', + keys: '$keys_EnumerableMap_UintToUintMap(uint256)', }), { setReturn: 'return$set_EnumerableMap_UintToUintMap_uint256_uint256', @@ -131,6 +135,7 @@ contract('EnumerableMap', function (accounts) { length: '$length_EnumerableMap_Bytes32ToUintMap(uint256)', at: '$at_EnumerableMap_Bytes32ToUintMap(uint256,uint256)', contains: '$contains_EnumerableMap_Bytes32ToUintMap(uint256,bytes32)', + keys: '$keys_EnumerableMap_Bytes32ToUintMap(uint256)', }), { setReturn: 'return$set_EnumerableMap_Bytes32ToUintMap_bytes32_uint256', From a28aafdc85a592776544f7978c6b1a462d28ede2 Mon Sep 17 00:00:00 2001 From: Francisco Date: Wed, 4 Jan 2023 11:03:40 -0300 Subject: [PATCH 20/29] Use Prettier for JS files (#3913) Co-authored-by: Hadrien Croubois --- .prettierrc | 5 +- .solcover.js | 26 +- docs/templates/helpers.js | 16 +- docs/templates/properties.js | 10 +- hardhat.config.js | 7 +- hardhat/ignore-unreachable-warnings.js | 4 +- hardhat/skip-foundry-tests.js | 7 +- package-lock.json | 2 +- package.json | 12 +- scripts/checks/compareGasReports.js | 176 ++++++----- scripts/checks/inheritance-ordering.js | 38 ++- scripts/gen-nav.js | 16 +- scripts/generate/format-lines.js | 8 +- scripts/generate/run.js | 10 +- scripts/generate/templates/Checkpoints.js | 10 +- scripts/generate/templates/EnumerableSet.js | 5 +- scripts/generate/templates/SafeCast.js | 97 +++--- scripts/generate/templates/conversion.js | 36 +-- scripts/helpers.js | 23 +- scripts/migrate-imports.js | 12 +- scripts/release/synchronize-versions.js | 2 +- .../release/update-changelog-release-date.js | 5 +- scripts/release/update-comment.js | 2 +- scripts/remove-ignored-artifacts.js | 6 +- scripts/update-docs-branch.js | 14 +- test/access/AccessControl.behavior.js | 18 +- test/access/AccessControl.test.js | 5 +- test/access/AccessControlCrossChain.test.js | 28 +- test/access/Ownable.test.js | 12 +- test/crosschain/CrossChainEnabled.test.js | 20 +- test/finance/PaymentSplitter.test.js | 85 +++-- test/finance/VestingWallet.behavior.js | 39 +-- test/finance/VestingWallet.test.js | 18 +- test/governance/Governor.test.js | 297 +++++++++--------- test/governance/TimelockController.test.js | 200 +++++------- .../GovernorCompatibilityBravo.test.js | 122 +++---- .../extensions/GovernorComp.test.js | 19 +- .../extensions/GovernorERC721.test.js | 61 ++-- .../GovernorPreventLateQuorum.test.js | 80 +++-- .../GovernorTimelockCompound.test.js | 193 +++++------- .../GovernorTimelockControl.test.js | 174 +++++----- .../GovernorVotesQuorumFraction.test.js | 92 +++--- .../extensions/GovernorWithParams.test.js | 48 +-- test/governance/utils/Votes.behavior.js | 106 ++++--- test/governance/utils/Votes.test.js | 11 +- test/helpers/chainid.js | 2 +- test/helpers/create2.js | 13 +- test/helpers/crosschain.js | 54 ++-- test/helpers/customError.js | 6 +- test/helpers/eip712.js | 16 +- test/helpers/enums.js | 27 +- test/helpers/erc1967.js | 4 +- test/helpers/governance.js | 177 +++++------ test/helpers/sign.js | 48 +-- test/helpers/txpool.js | 10 +- test/metatx/MinimalForwarder.test.js | 48 ++- test/migrate-imports.test.js | 5 +- test/proxy/Clones.behaviour.js | 44 +-- test/proxy/Clones.test.js | 26 +- test/proxy/Proxy.behaviour.js | 15 +- test/proxy/beacon/BeaconProxy.test.js | 31 +- test/proxy/beacon/UpgradeableBeacon.test.js | 10 +- test/proxy/transparent/ProxyAdmin.test.js | 18 +- .../TransparentUpgradeableProxy.behaviour.js | 41 ++- test/proxy/utils/UUPSUpgradeable.test.js | 10 +- test/security/Pausable.test.js | 14 +- test/security/PullPayment.test.js | 2 +- test/security/ReentrancyGuard.test.js | 11 +- test/token/ERC1155/ERC1155.behavior.js | 291 +++++++++-------- test/token/ERC1155/ERC1155.test.js | 53 +--- .../extensions/ERC1155Burnable.test.js | 16 +- .../extensions/ERC1155Pausable.test.js | 8 +- .../ERC1155/extensions/ERC1155Supply.test.js | 16 +- .../extensions/ERC1155URIStorage.test.js | 2 +- .../presets/ERC1155PresetMinterPauser.test.js | 38 ++- .../token/ERC1155/utils/ERC1155Holder.test.js | 12 +- test/token/ERC20/ERC20.behavior.js | 97 +++--- test/token/ERC20/ERC20.test.js | 67 ++-- .../extensions/ERC20Burnable.behavior.js | 19 +- .../ERC20/extensions/ERC20Burnable.test.js | 2 +- .../ERC20/extensions/ERC20Capped.behavior.js | 2 +- .../ERC20/extensions/ERC20FlashMint.test.js | 93 +++++- .../ERC20/extensions/ERC20Pausable.test.js | 18 +- .../ERC20/extensions/ERC20Snapshot.test.js | 26 +- .../token/ERC20/extensions/ERC20Votes.test.js | 249 +++++++++------ .../ERC20/extensions/ERC20VotesComp.test.js | 231 ++++++++------ .../ERC20/extensions/ERC20Wrapper.test.js | 2 +- test/token/ERC20/extensions/ERC4626.test.js | 8 +- .../extensions/draft-ERC20Permit.test.js | 11 +- .../presets/ERC20PresetMinterPauser.test.js | 7 +- test/token/ERC20/utils/SafeERC20.test.js | 34 +- test/token/ERC20/utils/TokenTimelock.test.js | 2 +- test/token/ERC721/ERC721.behavior.js | 197 +++++------- test/token/ERC721/ERC721.test.js | 5 +- .../ERC721/extensions/ERC721Burnable.test.js | 13 +- .../extensions/ERC721Consecutive.test.js | 93 +++--- .../ERC721/extensions/ERC721Pausable.test.js | 19 +- .../ERC721/extensions/ERC721Royalty.test.js | 2 +- .../extensions/ERC721URIStorage.test.js | 17 +- .../ERC721/extensions/ERC721Votes.test.js | 24 +- .../ERC721PresetMinterPauserAutoId.test.js | 7 +- test/token/ERC721/utils/ERC721Holder.test.js | 2 +- test/token/ERC777/ERC777.behavior.js | 146 ++++++--- test/token/ERC777/ERC777.test.js | 105 ++----- test/token/common/ERC2981.behavior.js | 7 +- test/utils/Address.test.js | 104 +++--- test/utils/Arrays.test.js | 24 +- test/utils/Checkpoints.test.js | 45 +-- test/utils/Context.behavior.js | 2 +- test/utils/Context.test.js | 2 +- test/utils/Create2.test.js | 67 ++-- test/utils/Multicall.test.js | 35 ++- test/utils/Strings.test.js | 15 +- test/utils/cryptography/ECDSA.test.js | 177 +++++------ test/utils/cryptography/MerkleProof.test.js | 36 +-- .../cryptography/SignatureChecker.test.js | 72 ++--- test/utils/escrow/ConditionalEscrow.test.js | 5 +- test/utils/escrow/Escrow.behavior.js | 10 +- test/utils/escrow/Escrow.test.js | 2 +- test/utils/escrow/RefundEscrow.test.js | 47 ++- test/utils/introspection/ERC165.test.js | 4 +- .../utils/introspection/ERC165Checker.test.js | 23 +- .../utils/introspection/ERC165Storage.test.js | 4 +- .../introspection/ERC1820Implementer.test.js | 39 ++- .../SupportsInterface.behavior.js | 33 +- test/utils/math/Math.test.js | 98 +++--- test/utils/math/SafeCast.test.js | 24 +- test/utils/math/SafeMath.test.js | 80 ++--- test/utils/math/SignedMath.test.js | 8 +- test/utils/math/SignedSafeMath.test.js | 4 +- test/utils/structs/DoubleEndedQueue.test.js | 13 +- test/utils/structs/EnumerableMap.behavior.js | 65 ++-- test/utils/structs/EnumerableMap.test.js | 31 +- test/utils/structs/EnumerableSet.behavior.js | 26 +- test/utils/structs/EnumerableSet.test.js | 13 +- 135 files changed, 2737 insertions(+), 3121 deletions(-) diff --git a/.prettierrc b/.prettierrc index 923a710a6..e08e24273 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,12 +1,13 @@ { + "printWidth": 120, "singleQuote": true, "trailingComma": "all", + "arrowParens": "avoid", "overrides": [ { "files": "*.sol", "options": { - "singleQuote": false, - "printWidth": 120 + "singleQuote": false } } ] diff --git a/.solcover.js b/.solcover.js index 6cf991ef1..e0dea5e2c 100644 --- a/.solcover.js +++ b/.solcover.js @@ -1,15 +1,13 @@ module.exports = { - norpc: true, - testCommand: 'npm test', - compileCommand: 'npm run compile', - skipFiles: [ - 'mocks', - ], - providerOptions: { - default_balance_ether: '10000000000000000000000000', - }, - mocha: { - fgrep: '[skip-on-coverage]', - invert: true, - }, -} + norpc: true, + testCommand: 'npm test', + compileCommand: 'npm run compile', + skipFiles: ['mocks'], + providerOptions: { + default_balance_ether: '10000000000000000000000000', + }, + mocha: { + fgrep: '[skip-on-coverage]', + invert: true, + }, +}; diff --git a/docs/templates/helpers.js b/docs/templates/helpers.js index 8c94d757c..0d587caa8 100644 --- a/docs/templates/helpers.js +++ b/docs/templates/helpers.js @@ -2,26 +2,26 @@ const { version } = require('../../package.json'); module.exports['oz-version'] = () => version; -module.exports['readme-path'] = (opts) => { +module.exports['readme-path'] = opts => { return 'contracts/' + opts.data.root.id.replace(/\.adoc$/, '') + '/README.adoc'; }; -module.exports.names = (params) => params.map(p => p.name).join(', '); +module.exports.names = params => params.map(p => p.name).join(', '); -module.exports['typed-params'] = (params) => { +module.exports['typed-params'] = params => { return params.map(p => `${p.type}${p.name ? ' ' + p.name : ''}`).join(', '); }; -const slug = module.exports.slug = (str) => { +const slug = (module.exports.slug = str => { if (str === undefined) { throw new Error('Missing argument'); } return str.replace(/\W/g, '-'); -}; +}); const linksCache = new WeakMap(); -function getAllLinks (items) { +function getAllLinks(items) { if (linksCache.has(items)) { return linksCache.get(items); } @@ -34,11 +34,11 @@ function getAllLinks (items) { return res; } -module.exports['with-prelude'] = (opts) => { +module.exports['with-prelude'] = opts => { const links = getAllLinks(opts.data.site.items); const contents = opts.fn(); const neededLinks = contents - .match(/\{[-._a-z0-9]+\}/ig) + .match(/\{[-._a-z0-9]+\}/gi) .map(m => m.replace(/^\{(.+)\}$/, '$1')) .filter(k => k in links); const prelude = neededLinks.map(k => `:${k}: ${links[k]}`).join('\n'); diff --git a/docs/templates/properties.js b/docs/templates/properties.js index 5dde3a471..99bdf88b2 100644 --- a/docs/templates/properties.js +++ b/docs/templates/properties.js @@ -1,7 +1,7 @@ const { isNodeType } = require('solidity-ast/utils'); const { slug } = require('./helpers'); -module.exports.anchor = function anchor ({ item, contract }) { +module.exports.anchor = function anchor({ item, contract }) { let res = ''; if (contract) { res += contract.name + '-'; @@ -37,13 +37,9 @@ module.exports['has-events'] = function ({ item }) { module.exports['inherited-functions'] = function ({ item }) { const { inheritance } = item; - const baseFunctions = new Set( - inheritance.flatMap(c => c.functions.flatMap(f => f.baseFunctions ?? [])), - ); + const baseFunctions = new Set(inheritance.flatMap(c => c.functions.flatMap(f => f.baseFunctions ?? []))); return inheritance.map((contract, i) => ({ contract, - functions: contract.functions.filter(f => - !baseFunctions.has(f.id) && (f.name !== 'constructor' || i === 0), - ), + functions: contract.functions.filter(f => !baseFunctions.has(f.id) && (f.name !== 'constructor' || i === 0)), })); }; diff --git a/hardhat.config.js b/hardhat.config.js index 1722faf91..74f40c4d1 100644 --- a/hardhat.config.js +++ b/hardhat.config.js @@ -29,7 +29,7 @@ const argv = require('yargs/yargs')() mode: { alias: 'compileMode', type: 'string', - choices: [ 'production', 'development' ], + choices: ['production', 'development'], default: 'development', }, ir: { @@ -46,8 +46,7 @@ const argv = require('yargs/yargs')() alias: 'coinmarketcapApiKey', type: 'string', }, - }) - .argv; + }).argv; require('@nomiclabs/hardhat-truffle5'); require('hardhat-ignore-warnings'); @@ -106,7 +105,7 @@ if (argv.gas) { outputFile: argv.gasReport, coinmarketcap: argv.coinmarketcap, }; -}; +} if (argv.coverage) { require('solidity-coverage'); diff --git a/hardhat/ignore-unreachable-warnings.js b/hardhat/ignore-unreachable-warnings.js index c9d3c36a4..8e3e34340 100644 --- a/hardhat/ignore-unreachable-warnings.js +++ b/hardhat/ignore-unreachable-warnings.js @@ -38,9 +38,7 @@ task(TASK_COMPILE_SOLIDITY_COMPILE, async (params, _, runSuper) => { if (marked) { result.output = { ...result.output, - errors: result.output.errors?.filter( - e => e.severity !== 'warning' || e.errorCode !== W_UNREACHABLE_CODE, - ), + errors: result.output.errors?.filter(e => e.severity !== 'warning' || e.errorCode !== W_UNREACHABLE_CODE), }; } return result; diff --git a/hardhat/skip-foundry-tests.js b/hardhat/skip-foundry-tests.js index b8030288d..965ba37c3 100644 --- a/hardhat/skip-foundry-tests.js +++ b/hardhat/skip-foundry-tests.js @@ -1,7 +1,6 @@ const { subtask } = require('hardhat/config'); const { TASK_COMPILE_SOLIDITY_GET_SOURCE_PATHS } = require('hardhat/builtin-tasks/task-names'); -subtask(TASK_COMPILE_SOLIDITY_GET_SOURCE_PATHS) - .setAction(async (_, __, runSuper) => - (await runSuper()).filter((path) => !path.endsWith('.t.sol')), - ); +subtask(TASK_COMPILE_SOLIDITY_GET_SOURCE_PATHS).setAction(async (_, __, runSuper) => + (await runSuper()).filter(path => !path.endsWith('.t.sol')), +); diff --git a/package-lock.json b/package-lock.json index 172fa0944..c847f2c92 100644 --- a/package-lock.json +++ b/package-lock.json @@ -34,7 +34,7 @@ "lodash.zip": "^4.2.0", "merkletreejs": "^0.2.13", "micromatch": "^4.0.2", - "prettier": "^2.3.0", + "prettier": "^2.8.1", "prettier-plugin-solidity": "^1.1.0", "rimraf": "^3.0.2", "semver": "^7.3.5", diff --git a/package.json b/package.json index 3ea1d7301..41d1131bb 100644 --- a/package.json +++ b/package.json @@ -14,14 +14,14 @@ "compile": "hardhat compile", "coverage": "env COVERAGE=true hardhat coverage", "docs": "npm run prepare-docs && oz-docs", - "docs:watch": "oz-docs watch contracts 'docs/templates' docs/config.js", + "docs:watch": "oz-docs watch contracts docs/templates docs/config.js", "prepare-docs": "scripts/prepare-docs.sh", "lint": "npm run lint:js && npm run lint:sol", "lint:fix": "npm run lint:js:fix && npm run lint:sol:fix", - "lint:js": "eslint --ignore-path .gitignore .", - "lint:js:fix": "eslint --ignore-path .gitignore . --fix", - "lint:sol": "solhint '{contracts,test}/**/*.sol' && prettier -c '{contracts,test}/**/*.sol'", - "lint:sol:fix": "prettier --write '{contracts,test}/**/*.sol'", + "lint:js": "prettier --loglevel warn --ignore-path .gitignore '**/*.{js,ts}' --check && eslint --ignore-path .gitignore .", + "lint:js:fix": "prettier --loglevel warn --ignore-path .gitignore '**/*.{js,ts}' --write && eslint --ignore-path .gitignore . --fix", + "lint:sol": "prettier --loglevel warn --ignore-path .gitignore '{contracts,test}/**/*.sol' --write && solhint '{contracts,test}/**/*.sol'", + "lint:sol:fix": "prettier --loglevel warn --ignore-path .gitignore '{contracts,test}/**/*.sol' --write", "clean": "hardhat clean && rimraf build contracts/build", "prepare": "scripts/prepare.sh", "prepack": "scripts/prepack.sh", @@ -75,7 +75,7 @@ "lodash.zip": "^4.2.0", "merkletreejs": "^0.2.13", "micromatch": "^4.0.2", - "prettier": "^2.3.0", + "prettier": "^2.8.1", "prettier-plugin-solidity": "^1.1.0", "rimraf": "^3.0.2", "semver": "^7.3.5", diff --git a/scripts/checks/compareGasReports.js b/scripts/checks/compareGasReports.js index 5e3a0e7cd..ca99dea0d 100755 --- a/scripts/checks/compareGasReports.js +++ b/scripts/checks/compareGasReports.js @@ -7,7 +7,7 @@ const { argv } = require('yargs') .options({ style: { type: 'string', - choices: [ 'shell', 'markdown' ], + choices: ['shell', 'markdown'], default: 'shell', }, }); @@ -16,52 +16,55 @@ const { argv } = require('yargs') const BASE_TX_COST = 21000; // Utilities -function sum (...args) { +function sum(...args) { return args.reduce((a, b) => a + b, 0); } -function average (...args) { +function average(...args) { return sum(...args) / args.length; } -function variation (current, previous, offset = 0) { +function variation(current, previous, offset = 0) { return { value: current, delta: current - previous, - prcnt: 100 * (current - previous) / (previous - offset), + prcnt: (100 * (current - previous)) / (previous - offset), }; } // Report class class Report { // Read report file - static load (filepath) { + static load(filepath) { return JSON.parse(fs.readFileSync(filepath, 'utf8')); } // Compare two reports - static compare (update, ref, opts = { hideEqual: true }) { + static compare(update, ref, opts = { hideEqual: true }) { if (JSON.stringify(update.config.metadata) !== JSON.stringify(ref.config.metadata)) { throw new Error('Reports produced with non matching metadata'); } const deployments = update.info.deployments - .map(contract => Object.assign( - contract, - { previousVersion: ref.info.deployments.find(({ name }) => name === contract.name) }, - )) + .map(contract => + Object.assign(contract, { previousVersion: ref.info.deployments.find(({ name }) => name === contract.name) }), + ) .filter(contract => contract.gasData?.length && contract.previousVersion?.gasData?.length) - .flatMap(contract => [{ - contract: contract.name, - method: '[bytecode length]', - avg: variation(contract.bytecode.length / 2 - 1, contract.previousVersion.bytecode.length / 2 - 1), - }, { - contract: contract.name, - method: '[construction cost]', - avg: variation( - ...[contract.gasData, contract.previousVersion.gasData].map(x => Math.round(average(...x))), - BASE_TX_COST), - }]) + .flatMap(contract => [ + { + contract: contract.name, + method: '[bytecode length]', + avg: variation(contract.bytecode.length / 2 - 1, contract.previousVersion.bytecode.length / 2 - 1), + }, + { + contract: contract.name, + method: '[construction cost]', + avg: variation( + ...[contract.gasData, contract.previousVersion.gasData].map(x => Math.round(average(...x))), + BASE_TX_COST, + ), + }, + ]) .sort((a, b) => `${a.contract}:${a.method}`.localeCompare(`${b.contract}:${b.method}`)); const methods = Object.keys(update.info.methods) @@ -77,21 +80,22 @@ class Report { })) .sort((a, b) => `${a.contract}:${a.method}`.localeCompare(`${b.contract}:${b.method}`)); - return [].concat(deployments, methods) + return [] + .concat(deployments, methods) .filter(row => !opts.hideEqual || row.min?.delta || row.max?.delta || row.avg?.delta); } } // Display -function center (text, length) { +function center(text, length) { return text.padStart((text.length + length) / 2).padEnd(length); } -function plusSign (num) { +function plusSign(num) { return num > 0 ? '+' : ''; } -function formatCellShell (cell) { +function formatCellShell(cell) { const format = chalk[cell?.delta > 0 ? 'red' : cell?.delta < 0 ? 'green' : 'reset']; return [ format((!isFinite(cell?.value) ? '-' : cell.value.toString()).padStart(8)), @@ -100,7 +104,7 @@ function formatCellShell (cell) { ]; } -function formatCmpShell (rows) { +function formatCmpShell(rows) { const contractLength = Math.max(8, ...rows.map(({ contract }) => contract.length)); const methodLength = Math.max(7, ...rows.map(({ method }) => method.length)); @@ -113,54 +117,60 @@ function formatCmpShell (rows) { { txt: 'Avg', length: 30 }, { txt: '', length: 0 }, ]; - const HEADER = COLS.map(entry => chalk.bold(center(entry.txt, entry.length || 0))).join(' | ').trim(); - const SEPARATOR = COLS.map(({ length }) => length > 0 ? '-'.repeat(length + 2) : '').join('|').trim(); + const HEADER = COLS.map(entry => chalk.bold(center(entry.txt, entry.length || 0))) + .join(' | ') + .trim(); + const SEPARATOR = COLS.map(({ length }) => (length > 0 ? '-'.repeat(length + 2) : '')) + .join('|') + .trim(); return [ '', HEADER, - ...rows.map(entry => [ - '', - chalk.grey(entry.contract.padEnd(contractLength)), - entry.method.padEnd(methodLength), - ...formatCellShell(entry.min), - ...formatCellShell(entry.max), - ...formatCellShell(entry.avg), - '', - ].join(' | ').trim()), + ...rows.map(entry => + [ + '', + chalk.grey(entry.contract.padEnd(contractLength)), + entry.method.padEnd(methodLength), + ...formatCellShell(entry.min), + ...formatCellShell(entry.max), + ...formatCellShell(entry.avg), + '', + ] + .join(' | ') + .trim(), + ), '', - ].join(`\n${SEPARATOR}\n`).trim(); + ] + .join(`\n${SEPARATOR}\n`) + .trim(); } -function alignPattern (align) { +function alignPattern(align) { switch (align) { - case 'left': - case undefined: - return ':-'; - case 'right': - return '-:'; - case 'center': - return ':-:'; + case 'left': + case undefined: + return ':-'; + case 'right': + return '-:'; + case 'center': + return ':-:'; } } -function trend (value) { - return value > 0 - ? ':x:' - : value < 0 - ? ':heavy_check_mark:' - : ':heavy_minus_sign:'; +function trend(value) { + return value > 0 ? ':x:' : value < 0 ? ':heavy_check_mark:' : ':heavy_minus_sign:'; } -function formatCellMarkdown (cell) { +function formatCellMarkdown(cell) { return [ - (!isFinite(cell?.value) ? '-' : cell.value.toString()), - (!isFinite(cell?.delta) ? '-' : plusSign(cell.delta) + cell.delta.toString()), - (!isFinite(cell?.prcnt) ? '-' : plusSign(cell.prcnt) + cell.prcnt.toFixed(2) + '%' + trend(cell.delta)), + !isFinite(cell?.value) ? '-' : cell.value.toString(), + !isFinite(cell?.delta) ? '-' : plusSign(cell.delta) + cell.delta.toString(), + !isFinite(cell?.prcnt) ? '-' : plusSign(cell.prcnt) + cell.prcnt.toFixed(2) + '%' + trend(cell.delta), ]; } -function formatCmpMarkdown (rows) { +function formatCmpMarkdown(rows) { const COLS = [ { txt: '' }, { txt: 'Contract', align: 'left' }, @@ -176,36 +186,48 @@ function formatCmpMarkdown (rows) { { txt: '%', align: 'right' }, { txt: '' }, ]; - const HEADER = COLS.map(entry => entry.txt).join(' | ').trim(); - const SEPARATOR = COLS.map(entry => entry.txt ? alignPattern(entry.align) : '').join('|').trim(); + const HEADER = COLS.map(entry => entry.txt) + .join(' | ') + .trim(); + const SEPARATOR = COLS.map(entry => (entry.txt ? alignPattern(entry.align) : '')) + .join('|') + .trim(); return [ '# Changes to gas costs', '', HEADER, SEPARATOR, - rows.map(entry => [ - '', - entry.contract, - entry.method, - ...formatCellMarkdown(entry.min), - ...formatCellMarkdown(entry.max), - ...formatCellMarkdown(entry.avg), - '', - ].join(' | ').trim()).join('\n'), + rows + .map(entry => + [ + '', + entry.contract, + entry.method, + ...formatCellMarkdown(entry.min), + ...formatCellMarkdown(entry.max), + ...formatCellMarkdown(entry.avg), + '', + ] + .join(' | ') + .trim(), + ) + .join('\n'), '', - ].join('\n').trim(); + ] + .join('\n') + .trim(); } // MAIN const report = Report.compare(Report.load(argv._[0]), Report.load(argv._[1])); switch (argv.style) { -case 'markdown': - console.log(formatCmpMarkdown(report)); - break; -case 'shell': -default: - console.log(formatCmpShell(report)); - break; + case 'markdown': + console.log(formatCmpMarkdown(report)); + break; + case 'shell': + default: + console.log(formatCmpShell(report)); + break; } diff --git a/scripts/checks/inheritance-ordering.js b/scripts/checks/inheritance-ordering.js index 3ade7409a..45c707e6f 100755 --- a/scripts/checks/inheritance-ordering.js +++ b/scripts/checks/inheritance-ordering.js @@ -21,28 +21,32 @@ for (const artifact of artifacts) { names[contractDef.id] = contractDef.name; linearized.push(contractDef.linearizedBaseContracts); - contractDef.linearizedBaseContracts.forEach((c1, i, contracts) => contracts.slice(i + 1).forEach(c2 => { - graph.setEdge(c1, c2); - })); + contractDef.linearizedBaseContracts.forEach((c1, i, contracts) => + contracts.slice(i + 1).forEach(c2 => { + graph.setEdge(c1, c2); + }), + ); } } /// graphlib.alg.findCycles will not find minimal cycles. /// We are only interested int cycles of lengths 2 (needs proof) - graph.nodes().forEach((x, i, nodes) => nodes - .slice(i + 1) - .filter(y => graph.hasEdge(x, y) && graph.hasEdge(y, x)) - .forEach(y => { - console.log(`Conflict between ${names[x]} and ${names[y]} detected in the following dependency chains:`); - linearized - .filter(chain => chain.includes(parseInt(x)) && chain.includes(parseInt(y))) - .forEach(chain => { - const comp = chain.indexOf(parseInt(x)) < chain.indexOf(parseInt(y)) ? '>' : '<'; - console.log(`- ${names[x]} ${comp} ${names[y]} in ${names[chain.find(Boolean)]}`); - // console.log(`- ${names[x]} ${comp} ${names[y]}: ${chain.reverse().map(id => names[id]).join(', ')}`); - }); - process.exitCode = 1; - })); + graph.nodes().forEach((x, i, nodes) => + nodes + .slice(i + 1) + .filter(y => graph.hasEdge(x, y) && graph.hasEdge(y, x)) + .forEach(y => { + console.log(`Conflict between ${names[x]} and ${names[y]} detected in the following dependency chains:`); + linearized + .filter(chain => chain.includes(parseInt(x)) && chain.includes(parseInt(y))) + .forEach(chain => { + const comp = chain.indexOf(parseInt(x)) < chain.indexOf(parseInt(y)) ? '>' : '<'; + console.log(`- ${names[x]} ${comp} ${names[y]} in ${names[chain.find(Boolean)]}`); + // console.log(`- ${names[x]} ${comp} ${names[y]}: ${chain.reverse().map(id => names[id]).join(', ')}`); + }); + process.exitCode = 1; + }), + ); } if (!process.exitCode) { diff --git a/scripts/gen-nav.js b/scripts/gen-nav.js index b39d23e0d..de3d0daba 100644 --- a/scripts/gen-nav.js +++ b/scripts/gen-nav.js @@ -10,18 +10,18 @@ const files = glob.sync(baseDir + '/**/*.adoc').map(f => path.relative(baseDir, console.log('.API'); -function getPageTitle (directory) { +function getPageTitle(directory) { switch (directory) { - case 'metatx': - return 'Meta Transactions'; - case 'common': - return 'Common (Tokens)'; - default: - return startCase(directory); + case 'metatx': + return 'Meta Transactions'; + case 'common': + return 'Common (Tokens)'; + default: + return startCase(directory); } } -const links = files.map((file) => { +const links = files.map(file => { const doc = file.replace(baseDir, ''); const title = path.parse(file).name; diff --git a/scripts/generate/format-lines.js b/scripts/generate/format-lines.js index e1f1823e8..fa3d6b120 100644 --- a/scripts/generate/format-lines.js +++ b/scripts/generate/format-lines.js @@ -1,14 +1,14 @@ -function formatLines (...lines) { +function formatLines(...lines) { return [...indentEach(0, lines)].join('\n') + '\n'; } -function *indentEach (indent, lines) { +function* indentEach(indent, lines) { for (const line of lines) { if (Array.isArray(line)) { - yield * indentEach(indent + 1, line); + yield* indentEach(indent + 1, line); } else { const padding = ' '.repeat(indent); - yield * line.split('\n').map(subline => subline === '' ? '' : padding + subline); + yield* line.split('\n').map(subline => (subline === '' ? '' : padding + subline)); } } } diff --git a/scripts/generate/run.js b/scripts/generate/run.js index 51ddba339..a34823223 100755 --- a/scripts/generate/run.js +++ b/scripts/generate/run.js @@ -5,17 +5,15 @@ const fs = require('fs'); const path = require('path'); const format = require('./format-lines'); -function getVersion (path) { +function getVersion(path) { try { - return fs - .readFileSync(path, 'utf8') - .match(/\/\/ OpenZeppelin Contracts \(last updated v[^)]+\)/)[0]; + return fs.readFileSync(path, 'utf8').match(/\/\/ OpenZeppelin Contracts \(last updated v[^)]+\)/)[0]; } catch (err) { return null; } } -for (const [ file, template ] of Object.entries({ +for (const [file, template] of Object.entries({ 'utils/math/SafeCast.sol': './templates/SafeCast.js', 'utils/structs/EnumerableSet.sol': './templates/EnumerableSet.js', 'utils/structs/EnumerableMap.sol': './templates/EnumerableMap.js', @@ -27,7 +25,7 @@ for (const [ file, template ] of Object.entries({ const version = getVersion(output); const content = format( '// SPDX-License-Identifier: MIT', - ...(version ? [ version + ` (${file})` ] : []), + ...(version ? [version + ` (${file})`] : []), `// This file was procedurally generated from ${input}.`, '', require(template), diff --git a/scripts/generate/templates/Checkpoints.js b/scripts/generate/templates/Checkpoints.js index 858ddb4aa..afac25991 100644 --- a/scripts/generate/templates/Checkpoints.js +++ b/scripts/generate/templates/Checkpoints.js @@ -1,6 +1,6 @@ const format = require('../format-lines'); -const VALUE_SIZES = [ 224, 160 ]; +const VALUE_SIZES = [224, 160]; const header = `\ pragma solidity ^0.8.0; @@ -264,7 +264,7 @@ function _unsafeAccess(${opts.checkpointTypeName}[] storage self, uint256 pos) /* eslint-enable max-len */ // OPTIONS -const defaultOpts = (size) => ({ +const defaultOpts = size => ({ historyTypeName: `Trace${size}`, checkpointTypeName: `Checkpoint${size}`, checkpointFieldName: '_checkpoints', @@ -293,11 +293,7 @@ module.exports = format( legacyOperations(LEGACY_OPTS), common(LEGACY_OPTS), // New flavors - ...OPTS.flatMap(opts => [ - types(opts), - operations(opts), - common(opts), - ]), + ...OPTS.flatMap(opts => [types(opts), operations(opts), common(opts)]), ], '}', ); diff --git a/scripts/generate/templates/EnumerableSet.js b/scripts/generate/templates/EnumerableSet.js index 22178ecca..a3af2c304 100644 --- a/scripts/generate/templates/EnumerableSet.js +++ b/scripts/generate/templates/EnumerableSet.js @@ -245,9 +245,6 @@ function values(${name} storage set) internal view returns (${type}[] memory) { module.exports = format( header.trimEnd(), 'library EnumerableSet {', - [ - defaultSet(), - TYPES.map(details => customSet(details).trimEnd()).join('\n\n'), - ], + [defaultSet(), TYPES.map(details => customSet(details).trimEnd()).join('\n\n')], '}', ); diff --git a/scripts/generate/templates/SafeCast.js b/scripts/generate/templates/SafeCast.js index 8cf174206..3e2b148fd 100644 --- a/scripts/generate/templates/SafeCast.js +++ b/scripts/generate/templates/SafeCast.js @@ -8,55 +8,55 @@ const LENGTHS = range(8, 256, 8).reverse(); // 248 → 8 (in steps of 8) // This is used in the docs for each function. const version = (selector, length) => { switch (selector) { - case 'toUint(uint)': { - switch (length) { - case 8: - case 16: - case 32: - case 64: - case 128: - return '2.5'; - case 96: - case 224: - return '4.2'; - default: - assert(LENGTHS.includes(length)); - return '4.7'; + case 'toUint(uint)': { + switch (length) { + case 8: + case 16: + case 32: + case 64: + case 128: + return '2.5'; + case 96: + case 224: + return '4.2'; + default: + assert(LENGTHS.includes(length)); + return '4.7'; + } } - } - case 'toInt(int)': { - switch (length) { - case 8: - case 16: - case 32: - case 64: - case 128: - return '3.1'; - default: - assert(LENGTHS.includes(length)); - return '4.7'; + case 'toInt(int)': { + switch (length) { + case 8: + case 16: + case 32: + case 64: + case 128: + return '3.1'; + default: + assert(LENGTHS.includes(length)); + return '4.7'; + } + } + case 'toUint(int)': { + switch (length) { + case 256: + return '3.0'; + default: + assert(false); + return; + } + } + case 'toInt(uint)': { + switch (length) { + case 256: + return '3.0'; + default: + assert(false); + return; + } } - } - case 'toUint(int)': { - switch (length) { - case 256: - return '3.0'; default: assert(false); - return; - } - } - case 'toInt(uint)': { - switch (length) { - case 256: - return '3.0'; - default: - assert(false); - return; - } - } - default: - assert(false); } }; @@ -158,11 +158,6 @@ function toUint${length}(int${length} value) internal pure returns (uint${length module.exports = format( header.trimEnd(), 'library SafeCast {', - [ - ...LENGTHS.map(toUintDownCast), - toUint(256), - ...LENGTHS.map(toIntDownCast), - toInt(256), - ], + [...LENGTHS.map(toUintDownCast), toUint(256), ...LENGTHS.map(toIntDownCast), toInt(256)], '}', ); diff --git a/scripts/generate/templates/conversion.js b/scripts/generate/templates/conversion.js index 5c26c6821..9221f7c21 100644 --- a/scripts/generate/templates/conversion.js +++ b/scripts/generate/templates/conversion.js @@ -1,26 +1,26 @@ -function toBytes32 (type, value) { +function toBytes32(type, value) { switch (type) { - case 'bytes32': - return value; - case 'uint256': - return `bytes32(${value})`; - case 'address': - return `bytes32(uint256(uint160(${value})))`; - default: - throw new Error(`Conversion from ${type} to bytes32 not supported`); + case 'bytes32': + return value; + case 'uint256': + return `bytes32(${value})`; + case 'address': + return `bytes32(uint256(uint160(${value})))`; + default: + throw new Error(`Conversion from ${type} to bytes32 not supported`); } } -function fromBytes32 (type, value) { +function fromBytes32(type, value) { switch (type) { - case 'bytes32': - return value; - case 'uint256': - return `uint256(${value})`; - case 'address': - return `address(uint160(uint256(${value})))`; - default: - throw new Error(`Conversion from bytes32 to ${type} not supported`); + case 'bytes32': + return value; + case 'uint256': + return `uint256(${value})`; + case 'address': + return `address(uint160(uint256(${value})))`; + default: + throw new Error(`Conversion from bytes32 to ${type} not supported`); } } diff --git a/scripts/helpers.js b/scripts/helpers.js index cbd0e01e3..26d0a2baa 100644 --- a/scripts/helpers.js +++ b/scripts/helpers.js @@ -1,18 +1,27 @@ -function chunk (array, size = 1) { +function chunk(array, size = 1) { return Array.range(Math.ceil(array.length / size)).map(i => array.slice(i * size, i * size + size)); } -function range (start, stop = undefined, step = 1) { - if (!stop) { stop = start; start = 0; } - return start < stop ? Array(Math.ceil((stop - start) / step)).fill().map((_, i) => start + i * step) : []; +function range(start, stop = undefined, step = 1) { + if (!stop) { + stop = start; + start = 0; + } + return start < stop + ? Array(Math.ceil((stop - start) / step)) + .fill() + .map((_, i) => start + i * step) + : []; } -function unique (array, op = x => x) { +function unique(array, op = x => x) { return array.filter((obj, i) => array.findIndex(entry => op(obj) === op(entry)) === i); } -function zip (...args) { - return Array(Math.max(...args.map(arg => arg.length))).fill(null).map((_, i) => args.map(arg => arg[i])); +function zip(...args) { + return Array(Math.max(...args.map(arg => arg.length))) + .fill(null) + .map((_, i) => args.map(arg => arg[i])); } module.exports = { diff --git a/scripts/migrate-imports.js b/scripts/migrate-imports.js index 04ebce76c..f60441903 100755 --- a/scripts/migrate-imports.js +++ b/scripts/migrate-imports.js @@ -92,7 +92,7 @@ const pathUpdates = { 'token/ERC20/extensions/draft-IERC20Permit.sol': 'token/ERC20/extensions/IERC20Permit.sol', }; -async function main (paths = [ 'contracts' ]) { +async function main(paths = ['contracts']) { const files = await listFilesRecursively(paths, /\.sol$/); const updatedFiles = []; @@ -112,7 +112,7 @@ async function main (paths = [ 'contracts' ]) { } } -async function listFilesRecursively (paths, filter) { +async function listFilesRecursively(paths, filter) { const queue = paths; const files = []; @@ -133,7 +133,7 @@ async function listFilesRecursively (paths, filter) { return files; } -async function updateFile (file, update) { +async function updateFile(file, update) { const content = await fs.readFile(file, 'utf8'); const updatedContent = update(content); if (updatedContent !== content) { @@ -144,8 +144,8 @@ async function updateFile (file, update) { } } -function updateImportPaths (source) { - for (const [ oldPath, newPath ] of Object.entries(pathUpdates)) { +function updateImportPaths(source) { + for (const [oldPath, newPath] of Object.entries(pathUpdates)) { source = source.replace( path.join('@openzeppelin/contracts', oldPath), path.join('@openzeppelin/contracts', newPath), @@ -159,7 +159,7 @@ function updateImportPaths (source) { return source; } -function getUpgradeablePath (file) { +function getUpgradeablePath(file) { const { dir, name, ext } = path.parse(file); const upgradeableName = name + 'Upgradeable'; return path.format({ dir, ext, name: upgradeableName }); diff --git a/scripts/release/synchronize-versions.js b/scripts/release/synchronize-versions.js index 15915a1c8..c17ad614d 100755 --- a/scripts/release/synchronize-versions.js +++ b/scripts/release/synchronize-versions.js @@ -8,7 +8,7 @@ const cp = require('child_process'); setVersion('contracts/package.json'); -function setVersion (file) { +function setVersion(file) { const json = JSON.parse(fs.readFileSync(file)); json.version = process.env.npm_package_version; fs.writeFileSync(file, JSON.stringify(json, null, 2) + '\n'); diff --git a/scripts/release/update-changelog-release-date.js b/scripts/release/update-changelog-release-date.js index c368eb7b0..b1a4a177f 100755 --- a/scripts/release/update-changelog-release-date.js +++ b/scripts/release/update-changelog-release-date.js @@ -25,9 +25,8 @@ if (!header.test(changelog)) { process.exit(1); } -const newHeader = pkg.version.indexOf(suffix) === -1 - ? `## ${version} (${new Date().toISOString().split('T')[0]})` - : `## ${version}`; +const newHeader = + pkg.version.indexOf(suffix) === -1 ? `## ${version} (${new Date().toISOString().split('T')[0]})` : `## ${version}`; fs.writeFileSync('CHANGELOG.md', changelog.replace(header, newHeader)); diff --git a/scripts/release/update-comment.js b/scripts/release/update-comment.js index 7baf8c2b4..da2028c68 100755 --- a/scripts/release/update-comment.js +++ b/scripts/release/update-comment.js @@ -13,7 +13,7 @@ if (gitStatus.length > 0) { const { version } = require('../../package.json'); // Get latest tag according to semver. -const [ tag ] = run('git', 'tag') +const [tag] = run('git', 'tag') .split(/\r?\n/) .filter(semver.coerce) // check version can be processed .filter(v => semver.lt(semver.coerce(v), version)) // only consider older tags, ignore current prereleases diff --git a/scripts/remove-ignored-artifacts.js b/scripts/remove-ignored-artifacts.js index 2ef278899..f3e45b8d1 100644 --- a/scripts/remove-ignored-artifacts.js +++ b/scripts/remove-ignored-artifacts.js @@ -6,7 +6,7 @@ const fs = require('fs'); const path = require('path'); const match = require('micromatch'); -function readJSON (path) { +function readJSON(path) { return JSON.parse(fs.readFileSync(path)); } @@ -15,11 +15,11 @@ const pkgFiles = readJSON('package.json').files; // Get only negated patterns. const ignorePatterns = pkgFiles .filter(pat => pat.startsWith('!')) -// Remove the negation part. Makes micromatch usage more intuitive. + // Remove the negation part. Makes micromatch usage more intuitive. .map(pat => pat.slice(1)); const ignorePatternsSubtrees = ignorePatterns -// Add **/* to ignore all files contained in the directories. + // Add **/* to ignore all files contained in the directories. .concat(ignorePatterns.map(pat => path.join(pat, '**/*'))) .map(p => p.replace(/^\//, '')); diff --git a/scripts/update-docs-branch.js b/scripts/update-docs-branch.js index 82bb7e060..4e94ba6b1 100644 --- a/scripts/update-docs-branch.js +++ b/scripts/update-docs-branch.js @@ -1,7 +1,15 @@ const proc = require('child_process'); const read = cmd => proc.execSync(cmd, { encoding: 'utf8' }).trim(); -const run = cmd => { proc.execSync(cmd, { stdio: 'inherit' }); }; -const tryRead = cmd => { try { return read(cmd); } catch (e) { return undefined; } }; +const run = cmd => { + proc.execSync(cmd, { stdio: 'inherit' }); +}; +const tryRead = cmd => { + try { + return read(cmd); + } catch (e) { + return undefined; + } +}; const releaseBranchRegex = /^release-v(?(?\d+)\.(?\d+)(?:\.(?\d+))?)$/; @@ -33,7 +41,7 @@ if (!matchingDocsBranches) { if (others.length > 0) { console.error( `Found conflicting ${docsBranch} branches.\n` + - 'Either local branch is outdated or there are multiple matching remote branches.', + 'Either local branch is outdated or there are multiple matching remote branches.', ); process.exit(1); } diff --git a/test/access/AccessControl.behavior.js b/test/access/AccessControl.behavior.js index 310ac3693..a93560983 100644 --- a/test/access/AccessControl.behavior.js +++ b/test/access/AccessControl.behavior.js @@ -7,7 +7,7 @@ const DEFAULT_ADMIN_ROLE = '0x00000000000000000000000000000000000000000000000000 const ROLE = web3.utils.soliditySha3('ROLE'); const OTHER_ROLE = web3.utils.soliditySha3('OTHER_ROLE'); -function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, otherAdmin) { +function shouldBehaveLikeAccessControl(errorPrefix, admin, authorized, other, otherAdmin) { shouldSupportInterfaces(['AccessControl']); describe('default admin', function () { @@ -15,11 +15,11 @@ function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, o expect(await this.accessControl.hasRole(DEFAULT_ADMIN_ROLE, admin)).to.equal(true); }); - it('other roles\'s admin is the default admin role', async function () { + it("other roles's admin is the default admin role", async function () { expect(await this.accessControl.getRoleAdmin(ROLE)).to.equal(DEFAULT_ADMIN_ROLE); }); - it('default admin role\'s admin is itself', async function () { + it("default admin role's admin is itself", async function () { expect(await this.accessControl.getRoleAdmin(DEFAULT_ADMIN_ROLE)).to.equal(DEFAULT_ADMIN_ROLE); }); }); @@ -125,7 +125,7 @@ function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, o await this.accessControl.grantRole(OTHER_ROLE, otherAdmin, { from: admin }); }); - it('a role\'s admin role can be changed', async function () { + it("a role's admin role can be changed", async function () { expect(await this.accessControl.getRoleAdmin(ROLE)).to.equal(OTHER_ROLE); }); @@ -140,14 +140,14 @@ function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, o expectEvent(receipt, 'RoleRevoked', { account: authorized, role: ROLE, sender: otherAdmin }); }); - it('a role\'s previous admins no longer grant roles', async function () { + it("a role's previous admins no longer grant roles", async function () { await expectRevert( this.accessControl.grantRole(ROLE, authorized, { from: admin }), `${errorPrefix}: account ${admin.toLowerCase()} is missing role ${OTHER_ROLE}`, ); }); - it('a role\'s previous admins no longer revoke roles', async function () { + it("a role's previous admins no longer revoke roles", async function () { await expectRevert( this.accessControl.revokeRole(ROLE, authorized, { from: admin }), `${errorPrefix}: account ${admin.toLowerCase()} is missing role ${OTHER_ROLE}`, @@ -164,14 +164,14 @@ function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, o await this.accessControl.methods['$_checkRole(bytes32)'](ROLE, { from: authorized }); }); - it('revert if sender doesn\'t have role #1', async function () { + it("revert if sender doesn't have role #1", async function () { await expectRevert( 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 () { + it("revert if sender doesn't have role #2", async function () { await expectRevert( this.accessControl.methods['$_checkRole(bytes32)'](OTHER_ROLE, { from: authorized }), `${errorPrefix}: account ${authorized.toLowerCase()} is missing role ${OTHER_ROLE}`, @@ -180,7 +180,7 @@ function shouldBehaveLikeAccessControl (errorPrefix, admin, authorized, other, o }); } -function shouldBehaveLikeAccessControlEnumerable (errorPrefix, admin, authorized, other, otherAdmin, otherAuthorized) { +function shouldBehaveLikeAccessControlEnumerable(errorPrefix, admin, authorized, other, otherAdmin, otherAuthorized) { shouldSupportInterfaces(['AccessControlEnumerable']); describe('enumerating', function () { diff --git a/test/access/AccessControl.test.js b/test/access/AccessControl.test.js index a462d5e54..90efad3d0 100644 --- a/test/access/AccessControl.test.js +++ b/test/access/AccessControl.test.js @@ -1,7 +1,4 @@ -const { - DEFAULT_ADMIN_ROLE, - shouldBehaveLikeAccessControl, -} = require('./AccessControl.behavior.js'); +const { DEFAULT_ADMIN_ROLE, shouldBehaveLikeAccessControl } = require('./AccessControl.behavior.js'); const AccessControl = artifacts.require('$AccessControl'); diff --git a/test/access/AccessControlCrossChain.test.js b/test/access/AccessControlCrossChain.test.js index 5146848ed..d5a41076b 100644 --- a/test/access/AccessControlCrossChain.test.js +++ b/test/access/AccessControlCrossChain.test.js @@ -1,15 +1,13 @@ const { expectRevert } = require('@openzeppelin/test-helpers'); const { BridgeHelper } = require('../helpers/crosschain'); -const { - DEFAULT_ADMIN_ROLE, - shouldBehaveLikeAccessControl, -} = require('./AccessControl.behavior.js'); +const { DEFAULT_ADMIN_ROLE, shouldBehaveLikeAccessControl } = require('./AccessControl.behavior.js'); -const crossChainRoleAlias = (role) => web3.utils.leftPad( - web3.utils.toHex(web3.utils.toBN(role).xor(web3.utils.toBN(web3.utils.soliditySha3('CROSSCHAIN_ALIAS')))), - 64, -); +const crossChainRoleAlias = role => + web3.utils.leftPad( + web3.utils.toHex(web3.utils.toBN(role).xor(web3.utils.toBN(web3.utils.soliditySha3('CROSSCHAIN_ALIAS')))), + 64, + ); const AccessControlCrossChainMock = artifacts.require('$AccessControlCrossChainMock'); @@ -39,23 +37,13 @@ contract('AccessControl', function (accounts) { it('Crosschain calls not authorized to non-aliased addresses', async function () { await expectRevert( - this.bridge.call( - accounts[0], - this.accessControl, - '$_checkRole(bytes32)', - [ ROLE ], - ), + this.bridge.call(accounts[0], this.accessControl, '$_checkRole(bytes32)', [ROLE]), `AccessControl: account ${accounts[0].toLowerCase()} is missing role ${crossChainRoleAlias(ROLE)}`, ); }); it('Crosschain calls not authorized to non-aliased addresses', async function () { - await this.bridge.call( - accounts[1], - this.accessControl, - '$_checkRole(bytes32)', - [ ROLE ], - ); + await this.bridge.call(accounts[1], this.accessControl, '$_checkRole(bytes32)', [ROLE]); }); }); }); diff --git a/test/access/Ownable.test.js b/test/access/Ownable.test.js index b8ca81d28..dc308f98f 100644 --- a/test/access/Ownable.test.js +++ b/test/access/Ownable.test.js @@ -6,7 +6,7 @@ const { expect } = require('chai'); const Ownable = artifacts.require('$Ownable'); contract('Ownable', function (accounts) { - const [ owner, other ] = accounts; + const [owner, other] = accounts; beforeEach(async function () { this.ownable = await Ownable.new({ from: owner }); @@ -25,10 +25,7 @@ contract('Ownable', function (accounts) { }); it('prevents non-owners from transferring', async function () { - await expectRevert( - this.ownable.transferOwnership(other, { from: other }), - 'Ownable: caller is not the owner', - ); + await expectRevert(this.ownable.transferOwnership(other, { from: other }), 'Ownable: caller is not the owner'); }); it('guards ownership against stuck state', async function () { @@ -48,10 +45,7 @@ contract('Ownable', function (accounts) { }); it('prevents non-owners from renouncement', async function () { - await expectRevert( - this.ownable.renounceOwnership({ from: other }), - 'Ownable: caller is not the owner', - ); + await expectRevert(this.ownable.renounceOwnership({ from: other }), 'Ownable: caller is not the owner'); }); }); }); diff --git a/test/crosschain/CrossChainEnabled.test.js b/test/crosschain/CrossChainEnabled.test.js index bff955882..9e7d26308 100644 --- a/test/crosschain/CrossChainEnabled.test.js +++ b/test/crosschain/CrossChainEnabled.test.js @@ -1,7 +1,7 @@ const { BridgeHelper } = require('../helpers/crosschain'); const { expectRevertCustomError } = require('../helpers/customError'); -function randomAddress () { +function randomAddress() { return web3.utils.toChecksumAddress(web3.utils.randomHex(20)); } @@ -11,17 +11,11 @@ const CrossChainEnabledArbitrumL2Mock = artifacts.require('CrossChainEnabledArbi const CrossChainEnabledOptimismMock = artifacts.require('CrossChainEnabledOptimismMock'); const CrossChainEnabledPolygonChildMock = artifacts.require('CrossChainEnabledPolygonChildMock'); -function shouldBehaveLikeReceiver (sender = randomAddress()) { +function shouldBehaveLikeReceiver(sender = randomAddress()) { it('should reject same-chain calls', async function () { - await expectRevertCustomError( - this.receiver.crossChainRestricted(), - 'NotCrossChainCall()', - ); + await expectRevertCustomError(this.receiver.crossChainRestricted(), 'NotCrossChainCall()'); - await expectRevertCustomError( - this.receiver.crossChainOwnerRestricted(), - 'NotCrossChainCall()', - ); + await expectRevertCustomError(this.receiver.crossChainOwnerRestricted(), 'NotCrossChainCall()'); }); it('should restrict to cross-chain call from a invalid sender', async function () { @@ -32,11 +26,7 @@ function shouldBehaveLikeReceiver (sender = randomAddress()) { }); it('should grant access to cross-chain call from the owner', async function () { - await this.bridge.call( - await this.receiver.owner(), - this.receiver, - 'crossChainOwnerRestricted()', - ); + await this.bridge.call(await this.receiver.owner(), this.receiver, 'crossChainOwnerRestricted()'); }); } diff --git a/test/finance/PaymentSplitter.test.js b/test/finance/PaymentSplitter.test.js index ef74d4f69..1408c9f51 100644 --- a/test/finance/PaymentSplitter.test.js +++ b/test/finance/PaymentSplitter.test.js @@ -7,7 +7,7 @@ const PaymentSplitter = artifacts.require('PaymentSplitter'); const ERC20 = artifacts.require('$ERC20'); contract('PaymentSplitter', function (accounts) { - const [ owner, payee1, payee2, payee3, nonpayee1, payer1 ] = accounts; + const [owner, payee1, payee2, payee3, nonpayee1, payer1] = accounts; const amount = ether('1'); @@ -16,33 +16,32 @@ contract('PaymentSplitter', function (accounts) { }); it('rejects more payees than shares', async function () { - await expectRevert(PaymentSplitter.new([payee1, payee2, payee3], [20, 30]), + await expectRevert( + PaymentSplitter.new([payee1, payee2, payee3], [20, 30]), 'PaymentSplitter: payees and shares length mismatch', ); }); it('rejects more shares than payees', async function () { - await expectRevert(PaymentSplitter.new([payee1, payee2], [20, 30, 40]), + await expectRevert( + PaymentSplitter.new([payee1, payee2], [20, 30, 40]), 'PaymentSplitter: payees and shares length mismatch', ); }); it('rejects null payees', async function () { - await expectRevert(PaymentSplitter.new([payee1, ZERO_ADDRESS], [20, 30]), + await expectRevert( + PaymentSplitter.new([payee1, ZERO_ADDRESS], [20, 30]), 'PaymentSplitter: account is the zero address', ); }); it('rejects zero-valued shares', async function () { - await expectRevert(PaymentSplitter.new([payee1, payee2], [20, 0]), - 'PaymentSplitter: shares are 0', - ); + await expectRevert(PaymentSplitter.new([payee1, payee2], [20, 0]), 'PaymentSplitter: shares are 0'); }); it('rejects repeated payees', async function () { - await expectRevert(PaymentSplitter.new([payee1, payee1], [20, 30]), - 'PaymentSplitter: account already has shares', - ); + await expectRevert(PaymentSplitter.new([payee1, payee1], [20, 30]), 'PaymentSplitter: account already has shares'); }); context('once deployed', function () { @@ -60,11 +59,13 @@ contract('PaymentSplitter', function (accounts) { }); it('has payees', async function () { - await Promise.all(this.payees.map(async (payee, index) => { - expect(await this.contract.payee(index)).to.equal(payee); - expect(await this.contract.released(payee)).to.be.bignumber.equal('0'); - expect(await this.contract.releasable(payee)).to.be.bignumber.equal('0'); - })); + await Promise.all( + this.payees.map(async (payee, index) => { + expect(await this.contract.payee(index)).to.equal(payee); + expect(await this.contract.released(payee)).to.be.bignumber.equal('0'); + expect(await this.contract.releasable(payee)).to.be.bignumber.equal('0'); + }), + ); }); describe('accepts payments', function () { @@ -94,27 +95,25 @@ contract('PaymentSplitter', function (accounts) { describe('release', function () { describe('Ether', function () { it('reverts if no funds to claim', async function () { - await expectRevert(this.contract.release(payee1), - 'PaymentSplitter: account is not due payment', - ); + await expectRevert(this.contract.release(payee1), 'PaymentSplitter: account is not due payment'); }); it('reverts if non-payee want to claim', async function () { await send.ether(payer1, this.contract.address, amount); - await expectRevert(this.contract.release(nonpayee1), - 'PaymentSplitter: account has no shares', - ); + await expectRevert(this.contract.release(nonpayee1), 'PaymentSplitter: account has no shares'); }); }); describe('Token', function () { it('reverts if no funds to claim', async function () { - await expectRevert(this.contract.release(this.token.address, payee1), + await expectRevert( + this.contract.release(this.token.address, payee1), 'PaymentSplitter: account is not due payment', ); }); it('reverts if non-payee want to claim', async function () { await this.token.transfer(this.contract.address, amount, { from: owner }); - await expectRevert(this.contract.release(this.token.address, nonpayee1), + await expectRevert( + this.contract.release(this.token.address, nonpayee1), 'PaymentSplitter: account has no shares', ); }); @@ -183,31 +182,31 @@ contract('PaymentSplitter', function (accounts) { await this.token.transfer(this.contract.address, amount, { from: owner }); - expectEvent( - await this.contract.release(this.token.address, payee1), - 'ERC20PaymentReleased', - { token: this.token.address, to: payee1, amount: ether('0.20') }, - ); + expectEvent(await this.contract.release(this.token.address, payee1), 'ERC20PaymentReleased', { + token: this.token.address, + to: payee1, + amount: ether('0.20'), + }); await this.token.transfer(this.contract.address, amount, { from: owner }); - expectEvent( - await this.contract.release(this.token.address, payee1), - 'ERC20PaymentReleased', - { token: this.token.address, to: payee1, amount: ether('0.20') }, - ); + expectEvent(await this.contract.release(this.token.address, payee1), 'ERC20PaymentReleased', { + token: this.token.address, + to: payee1, + amount: ether('0.20'), + }); - expectEvent( - await this.contract.release(this.token.address, payee2), - 'ERC20PaymentReleased', - { token: this.token.address, to: payee2, amount: ether('0.20') }, - ); + expectEvent(await this.contract.release(this.token.address, payee2), 'ERC20PaymentReleased', { + token: this.token.address, + to: payee2, + amount: ether('0.20'), + }); - expectEvent( - await this.contract.release(this.token.address, payee3), - 'ERC20PaymentReleased', - { token: this.token.address, to: payee3, amount: ether('1.40') }, - ); + expectEvent(await this.contract.release(this.token.address, payee3), 'ERC20PaymentReleased', { + token: this.token.address, + to: payee3, + amount: ether('1.40'), + }); expect(await this.token.balanceOf(payee1)).to.be.bignumber.equal(ether('0.40')); expect(await this.token.balanceOf(payee2)).to.be.bignumber.equal(ether('0.20')); diff --git a/test/finance/VestingWallet.behavior.js b/test/finance/VestingWallet.behavior.js index 5ab6233ca..afd4c0495 100644 --- a/test/finance/VestingWallet.behavior.js +++ b/test/finance/VestingWallet.behavior.js @@ -2,34 +2,28 @@ const { time } = require('@nomicfoundation/hardhat-network-helpers'); const { expectEvent } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -function releasedEvent (token, amount) { - return token - ? [ 'ERC20Released', { token: token.address, amount } ] - : [ 'EtherReleased', { amount } ]; +function releasedEvent(token, amount) { + return token ? ['ERC20Released', { token: token.address, amount }] : ['EtherReleased', { amount }]; } -function shouldBehaveLikeVesting (beneficiary) { +function shouldBehaveLikeVesting(beneficiary) { it('check vesting schedule', async function () { - const [ vestedAmount, releasable, ...args ] = this.token - ? [ 'vestedAmount(address,uint64)', 'releasable(address)', this.token.address ] - : [ 'vestedAmount(uint64)', 'releasable()' ]; + const [vestedAmount, releasable, ...args] = this.token + ? ['vestedAmount(address,uint64)', 'releasable(address)', this.token.address] + : ['vestedAmount(uint64)', 'releasable()']; for (const timestamp of this.schedule) { await time.increaseTo(timestamp); const vesting = this.vestingFn(timestamp); - expect(await this.mock.methods[vestedAmount](...args, timestamp)) - .to.be.bignumber.equal(vesting); + expect(await this.mock.methods[vestedAmount](...args, timestamp)).to.be.bignumber.equal(vesting); - expect(await this.mock.methods[releasable](...args)) - .to.be.bignumber.equal(vesting); + expect(await this.mock.methods[releasable](...args)).to.be.bignumber.equal(vesting); } }); it('execute vesting schedule', async function () { - const [ release, ...args ] = this.token - ? [ 'release(address)', this.token.address ] - : [ 'release()' ]; + const [release, ...args] = this.token ? ['release(address)', this.token.address] : ['release()']; let released = web3.utils.toBN(0); const before = await this.getBalance(beneficiary); @@ -37,11 +31,7 @@ function shouldBehaveLikeVesting (beneficiary) { { const receipt = await this.mock.methods[release](...args); - await expectEvent.inTransaction( - receipt.tx, - this.mock, - ...releasedEvent(this.token, '0'), - ); + await expectEvent.inTransaction(receipt.tx, this.mock, ...releasedEvent(this.token, '0')); await this.checkRelease(receipt, beneficiary, '0'); @@ -53,16 +43,11 @@ function shouldBehaveLikeVesting (beneficiary) { const vested = this.vestingFn(timestamp); const receipt = await this.mock.methods[release](...args); - await expectEvent.inTransaction( - receipt.tx, - this.mock, - ...releasedEvent(this.token, vested.sub(released)), - ); + await expectEvent.inTransaction(receipt.tx, this.mock, ...releasedEvent(this.token, vested.sub(released))); await this.checkRelease(receipt, beneficiary, vested.sub(released)); - expect(await this.getBalance(beneficiary)) - .to.be.bignumber.equal(before.add(vested)); + expect(await this.getBalance(beneficiary)).to.be.bignumber.equal(before.add(vested)); released = vested; } diff --git a/test/finance/VestingWallet.test.js b/test/finance/VestingWallet.test.js index 81a1e228a..5b90a6916 100644 --- a/test/finance/VestingWallet.test.js +++ b/test/finance/VestingWallet.test.js @@ -7,10 +7,10 @@ const ERC20 = artifacts.require('$ERC20'); const { shouldBehaveLikeVesting } = require('./VestingWallet.behavior'); -const min = (...args) => args.slice(1).reduce((x, y) => x.lt(y) ? x : y, args[0]); +const min = (...args) => args.slice(1).reduce((x, y) => (x.lt(y) ? x : y), args[0]); contract('VestingWallet', function (accounts) { - const [ sender, beneficiary ] = accounts; + const [sender, beneficiary] = accounts; const amount = web3.utils.toBN(web3.utils.toWei('100')); const duration = web3.utils.toBN(4 * 365 * 86400); // 4 years @@ -35,7 +35,9 @@ contract('VestingWallet', function (accounts) { describe('vesting schedule', function () { beforeEach(async function () { - this.schedule = Array(64).fill().map((_, i) => web3.utils.toBN(i).mul(duration).divn(60).add(this.start)); + this.schedule = Array(64) + .fill() + .map((_, i) => web3.utils.toBN(i).mul(duration).divn(60).add(this.start)); this.vestingFn = timestamp => min(amount, amount.mul(timestamp.sub(this.start)).div(duration)); }); @@ -52,13 +54,9 @@ contract('VestingWallet', function (accounts) { describe('ERC20 vesting', function () { beforeEach(async function () { this.token = await ERC20.new('Name', 'Symbol'); - this.getBalance = (account) => this.token.balanceOf(account); - this.checkRelease = (receipt, to, value) => expectEvent.inTransaction( - receipt.tx, - this.token, - 'Transfer', - { from: this.mock.address, to, value }, - ); + this.getBalance = account => this.token.balanceOf(account); + this.checkRelease = (receipt, to, value) => + expectEvent.inTransaction(receipt.tx, this.token, 'Transfer', { from: this.mock.address, to, value }); await this.token.$_mint(this.mock.address, amount); }); diff --git a/test/governance/Governor.test.js b/test/governance/Governor.test.js index e5dd04cf0..cc3cc17ef 100644 --- a/test/governance/Governor.test.js +++ b/test/governance/Governor.test.js @@ -7,9 +7,7 @@ const Enums = require('../helpers/enums'); const { EIP712Domain } = require('../helpers/eip712'); const { GovernorHelper } = require('../helpers/governance'); -const { - shouldSupportInterfaces, -} = require('../utils/introspection/SupportsInterface.behavior'); +const { shouldSupportInterfaces } = require('../utils/introspection/SupportsInterface.behavior'); const Token = artifacts.require('$ERC20Votes'); const Governor = artifacts.require('$GovernorMock'); @@ -18,7 +16,7 @@ const ERC721 = artifacts.require('$ERC721'); const ERC1155 = artifacts.require('$ERC1155'); contract('Governor', function (accounts) { - const [ owner, proposer, voter1, voter2, voter3, voter4 ] = accounts; + const [owner, proposer, voter1, voter2, voter3, voter4] = accounts; const empty = web3.utils.toChecksumAddress(web3.utils.randomHex(20)); const name = 'OZ-Governor'; @@ -53,21 +51,19 @@ contract('Governor', function (accounts) { await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner }); await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner }); - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - data: this.receiver.contract.methods.mockFunction().encodeABI(), - value, - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + data: this.receiver.contract.methods.mockFunction().encodeABI(), + value, + }, + ], + '', + ); }); - shouldSupportInterfaces([ - 'ERC165', - 'ERC1155Receiver', - 'Governor', - 'GovernorWithParams', - ]); + shouldSupportInterfaces(['ERC165', 'ERC1155Receiver', 'Governor', 'GovernorWithParams']); it('deployment check', async function () { expect(await this.mock.name()).to.be.equal(name); @@ -89,21 +85,17 @@ contract('Governor', function (accounts) { // Run proposal const txPropose = await this.helper.propose({ from: proposer }); - expectEvent( - txPropose, - 'ProposalCreated', - { - proposalId: this.proposal.id, - proposer, - targets: this.proposal.targets, - // values: this.proposal.values, - signatures: this.proposal.signatures, - calldatas: this.proposal.data, - startBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay), - endBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay).add(votingPeriod), - description: this.proposal.description, - }, - ); + expectEvent(txPropose, 'ProposalCreated', { + proposalId: this.proposal.id, + proposer, + targets: this.proposal.targets, + // values: this.proposal.values, + signatures: this.proposal.signatures, + calldatas: this.proposal.data, + startBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay), + endBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay).add(votingPeriod), + description: this.proposal.description, + }); await this.helper.waitForSnapshot(); @@ -118,51 +110,31 @@ contract('Governor', function (accounts) { }, ); - expectEvent( - await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 }), - 'VoteCast', - { - voter: voter2, - support: Enums.VoteType.For, - weight: web3.utils.toWei('7'), - }, - ); + expectEvent(await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 }), 'VoteCast', { + voter: voter2, + support: Enums.VoteType.For, + weight: web3.utils.toWei('7'), + }); - expectEvent( - await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 }), - 'VoteCast', - { - voter: voter3, - support: Enums.VoteType.Against, - weight: web3.utils.toWei('5'), - }, - ); + expectEvent(await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 }), 'VoteCast', { + voter: voter3, + support: Enums.VoteType.Against, + weight: web3.utils.toWei('5'), + }); - expectEvent( - await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 }), - 'VoteCast', - { - voter: voter4, - support: Enums.VoteType.Abstain, - weight: web3.utils.toWei('2'), - }, - ); + expectEvent(await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 }), 'VoteCast', { + voter: voter4, + support: Enums.VoteType.Abstain, + weight: web3.utils.toWei('2'), + }); await this.helper.waitForDeadline(); const txExecute = await this.helper.execute(); - expectEvent( - txExecute, - 'ProposalExecuted', - { proposalId: this.proposal.id }, - ); + expectEvent(txExecute, 'ProposalExecuted', { proposalId: this.proposal.id }); - await expectEvent.inTransaction( - txExecute.tx, - this.receiver, - 'MockFunctionCalled', - ); + await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled'); // After expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false); @@ -176,10 +148,9 @@ contract('Governor', function (accounts) { const voterBySig = Wallet.generate(); const voterBySigAddress = web3.utils.toChecksumAddress(voterBySig.getAddressString()); - const signature = async (message) => { - return fromRpcSig(ethSigUtil.signTypedMessage( - voterBySig.getPrivateKey(), - { + const signature = async message => { + return fromRpcSig( + ethSigUtil.signTypedMessage(voterBySig.getPrivateKey(), { data: { types: { EIP712Domain, @@ -192,8 +163,8 @@ contract('Governor', function (accounts) { primaryType: 'Ballot', message, }, - }, - )); + }), + ); }; await this.token.delegate(voterBySigAddress, { from: voter1 }); @@ -201,11 +172,10 @@ contract('Governor', function (accounts) { // Run proposal await this.helper.propose(); await this.helper.waitForSnapshot(); - expectEvent( - await this.helper.vote({ support: Enums.VoteType.For, signature }), - 'VoteCast', - { voter: voterBySigAddress, support: Enums.VoteType.For }, - ); + expectEvent(await this.helper.vote({ support: Enums.VoteType.For, signature }), 'VoteCast', { + voter: voterBySigAddress, + support: Enums.VoteType.For, + }); await this.helper.waitForDeadline(); await this.helper.execute(); @@ -217,12 +187,15 @@ contract('Governor', function (accounts) { }); it('send ethers', async function () { - this.proposal = this.helper.setProposal([ - { - target: empty, - value, - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: empty, + value, + }, + ], + '', + ); // Before expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(value); @@ -320,12 +293,15 @@ contract('Governor', function (accounts) { }); it('if receiver revert without reason', async function () { - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - data: this.receiver.contract.methods.mockFunctionRevertsNoReason().encodeABI(), - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + data: this.receiver.contract.methods.mockFunctionRevertsNoReason().encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); @@ -335,12 +311,15 @@ contract('Governor', function (accounts) { }); it('if receiver revert with reason', async function () { - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - data: this.receiver.contract.methods.mockFunctionRevertsReason().encodeABI(), - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + data: this.receiver.contract.methods.mockFunctionRevertsReason().encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); @@ -457,34 +436,43 @@ contract('Governor', function (accounts) { describe('proposal length', function () { it('empty', async function () { - this.helper.setProposal([ ], ''); + this.helper.setProposal([], ''); await expectRevert(this.helper.propose(), 'Governor: empty proposal'); }); it('mismatch #1', async function () { - this.helper.setProposal({ - targets: [ ], - values: [ web3.utils.toWei('0') ], - data: [ this.receiver.contract.methods.mockFunction().encodeABI() ], - }, ''); + this.helper.setProposal( + { + targets: [], + values: [web3.utils.toWei('0')], + data: [this.receiver.contract.methods.mockFunction().encodeABI()], + }, + '', + ); await expectRevert(this.helper.propose(), 'Governor: invalid proposal length'); }); it('mismatch #2', async function () { - this.helper.setProposal({ - targets: [ this.receiver.address ], - values: [ ], - data: [ this.receiver.contract.methods.mockFunction().encodeABI() ], - }, ''); + this.helper.setProposal( + { + targets: [this.receiver.address], + values: [], + data: [this.receiver.contract.methods.mockFunction().encodeABI()], + }, + '', + ); await expectRevert(this.helper.propose(), 'Governor: invalid proposal length'); }); it('mismatch #3', async function () { - this.helper.setProposal({ - targets: [ this.receiver.address ], - values: [ web3.utils.toWei('0') ], - data: [ ], - }, ''); + this.helper.setProposal( + { + targets: [this.receiver.address], + values: [web3.utils.toWei('0')], + data: [], + }, + '', + ); await expectRevert(this.helper.propose(), 'Governor: invalid proposal length'); }); }); @@ -503,56 +491,57 @@ contract('Governor', function (accounts) { }); it('can setVotingDelay through governance', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.setVotingDelay('0').encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods.setVotingDelay('0').encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }); await this.helper.waitForDeadline(); - expectEvent( - await this.helper.execute(), - 'VotingDelaySet', - { oldVotingDelay: '4', newVotingDelay: '0' }, - ); + expectEvent(await this.helper.execute(), 'VotingDelaySet', { oldVotingDelay: '4', newVotingDelay: '0' }); expect(await this.mock.votingDelay()).to.be.bignumber.equal('0'); }); it('can setVotingPeriod through governance', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.setVotingPeriod('32').encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods.setVotingPeriod('32').encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }); await this.helper.waitForDeadline(); - expectEvent( - await this.helper.execute(), - 'VotingPeriodSet', - { oldVotingPeriod: '16', newVotingPeriod: '32' }, - ); + expectEvent(await this.helper.execute(), 'VotingPeriodSet', { oldVotingPeriod: '16', newVotingPeriod: '32' }); expect(await this.mock.votingPeriod()).to.be.bignumber.equal('32'); }); it('cannot setVotingPeriod to 0 through governance', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.setVotingPeriod('0').encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods.setVotingPeriod('0').encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); @@ -563,23 +552,25 @@ contract('Governor', function (accounts) { }); it('can setProposalThreshold to 0 through governance', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.setProposalThreshold('1000000000000000000').encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods.setProposalThreshold('1000000000000000000').encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }); await this.helper.waitForDeadline(); - expectEvent( - await this.helper.execute(), - 'ProposalThresholdSet', - { oldProposalThreshold: '0', newProposalThreshold: '1000000000000000000' }, - ); + expectEvent(await this.helper.execute(), 'ProposalThresholdSet', { + oldProposalThreshold: '0', + newProposalThreshold: '1000000000000000000', + }); expect(await this.mock.proposalThreshold()).to.be.bignumber.equal('1000000000000000000'); }); diff --git a/test/governance/TimelockController.test.js b/test/governance/TimelockController.test.js index 3b31f8189..83352ef85 100644 --- a/test/governance/TimelockController.test.js +++ b/test/governance/TimelockController.test.js @@ -3,9 +3,7 @@ const { ZERO_ADDRESS, ZERO_BYTES32 } = constants; const { expect } = require('chai'); -const { - shouldSupportInterfaces, -} = require('../utils/introspection/SupportsInterface.behavior'); +const { shouldSupportInterfaces } = require('../utils/introspection/SupportsInterface.behavior'); const TimelockController = artifacts.require('TimelockController'); const CallReceiverMock = artifacts.require('CallReceiverMock'); @@ -17,42 +15,28 @@ const MINDELAY = time.duration.days(1); const salt = '0x025e7b0be353a74631ad648c667493c0e1cd31caa4cc2d3520fdc171ea0cc726'; // a random value -function genOperation (target, value, data, predecessor, salt) { - const id = web3.utils.keccak256(web3.eth.abi.encodeParameters([ - 'address', - 'uint256', - 'bytes', - 'uint256', - 'bytes32', - ], [ - target, - value, - data, - predecessor, - salt, - ])); +function genOperation(target, value, data, predecessor, salt) { + const id = web3.utils.keccak256( + web3.eth.abi.encodeParameters( + ['address', 'uint256', 'bytes', 'uint256', 'bytes32'], + [target, value, data, predecessor, salt], + ), + ); return { id, target, value, data, predecessor, salt }; } -function genOperationBatch (targets, values, payloads, predecessor, salt) { - const id = web3.utils.keccak256(web3.eth.abi.encodeParameters([ - 'address[]', - 'uint256[]', - 'bytes[]', - 'uint256', - 'bytes32', - ], [ - targets, - values, - payloads, - predecessor, - salt, - ])); +function genOperationBatch(targets, values, payloads, predecessor, salt) { + const id = web3.utils.keccak256( + web3.eth.abi.encodeParameters( + ['address[]', 'uint256[]', 'bytes[]', 'uint256', 'bytes32'], + [targets, values, payloads, predecessor, salt], + ), + ); return { id, targets, values, payloads, predecessor, salt }; } contract('TimelockController', function (accounts) { - const [ , admin, proposer, canceller, executor, other ] = accounts; + const [, admin, proposer, canceller, executor, other] = accounts; const TIMELOCK_ADMIN_ROLE = web3.utils.soliditySha3('TIMELOCK_ADMIN_ROLE'); const PROPOSER_ROLE = web3.utils.soliditySha3('PROPOSER_ROLE'); @@ -61,12 +45,7 @@ contract('TimelockController', function (accounts) { beforeEach(async function () { // Deploy new timelock - this.mock = await TimelockController.new( - MINDELAY, - [ proposer ], - [ executor ], - admin, - ); + this.mock = await TimelockController.new(MINDELAY, [proposer], [executor], admin); expect(await this.mock.hasRole(CANCELLER_ROLE, proposer)).to.be.equal(true); await this.mock.revokeRole(CANCELLER_ROLE, proposer, { from: admin }); @@ -77,9 +56,7 @@ contract('TimelockController', function (accounts) { this.implementation2 = await Implementation2.new({ from: admin }); }); - shouldSupportInterfaces([ - 'ERC1155Receiver', - ]); + shouldSupportInterfaces(['ERC1155Receiver']); it('initial state', async function () { expect(await this.mock.getMinDelay()).to.be.bignumber.equal(MINDELAY); @@ -89,27 +66,21 @@ contract('TimelockController', function (accounts) { expect(await this.mock.EXECUTOR_ROLE()).to.be.equal(EXECUTOR_ROLE); expect(await this.mock.CANCELLER_ROLE()).to.be.equal(CANCELLER_ROLE); - expect(await Promise.all([ PROPOSER_ROLE, CANCELLER_ROLE, EXECUTOR_ROLE ].map(role => - this.mock.hasRole(role, proposer), - ))).to.be.deep.equal([ true, false, false ]); + expect( + await Promise.all([PROPOSER_ROLE, CANCELLER_ROLE, EXECUTOR_ROLE].map(role => this.mock.hasRole(role, proposer))), + ).to.be.deep.equal([true, false, false]); - expect(await Promise.all([ PROPOSER_ROLE, CANCELLER_ROLE, EXECUTOR_ROLE ].map(role => - this.mock.hasRole(role, canceller), - ))).to.be.deep.equal([ false, true, false ]); + expect( + await Promise.all([PROPOSER_ROLE, CANCELLER_ROLE, EXECUTOR_ROLE].map(role => this.mock.hasRole(role, canceller))), + ).to.be.deep.equal([false, true, false]); - expect(await Promise.all([ PROPOSER_ROLE, CANCELLER_ROLE, EXECUTOR_ROLE ].map(role => - this.mock.hasRole(role, executor), - ))).to.be.deep.equal([ false, false, true ]); + expect( + await Promise.all([PROPOSER_ROLE, CANCELLER_ROLE, EXECUTOR_ROLE].map(role => this.mock.hasRole(role, executor))), + ).to.be.deep.equal([false, false, true]); }); it('optional admin', async function () { - const mock = await TimelockController.new( - MINDELAY, - [ proposer ], - [ executor ], - ZERO_ADDRESS, - { from: other }, - ); + const mock = await TimelockController.new(MINDELAY, [proposer], [executor], ZERO_ADDRESS, { from: other }); expect(await mock.hasRole(TIMELOCK_ADMIN_ROLE, admin)).to.be.equal(false); expect(await mock.hasRole(TIMELOCK_ADMIN_ROLE, other)).to.be.equal(false); @@ -125,13 +96,15 @@ contract('TimelockController', function (accounts) { '0xba41db3be0a9929145cfe480bd0f1f003689104d275ae912099f925df424ef94', '0x60d9109846ab510ed75c15f979ae366a8a2ace11d34ba9788c13ac296db50e6e', ); - expect(await this.mock.hashOperation( - this.operation.target, - this.operation.value, - this.operation.data, - this.operation.predecessor, - this.operation.salt, - )).to.be.equal(this.operation.id); + expect( + await this.mock.hashOperation( + this.operation.target, + this.operation.value, + this.operation.data, + this.operation.predecessor, + this.operation.salt, + ), + ).to.be.equal(this.operation.id); }); it('hashOperationBatch', async function () { @@ -142,13 +115,15 @@ contract('TimelockController', function (accounts) { '0xce8f45069cc71d25f71ba05062de1a3974f9849b004de64a70998bca9d29c2e7', '0x8952d74c110f72bfe5accdf828c74d53a7dfb71235dfa8a1e8c75d8576b372ff', ); - expect(await this.mock.hashOperationBatch( - this.operation.targets, - this.operation.values, - this.operation.payloads, - this.operation.predecessor, - this.operation.salt, - )).to.be.equal(this.operation.id); + expect( + await this.mock.hashOperationBatch( + this.operation.targets, + this.operation.values, + this.operation.payloads, + this.operation.predecessor, + this.operation.salt, + ), + ).to.be.equal(this.operation.id); }); }); describe('simple', function () { @@ -185,8 +160,9 @@ contract('TimelockController', function (accounts) { const block = await web3.eth.getBlock(receipt.receipt.blockHash); - expect(await this.mock.getTimestamp(this.operation.id)) - .to.be.bignumber.equal(web3.utils.toBN(block.timestamp).add(MINDELAY)); + expect(await this.mock.getTimestamp(this.operation.id)).to.be.bignumber.equal( + web3.utils.toBN(block.timestamp).add(MINDELAY), + ); }); it('prevent overwriting active operation', async function () { @@ -392,8 +368,9 @@ contract('TimelockController', function (accounts) { const block = await web3.eth.getBlock(receipt.receipt.blockHash); - expect(await this.mock.getTimestamp(this.operation.id)) - .to.be.bignumber.equal(web3.utils.toBN(block.timestamp).add(MINDELAY)); + expect(await this.mock.getTimestamp(this.operation.id)).to.be.bignumber.equal( + web3.utils.toBN(block.timestamp).add(MINDELAY), + ); }); it('prevent overwriting active operation', async function () { @@ -637,16 +614,8 @@ contract('TimelockController', function (accounts) { it('partial execution', async function () { const operation = genOperationBatch( - [ - this.callreceivermock.address, - this.callreceivermock.address, - this.callreceivermock.address, - ], - [ - 0, - 0, - 0, - ], + [this.callreceivermock.address, this.callreceivermock.address, this.callreceivermock.address], + [0, 0, 0], [ this.callreceivermock.contract.methods.mockFunction().encodeABI(), this.callreceivermock.contract.methods.mockFunctionThrows().encodeABI(), @@ -724,10 +693,7 @@ contract('TimelockController', function (accounts) { describe('maintenance', function () { it('prevent unauthorized maintenance', async function () { - await expectRevert( - this.mock.updateDelay(0, { from: other }), - 'TimelockController: caller must be timelock', - ); + await expectRevert(this.mock.updateDelay(0, { from: other }), 'TimelockController: caller must be timelock'); }); it('timelock scheduled maintenance', async function () { @@ -889,14 +855,9 @@ contract('TimelockController', function (accounts) { ); await time.increase(MINDELAY); await expectRevert( - this.mock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor }, - ), + this.mock.execute(operation.target, operation.value, operation.data, operation.predecessor, operation.salt, { + from: executor, + }), 'TimelockController: underlying transaction reverted', ); }); @@ -921,14 +882,9 @@ contract('TimelockController', function (accounts) { ); await time.increase(MINDELAY); await expectRevert( - this.mock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor }, - ), + this.mock.execute(operation.target, operation.value, operation.data, operation.predecessor, operation.salt, { + from: executor, + }), 'TimelockController: underlying transaction reverted', ); }); @@ -953,14 +909,10 @@ contract('TimelockController', function (accounts) { ); await time.increase(MINDELAY); await expectRevert( - this.mock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor, gas: '70000' }, - ), + this.mock.execute(operation.target, operation.value, operation.data, operation.predecessor, operation.salt, { + from: executor, + gas: '70000', + }), 'TimelockController: underlying transaction reverted', ); }); @@ -1025,14 +977,9 @@ contract('TimelockController', function (accounts) { expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); await expectRevert( - this.mock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor }, - ), + this.mock.execute(operation.target, operation.value, operation.data, operation.predecessor, operation.salt, { + from: executor, + }), 'TimelockController: underlying transaction reverted', ); @@ -1064,14 +1011,9 @@ contract('TimelockController', function (accounts) { expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); await expectRevert( - this.mock.execute( - operation.target, - operation.value, - operation.data, - operation.predecessor, - operation.salt, - { from: executor }, - ), + this.mock.execute(operation.target, operation.value, operation.data, operation.predecessor, operation.salt, { + from: executor, + }), 'TimelockController: underlying transaction reverted', ); diff --git a/test/governance/compatibility/GovernorCompatibilityBravo.test.js b/test/governance/compatibility/GovernorCompatibilityBravo.test.js index 1c25be36a..231d57b27 100644 --- a/test/governance/compatibility/GovernorCompatibilityBravo.test.js +++ b/test/governance/compatibility/GovernorCompatibilityBravo.test.js @@ -9,12 +9,17 @@ const Timelock = artifacts.require('CompTimelock'); const Governor = artifacts.require('$GovernorCompatibilityBravoMock'); const CallReceiver = artifacts.require('CallReceiverMock'); -function makeContractAddress (creator, nonce) { - return web3.utils.toChecksumAddress(web3.utils.sha3(RLP.encode([creator, nonce])).slice(12).substring(14)); +function makeContractAddress(creator, nonce) { + return web3.utils.toChecksumAddress( + web3.utils + .sha3(RLP.encode([creator, nonce])) + .slice(12) + .substring(14), + ); } contract('GovernorCompatibilityBravo', function (accounts) { - const [ owner, proposer, voter1, voter2, voter3, voter4, other ] = accounts; + const [owner, proposer, voter1, voter2, voter3, voter4, other] = accounts; const name = 'OZ-Governor'; // const version = '1'; @@ -27,7 +32,7 @@ contract('GovernorCompatibilityBravo', function (accounts) { const value = web3.utils.toWei('1'); beforeEach(async function () { - const [ deployer ] = await web3.eth.getAccounts(); + const [deployer] = await web3.eth.getAccounts(); this.token = await Token.new(tokenName, tokenSymbol, tokenName); @@ -58,13 +63,16 @@ contract('GovernorCompatibilityBravo', function (accounts) { await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner }); // default proposal - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - value, - signature: 'mockFunction()', - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + value, + signature: 'mockFunction()', + }, + ], + '', + ); }); it('deployment check', async function () { @@ -141,31 +149,19 @@ contract('GovernorCompatibilityBravo', function (accounts) { expect(voteReceipt4.support).to.be.bignumber.equal(Enums.VoteType.Abstain); expect(voteReceipt4.votes).to.be.bignumber.equal(web3.utils.toWei('2')); - expectEvent( - txPropose, - 'ProposalCreated', - { - proposalId: this.proposal.id, - proposer, - targets: this.proposal.targets, - // values: this.proposal.values, - signatures: this.proposal.signatures.map(() => ''), // this event doesn't contain the proposal detail - calldatas: this.proposal.fulldata, - startBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay), - endBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay).add(votingPeriod), - description: this.proposal.description, - }, - ); - expectEvent( - txExecute, - 'ProposalExecuted', - { proposalId: this.proposal.id }, - ); - await expectEvent.inTransaction( - txExecute.tx, - this.receiver, - 'MockFunctionCalled', - ); + expectEvent(txPropose, 'ProposalCreated', { + proposalId: this.proposal.id, + proposer, + targets: this.proposal.targets, + // values: this.proposal.values, + signatures: this.proposal.signatures.map(() => ''), // this event doesn't contain the proposal detail + calldatas: this.proposal.fulldata, + startBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay), + endBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay).add(votingPeriod), + description: this.proposal.description, + }); + expectEvent(txExecute, 'ProposalExecuted', { proposalId: this.proposal.id }); + await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled'); }); it('double voting is forbidden', async function () { @@ -180,16 +176,19 @@ contract('GovernorCompatibilityBravo', function (accounts) { it('with function selector and arguments', async function () { const target = this.receiver.address; - this.helper.setProposal([ - { target, data: this.receiver.contract.methods.mockFunction().encodeABI() }, - { target, data: this.receiver.contract.methods.mockFunctionWithArgs(17, 42).encodeABI() }, - { target, signature: 'mockFunctionNonPayable()' }, - { - target, - signature: 'mockFunctionWithArgs(uint256,uint256)', - data: web3.eth.abi.encodeParameters(['uint256', 'uint256'], [18, 43]), - }, - ], ''); + this.helper.setProposal( + [ + { target, data: this.receiver.contract.methods.mockFunction().encodeABI() }, + { target, data: this.receiver.contract.methods.mockFunctionWithArgs(17, 42).encodeABI() }, + { target, signature: 'mockFunctionNonPayable()' }, + { + target, + signature: 'mockFunctionWithArgs(uint256,uint256)', + data: web3.eth.abi.encodeParameters(['uint256', 'uint256'], [18, 43]), + }, + ], + '', + ); await this.helper.propose({ from: proposer }); await this.helper.waitForSnapshot(); @@ -199,37 +198,16 @@ contract('GovernorCompatibilityBravo', function (accounts) { await this.helper.waitForEta(); const txExecute = await this.helper.execute(); - await expectEvent.inTransaction( - txExecute.tx, - this.receiver, - 'MockFunctionCalled', - ); - await expectEvent.inTransaction( - txExecute.tx, - this.receiver, - 'MockFunctionCalled', - ); - await expectEvent.inTransaction( - txExecute.tx, - this.receiver, - 'MockFunctionCalledWithArgs', - { a: '17', b: '42' }, - ); - await expectEvent.inTransaction( - txExecute.tx, - this.receiver, - 'MockFunctionCalledWithArgs', - { a: '18', b: '43' }, - ); + await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled'); + await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled'); + await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalledWithArgs', { a: '17', b: '42' }); + await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalledWithArgs', { a: '18', b: '43' }); }); describe('should revert', function () { describe('on propose', function () { it('if proposal does not meet proposalThreshold', async function () { - await expectRevert( - this.helper.propose({ from: other }), - 'Governor: proposer votes below proposal threshold', - ); + await expectRevert(this.helper.propose({ from: other }), 'Governor: proposer votes below proposal threshold'); }); }); diff --git a/test/governance/extensions/GovernorComp.test.js b/test/governance/extensions/GovernorComp.test.js index d32480ec1..8d48b4ddc 100644 --- a/test/governance/extensions/GovernorComp.test.js +++ b/test/governance/extensions/GovernorComp.test.js @@ -8,7 +8,7 @@ const Governor = artifacts.require('$GovernorCompMock'); const CallReceiver = artifacts.require('CallReceiverMock'); contract('GovernorComp', function (accounts) { - const [ owner, voter1, voter2, voter3, voter4 ] = accounts; + const [owner, voter1, voter2, voter3, voter4] = accounts; const name = 'OZ-Governor'; // const version = '1'; @@ -36,13 +36,16 @@ contract('GovernorComp', function (accounts) { await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner }); // default proposal - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - value, - data: this.receiver.contract.methods.mockFunction().encodeABI(), - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + value, + data: this.receiver.contract.methods.mockFunction().encodeABI(), + }, + ], + '', + ); }); it('deployment check', async function () { diff --git a/test/governance/extensions/GovernorERC721.test.js b/test/governance/extensions/GovernorERC721.test.js index 4c402737b..b0babbd37 100644 --- a/test/governance/extensions/GovernorERC721.test.js +++ b/test/governance/extensions/GovernorERC721.test.js @@ -8,7 +8,7 @@ const Governor = artifacts.require('$GovernorVoteMocks'); const CallReceiver = artifacts.require('CallReceiverMock'); contract('GovernorERC721', function (accounts) { - const [ owner, voter1, voter2, voter3, voter4 ] = accounts; + const [owner, voter1, voter2, voter3, voter4] = accounts; const name = 'OZ-Governor'; // const version = '1'; @@ -33,7 +33,7 @@ contract('GovernorERC721', 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 }); @@ -41,13 +41,16 @@ contract('GovernorERC721', function (accounts) { await this.helper.delegate({ token: this.token, to: voter4, tokenId: NFT4 }, { from: owner }); // default proposal - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - value, - data: this.receiver.contract.methods.mockFunction().encodeABI(), - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + value, + data: this.receiver.contract.methods.mockFunction().encodeABI(), + }, + ], + '', + ); }); it('deployment check', async function () { @@ -62,29 +65,29 @@ contract('GovernorERC721', function (accounts) { await this.helper.propose(); await this.helper.waitForSnapshot(); - expectEvent( - await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }), - 'VoteCast', - { voter: voter1, support: Enums.VoteType.For, weight: '1' }, - ); + expectEvent(await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }), 'VoteCast', { + voter: voter1, + support: Enums.VoteType.For, + weight: '1', + }); - expectEvent( - await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 }), - 'VoteCast', - { voter: voter2, support: Enums.VoteType.For, weight: '2' }, - ); + expectEvent(await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 }), 'VoteCast', { + voter: voter2, + support: Enums.VoteType.For, + weight: '2', + }); - expectEvent( - await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 }), - 'VoteCast', - { voter: voter3, support: Enums.VoteType.Against, weight: '1' }, - ); + expectEvent(await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 }), 'VoteCast', { + voter: voter3, + support: Enums.VoteType.Against, + weight: '1', + }); - expectEvent( - await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 }), - 'VoteCast', - { voter: voter4, support: Enums.VoteType.Abstain, weight: '1' }, - ); + expectEvent(await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 }), 'VoteCast', { + voter: voter4, + support: Enums.VoteType.Abstain, + weight: '1', + }); await this.helper.waitForDeadline(); await this.helper.execute(); diff --git a/test/governance/extensions/GovernorPreventLateQuorum.test.js b/test/governance/extensions/GovernorPreventLateQuorum.test.js index b179e26f7..ffec8ace6 100644 --- a/test/governance/extensions/GovernorPreventLateQuorum.test.js +++ b/test/governance/extensions/GovernorPreventLateQuorum.test.js @@ -8,7 +8,7 @@ const Governor = artifacts.require('$GovernorPreventLateQuorumMock'); const CallReceiver = artifacts.require('CallReceiverMock'); contract('GovernorPreventLateQuorum', function (accounts) { - const [ owner, proposer, voter1, voter2, voter3, voter4 ] = accounts; + const [owner, proposer, voter1, voter2, voter3, voter4] = accounts; const name = 'OZ-Governor'; // const version = '1'; @@ -46,13 +46,16 @@ contract('GovernorPreventLateQuorum', function (accounts) { await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner }); // default proposal - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - value, - data: this.receiver.contract.methods.mockFunction().encodeABI(), - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + value, + data: this.receiver.contract.methods.mockFunction().encodeABI(), + }, + ], + '', + ); }); it('deployment check', async function () { @@ -91,21 +94,17 @@ contract('GovernorPreventLateQuorum', function (accounts) { expect(await this.mock.proposalSnapshot(this.proposal.id)).to.be.bignumber.equal(startBlock); expect(await this.mock.proposalDeadline(this.proposal.id)).to.be.bignumber.equal(endBlock); - expectEvent( - txPropose, - 'ProposalCreated', - { - proposalId: this.proposal.id, - proposer, - targets: this.proposal.targets, - // values: this.proposal.values.map(value => new BN(value)), - signatures: this.proposal.signatures, - calldatas: this.proposal.data, - startBlock, - endBlock, - description: this.proposal.description, - }, - ); + expectEvent(txPropose, 'ProposalCreated', { + proposalId: this.proposal.id, + proposer, + targets: this.proposal.targets, + // values: this.proposal.values.map(value => new BN(value)), + signatures: this.proposal.signatures, + calldatas: this.proposal.data, + startBlock, + endBlock, + description: this.proposal.description, + }); }); it('Delay is extended to prevent last minute take-over', async function () { @@ -138,39 +137,34 @@ contract('GovernorPreventLateQuorum', function (accounts) { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Defeated); // check extension event - expectEvent( - txVote, - 'ProposalExtended', - { proposalId: this.proposal.id, extendedDeadline }, - ); + expectEvent(txVote, 'ProposalExtended', { proposalId: this.proposal.id, extendedDeadline }); }); describe('onlyGovernance updates', function () { it('setLateQuorumVoteExtension is protected', async function () { - await expectRevert( - this.mock.setLateQuorumVoteExtension(0), - 'Governor: onlyGovernance', - ); + await expectRevert(this.mock.setLateQuorumVoteExtension(0), 'Governor: onlyGovernance'); }); it('can setLateQuorumVoteExtension through governance', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.setLateQuorumVoteExtension('0').encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods.setLateQuorumVoteExtension('0').encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }); await this.helper.waitForDeadline(); - expectEvent( - await this.helper.execute(), - 'LateQuorumVoteExtensionSet', - { oldVoteExtension: lateQuorumVoteExtension, newVoteExtension: '0' }, - ); + expectEvent(await this.helper.execute(), 'LateQuorumVoteExtensionSet', { + oldVoteExtension: lateQuorumVoteExtension, + newVoteExtension: '0', + }); expect(await this.mock.lateQuorumVoteExtension()).to.be.bignumber.equal('0'); }); diff --git a/test/governance/extensions/GovernorTimelockCompound.test.js b/test/governance/extensions/GovernorTimelockCompound.test.js index 3e8e10b10..334659e07 100644 --- a/test/governance/extensions/GovernorTimelockCompound.test.js +++ b/test/governance/extensions/GovernorTimelockCompound.test.js @@ -4,21 +4,24 @@ const RLP = require('rlp'); const Enums = require('../../helpers/enums'); const { GovernorHelper } = require('../../helpers/governance'); -const { - shouldSupportInterfaces, -} = require('../../utils/introspection/SupportsInterface.behavior'); +const { shouldSupportInterfaces } = require('../../utils/introspection/SupportsInterface.behavior'); const Token = artifacts.require('$ERC20Votes'); const Timelock = artifacts.require('CompTimelock'); const Governor = artifacts.require('$GovernorTimelockCompoundMock'); const CallReceiver = artifacts.require('CallReceiverMock'); -function makeContractAddress (creator, nonce) { - return web3.utils.toChecksumAddress(web3.utils.sha3(RLP.encode([creator, nonce])).slice(12).substring(14)); +function makeContractAddress(creator, nonce) { + return web3.utils.toChecksumAddress( + web3.utils + .sha3(RLP.encode([creator, nonce])) + .slice(12) + .substring(14), + ); } contract('GovernorTimelockCompound', function (accounts) { - const [ owner, voter1, voter2, voter3, voter4, other ] = accounts; + const [owner, voter1, voter2, voter3, voter4, other] = accounts; const name = 'OZ-Governor'; // const version = '1'; @@ -30,7 +33,7 @@ contract('GovernorTimelockCompound', function (accounts) { const value = web3.utils.toWei('1'); beforeEach(async function () { - const [ deployer ] = await web3.eth.getAccounts(); + const [deployer] = await web3.eth.getAccounts(); this.token = await Token.new(tokenName, tokenSymbol, tokenName); @@ -39,15 +42,7 @@ contract('GovernorTimelockCompound', function (accounts) { const predictGovernor = makeContractAddress(deployer, nonce + 1); this.timelock = await Timelock.new(predictGovernor, 2 * 86400); - this.mock = await Governor.new( - name, - votingDelay, - votingPeriod, - 0, - this.timelock.address, - this.token.address, - 0, - ); + this.mock = await Governor.new(name, votingDelay, votingPeriod, 0, this.timelock.address, this.token.address, 0); this.receiver = await CallReceiver.new(); this.helper = new GovernorHelper(this.mock); @@ -61,23 +56,21 @@ contract('GovernorTimelockCompound', function (accounts) { await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner }); // default proposal - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - value, - data: this.receiver.contract.methods.mockFunction().encodeABI(), - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + value, + data: this.receiver.contract.methods.mockFunction().encodeABI(), + }, + ], + '', + ); }); - shouldSupportInterfaces([ - 'ERC165', - 'Governor', - 'GovernorWithParams', - 'GovernorTimelock', - ]); + shouldSupportInterfaces(['ERC165', 'Governor', 'GovernorWithParams', 'GovernorTimelock']); - it('doesn\'t accept ether transfers', async function () { + it("doesn't accept ether transfers", async function () { await expectRevert.unspecified(web3.eth.sendTransaction({ from: owner, to: this.mock.address, value: 1 })); }); @@ -129,20 +122,14 @@ contract('GovernorTimelockCompound', function (accounts) { target: this.token.address, data: this.token.contract.methods.approve(this.receiver.address, constants.MAX_UINT256).encodeABI(), }; - this.helper.setProposal([ action, action ], ''); + this.helper.setProposal([action, action], ''); await this.helper.propose(); await this.helper.waitForSnapshot(); await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }); await this.helper.waitForDeadline(); - await expectRevert( - this.helper.queue(), - 'GovernorTimelockCompound: identical proposal action already queued', - ); - await expectRevert( - this.helper.execute(), - 'GovernorTimelockCompound: proposal not yet queued', - ); + await expectRevert(this.helper.queue(), 'GovernorTimelockCompound: identical proposal action already queued'); + await expectRevert(this.helper.execute(), 'GovernorTimelockCompound: proposal not yet queued'); }); }); @@ -155,10 +142,7 @@ contract('GovernorTimelockCompound', function (accounts) { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded); - await expectRevert( - this.helper.execute(), - 'GovernorTimelockCompound: proposal not yet queued', - ); + await expectRevert(this.helper.execute(), 'GovernorTimelockCompound: proposal not yet queued'); }); it('if too early', async function () { @@ -172,7 +156,7 @@ contract('GovernorTimelockCompound', function (accounts) { await expectRevert( this.helper.execute(), - 'Timelock::executeTransaction: Transaction hasn\'t surpassed time lock', + "Timelock::executeTransaction: Transaction hasn't surpassed time lock", ); }); @@ -186,10 +170,7 @@ contract('GovernorTimelockCompound', function (accounts) { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Expired); - await expectRevert( - this.helper.execute(), - 'Governor: proposal not successful', - ); + await expectRevert(this.helper.execute(), 'Governor: proposal not successful'); }); it('if already executed', async function () { @@ -200,10 +181,7 @@ contract('GovernorTimelockCompound', function (accounts) { await this.helper.queue(); await this.helper.waitForEta(); await this.helper.execute(); - await expectRevert( - this.helper.execute(), - 'Governor: proposal not successful', - ); + await expectRevert(this.helper.execute(), 'Governor: proposal not successful'); }); }); }); @@ -215,11 +193,7 @@ contract('GovernorTimelockCompound', function (accounts) { await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }); await this.helper.waitForDeadline(); - expectEvent( - await this.helper.cancel(), - 'ProposalCanceled', - { proposalId: this.proposal.id }, - ); + expectEvent(await this.helper.cancel(), 'ProposalCanceled', { proposalId: this.proposal.id }); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); await expectRevert(this.helper.queue(), 'Governor: proposal not successful'); @@ -232,11 +206,7 @@ contract('GovernorTimelockCompound', function (accounts) { await this.helper.waitForDeadline(); await this.helper.queue(); - expectEvent( - await this.helper.cancel(), - 'ProposalCanceled', - { proposalId: this.proposal.id }, - ); + expectEvent(await this.helper.cancel(), 'ProposalCanceled', { proposalId: this.proposal.id }); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); await expectRevert(this.helper.execute(), 'Governor: proposal not successful'); @@ -251,26 +221,23 @@ contract('GovernorTimelockCompound', function (accounts) { it('is protected', async function () { await expectRevert( - this.mock.relay( - this.token.address, - 0, - this.token.contract.methods.transfer(other, 1).encodeABI(), - ), + this.mock.relay(this.token.address, 0, this.token.contract.methods.transfer(other, 1).encodeABI()), 'Governor: onlyGovernance', ); }); it('can be executed through governance', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.relay( - this.token.address, - 0, - this.token.contract.methods.transfer(other, 1).encodeABI(), - ).encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods + .relay(this.token.address, 0, this.token.contract.methods.transfer(other, 1).encodeABI()) + .encodeABI(), + }, + ], + '', + ); expect(await this.token.balanceOf(this.mock.address), 1); expect(await this.token.balanceOf(other), 0); @@ -286,12 +253,11 @@ contract('GovernorTimelockCompound', function (accounts) { expect(await this.token.balanceOf(this.mock.address), 0); expect(await this.token.balanceOf(other), 1); - expectEvent.inTransaction( - txExecute.tx, - this.token, - 'Transfer', - { from: this.mock.address, to: other, value: '1' }, - ); + expectEvent.inTransaction(txExecute.tx, this.token, 'Transfer', { + from: this.mock.address, + to: other, + value: '1', + }); }); }); @@ -301,23 +267,23 @@ contract('GovernorTimelockCompound', function (accounts) { }); it('is protected', async function () { - await expectRevert( - this.mock.updateTimelock(this.newTimelock.address), - 'Governor: onlyGovernance', - ); + await expectRevert(this.mock.updateTimelock(this.newTimelock.address), 'Governor: onlyGovernance'); }); it('can be executed through governance to', async function () { - this.helper.setProposal([ - { - target: this.timelock.address, - data: this.timelock.contract.methods.setPendingAdmin(owner).encodeABI(), - }, - { - target: this.mock.address, - data: this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.timelock.address, + data: this.timelock.contract.methods.setPendingAdmin(owner).encodeABI(), + }, + { + target: this.mock.address, + data: this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); @@ -327,11 +293,10 @@ contract('GovernorTimelockCompound', function (accounts) { await this.helper.waitForEta(); const txExecute = await this.helper.execute(); - expectEvent( - txExecute, - 'TimelockChange', - { oldTimelock: this.timelock.address, newTimelock: this.newTimelock.address }, - ); + expectEvent(txExecute, 'TimelockChange', { + oldTimelock: this.timelock.address, + newTimelock: this.newTimelock.address, + }); expect(await this.mock.timelock()).to.be.bignumber.equal(this.newTimelock.address); }); @@ -339,12 +304,15 @@ contract('GovernorTimelockCompound', function (accounts) { it('can transfer timelock to new governor', async function () { const newGovernor = await Governor.new(name, 8, 32, 0, this.timelock.address, this.token.address, 0); - this.helper.setProposal([ - { - target: this.timelock.address, - data: this.timelock.contract.methods.setPendingAdmin(newGovernor.address).encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.timelock.address, + data: this.timelock.contract.methods.setPendingAdmin(newGovernor.address).encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); @@ -354,12 +322,9 @@ contract('GovernorTimelockCompound', function (accounts) { await this.helper.waitForEta(); const txExecute = await this.helper.execute(); - await expectEvent.inTransaction( - txExecute.tx, - this.timelock, - 'NewPendingAdmin', - { newPendingAdmin: newGovernor.address }, - ); + await expectEvent.inTransaction(txExecute.tx, this.timelock, 'NewPendingAdmin', { + newPendingAdmin: newGovernor.address, + }); await newGovernor.__acceptAdmin(); expect(await this.timelock.admin()).to.be.bignumber.equal(newGovernor.address); diff --git a/test/governance/extensions/GovernorTimelockControl.test.js b/test/governance/extensions/GovernorTimelockControl.test.js index 167734e9b..2e8c75888 100644 --- a/test/governance/extensions/GovernorTimelockControl.test.js +++ b/test/governance/extensions/GovernorTimelockControl.test.js @@ -3,9 +3,7 @@ const { expect } = require('chai'); const Enums = require('../../helpers/enums'); const { GovernorHelper } = require('../../helpers/governance'); -const { - shouldSupportInterfaces, -} = require('../../utils/introspection/SupportsInterface.behavior'); +const { shouldSupportInterfaces } = require('../../utils/introspection/SupportsInterface.behavior'); const Token = artifacts.require('$ERC20Votes'); const Timelock = artifacts.require('TimelockController'); @@ -13,7 +11,7 @@ const Governor = artifacts.require('$GovernorTimelockControlMock'); const CallReceiver = artifacts.require('CallReceiverMock'); contract('GovernorTimelockControl', function (accounts) { - const [ owner, voter1, voter2, voter3, voter4, other ] = accounts; + const [owner, voter1, voter2, voter3, voter4, other] = accounts; const TIMELOCK_ADMIN_ROLE = web3.utils.soliditySha3('TIMELOCK_ADMIN_ROLE'); const PROPOSER_ROLE = web3.utils.soliditySha3('PROPOSER_ROLE'); @@ -30,19 +28,11 @@ contract('GovernorTimelockControl', function (accounts) { const value = web3.utils.toWei('1'); beforeEach(async function () { - const [ deployer ] = await web3.eth.getAccounts(); + const [deployer] = await web3.eth.getAccounts(); this.token = await Token.new(tokenName, tokenSymbol, tokenName); this.timelock = await Timelock.new(3600, [], [], deployer); - this.mock = await Governor.new( - name, - votingDelay, - votingPeriod, - 0, - this.timelock.address, - this.token.address, - 0, - ); + this.mock = await Governor.new(name, votingDelay, votingPeriod, 0, this.timelock.address, this.token.address, 0); this.receiver = await CallReceiver.new(); this.helper = new GovernorHelper(this.mock); @@ -69,13 +59,16 @@ contract('GovernorTimelockControl', function (accounts) { await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner }); // default proposal - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - value, - data: this.receiver.contract.methods.mockFunction().encodeABI(), - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + value, + data: this.receiver.contract.methods.mockFunction().encodeABI(), + }, + ], + '', + ); this.proposal.timelockid = await this.timelock.hashOperationBatch( ...this.proposal.shortProposal.slice(0, 3), '0x0', @@ -83,14 +76,9 @@ contract('GovernorTimelockControl', function (accounts) { ); }); - shouldSupportInterfaces([ - 'ERC165', - 'Governor', - 'GovernorWithParams', - 'GovernorTimelock', - ]); + shouldSupportInterfaces(['ERC165', 'Governor', 'GovernorWithParams', 'GovernorTimelock']); - it('doesn\'t accept ether transfers', async function () { + it("doesn't accept ether transfers", async function () { await expectRevert.unspecified(web3.eth.sendTransaction({ from: owner, to: this.mock.address, value: 1 })); }); @@ -197,11 +185,7 @@ contract('GovernorTimelockControl', function (accounts) { await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }); await this.helper.waitForDeadline(); - expectEvent( - await this.helper.cancel(), - 'ProposalCanceled', - { proposalId: this.proposal.id }, - ); + expectEvent(await this.helper.cancel(), 'ProposalCanceled', { proposalId: this.proposal.id }); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); await expectRevert(this.helper.queue(), 'Governor: proposal not successful'); @@ -214,11 +198,7 @@ contract('GovernorTimelockControl', function (accounts) { await this.helper.waitForDeadline(); await this.helper.queue(); - expectEvent( - await this.helper.cancel(), - 'ProposalCanceled', - { proposalId: this.proposal.id }, - ); + expectEvent(await this.helper.cancel(), 'ProposalCanceled', { proposalId: this.proposal.id }); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); await expectRevert(this.helper.execute(), 'Governor: proposal not successful'); @@ -233,11 +213,9 @@ contract('GovernorTimelockControl', function (accounts) { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Queued); - expectEvent( - await this.timelock.cancel(this.proposal.timelockid, { from: owner }), - 'Cancelled', - { id: this.proposal.timelockid }, - ); + expectEvent(await this.timelock.cancel(this.proposal.timelockid, { from: owner }), 'Cancelled', { + id: this.proposal.timelockid, + }); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); }); @@ -251,26 +229,23 @@ contract('GovernorTimelockControl', function (accounts) { it('is protected', async function () { await expectRevert( - this.mock.relay( - this.token.address, - 0, - this.token.contract.methods.transfer(other, 1).encodeABI(), - ), + this.mock.relay(this.token.address, 0, this.token.contract.methods.transfer(other, 1).encodeABI()), 'Governor: onlyGovernance', ); }); it('can be executed through governance', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.relay( - this.token.address, - 0, - this.token.contract.methods.transfer(other, 1).encodeABI(), - ).encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods + .relay(this.token.address, 0, this.token.contract.methods.transfer(other, 1).encodeABI()) + .encodeABI(), + }, + ], + '', + ); expect(await this.token.balanceOf(this.mock.address), 1); expect(await this.token.balanceOf(other), 0); @@ -286,29 +261,27 @@ contract('GovernorTimelockControl', function (accounts) { expect(await this.token.balanceOf(this.mock.address), 0); expect(await this.token.balanceOf(other), 1); - expectEvent.inTransaction( - txExecute.tx, - this.token, - 'Transfer', - { from: this.mock.address, to: other, value: '1' }, - ); + expectEvent.inTransaction(txExecute.tx, this.token, 'Transfer', { + from: this.mock.address, + to: other, + value: '1', + }); }); it('is payable and can transfer eth to EOA', async function () { const t2g = web3.utils.toBN(128); // timelock to governor const g2o = web3.utils.toBN(100); // governor to eoa (other) - this.helper.setProposal([ - { - target: this.mock.address, - value: t2g, - data: this.mock.contract.methods.relay( - other, - g2o, - '0x', - ).encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + value: t2g, + data: this.mock.contract.methods.relay(other, g2o, '0x').encodeABI(), + }, + ], + '', + ); expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(web3.utils.toBN(0)); const timelockBalance = await web3.eth.getBalance(this.timelock.address).then(web3.utils.toBN); @@ -356,28 +329,23 @@ contract('GovernorTimelockControl', function (accounts) { describe('updateTimelock', function () { beforeEach(async function () { - this.newTimelock = await Timelock.new( - 3600, - [ this.mock.address ], - [ this.mock.address ], - constants.ZERO_ADDRESS, - ); + this.newTimelock = await Timelock.new(3600, [this.mock.address], [this.mock.address], constants.ZERO_ADDRESS); }); it('is protected', async function () { - await expectRevert( - this.mock.updateTimelock(this.newTimelock.address), - 'Governor: onlyGovernance', - ); + await expectRevert(this.mock.updateTimelock(this.newTimelock.address), 'Governor: onlyGovernance'); }); it('can be executed through governance to', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); @@ -387,11 +355,10 @@ contract('GovernorTimelockControl', function (accounts) { await this.helper.waitForEta(); const txExecute = await this.helper.execute(); - expectEvent( - txExecute, - 'TimelockChange', - { oldTimelock: this.timelock.address, newTimelock: this.newTimelock.address }, - ); + expectEvent(txExecute, 'TimelockChange', { + oldTimelock: this.timelock.address, + newTimelock: this.newTimelock.address, + }); expect(await this.mock.timelock()).to.be.bignumber.equal(this.newTimelock.address); }); @@ -399,12 +366,15 @@ contract('GovernorTimelockControl', function (accounts) { }); it('clear queue of pending governor calls', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.nonGovernanceFunction().encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods.nonGovernanceFunction().encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); diff --git a/test/governance/extensions/GovernorVotesQuorumFraction.test.js b/test/governance/extensions/GovernorVotesQuorumFraction.test.js index 763f03068..84d36f926 100644 --- a/test/governance/extensions/GovernorVotesQuorumFraction.test.js +++ b/test/governance/extensions/GovernorVotesQuorumFraction.test.js @@ -8,7 +8,7 @@ const Governor = artifacts.require('$GovernorMock'); const CallReceiver = artifacts.require('CallReceiverMock'); contract('GovernorVotesQuorumFraction', function (accounts) { - const [ owner, voter1, voter2, voter3, voter4 ] = accounts; + const [owner, voter1, voter2, voter3, voter4] = accounts; const name = 'OZ-Governor'; // const version = '1'; @@ -24,14 +24,7 @@ contract('GovernorVotesQuorumFraction', function (accounts) { beforeEach(async function () { this.owner = owner; this.token = await Token.new(tokenName, tokenSymbol, tokenName); - this.mock = await Governor.new( - name, - votingDelay, - votingPeriod, - 0, - this.token.address, - ratio, - ); + this.mock = await Governor.new(name, votingDelay, votingPeriod, 0, this.token.address, ratio); this.receiver = await CallReceiver.new(); this.helper = new GovernorHelper(this.mock); @@ -45,13 +38,16 @@ contract('GovernorVotesQuorumFraction', function (accounts) { await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner }); // default proposal - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - value, - data: this.receiver.contract.methods.mockFunction().encodeABI(), - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + value, + data: this.receiver.contract.methods.mockFunction().encodeABI(), + }, + ], + '', + ); }); it('deployment check', async function () { @@ -62,8 +58,9 @@ contract('GovernorVotesQuorumFraction', function (accounts) { expect(await this.mock.quorum(0)).to.be.bignumber.equal('0'); expect(await this.mock.quorumNumerator()).to.be.bignumber.equal(ratio); expect(await this.mock.quorumDenominator()).to.be.bignumber.equal('100'); - expect(await time.latestBlock().then(blockNumber => this.mock.quorum(blockNumber.subn(1)))) - .to.be.bignumber.equal(tokenSupply.mul(ratio).divn(100)); + expect(await time.latestBlock().then(blockNumber => this.mock.quorum(blockNumber.subn(1)))).to.be.bignumber.equal( + tokenSupply.mul(ratio).divn(100), + ); }); it('quroum reached', async function () { @@ -84,61 +81,62 @@ contract('GovernorVotesQuorumFraction', function (accounts) { describe('onlyGovernance updates', function () { it('updateQuorumNumerator is protected', async function () { - await expectRevert( - this.mock.updateQuorumNumerator(newRatio), - 'Governor: onlyGovernance', - ); + await expectRevert(this.mock.updateQuorumNumerator(newRatio), 'Governor: onlyGovernance'); }); it('can updateQuorumNumerator through governance', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.updateQuorumNumerator(newRatio).encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods.updateQuorumNumerator(newRatio).encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }); await this.helper.waitForDeadline(); - expectEvent( - await this.helper.execute(), - 'QuorumNumeratorUpdated', - { oldQuorumNumerator: ratio, newQuorumNumerator: newRatio }, - ); + expectEvent(await this.helper.execute(), 'QuorumNumeratorUpdated', { + oldQuorumNumerator: ratio, + newQuorumNumerator: newRatio, + }); expect(await this.mock.quorumNumerator()).to.be.bignumber.equal(newRatio); expect(await this.mock.quorumDenominator()).to.be.bignumber.equal('100'); // it takes one block for the new quorum to take effect - expect(await time.latestBlock().then(blockNumber => this.mock.quorum(blockNumber.subn(1)))) - .to.be.bignumber.equal(tokenSupply.mul(ratio).divn(100)); + expect(await time.latestBlock().then(blockNumber => this.mock.quorum(blockNumber.subn(1)))).to.be.bignumber.equal( + tokenSupply.mul(ratio).divn(100), + ); await time.advanceBlock(); - expect(await time.latestBlock().then(blockNumber => this.mock.quorum(blockNumber.subn(1)))) - .to.be.bignumber.equal(tokenSupply.mul(newRatio).divn(100)); + expect(await time.latestBlock().then(blockNumber => this.mock.quorum(blockNumber.subn(1)))).to.be.bignumber.equal( + tokenSupply.mul(newRatio).divn(100), + ); }); it('cannot updateQuorumNumerator over the maximum', async function () { - this.helper.setProposal([ - { - target: this.mock.address, - data: this.mock.contract.methods.updateQuorumNumerator('101').encodeABI(), - }, - ], ''); + this.helper.setProposal( + [ + { + target: this.mock.address, + data: this.mock.contract.methods.updateQuorumNumerator('101').encodeABI(), + }, + ], + '', + ); await this.helper.propose(); await this.helper.waitForSnapshot(); await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }); await this.helper.waitForDeadline(); - await expectRevert( - this.helper.execute(), - 'GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator', - ); + await expectRevert(this.helper.execute(), 'GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator'); }); }); }); diff --git a/test/governance/extensions/GovernorWithParams.test.js b/test/governance/extensions/GovernorWithParams.test.js index 981fe0715..26e948544 100644 --- a/test/governance/extensions/GovernorWithParams.test.js +++ b/test/governance/extensions/GovernorWithParams.test.js @@ -16,13 +16,10 @@ const rawParams = { strParam: 'These are my params', }; -const encodedParams = web3.eth.abi.encodeParameters( - [ 'uint256', 'string' ], - Object.values(rawParams), -); +const encodedParams = web3.eth.abi.encodeParameters(['uint256', 'string'], Object.values(rawParams)); contract('GovernorWithParams', function (accounts) { - const [ owner, proposer, voter1, voter2, voter3, voter4 ] = accounts; + const [owner, proposer, voter1, voter2, voter3, voter4] = accounts; const name = 'OZ-Governor'; const version = '1'; @@ -50,13 +47,16 @@ contract('GovernorWithParams', function (accounts) { await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner }); // default proposal - this.proposal = this.helper.setProposal([ - { - target: this.receiver.address, - value, - data: this.receiver.contract.methods.mockFunction().encodeABI(), - }, - ], ''); + this.proposal = this.helper.setProposal( + [ + { + target: this.receiver.address, + value, + data: this.receiver.contract.methods.mockFunction().encodeABI(), + }, + ], + '', + ); }); it('deployment check', async function () { @@ -89,11 +89,14 @@ contract('GovernorWithParams', function (accounts) { const weight = new BN(web3.utils.toWei('7')).sub(rawParams.uintParam); - const tx = await this.helper.vote({ - support: Enums.VoteType.For, - reason: 'no particular reason', - params: encodedParams, - }, { from: voter2 }); + const tx = await this.helper.vote( + { + support: Enums.VoteType.For, + reason: 'no particular reason', + params: encodedParams, + }, + { from: voter2 }, + ); expectEvent(tx, 'CountParams', { ...rawParams }); expectEvent(tx, 'VoteCastWithParams', { @@ -113,10 +116,9 @@ contract('GovernorWithParams', function (accounts) { const voterBySig = Wallet.generate(); const voterBySigAddress = web3.utils.toChecksumAddress(voterBySig.getAddressString()); - const signature = async (message) => { - return fromRpcSig(ethSigUtil.signTypedMessage( - voterBySig.getPrivateKey(), - { + const signature = async message => { + return fromRpcSig( + ethSigUtil.signTypedMessage(voterBySig.getPrivateKey(), { data: { types: { EIP712Domain, @@ -131,8 +133,8 @@ contract('GovernorWithParams', function (accounts) { primaryType: 'ExtendedBallot', message, }, - }, - )); + }), + ); }; await this.token.delegate(voterBySigAddress, { from: voter2 }); diff --git a/test/governance/utils/Votes.behavior.js b/test/governance/utils/Votes.behavior.js index fc3af64dd..5062a9c97 100644 --- a/test/governance/utils/Votes.behavior.js +++ b/test/governance/utils/Votes.behavior.js @@ -16,16 +16,14 @@ const Delegation = [ const version = '1'; -function shouldBehaveLikeVotes () { +function shouldBehaveLikeVotes() { describe('run votes workflow', function () { it('initial nonce is 0', async function () { expect(await this.votes.nonces(this.account1)).to.be.bignumber.equal('0'); }); it('domain separator', async function () { - expect( - await this.votes.DOMAIN_SEPARATOR(), - ).to.equal( + expect(await this.votes.DOMAIN_SEPARATOR()).to.equal( await domainSeparator({ name: this.name, version, @@ -54,14 +52,16 @@ function shouldBehaveLikeVotes () { }); it('accept signed delegation', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.votes.address, this.name, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.votes.address, this.name, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); expect(await this.votes.delegates(delegatorAddress)).to.be.equal(ZERO_ADDRESS); @@ -86,14 +86,16 @@ function shouldBehaveLikeVotes () { }); it('rejects reused signature', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.votes.address, this.name, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.votes.address, this.name, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); await this.votes.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); @@ -104,14 +106,16 @@ function shouldBehaveLikeVotes () { }); it('rejects bad delegatee', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.votes.address, this.name, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.votes.address, this.name, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); const receipt = await this.votes.delegateBySig(this.account1Delegatee, nonce, MAX_UINT256, v, r, s); const { args } = receipt.logs.find(({ event }) => event === 'DelegateChanged'); @@ -121,14 +125,16 @@ function shouldBehaveLikeVotes () { }); it('rejects bad nonce', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.votes.address, this.name, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.votes.address, this.name, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); await expectRevert( this.votes.delegateBySig(delegatorAddress, nonce + 1, MAX_UINT256, v, r, s), 'Votes: invalid nonce', @@ -137,14 +143,16 @@ function shouldBehaveLikeVotes () { it('rejects expired permit', async function () { const expiry = (await time.latest()) - time.duration.weeks(1); - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.votes.address, this.name, { - delegatee: delegatorAddress, - nonce, - expiry, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.votes.address, this.name, { + delegatee: delegatorAddress, + nonce, + expiry, + }), + ), + ); await expectRevert( this.votes.delegateBySig(delegatorAddress, nonce, expiry, v, r, s), @@ -239,10 +247,7 @@ function shouldBehaveLikeVotes () { }); it('reverts if block number >= current block', async function () { - await expectRevert( - this.votes.getPastTotalSupply(5e10), - 'block not yet mined', - ); + await expectRevert(this.votes.getPastTotalSupply(5e10), 'block not yet mined'); }); it('returns 0 if there are no checkpoints', async function () { @@ -311,10 +316,7 @@ function shouldBehaveLikeVotes () { describe('getPastVotes', function () { it('reverts if block number >= current block', async function () { - await expectRevert( - this.votes.getPastVotes(this.account2, 5e10), - 'block not yet mined', - ); + await expectRevert(this.votes.getPastVotes(this.account2, 5e10), 'block not yet mined'); }); it('returns 0 if there are no checkpoints', async function () { diff --git a/test/governance/utils/Votes.test.js b/test/governance/utils/Votes.test.js index e9b50b0a3..7cf998b2d 100644 --- a/test/governance/utils/Votes.test.js +++ b/test/governance/utils/Votes.test.js @@ -4,14 +4,12 @@ const { expect } = require('chai'); const { getChainId } = require('../../helpers/chainid'); -const { - shouldBehaveLikeVotes, -} = require('./Votes.behavior'); +const { shouldBehaveLikeVotes } = require('./Votes.behavior'); const Votes = artifacts.require('$VotesMock'); contract('Votes', function (accounts) { - const [ account1, account2, account3 ] = accounts; + const [account1, account2, account3] = accounts; beforeEach(async function () { this.name = 'My Vote'; this.votes = await Votes.new(this.name, '1'); @@ -29,10 +27,7 @@ contract('Votes', function (accounts) { }); it('reverts if block number >= current block', async function () { - await expectRevert( - this.votes.getPastTotalSupply(this.tx3.receipt.blockNumber + 1), - 'Votes: block not yet mined', - ); + await expectRevert(this.votes.getPastTotalSupply(this.tx3.receipt.blockNumber + 1), 'Votes: block not yet mined'); }); it('delegates', async function () { diff --git a/test/helpers/chainid.js b/test/helpers/chainid.js index f67b91bda..58757eb80 100644 --- a/test/helpers/chainid.js +++ b/test/helpers/chainid.js @@ -1,6 +1,6 @@ const hre = require('hardhat'); -async function getChainId () { +async function getChainId() { const chainIdHex = await hre.network.provider.send('eth_chainId', []); return new hre.web3.utils.BN(chainIdHex, 'hex'); } diff --git a/test/helpers/create2.js b/test/helpers/create2.js index 3e57764c8..afe07dae3 100644 --- a/test/helpers/create2.js +++ b/test/helpers/create2.js @@ -1,10 +1,9 @@ -function computeCreate2Address (saltHex, bytecode, deployer) { - return web3.utils.toChecksumAddress(`0x${web3.utils.sha3(`0x${[ - 'ff', - deployer, - saltHex, - web3.utils.soliditySha3(bytecode), - ].map(x => x.replace(/0x/, '')).join('')}`).slice(-40)}`); +function computeCreate2Address(saltHex, bytecode, deployer) { + return web3.utils.toChecksumAddress( + `0x${web3.utils + .sha3(`0x${['ff', deployer, saltHex, web3.utils.soliditySha3(bytecode)].map(x => x.replace(/0x/, '')).join('')}`) + .slice(-40)}`, + ); } module.exports = { diff --git a/test/helpers/crosschain.js b/test/helpers/crosschain.js index d4d25d1a1..9e6ff9610 100644 --- a/test/helpers/crosschain.js +++ b/test/helpers/crosschain.js @@ -7,54 +7,52 @@ const BridgeOptimismMock = artifacts.require('BridgeOptimismMock'); const BridgePolygonChildMock = artifacts.require('BridgePolygonChildMock'); class BridgeHelper { - static async deploy (type) { + static async deploy(type) { return new BridgeHelper(await deployBridge(type)); } - constructor (bridge) { + constructor(bridge) { this.bridge = bridge; this.address = bridge.address; } - call (from, target, selector = undefined, args = []) { + call(from, target, selector = undefined, args = []) { return this.bridge.relayAs( target.address || target, - selector - ? target.contract.methods[selector](...args).encodeABI() - : '0x', + selector ? target.contract.methods[selector](...args).encodeABI() : '0x', from, ); } } -async function deployBridge (type = 'Arbitrum-L2') { +async function deployBridge(type = 'Arbitrum-L2') { switch (type) { - case 'AMB': - return BridgeAMBMock.new(); + case 'AMB': + return BridgeAMBMock.new(); - case 'Arbitrum-L1': - return BridgeArbitrumL1Mock.new(); + case 'Arbitrum-L1': + return BridgeArbitrumL1Mock.new(); - case 'Arbitrum-L2': { - const instance = await BridgeArbitrumL2Mock.new(); - const code = await web3.eth.getCode(instance.address); - await promisify(web3.currentProvider.send.bind(web3.currentProvider))({ - jsonrpc: '2.0', - method: 'hardhat_setCode', - params: [ '0x0000000000000000000000000000000000000064', code ], - id: new Date().getTime(), - }); - return BridgeArbitrumL2Mock.at('0x0000000000000000000000000000000000000064'); - } + case 'Arbitrum-L2': { + const instance = await BridgeArbitrumL2Mock.new(); + const code = await web3.eth.getCode(instance.address); + await promisify(web3.currentProvider.send.bind(web3.currentProvider))({ + jsonrpc: '2.0', + method: 'hardhat_setCode', + params: ['0x0000000000000000000000000000000000000064', code], + id: new Date().getTime(), + }); + return BridgeArbitrumL2Mock.at('0x0000000000000000000000000000000000000064'); + } - case 'Optimism': - return BridgeOptimismMock.new(); + case 'Optimism': + return BridgeOptimismMock.new(); - case 'Polygon-Child': - return BridgePolygonChildMock.new(); + case 'Polygon-Child': + return BridgePolygonChildMock.new(); - default: - throw new Error(`CrossChain: ${type} is not supported`); + default: + throw new Error(`CrossChain: ${type} is not supported`); } } diff --git a/test/helpers/customError.js b/test/helpers/customError.js index 8fea43426..3cfcd7277 100644 --- a/test/helpers/customError.js +++ b/test/helpers/customError.js @@ -3,10 +3,10 @@ const { config } = require('hardhat'); const optimizationsEnabled = config.solidity.compilers.some(c => c.settings.optimizer.enabled); /** Revert handler that supports custom errors. */ -async function expectRevertCustomError (promise, reason) { +async function expectRevertCustomError(promise, reason) { try { await promise; - expect.fail('Expected promise to throw but it didn\'t'); + expect.fail("Expected promise to throw but it didn't"); } catch (revert) { if (reason) { if (optimizationsEnabled) { @@ -17,7 +17,7 @@ async function expectRevertCustomError (promise, reason) { } } } -}; +} module.exports = { expectRevertCustomError, diff --git a/test/helpers/eip712.js b/test/helpers/eip712.js index 26e2218bb..9851df662 100644 --- a/test/helpers/eip712.js +++ b/test/helpers/eip712.js @@ -16,15 +16,15 @@ const Permit = [ { name: 'deadline', type: 'uint256' }, ]; -function bufferToHexString (buffer) { +function bufferToHexString(buffer) { return '0x' + buffer.toString('hex'); } -function hexStringToBuffer (hexstr) { +function hexStringToBuffer(hexstr) { return Buffer.from(hexstr.replace(/^0x/, ''), 'hex'); } -async function domainSeparator ({ name, version, chainId, verifyingContract }) { +async function domainSeparator({ name, version, chainId, verifyingContract }) { return bufferToHexString( ethSigUtil.TypedDataUtils.hashStruct( 'EIP712Domain', @@ -34,12 +34,10 @@ async function domainSeparator ({ name, version, chainId, verifyingContract }) { ); } -async function hashTypedData (domain, structHash) { - return domainSeparator(domain).then(separator => bufferToHexString(keccak256(Buffer.concat([ - '0x1901', - separator, - structHash, - ].map(str => hexStringToBuffer(str)))))); +async function hashTypedData(domain, structHash) { + return domainSeparator(domain).then(separator => + bufferToHexString(keccak256(Buffer.concat(['0x1901', separator, structHash].map(str => hexStringToBuffer(str))))), + ); } module.exports = { diff --git a/test/helpers/enums.js b/test/helpers/enums.js index 26825de33..ced6c3858 100644 --- a/test/helpers/enums.js +++ b/test/helpers/enums.js @@ -1,29 +1,12 @@ const { BN } = require('@openzeppelin/test-helpers'); -function Enum (...options) { - return Object.fromEntries(options.map((key, i) => [ key, new BN(i) ])); +function Enum(...options) { + return Object.fromEntries(options.map((key, i) => [key, new BN(i)])); } module.exports = { Enum, - ProposalState: Enum( - 'Pending', - 'Active', - 'Canceled', - 'Defeated', - 'Succeeded', - 'Queued', - 'Expired', - 'Executed', - ), - VoteType: Enum( - 'Against', - 'For', - 'Abstain', - ), - Rounding: Enum( - 'Down', - 'Up', - 'Zero', - ), + ProposalState: Enum('Pending', 'Active', 'Canceled', 'Defeated', 'Succeeded', 'Queued', 'Expired', 'Executed'), + VoteType: Enum('Against', 'For', 'Abstain'), + Rounding: Enum('Down', 'Up', 'Zero'), }; diff --git a/test/helpers/erc1967.js b/test/helpers/erc1967.js index aab0e2288..9abbcc8b9 100644 --- a/test/helpers/erc1967.js +++ b/test/helpers/erc1967.js @@ -2,11 +2,11 @@ const ImplementationLabel = 'eip1967.proxy.implementation'; const AdminLabel = 'eip1967.proxy.admin'; const BeaconLabel = 'eip1967.proxy.beacon'; -function labelToSlot (label) { +function labelToSlot(label) { return '0x' + web3.utils.toBN(web3.utils.keccak256(label)).subn(1).toString(16); } -function getSlot (address, slot) { +function getSlot(address, slot) { return web3.eth.getStorageAt( web3.utils.isAddress(address) ? address : address.address, web3.utils.isHex(slot) ? slot : labelToSlot(slot), diff --git a/test/helpers/governance.js b/test/helpers/governance.js index 66a479b52..ff341aa12 100644 --- a/test/helpers/governance.js +++ b/test/helpers/governance.js @@ -1,37 +1,38 @@ const { time } = require('@openzeppelin/test-helpers'); -function zip (...args) { +function zip(...args) { return Array(Math.max(...args.map(array => array.length))) .fill() .map((_, i) => args.map(array => array[i])); } -function concatHex (...args) { +function concatHex(...args) { return web3.utils.bytesToHex([].concat(...args.map(h => web3.utils.hexToBytes(h || '0x')))); } -function concatOpts (args, opts = null) { +function concatOpts(args, opts = null) { return opts ? args.concat(opts) : args; } class GovernorHelper { - constructor (governor) { + constructor(governor) { this.governor = governor; } - delegate (delegation = {}, opts = null) { + delegate(delegation = {}, opts = null) { return Promise.all([ delegation.token.delegate(delegation.to, { from: delegation.to }), - delegation.value && - delegation.token.transfer(...concatOpts([ delegation.to, delegation.value ]), opts), + delegation.value && delegation.token.transfer(...concatOpts([delegation.to, delegation.value]), opts), delegation.tokenId && - delegation.token.ownerOf(delegation.tokenId).then(owner => - delegation.token.transferFrom(...concatOpts([ owner, delegation.to, delegation.tokenId ], opts)), - ), + delegation.token + .ownerOf(delegation.tokenId) + .then(owner => + delegation.token.transferFrom(...concatOpts([owner, delegation.to, delegation.tokenId], opts)), + ), ]); } - propose (opts = null) { + propose(opts = null) { const proposal = this.currentProposal; return this.governor.methods[ @@ -41,104 +42,90 @@ class GovernorHelper { ](...concatOpts(proposal.fullProposal, opts)); } - queue (opts = null) { + queue(opts = null) { const proposal = this.currentProposal; return proposal.useCompatibilityInterface - ? this.governor.methods['queue(uint256)'](...concatOpts( - [ proposal.id ], - opts, - )) - : this.governor.methods['queue(address[],uint256[],bytes[],bytes32)'](...concatOpts( - proposal.shortProposal, - opts, - )); + ? this.governor.methods['queue(uint256)'](...concatOpts([proposal.id], opts)) + : this.governor.methods['queue(address[],uint256[],bytes[],bytes32)']( + ...concatOpts(proposal.shortProposal, opts), + ); } - execute (opts = null) { + execute(opts = null) { const proposal = this.currentProposal; return proposal.useCompatibilityInterface - ? this.governor.methods['execute(uint256)'](...concatOpts( - [ proposal.id ], - opts, - )) - : this.governor.methods['execute(address[],uint256[],bytes[],bytes32)'](...concatOpts( - proposal.shortProposal, - opts, - )); + ? this.governor.methods['execute(uint256)'](...concatOpts([proposal.id], opts)) + : this.governor.methods['execute(address[],uint256[],bytes[],bytes32)']( + ...concatOpts(proposal.shortProposal, opts), + ); } - cancel (opts = null) { + cancel(opts = null) { const proposal = this.currentProposal; return proposal.useCompatibilityInterface - ? this.governor.methods['cancel(uint256)'](...concatOpts( - [ proposal.id ], - opts, - )) - : this.governor.methods['$_cancel(address[],uint256[],bytes[],bytes32)'](...concatOpts( - proposal.shortProposal, - opts, - )); + ? this.governor.methods['cancel(uint256)'](...concatOpts([proposal.id], opts)) + : this.governor.methods['$_cancel(address[],uint256[],bytes[],bytes32)']( + ...concatOpts(proposal.shortProposal, opts), + ); } - vote (vote = {}, opts = null) { + vote(vote = {}, opts = null) { const proposal = this.currentProposal; return vote.signature - // if signature, and either params or reason → - ? vote.params || vote.reason - ? vote.signature({ - proposalId: proposal.id, - support: vote.support, - reason: vote.reason || '', - params: vote.params || '', - }).then(({ v, r, s }) => this.governor.castVoteWithReasonAndParamsBySig(...concatOpts( - [ proposal.id, vote.support, vote.reason || '', vote.params || '', v, r, s ], - opts, - ))) - : vote.signature({ - proposalId: proposal.id, - support: vote.support, - }).then(({ v, r, s }) => this.governor.castVoteBySig(...concatOpts( - [ proposal.id, vote.support, v, r, s ], - opts, - ))) + ? // if signature, and either params or reason → + vote.params || vote.reason + ? vote + .signature({ + proposalId: proposal.id, + support: vote.support, + reason: vote.reason || '', + params: vote.params || '', + }) + .then(({ v, r, s }) => + this.governor.castVoteWithReasonAndParamsBySig( + ...concatOpts([proposal.id, vote.support, vote.reason || '', vote.params || '', v, r, s], opts), + ), + ) + : vote + .signature({ + proposalId: proposal.id, + support: vote.support, + }) + .then(({ v, r, s }) => + this.governor.castVoteBySig(...concatOpts([proposal.id, vote.support, v, r, s], opts)), + ) : vote.params - // otherwise if params - ? this.governor.castVoteWithReasonAndParams(...concatOpts( - [ proposal.id, vote.support, vote.reason || '', vote.params ], - opts, - )) - : vote.reason - // otherwise if reason - ? this.governor.castVoteWithReason(...concatOpts( - [ proposal.id, vote.support, vote.reason ], - opts, - )) - : this.governor.castVote(...concatOpts( - [ proposal.id, vote.support ], - opts, - )); + ? // otherwise if params + this.governor.castVoteWithReasonAndParams( + ...concatOpts([proposal.id, vote.support, vote.reason || '', vote.params], opts), + ) + : vote.reason + ? // otherwise if reason + this.governor.castVoteWithReason(...concatOpts([proposal.id, vote.support, vote.reason], opts)) + : this.governor.castVote(...concatOpts([proposal.id, vote.support], opts)); } - waitForSnapshot (offset = 0) { + waitForSnapshot(offset = 0) { const proposal = this.currentProposal; - return this.governor.proposalSnapshot(proposal.id) + return this.governor + .proposalSnapshot(proposal.id) .then(blockNumber => time.advanceBlockTo(blockNumber.addn(offset))); } - waitForDeadline (offset = 0) { + waitForDeadline(offset = 0) { const proposal = this.currentProposal; - return this.governor.proposalDeadline(proposal.id) + return this.governor + .proposalDeadline(proposal.id) .then(blockNumber => time.advanceBlockTo(blockNumber.addn(offset))); } - waitForEta (offset = 0) { + waitForEta(offset = 0) { const proposal = this.currentProposal; - return this.governor.proposalEta(proposal.id) - .then(timestamp => time.increaseTo(timestamp.addn(offset))); + return this.governor.proposalEta(proposal.id).then(timestamp => time.increaseTo(timestamp.addn(offset))); } /** @@ -146,7 +133,7 @@ class GovernorHelper { * 1) an array of objects [{ target, value, data, signature? }] * 2) an object of arrays { targets: [], values: [], data: [], signatures?: [] } */ - setProposal (actions, description) { + setProposal(actions, description) { let targets, values, signatures, data, useCompatibilityInterface; if (Array.isArray(actions)) { @@ -160,33 +147,25 @@ class GovernorHelper { ({ targets, values, signatures = [], data } = actions); } - const fulldata = zip(signatures.map(s => s && web3.eth.abi.encodeFunctionSignature(s)), data) - .map(hexs => concatHex(...hexs)); + const fulldata = zip( + signatures.map(s => s && web3.eth.abi.encodeFunctionSignature(s)), + data, + ).map(hexs => concatHex(...hexs)); const descriptionHash = web3.utils.keccak256(description); // condensed version for queueing end executing - const shortProposal = [ - targets, - values, - fulldata, - descriptionHash, - ]; + const shortProposal = [targets, values, fulldata, descriptionHash]; // full version for proposing - const fullProposal = [ - targets, - values, - ...(useCompatibilityInterface ? [ signatures ] : []), - data, - description, - ]; + const fullProposal = [targets, values, ...(useCompatibilityInterface ? [signatures] : []), data, description]; // proposal id - const id = web3.utils.toBN(web3.utils.keccak256(web3.eth.abi.encodeParameters( - [ 'address[]', 'uint256[]', 'bytes[]', 'bytes32' ], - shortProposal, - ))); + const id = web3.utils.toBN( + web3.utils.keccak256( + web3.eth.abi.encodeParameters(['address[]', 'uint256[]', 'bytes[]', 'bytes32'], shortProposal), + ), + ); this.currentProposal = { id, diff --git a/test/helpers/sign.js b/test/helpers/sign.js index 4c14d1f1d..417ef591d 100644 --- a/test/helpers/sign.js +++ b/test/helpers/sign.js @@ -1,4 +1,4 @@ -function toEthSignedMessageHash (messageHex) { +function toEthSignedMessageHash(messageHex) { const messageBuffer = Buffer.from(messageHex.substring(2), 'hex'); const prefix = Buffer.from(`\u0019Ethereum Signed Message:\n${messageBuffer.length}`); return web3.utils.sha3(Buffer.concat([prefix, messageBuffer])); @@ -13,33 +13,33 @@ function toEthSignedMessageHash (messageHex) { * @param methodName string * @param methodArgs any[] */ -const getSignFor = (contract, signer) => (redeemer, methodName, methodArgs = []) => { - const parts = [ - contract.address, - redeemer, - ]; +const getSignFor = + (contract, signer) => + (redeemer, methodName, methodArgs = []) => { + const parts = [contract.address, redeemer]; - const REAL_SIGNATURE_SIZE = 2 * 65; // 65 bytes in hexadecimal string length - const PADDED_SIGNATURE_SIZE = 2 * 96; // 96 bytes in hexadecimal string length - const DUMMY_SIGNATURE = `0x${web3.utils.padLeft('', REAL_SIGNATURE_SIZE)}`; + const REAL_SIGNATURE_SIZE = 2 * 65; // 65 bytes in hexadecimal string length + const PADDED_SIGNATURE_SIZE = 2 * 96; // 96 bytes in hexadecimal string length + const DUMMY_SIGNATURE = `0x${web3.utils.padLeft('', REAL_SIGNATURE_SIZE)}`; - // if we have a method, add it to the parts that we're signing - if (methodName) { - if (methodArgs.length > 0) { - parts.push( - contract.contract.methods[methodName](...methodArgs.concat([DUMMY_SIGNATURE])).encodeABI() - .slice(0, -1 * PADDED_SIGNATURE_SIZE), - ); - } else { - const abi = contract.abi.find(abi => abi.name === methodName); - parts.push(abi.signature); + // if we have a method, add it to the parts that we're signing + if (methodName) { + if (methodArgs.length > 0) { + parts.push( + contract.contract.methods[methodName](...methodArgs.concat([DUMMY_SIGNATURE])) + .encodeABI() + .slice(0, -1 * PADDED_SIGNATURE_SIZE), + ); + } else { + const abi = contract.abi.find(abi => abi.name === methodName); + parts.push(abi.signature); + } } - } - // return the signature of the "Ethereum Signed Message" hash of the hash of `parts` - const messageHex = web3.utils.soliditySha3(...parts); - return web3.eth.sign(messageHex, signer); -}; + // return the signature of the "Ethereum Signed Message" hash of the hash of `parts` + const messageHex = web3.utils.soliditySha3(...parts); + return web3.eth.sign(messageHex, signer); + }; module.exports = { toEthSignedMessageHash, diff --git a/test/helpers/txpool.js b/test/helpers/txpool.js index 895246b72..ecdba5462 100644 --- a/test/helpers/txpool.js +++ b/test/helpers/txpool.js @@ -3,20 +3,18 @@ const { promisify } = require('util'); const queue = promisify(setImmediate); -async function countPendingTransactions () { - return parseInt( - await network.provider.send('eth_getBlockTransactionCountByNumber', ['pending']), - ); +async function countPendingTransactions() { + return parseInt(await network.provider.send('eth_getBlockTransactionCountByNumber', ['pending'])); } -async function batchInBlock (txs) { +async function batchInBlock(txs) { try { // disable auto-mining await network.provider.send('evm_setAutomine', [false]); // send all transactions const promises = txs.map(fn => fn()); // wait for node to have all pending transactions - while (txs.length > await countPendingTransactions()) { + while (txs.length > (await countPendingTransactions())) { await queue(); } // mine one block diff --git a/test/metatx/MinimalForwarder.test.js b/test/metatx/MinimalForwarder.test.js index 15778505e..24de1719d 100644 --- a/test/metatx/MinimalForwarder.test.js +++ b/test/metatx/MinimalForwarder.test.js @@ -47,24 +47,21 @@ contract('MinimalForwarder', function (accounts) { nonce: Number(await this.forwarder.getNonce(this.sender)), data: '0x', }; - this.sign = () => ethSigUtil.signTypedMessage( - this.wallet.getPrivateKey(), - { + this.sign = () => + ethSigUtil.signTypedMessage(this.wallet.getPrivateKey(), { data: { types: this.types, domain: this.domain, primaryType: 'ForwardRequest', message: this.req, }, - }, - ); + }); }); context('verify', function () { context('valid signature', function () { beforeEach(async function () { - expect(await this.forwarder.getNonce(this.req.from)) - .to.be.bignumber.equal(web3.utils.toBN(this.req.nonce)); + expect(await this.forwarder.getNonce(this.req.from)).to.be.bignumber.equal(web3.utils.toBN(this.req.nonce)); }); it('success', async function () { @@ -72,37 +69,34 @@ contract('MinimalForwarder', function (accounts) { }); afterEach(async function () { - expect(await this.forwarder.getNonce(this.req.from)) - .to.be.bignumber.equal(web3.utils.toBN(this.req.nonce)); + expect(await this.forwarder.getNonce(this.req.from)).to.be.bignumber.equal(web3.utils.toBN(this.req.nonce)); }); }); context('invalid signature', function () { it('tampered from', async function () { - expect(await this.forwarder.verify({ ...this.req, from: accounts[0] }, this.sign())) - .to.be.equal(false); + expect(await this.forwarder.verify({ ...this.req, from: accounts[0] }, this.sign())).to.be.equal(false); }); it('tampered to', async function () { - expect(await this.forwarder.verify({ ...this.req, to: accounts[0] }, this.sign())) - .to.be.equal(false); + expect(await this.forwarder.verify({ ...this.req, to: accounts[0] }, this.sign())).to.be.equal(false); }); it('tampered value', async function () { - expect(await this.forwarder.verify({ ...this.req, value: web3.utils.toWei('1') }, this.sign())) - .to.be.equal(false); + expect(await this.forwarder.verify({ ...this.req, value: web3.utils.toWei('1') }, this.sign())).to.be.equal( + false, + ); }); it('tampered nonce', async function () { - expect(await this.forwarder.verify({ ...this.req, nonce: this.req.nonce + 1 }, this.sign())) - .to.be.equal(false); + expect(await this.forwarder.verify({ ...this.req, nonce: this.req.nonce + 1 }, this.sign())).to.be.equal( + false, + ); }); it('tampered data', async function () { - expect(await this.forwarder.verify({ ...this.req, data: '0x1742' }, this.sign())) - .to.be.equal(false); + expect(await this.forwarder.verify({ ...this.req, data: '0x1742' }, this.sign())).to.be.equal(false); }); it('tampered signature', async function () { const tamperedsign = web3.utils.hexToBytes(this.sign()); tamperedsign[42] ^= 0xff; - expect(await this.forwarder.verify(this.req, web3.utils.bytesToHex(tamperedsign))) - .to.be.equal(false); + expect(await this.forwarder.verify(this.req, web3.utils.bytesToHex(tamperedsign))).to.be.equal(false); }); }); }); @@ -110,8 +104,7 @@ contract('MinimalForwarder', function (accounts) { context('execute', function () { context('valid signature', function () { beforeEach(async function () { - expect(await this.forwarder.getNonce(this.req.from)) - .to.be.bignumber.equal(web3.utils.toBN(this.req.nonce)); + expect(await this.forwarder.getNonce(this.req.from)).to.be.bignumber.equal(web3.utils.toBN(this.req.nonce)); }); it('success', async function () { @@ -119,8 +112,9 @@ contract('MinimalForwarder', function (accounts) { }); afterEach(async function () { - expect(await this.forwarder.getNonce(this.req.from)) - .to.be.bignumber.equal(web3.utils.toBN(this.req.nonce + 1)); + expect(await this.forwarder.getNonce(this.req.from)).to.be.bignumber.equal( + web3.utils.toBN(this.req.nonce + 1), + ); }); }); @@ -172,9 +166,7 @@ contract('MinimalForwarder', function (accounts) { this.req.data = receiver.contract.methods.mockFunctionOutOfGas().encodeABI(); this.req.gas = 1000000; - await expectRevert.assertion( - this.forwarder.execute(this.req, this.sign(), { gas: gasAvailable }), - ); + await expectRevert.assertion(this.forwarder.execute(this.req, this.sign(), { gas: gasAvailable })); const { transactions } = await web3.eth.getBlock('latest'); const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]); diff --git a/test/migrate-imports.test.js b/test/migrate-imports.test.js index 639767c25..7ec9a97ab 100644 --- a/test/migrate-imports.test.js +++ b/test/migrate-imports.test.js @@ -1,5 +1,8 @@ const path = require('path'); -const { promises: fs, constants: { F_OK } } = require('fs'); +const { + promises: fs, + constants: { F_OK }, +} = require('fs'); const { expect } = require('chai'); const { pathUpdates, updateImportPaths, getUpgradeablePath } = require('../scripts/migrate-imports.js'); diff --git a/test/proxy/Clones.behaviour.js b/test/proxy/Clones.behaviour.js index 81c5ee35f..b5fd3c51b 100644 --- a/test/proxy/Clones.behaviour.js +++ b/test/proxy/Clones.behaviour.js @@ -4,7 +4,7 @@ const { expect } = require('chai'); const DummyImplementation = artifacts.require('DummyImplementation'); -module.exports = function shouldBehaveLikeClone (createClone) { +module.exports = function shouldBehaveLikeClone(createClone) { before('deploy implementation', async function () { this.implementation = web3.utils.toChecksumAddress((await DummyImplementation.new()).address); }); @@ -27,9 +27,7 @@ module.exports = function shouldBehaveLikeClone (createClone) { describe('when not sending balance', function () { beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData) - ).address; + this.proxy = (await createClone(this.implementation, initializeData)).address; }); assertProxyInitialization({ @@ -42,9 +40,7 @@ module.exports = function shouldBehaveLikeClone (createClone) { const value = 10e5; it('reverts', async function () { - await expectRevert.unspecified( - createClone(this.implementation, initializeData, { value }), - ); + await expectRevert.unspecified(createClone(this.implementation, initializeData, { value })); }); }); }); @@ -55,9 +51,7 @@ module.exports = function shouldBehaveLikeClone (createClone) { describe('when not sending balance', function () { beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData) - ).address; + this.proxy = (await createClone(this.implementation, initializeData)).address; }); assertProxyInitialization({ @@ -70,9 +64,7 @@ module.exports = function shouldBehaveLikeClone (createClone) { const value = 10e5; beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData, { value }) - ).address; + this.proxy = (await createClone(this.implementation, initializeData, { value })).address; }); assertProxyInitialization({ @@ -86,14 +78,13 @@ module.exports = function shouldBehaveLikeClone (createClone) { describe('initialization with parameters', function () { describe('non payable', function () { const expectedInitializedValue = 10; - const initializeData = new DummyImplementation('').contract - .methods.initializeNonPayableWithValue(expectedInitializedValue).encodeABI(); + const initializeData = new DummyImplementation('').contract.methods + .initializeNonPayableWithValue(expectedInitializedValue) + .encodeABI(); describe('when not sending balance', function () { beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData) - ).address; + this.proxy = (await createClone(this.implementation, initializeData)).address; }); assertProxyInitialization({ @@ -106,23 +97,20 @@ module.exports = function shouldBehaveLikeClone (createClone) { const value = 10e5; it('reverts', async function () { - await expectRevert.unspecified( - createClone(this.implementation, initializeData, { value }), - ); + await expectRevert.unspecified(createClone(this.implementation, initializeData, { value })); }); }); }); describe('payable', function () { const expectedInitializedValue = 42; - const initializeData = new DummyImplementation('').contract - .methods.initializePayableWithValue(expectedInitializedValue).encodeABI(); + const initializeData = new DummyImplementation('').contract.methods + .initializePayableWithValue(expectedInitializedValue) + .encodeABI(); describe('when not sending balance', function () { beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData) - ).address; + this.proxy = (await createClone(this.implementation, initializeData)).address; }); assertProxyInitialization({ @@ -135,9 +123,7 @@ module.exports = function shouldBehaveLikeClone (createClone) { const value = 10e5; beforeEach('creating proxy', async function () { - this.proxy = ( - await createClone(this.implementation, initializeData, { value }) - ).address; + this.proxy = (await createClone(this.implementation, initializeData, { value })).address; }); assertProxyInitialization({ diff --git a/test/proxy/Clones.test.js b/test/proxy/Clones.test.js index 09f719cec..947b2ed95 100644 --- a/test/proxy/Clones.test.js +++ b/test/proxy/Clones.test.js @@ -7,7 +7,7 @@ const shouldBehaveLikeClone = require('./Clones.behaviour'); const Clones = artifacts.require('$Clones'); contract('Clones', function (accounts) { - const [ deployer ] = accounts; + const [deployer] = accounts; describe('clone', function () { shouldBehaveLikeClone(async (implementation, initData, opts = {}) => { @@ -34,15 +34,9 @@ contract('Clones', function (accounts) { const salt = web3.utils.randomHex(32); const factory = await Clones.new(); // deploy once - expectEvent( - await factory.$cloneDeterministic(implementation, salt), - 'return$cloneDeterministic', - ); + expectEvent(await factory.$cloneDeterministic(implementation, salt), 'return$cloneDeterministic'); // deploy twice - await expectRevert( - factory.$cloneDeterministic(implementation, salt), - 'ERC1167: create2 failed', - ); + await expectRevert(factory.$cloneDeterministic(implementation, salt), 'ERC1167: create2 failed'); }); it('address prediction', async function () { @@ -57,17 +51,11 @@ contract('Clones', function (accounts) { '5af43d82803e903d91602b57fd5bf3', ].join(''); - expect(computeCreate2Address( - salt, - creationCode, - factory.address, - )).to.be.equal(predicted); + expect(computeCreate2Address(salt, creationCode, factory.address)).to.be.equal(predicted); - expectEvent( - await factory.$cloneDeterministic(implementation, salt), - 'return$cloneDeterministic', - { instance: predicted }, - ); + expectEvent(await factory.$cloneDeterministic(implementation, salt), 'return$cloneDeterministic', { + instance: predicted, + }); }); }); }); diff --git a/test/proxy/Proxy.behaviour.js b/test/proxy/Proxy.behaviour.js index 435792f23..0867b93c9 100644 --- a/test/proxy/Proxy.behaviour.js +++ b/test/proxy/Proxy.behaviour.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const DummyImplementation = artifacts.require('DummyImplementation'); -module.exports = function shouldBehaveLikeProxy (createProxy, proxyAdminAddress, proxyCreator) { +module.exports = function shouldBehaveLikeProxy(createProxy, proxyAdminAddress, proxyCreator) { it('cannot be initialized with a non-contract address', async function () { const nonContractAddress = proxyCreator; const initializeData = Buffer.from(''); @@ -141,8 +141,9 @@ module.exports = function shouldBehaveLikeProxy (createProxy, proxyAdminAddress, describe('initialization with parameters', function () { describe('non payable', function () { const expectedInitializedValue = 10; - const initializeData = new DummyImplementation('').contract - .methods.initializeNonPayableWithValue(expectedInitializedValue).encodeABI(); + const initializeData = new DummyImplementation('').contract.methods + .initializeNonPayableWithValue(expectedInitializedValue) + .encodeABI(); describe('when not sending balance', function () { beforeEach('creating proxy', async function () { @@ -172,8 +173,9 @@ module.exports = function shouldBehaveLikeProxy (createProxy, proxyAdminAddress, describe('payable', function () { const expectedInitializedValue = 42; - const initializeData = new DummyImplementation('').contract - .methods.initializePayableWithValue(expectedInitializedValue).encodeABI(); + const initializeData = new DummyImplementation('').contract.methods + .initializePayableWithValue(expectedInitializedValue) + .encodeABI(); describe('when not sending balance', function () { beforeEach('creating proxy', async function () { @@ -210,8 +212,7 @@ module.exports = function shouldBehaveLikeProxy (createProxy, proxyAdminAddress, }); describe('reverting initialization', function () { - const initializeData = new DummyImplementation('').contract - .methods.reverts().encodeABI(); + const initializeData = new DummyImplementation('').contract.methods.reverts().encodeABI(); it('reverts', async function () { await expectRevert( diff --git a/test/proxy/beacon/BeaconProxy.test.js b/test/proxy/beacon/BeaconProxy.test.js index 0a4a8d0cf..968f00be8 100644 --- a/test/proxy/beacon/BeaconProxy.test.js +++ b/test/proxy/beacon/BeaconProxy.test.js @@ -15,25 +15,17 @@ contract('BeaconProxy', function (accounts) { describe('bad beacon is not accepted', async function () { it('non-contract beacon', async function () { - await expectRevert( - BeaconProxy.new(anotherAccount, '0x'), - 'ERC1967: new beacon is not a contract', - ); + await expectRevert(BeaconProxy.new(anotherAccount, '0x'), 'ERC1967: new beacon is not a contract'); }); it('non-compliant beacon', async function () { const beacon = await BadBeaconNoImpl.new(); - await expectRevert.unspecified( - BeaconProxy.new(beacon.address, '0x'), - ); + await expectRevert.unspecified(BeaconProxy.new(beacon.address, '0x')); }); it('non-contract implementation', async function () { const beacon = await BadBeaconNotContract.new(); - await expectRevert( - BeaconProxy.new(beacon.address, '0x'), - 'ERC1967: beacon implementation is not a contract', - ); + await expectRevert(BeaconProxy.new(beacon.address, '0x'), 'ERC1967: beacon implementation is not a contract'); }); }); @@ -69,18 +61,14 @@ contract('BeaconProxy', function (accounts) { it('non-payable initialization', async function () { const value = '55'; - const data = this.implementationV0.contract.methods - .initializeNonPayableWithValue(value) - .encodeABI(); + const data = this.implementationV0.contract.methods.initializeNonPayableWithValue(value).encodeABI(); this.proxy = await BeaconProxy.new(this.beacon.address, data); await this.assertInitialized({ value, balance: '0' }); }); it('payable initialization', async function () { const value = '55'; - const data = this.implementationV0.contract.methods - .initializePayableWithValue(value) - .encodeABI(); + const data = this.implementationV0.contract.methods.initializePayableWithValue(value).encodeABI(); const balance = '100'; this.proxy = await BeaconProxy.new(this.beacon.address, data, { value: balance }); await this.assertInitialized({ value, balance }); @@ -88,10 +76,7 @@ contract('BeaconProxy', function (accounts) { it('reverting initialization', async function () { const data = this.implementationV0.contract.methods.reverts().encodeABI(); - await expectRevert( - BeaconProxy.new(this.beacon.address, data), - 'DummyImplementation reverted', - ); + await expectRevert(BeaconProxy.new(this.beacon.address, data), 'DummyImplementation reverted'); }); }); @@ -99,9 +84,7 @@ contract('BeaconProxy', function (accounts) { const beacon = await UpgradeableBeacon.new(this.implementationV0.address); const value = '10'; - const data = this.implementationV0.contract.methods - .initializeNonPayableWithValue(value) - .encodeABI(); + const data = this.implementationV0.contract.methods.initializeNonPayableWithValue(value).encodeABI(); const proxy = await BeaconProxy.new(beacon.address, data); const dummy = new DummyImplementation(proxy.address); diff --git a/test/proxy/beacon/UpgradeableBeacon.test.js b/test/proxy/beacon/UpgradeableBeacon.test.js index 0c49906d6..d65f3e0a5 100644 --- a/test/proxy/beacon/UpgradeableBeacon.test.js +++ b/test/proxy/beacon/UpgradeableBeacon.test.js @@ -9,10 +9,7 @@ contract('UpgradeableBeacon', function (accounts) { const [owner, other] = accounts; it('cannot be created with non-contract implementation', async function () { - await expectRevert( - UpgradeableBeacon.new(accounts[0]), - 'UpgradeableBeacon: implementation is not a contract', - ); + await expectRevert(UpgradeableBeacon.new(accounts[0]), 'UpgradeableBeacon: implementation is not a contract'); }); context('once deployed', async function () { @@ -41,10 +38,7 @@ contract('UpgradeableBeacon', function (accounts) { it('cannot be upgraded by other account', async function () { const v2 = await Implementation2.new(); - await expectRevert( - this.beacon.upgradeTo(v2.address, { from: other }), - 'Ownable: caller is not the owner', - ); + await expectRevert(this.beacon.upgradeTo(v2.address, { from: other }), 'Ownable: caller is not the owner'); }); }); }); diff --git a/test/proxy/transparent/ProxyAdmin.test.js b/test/proxy/transparent/ProxyAdmin.test.js index 07adba6ad..811dc5671 100644 --- a/test/proxy/transparent/ProxyAdmin.test.js +++ b/test/proxy/transparent/ProxyAdmin.test.js @@ -90,9 +90,9 @@ contract('ProxyAdmin', function (accounts) { it('fails to upgrade', async function () { const callData = new ImplV1('').contract.methods.initializeNonPayableWithValue(1337).encodeABI(); await expectRevert( - this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, - { from: anotherAccount }, - ), + this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, { + from: anotherAccount, + }), 'caller is not the owner', ); }); @@ -103,9 +103,9 @@ contract('ProxyAdmin', function (accounts) { it('fails to upgrade', async function () { const callData = '0x12345678'; await expectRevert.unspecified( - this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, - { from: proxyAdminOwner }, - ), + this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, { + from: proxyAdminOwner, + }), ); }); }); @@ -113,9 +113,9 @@ contract('ProxyAdmin', function (accounts) { context('with valid callData', function () { it('upgrades implementation', async function () { const callData = new ImplV1('').contract.methods.initializeNonPayableWithValue(1337).encodeABI(); - await this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, - { from: proxyAdminOwner }, - ); + await this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, { + from: proxyAdminOwner, + }); const implementationAddress = await this.proxyAdmin.getProxyImplementation(this.proxy.address); expect(implementationAddress).to.be.equal(this.implementationV2.address); }); diff --git a/test/proxy/transparent/TransparentUpgradeableProxy.behaviour.js b/test/proxy/transparent/TransparentUpgradeableProxy.behaviour.js index 33fef6f41..da8f21bee 100644 --- a/test/proxy/transparent/TransparentUpgradeableProxy.behaviour.js +++ b/test/proxy/transparent/TransparentUpgradeableProxy.behaviour.js @@ -16,7 +16,7 @@ const InitializableMock = artifacts.require('InitializableMock'); const DummyImplementation = artifacts.require('DummyImplementation'); const ClashingImplementation = artifacts.require('ClashingImplementation'); -module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createProxy, accounts) { +module.exports = function shouldBehaveLikeTransparentUpgradeableProxy(createProxy, accounts) { const [proxyAdminAddress, proxyAdminOwner, anotherAccount] = accounts; before(async function () { @@ -60,12 +60,9 @@ module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createPro }); it('emits an event', async function () { - expectEvent( - await this.proxy.upgradeTo(this.implementationV1, { from }), - 'Upgraded', { - implementation: this.implementationV1, - }, - ); + expectEvent(await this.proxy.upgradeTo(this.implementationV1, { from }), 'Upgraded', { + implementation: this.implementationV1, + }); }); }); @@ -83,9 +80,7 @@ module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createPro const from = anotherAccount; it('reverts', async function () { - await expectRevert.unspecified( - this.proxy.upgradeTo(this.implementationV1, { from }), - ); + await expectRevert.unspecified(this.proxy.upgradeTo(this.implementationV1, { from })); }); }); }); @@ -178,7 +173,7 @@ module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createPro expectEvent(this.receipt, 'Upgraded', { implementation: this.behaviorV1.address }); }); - it('calls the \'initialize\' function and sends given value to the proxy', async function () { + it("calls the 'initialize' function and sends given value to the proxy", async function () { const migratable = new MigratableMockV1(this.proxyAddress); const x = await migratable.x(); @@ -194,8 +189,10 @@ module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createPro beforeEach(async function () { this.behaviorV2 = await MigratableMockV2.new(); this.balancePreviousV2 = new BN(await web3.eth.getBalance(this.proxyAddress)); - this.receipt = - await this.proxy.upgradeToAndCall(this.behaviorV2.address, v2MigrationData, { from, value }); + this.receipt = await this.proxy.upgradeToAndCall(this.behaviorV2.address, v2MigrationData, { + from, + value, + }); }); it('upgrades to the requested version and emits an event', async function () { @@ -204,7 +201,7 @@ module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createPro expectEvent(this.receipt, 'Upgraded', { implementation: this.behaviorV2.address }); }); - it('calls the \'migrate\' function and sends given value to the proxy', async function () { + it("calls the 'migrate' function and sends given value to the proxy", async function () { const migratable = new MigratableMockV2(this.proxyAddress); const x = await migratable.x(); @@ -223,8 +220,10 @@ module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createPro beforeEach(async function () { this.behaviorV3 = await MigratableMockV3.new(); this.balancePreviousV3 = new BN(await web3.eth.getBalance(this.proxyAddress)); - this.receipt = - await this.proxy.upgradeToAndCall(this.behaviorV3.address, v3MigrationData, { from, value }); + this.receipt = await this.proxy.upgradeToAndCall(this.behaviorV3.address, v3MigrationData, { + from, + value, + }); }); it('upgrades to the requested version and emits an event', async function () { @@ -233,7 +232,7 @@ module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createPro expectEvent(this.receipt, 'Upgraded', { implementation: this.behaviorV3.address }); }); - it('calls the \'migrate\' function and sends given value to the proxy', async function () { + it("calls the 'migrate' function and sends given value to the proxy", async function () { const migratable = new MigratableMockV3(this.proxyAddress); const x = await migratable.x(); @@ -256,9 +255,7 @@ module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createPro it('reverts', async function () { const behaviorV1 = await MigratableMockV1.new(); const v1MigrationData = new MigratableMockV1('').contract.methods.initialize(42).encodeABI(); - await expectRevert.unspecified( - this.proxy.upgradeToAndCall(behaviorV1.address, v1MigrationData, { from }), - ); + await expectRevert.unspecified(this.proxy.upgradeToAndCall(behaviorV1.address, v1MigrationData, { from })); }); }); }); @@ -419,9 +416,7 @@ module.exports = function shouldBehaveLikeTransparentUpgradeableProxy (createPro await proxy.upgradeTo(instance2.address, { from: proxyAdminAddress }); const data = '0x'; - await expectRevert.unspecified( - web3.eth.sendTransaction({ to: proxy.address, from: anotherAccount, data }), - ); + await expectRevert.unspecified(web3.eth.sendTransaction({ to: proxy.address, from: anotherAccount, data })); const proxyInstance2 = new Implementation2(proxy.address); const res = await proxyInstance2.getValue(); diff --git a/test/proxy/utils/UUPSUpgradeable.test.js b/test/proxy/utils/UUPSUpgradeable.test.js index 20324e67b..b0c1b3f6f 100644 --- a/test/proxy/utils/UUPSUpgradeable.test.js +++ b/test/proxy/utils/UUPSUpgradeable.test.js @@ -65,14 +65,14 @@ contract('UUPSUpgradeable', function () { it('can upgrade from legacy implementations', async function () { const legacyImpl = await UUPSUpgradeableLegacyMock.new(); - const legacyInstance = await ERC1967Proxy.new(legacyImpl.address, '0x') - .then(({ address }) => UUPSUpgradeableLegacyMock.at(address)); + const legacyInstance = await ERC1967Proxy.new(legacyImpl.address, '0x').then(({ address }) => + UUPSUpgradeableLegacyMock.at(address), + ); const receipt = await legacyInstance.upgradeTo(this.implInitial.address); - const UpgradedEvents = receipt.logs.filter(({ address, event }) => - address === legacyInstance.address && - event === 'Upgraded', + const UpgradedEvents = receipt.logs.filter( + ({ address, event }) => address === legacyInstance.address && event === 'Upgraded', ); expect(UpgradedEvents.length).to.be.equal(1); diff --git a/test/security/Pausable.test.js b/test/security/Pausable.test.js index 86701bcfd..5cca11e47 100644 --- a/test/security/Pausable.test.js +++ b/test/security/Pausable.test.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const PausableMock = artifacts.require('PausableMock'); contract('Pausable', function (accounts) { - const [ pauser ] = accounts; + const [pauser] = accounts; beforeEach(async function () { this.pausable = await PausableMock.new(); @@ -24,15 +24,13 @@ contract('Pausable', function (accounts) { }); it('cannot take drastic measure in non-pause', async function () { - await expectRevert(this.pausable.drasticMeasure(), - 'Pausable: not paused', - ); + await expectRevert(this.pausable.drasticMeasure(), 'Pausable: not paused'); expect(await this.pausable.drasticMeasureTaken()).to.equal(false); }); context('when paused', function () { beforeEach(async function () { - (this.receipt = await this.pausable.pause({ from: pauser })); + this.receipt = await this.pausable.pause({ from: pauser }); }); it('emits a Paused event', function () { @@ -60,7 +58,7 @@ contract('Pausable', function (accounts) { context('when unpaused', function () { beforeEach(async function () { - (this.receipt = await this.pausable.unpause({ from: pauser })); + this.receipt = await this.pausable.unpause({ from: pauser }); }); it('emits an Unpaused event', function () { @@ -74,9 +72,7 @@ contract('Pausable', function (accounts) { }); it('should prevent drastic measure', async function () { - await expectRevert(this.pausable.drasticMeasure(), - 'Pausable: not paused', - ); + await expectRevert(this.pausable.drasticMeasure(), 'Pausable: not paused'); }); it('reverts when re-unpausing', async function () { diff --git a/test/security/PullPayment.test.js b/test/security/PullPayment.test.js index 1552ed994..5bf72bbe6 100644 --- a/test/security/PullPayment.test.js +++ b/test/security/PullPayment.test.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const PullPaymentMock = artifacts.require('PullPaymentMock'); contract('PullPayment', function (accounts) { - const [ payer, payee1, payee2 ] = accounts; + const [payer, payee1, payee2] = accounts; const amount = ether('17'); diff --git a/test/security/ReentrancyGuard.test.js b/test/security/ReentrancyGuard.test.js index 172a29b1f..1a80bc860 100644 --- a/test/security/ReentrancyGuard.test.js +++ b/test/security/ReentrancyGuard.test.js @@ -19,8 +19,7 @@ contract('ReentrancyGuard', function () { it('does not allow remote callback', async function () { const attacker = await ReentrancyAttack.new(); - await expectRevert( - this.reentrancyMock.countAndCall(attacker.address), 'ReentrancyAttack: failed call'); + await expectRevert(this.reentrancyMock.countAndCall(attacker.address), 'ReentrancyAttack: failed call'); }); it('_reentrancyGuardEntered should be true when guarded', async function () { @@ -35,14 +34,10 @@ contract('ReentrancyGuard', function () { // I put them here as documentation, and to monitor any changes // in the side-effects. it('does not allow local recursion', async function () { - await expectRevert( - this.reentrancyMock.countLocalRecursive(10), 'ReentrancyGuard: reentrant call', - ); + await expectRevert(this.reentrancyMock.countLocalRecursive(10), 'ReentrancyGuard: reentrant call'); }); it('does not allow indirect local recursion', async function () { - await expectRevert( - this.reentrancyMock.countThisRecursive(10), 'ReentrancyMock: failed call', - ); + await expectRevert(this.reentrancyMock.countThisRecursive(10), 'ReentrancyMock: failed call'); }); }); diff --git a/test/token/ERC1155/ERC1155.behavior.js b/test/token/ERC1155/ERC1155.behavior.js index 37afea0aa..96d448a9e 100644 --- a/test/token/ERC1155/ERC1155.behavior.js +++ b/test/token/ERC1155/ERC1155.behavior.js @@ -7,7 +7,7 @@ const { shouldSupportInterfaces } = require('../../utils/introspection/SupportsI const ERC1155ReceiverMock = artifacts.require('ERC1155ReceiverMock'); -function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, multiTokenHolder, recipient, proxy]) { +function shouldBehaveLikeERC1155([minter, firstTokenHolder, secondTokenHolder, multiTokenHolder, recipient, proxy]) { const firstTokenId = new BN(1); const secondTokenId = new BN(2); const unknownTokenId = new BN(3); @@ -27,22 +27,13 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, ); }); - context('when accounts don\'t own tokens', function () { + context("when accounts don't own tokens", function () { it('returns zero for given addresses', async function () { - expect(await this.token.balanceOf( - firstTokenHolder, - firstTokenId, - )).to.be.bignumber.equal('0'); + expect(await this.token.balanceOf(firstTokenHolder, firstTokenId)).to.be.bignumber.equal('0'); - expect(await this.token.balanceOf( - secondTokenHolder, - secondTokenId, - )).to.be.bignumber.equal('0'); + expect(await this.token.balanceOf(secondTokenHolder, secondTokenId)).to.be.bignumber.equal('0'); - expect(await this.token.balanceOf( - firstTokenHolder, - unknownTokenId, - )).to.be.bignumber.equal('0'); + expect(await this.token.balanceOf(firstTokenHolder, unknownTokenId)).to.be.bignumber.equal('0'); }); }); @@ -51,38 +42,23 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, await this.token.$_mint(firstTokenHolder, firstTokenId, firstAmount, '0x', { from: minter, }); - await this.token.$_mint( - secondTokenHolder, - secondTokenId, - secondAmount, - '0x', - { - from: minter, - }, - ); + await this.token.$_mint(secondTokenHolder, secondTokenId, secondAmount, '0x', { + from: minter, + }); }); it('returns the amount of tokens owned by the given addresses', async function () { - expect(await this.token.balanceOf( - firstTokenHolder, - firstTokenId, - )).to.be.bignumber.equal(firstAmount); + expect(await this.token.balanceOf(firstTokenHolder, firstTokenId)).to.be.bignumber.equal(firstAmount); - expect(await this.token.balanceOf( - secondTokenHolder, - secondTokenId, - )).to.be.bignumber.equal(secondAmount); + expect(await this.token.balanceOf(secondTokenHolder, secondTokenId)).to.be.bignumber.equal(secondAmount); - expect(await this.token.balanceOf( - firstTokenHolder, - unknownTokenId, - )).to.be.bignumber.equal('0'); + expect(await this.token.balanceOf(firstTokenHolder, unknownTokenId)).to.be.bignumber.equal('0'); }); }); }); describe('balanceOfBatch', function () { - it('reverts when input arrays don\'t match up', async function () { + it("reverts when input arrays don't match up", async function () { await expectRevert( this.token.balanceOfBatch( [firstTokenHolder, secondTokenHolder, firstTokenHolder, secondTokenHolder], @@ -110,7 +86,7 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, ); }); - context('when accounts don\'t own tokens', function () { + context("when accounts don't own tokens", function () { it('returns zeros for each account', async function () { const result = await this.token.balanceOfBatch( [firstTokenHolder, secondTokenHolder, firstTokenHolder], @@ -128,15 +104,9 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, await this.token.$_mint(firstTokenHolder, firstTokenId, firstAmount, '0x', { from: minter, }); - await this.token.$_mint( - secondTokenHolder, - secondTokenId, - secondAmount, - '0x', - { - from: minter, - }, - ); + await this.token.$_mint(secondTokenHolder, secondTokenId, secondAmount, '0x', { + from: minter, + }); }); it('returns amounts owned by each account in order passed', async function () { @@ -167,7 +137,7 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, describe('setApprovalForAll', function () { let receipt; beforeEach(async function () { - (receipt = await this.token.setApprovalForAll(proxy, true, { from: multiTokenHolder })); + receipt = await this.token.setApprovalForAll(proxy, true, { from: multiTokenHolder }); }); it('sets approval status which can be queried via isApprovedForAll', async function () { @@ -196,46 +166,30 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, await this.token.$_mint(multiTokenHolder, firstTokenId, firstAmount, '0x', { from: minter, }); - await this.token.$_mint( - multiTokenHolder, - secondTokenId, - secondAmount, - '0x', - { - from: minter, - }, - ); + await this.token.$_mint(multiTokenHolder, secondTokenId, secondAmount, '0x', { + from: minter, + }); }); it('reverts when transferring more than balance', async function () { await expectRevert( - this.token.safeTransferFrom( - multiTokenHolder, - recipient, - firstTokenId, - firstAmount.addn(1), - '0x', - { from: multiTokenHolder }, - ), + this.token.safeTransferFrom(multiTokenHolder, recipient, firstTokenId, firstAmount.addn(1), '0x', { + from: multiTokenHolder, + }), 'ERC1155: insufficient balance for transfer', ); }); it('reverts when transferring to zero address', async function () { await expectRevert( - this.token.safeTransferFrom( - multiTokenHolder, - ZERO_ADDRESS, - firstTokenId, - firstAmount, - '0x', - { from: multiTokenHolder }, - ), + this.token.safeTransferFrom(multiTokenHolder, ZERO_ADDRESS, firstTokenId, firstAmount, '0x', { + from: multiTokenHolder, + }), 'ERC1155: transfer to the zero address', ); }); - function transferWasSuccessful ({ operator, from, id, value }) { + function transferWasSuccessful({ operator, from, id, value }) { it('debits transferred balance from sender', async function () { const newBalance = await this.token.balanceOf(from, id); expect(newBalance).to.be.a.bignumber.equal('0'); @@ -260,10 +214,16 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('when called by the multiTokenHolder', async function () { beforeEach(async function () { this.toWhom = recipient; - (this.transferLogs = - await this.token.safeTransferFrom(multiTokenHolder, recipient, firstTokenId, firstAmount, '0x', { + this.transferLogs = await this.token.safeTransferFrom( + multiTokenHolder, + recipient, + firstTokenId, + firstAmount, + '0x', + { from: multiTokenHolder, - })); + }, + ); }); transferWasSuccessful.call(this, { @@ -302,10 +262,16 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, beforeEach(async function () { this.toWhom = recipient; await this.token.setApprovalForAll(proxy, true, { from: multiTokenHolder }); - (this.transferLogs = - await this.token.safeTransferFrom(multiTokenHolder, recipient, firstTokenId, firstAmount, '0x', { + this.transferLogs = await this.token.safeTransferFrom( + multiTokenHolder, + recipient, + firstTokenId, + firstAmount, + '0x', + { from: proxy, - })); + }, + ); }); transferWasSuccessful.call(this, { @@ -315,7 +281,7 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, value: firstAmount, }); - it('preserves operator\'s balances not involved in the transfer', async function () { + it("preserves operator's balances not involved in the transfer", async function () { const balance1 = await this.token.balanceOf(proxy, firstTokenId); expect(balance1).to.be.a.bignumber.equal('0'); @@ -328,8 +294,10 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('when sending to a valid receiver', function () { beforeEach(async function () { this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, false, - RECEIVER_BATCH_MAGIC_VALUE, false, + RECEIVER_SINGLE_MAGIC_VALUE, + false, + RECEIVER_BATCH_MAGIC_VALUE, + false, ); }); @@ -344,7 +312,7 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, '0x', { from: multiTokenHolder }, ); - (this.transferLogs = this.transferReceipt); + this.transferLogs = this.transferReceipt; }); transferWasSuccessful.call(this, { @@ -377,7 +345,7 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, data, { from: multiTokenHolder }, ); - (this.transferLogs = this.transferReceipt); + this.transferLogs = this.transferReceipt; }); transferWasSuccessful.call(this, { @@ -401,10 +369,7 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('to a receiver contract returning unexpected value', function () { beforeEach(async function () { - this.receiver = await ERC1155ReceiverMock.new( - '0x00c0ffee', false, - RECEIVER_BATCH_MAGIC_VALUE, false, - ); + this.receiver = await ERC1155ReceiverMock.new('0x00c0ffee', false, RECEIVER_BATCH_MAGIC_VALUE, false); }); it('reverts', async function () { @@ -420,8 +385,10 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('to a receiver contract that reverts', function () { beforeEach(async function () { this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, true, - RECEIVER_BATCH_MAGIC_VALUE, false, + RECEIVER_SINGLE_MAGIC_VALUE, + true, + RECEIVER_BATCH_MAGIC_VALUE, + false, ); }); @@ -452,46 +419,46 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, await this.token.$_mint(multiTokenHolder, firstTokenId, firstAmount, '0x', { from: minter, }); - await this.token.$_mint( - multiTokenHolder, - secondTokenId, - secondAmount, - '0x', - { - from: minter, - }, - ); + await this.token.$_mint(multiTokenHolder, secondTokenId, secondAmount, '0x', { + from: minter, + }); }); it('reverts when transferring amount more than any of balances', async function () { await expectRevert( this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, + multiTokenHolder, + recipient, [firstTokenId, secondTokenId], [firstAmount, secondAmount.addn(1)], - '0x', { from: multiTokenHolder }, + '0x', + { from: multiTokenHolder }, ), 'ERC1155: insufficient balance for transfer', ); }); - it('reverts when ids array length doesn\'t match amounts array length', async function () { + it("reverts when ids array length doesn't match amounts array length", async function () { await expectRevert( this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, + multiTokenHolder, + recipient, [firstTokenId], [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, + '0x', + { from: multiTokenHolder }, ), 'ERC1155: ids and amounts length mismatch', ); await expectRevert( this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, + multiTokenHolder, + recipient, [firstTokenId, secondTokenId], [firstAmount], - '0x', { from: multiTokenHolder }, + '0x', + { from: multiTokenHolder }, ), 'ERC1155: ids and amounts length mismatch', ); @@ -500,16 +467,18 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, it('reverts when transferring to zero address', async function () { await expectRevert( this.token.safeBatchTransferFrom( - multiTokenHolder, ZERO_ADDRESS, + multiTokenHolder, + ZERO_ADDRESS, [firstTokenId, secondTokenId], [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, + '0x', + { from: multiTokenHolder }, ), 'ERC1155: transfer to the zero address', ); }); - function batchTransferWasSuccessful ({ operator, from, ids, values }) { + function batchTransferWasSuccessful({ operator, from, ids, values }) { it('debits transferred balances from sender', async function () { const newBalances = await this.token.balanceOfBatch(new Array(ids.length).fill(from), ids); for (const newBalance of newBalances) { @@ -538,13 +507,14 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('when called by the multiTokenHolder', async function () { beforeEach(async function () { this.toWhom = recipient; - (this.transferLogs = - await this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, - )); + this.transferLogs = await this.token.safeBatchTransferFrom( + multiTokenHolder, + recipient, + [firstTokenId, secondTokenId], + [firstAmount, secondAmount], + '0x', + { from: multiTokenHolder }, + ); }); batchTransferWasSuccessful.call(this, { @@ -564,10 +534,12 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, it('reverts', async function () { await expectRevert( this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, + multiTokenHolder, + recipient, [firstTokenId, secondTokenId], [firstAmount, secondAmount], - '0x', { from: proxy }, + '0x', + { from: proxy }, ), 'ERC1155: caller is not token owner or approved', ); @@ -578,13 +550,14 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, beforeEach(async function () { this.toWhom = recipient; await this.token.setApprovalForAll(proxy, true, { from: multiTokenHolder }); - (this.transferLogs = - await this.token.safeBatchTransferFrom( - multiTokenHolder, recipient, - [firstTokenId, secondTokenId], - [firstAmount, secondAmount], - '0x', { from: proxy }, - )); + this.transferLogs = await this.token.safeBatchTransferFrom( + multiTokenHolder, + recipient, + [firstTokenId, secondTokenId], + [firstAmount, secondAmount], + '0x', + { from: proxy }, + ); }); batchTransferWasSuccessful.call(this, { @@ -594,7 +567,7 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, values: [firstAmount, secondAmount], }); - it('preserves operator\'s balances not involved in the transfer', async function () { + it("preserves operator's balances not involved in the transfer", async function () { const balance1 = await this.token.balanceOf(proxy, firstTokenId); expect(balance1).to.be.a.bignumber.equal('0'); const balance2 = await this.token.balanceOf(proxy, secondTokenId); @@ -606,8 +579,10 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('when sending to a valid receiver', function () { beforeEach(async function () { this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, false, - RECEIVER_BATCH_MAGIC_VALUE, false, + RECEIVER_SINGLE_MAGIC_VALUE, + false, + RECEIVER_BATCH_MAGIC_VALUE, + false, ); }); @@ -615,12 +590,14 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, beforeEach(async function () { this.toWhom = this.receiver.address; this.transferReceipt = await this.token.safeBatchTransferFrom( - multiTokenHolder, this.receiver.address, + multiTokenHolder, + this.receiver.address, [firstTokenId, secondTokenId], [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, + '0x', + { from: multiTokenHolder }, ); - (this.transferLogs = this.transferReceipt); + this.transferLogs = this.transferReceipt; }); batchTransferWasSuccessful.call(this, { @@ -646,12 +623,14 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, beforeEach(async function () { this.toWhom = this.receiver.address; this.transferReceipt = await this.token.safeBatchTransferFrom( - multiTokenHolder, this.receiver.address, + multiTokenHolder, + this.receiver.address, [firstTokenId, secondTokenId], [firstAmount, secondAmount], - data, { from: multiTokenHolder }, + data, + { from: multiTokenHolder }, ); - (this.transferLogs = this.transferReceipt); + this.transferLogs = this.transferReceipt; }); batchTransferWasSuccessful.call(this, { @@ -676,18 +655,22 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('to a receiver contract returning unexpected value', function () { beforeEach(async function () { this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, false, - RECEIVER_SINGLE_MAGIC_VALUE, false, + RECEIVER_SINGLE_MAGIC_VALUE, + false, + RECEIVER_SINGLE_MAGIC_VALUE, + false, ); }); it('reverts', async function () { await expectRevert( this.token.safeBatchTransferFrom( - multiTokenHolder, this.receiver.address, + multiTokenHolder, + this.receiver.address, [firstTokenId, secondTokenId], [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, + '0x', + { from: multiTokenHolder }, ), 'ERC1155: ERC1155Receiver rejected tokens', ); @@ -697,18 +680,22 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('to a receiver contract that reverts', function () { beforeEach(async function () { this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, false, - RECEIVER_BATCH_MAGIC_VALUE, true, + RECEIVER_SINGLE_MAGIC_VALUE, + false, + RECEIVER_BATCH_MAGIC_VALUE, + true, ); }); it('reverts', async function () { await expectRevert( this.token.safeBatchTransferFrom( - multiTokenHolder, this.receiver.address, + multiTokenHolder, + this.receiver.address, [firstTokenId, secondTokenId], [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, + '0x', + { from: multiTokenHolder }, ), 'ERC1155ReceiverMock: reverting on batch receive', ); @@ -718,18 +705,22 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, context('to a receiver contract that reverts only on single transfers', function () { beforeEach(async function () { this.receiver = await ERC1155ReceiverMock.new( - RECEIVER_SINGLE_MAGIC_VALUE, true, - RECEIVER_BATCH_MAGIC_VALUE, false, + RECEIVER_SINGLE_MAGIC_VALUE, + true, + RECEIVER_BATCH_MAGIC_VALUE, + false, ); this.toWhom = this.receiver.address; this.transferReceipt = await this.token.safeBatchTransferFrom( - multiTokenHolder, this.receiver.address, + multiTokenHolder, + this.receiver.address, [firstTokenId, secondTokenId], [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, + '0x', + { from: multiTokenHolder }, ); - (this.transferLogs = this.transferReceipt); + this.transferLogs = this.transferReceipt; }); batchTransferWasSuccessful.call(this, { @@ -755,10 +746,12 @@ function shouldBehaveLikeERC1155 ([minter, firstTokenHolder, secondTokenHolder, const invalidReceiver = this.token; await expectRevert.unspecified( this.token.safeBatchTransferFrom( - multiTokenHolder, invalidReceiver.address, + multiTokenHolder, + invalidReceiver.address, [firstTokenId, secondTokenId], [firstAmount, secondAmount], - '0x', { from: multiTokenHolder }, + '0x', + { from: multiTokenHolder }, ), ); }); diff --git a/test/token/ERC1155/ERC1155.test.js b/test/token/ERC1155/ERC1155.test.js index 4e295d59e..ff432d37c 100644 --- a/test/token/ERC1155/ERC1155.test.js +++ b/test/token/ERC1155/ERC1155.test.js @@ -38,7 +38,7 @@ contract('ERC1155', function (accounts) { 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 () { @@ -79,13 +79,9 @@ contract('ERC1155', function (accounts) { context('with minted batch of tokens', function () { beforeEach(async function () { - (this.receipt = await this.token.$_mintBatch( - tokenBatchHolder, - tokenBatchIds, - mintAmounts, - data, - { from: operator }, - )); + this.receipt = await this.token.$_mintBatch(tokenBatchHolder, tokenBatchIds, mintAmounts, data, { + from: operator, + }); }); it('emits a TransferBatch event', function () { @@ -110,28 +106,16 @@ 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), - 'ERC1155: burn from the zero address', - ); + it("reverts when burning the zero account's tokens", async function () { + await expectRevert(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), - 'ERC1155: burn amount exceeds balance', - ); + await expectRevert(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( - tokenHolder, - tokenId, - mintAmount, - data, - { from: operator }, - ); + await this.token.$_mint(tokenHolder, tokenId, mintAmount, data, { from: operator }); await expectRevert( this.token.$_burn(tokenHolder, tokenId, mintAmount.addn(1)), @@ -142,12 +126,7 @@ contract('ERC1155', function (accounts) { context('with minted-then-burnt tokens', function () { beforeEach(async function () { await this.token.$_mint(tokenHolder, tokenId, mintAmount, data); - (this.receipt = await this.token.$_burn( - tokenHolder, - tokenId, - burnAmount, - { from: operator }, - )); + this.receipt = await this.token.$_burn(tokenHolder, tokenId, burnAmount, { from: operator }); }); it('emits a TransferSingle event', function () { @@ -161,16 +140,13 @@ contract('ERC1155', function (accounts) { }); it('accounts for both minting and burning', async function () { - expect(await this.token.balanceOf( - tokenHolder, - tokenId, - )).to.be.bignumber.equal(mintAmount.sub(burnAmount)); + expect(await this.token.balanceOf(tokenHolder, tokenId)).to.be.bignumber.equal(mintAmount.sub(burnAmount)); }); }); }); describe('_burnBatch', function () { - it('reverts when burning the zero account\'s tokens', async function () { + it("reverts when burning the zero account's tokens", async function () { await expectRevert( this.token.$_burnBatch(ZERO_ADDRESS, tokenBatchIds, burnAmounts), 'ERC1155: burn from the zero address', @@ -199,12 +175,7 @@ contract('ERC1155', function (accounts) { context('with minted-then-burnt tokens', function () { beforeEach(async function () { await this.token.$_mintBatch(tokenBatchHolder, tokenBatchIds, mintAmounts, data); - (this.receipt = await this.token.$_burnBatch( - tokenBatchHolder, - tokenBatchIds, - burnAmounts, - { from: operator }, - )); + this.receipt = await this.token.$_burnBatch(tokenBatchHolder, tokenBatchIds, burnAmounts, { from: operator }); }); it('emits a TransferBatch event', function () { diff --git a/test/token/ERC1155/extensions/ERC1155Burnable.test.js b/test/token/ERC1155/extensions/ERC1155Burnable.test.js index 2c854e2e8..f80d9935a 100644 --- a/test/token/ERC1155/extensions/ERC1155Burnable.test.js +++ b/test/token/ERC1155/extensions/ERC1155Burnable.test.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const ERC1155Burnable = artifacts.require('$ERC1155Burnable'); contract('ERC1155Burnable', function (accounts) { - const [ holder, operator, other ] = accounts; + const [holder, operator, other] = accounts; const uri = 'https://token.com'; @@ -26,14 +26,14 @@ contract('ERC1155Burnable', function (accounts) { expect(await this.token.balanceOf(holder, tokenIds[0])).to.be.bignumber.equal('1'); }); - it('approved operators can burn the holder\'s tokens', async function () { + it("approved operators can burn the holder's tokens", async function () { await this.token.setApprovalForAll(operator, true, { from: holder }); await this.token.burn(holder, tokenIds[0], amounts[0].subn(1), { from: operator }); expect(await this.token.balanceOf(holder, tokenIds[0])).to.be.bignumber.equal('1'); }); - it('unapproved accounts cannot burn the holder\'s tokens', async function () { + it("unapproved accounts cannot burn the holder's tokens", async function () { await expectRevert( this.token.burn(holder, tokenIds[0], amounts[0].subn(1), { from: other }), 'ERC1155: caller is not token owner or approved', @@ -43,23 +43,23 @@ contract('ERC1155Burnable', function (accounts) { describe('burnBatch', function () { it('holder can burn their tokens', async function () { - await this.token.burnBatch(holder, tokenIds, [ amounts[0].subn(1), amounts[1].subn(2) ], { from: holder }); + await this.token.burnBatch(holder, tokenIds, [amounts[0].subn(1), amounts[1].subn(2)], { from: holder }); expect(await this.token.balanceOf(holder, tokenIds[0])).to.be.bignumber.equal('1'); expect(await this.token.balanceOf(holder, tokenIds[1])).to.be.bignumber.equal('2'); }); - it('approved operators can burn the holder\'s tokens', async function () { + it("approved operators can burn the holder's tokens", async function () { await this.token.setApprovalForAll(operator, true, { from: holder }); - await this.token.burnBatch(holder, tokenIds, [ amounts[0].subn(1), amounts[1].subn(2) ], { from: operator }); + await this.token.burnBatch(holder, tokenIds, [amounts[0].subn(1), amounts[1].subn(2)], { from: operator }); expect(await this.token.balanceOf(holder, tokenIds[0])).to.be.bignumber.equal('1'); expect(await this.token.balanceOf(holder, tokenIds[1])).to.be.bignumber.equal('2'); }); - it('unapproved accounts cannot burn the holder\'s tokens', async function () { + it("unapproved accounts cannot burn the holder's tokens", async function () { await expectRevert( - this.token.burnBatch(holder, tokenIds, [ amounts[0].subn(1), amounts[1].subn(2) ], { from: other }), + this.token.burnBatch(holder, tokenIds, [amounts[0].subn(1), amounts[1].subn(2)], { from: other }), 'ERC1155: caller is not token owner or approved', ); }); diff --git a/test/token/ERC1155/extensions/ERC1155Pausable.test.js b/test/token/ERC1155/extensions/ERC1155Pausable.test.js index e7ace3c2c..f4d5cedec 100644 --- a/test/token/ERC1155/extensions/ERC1155Pausable.test.js +++ b/test/token/ERC1155/extensions/ERC1155Pausable.test.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const ERC1155Pausable = artifacts.require('$ERC1155Pausable'); contract('ERC1155Pausable', function (accounts) { - const [ holder, operator, receiver, other ] = accounts; + const [holder, operator, receiver, other] = accounts; const uri = 'https://token.com'; @@ -50,9 +50,9 @@ contract('ERC1155Pausable', function (accounts) { it('reverts when trying to safeBatchTransferFrom from operator', async function () { await expectRevert( - this.token.safeBatchTransferFrom( - holder, receiver, [firstTokenId], [firstTokenAmount], '0x', { from: operator }, - ), + this.token.safeBatchTransferFrom(holder, receiver, [firstTokenId], [firstTokenAmount], '0x', { + from: operator, + }), 'ERC1155Pausable: token transfer while paused', ); }); diff --git a/test/token/ERC1155/extensions/ERC1155Supply.test.js b/test/token/ERC1155/extensions/ERC1155Supply.test.js index 0eb4952ab..721d5a782 100644 --- a/test/token/ERC1155/extensions/ERC1155Supply.test.js +++ b/test/token/ERC1155/extensions/ERC1155Supply.test.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const ERC1155Supply = artifacts.require('$ERC1155Supply'); contract('ERC1155Supply', function (accounts) { - const [ holder ] = accounts; + const [holder] = accounts; const uri = 'https://token.com'; @@ -48,8 +48,8 @@ contract('ERC1155Supply', function (accounts) { beforeEach(async function () { await this.token.$_mintBatch( holder, - [ firstTokenId, secondTokenId ], - [ firstTokenAmount, secondTokenAmount ], + [firstTokenId, secondTokenId], + [firstTokenAmount, secondTokenAmount], '0x', ); }); @@ -86,15 +86,11 @@ contract('ERC1155Supply', function (accounts) { beforeEach(async function () { await this.token.$_mintBatch( holder, - [ firstTokenId, secondTokenId ], - [ firstTokenAmount, secondTokenAmount ], + [firstTokenId, secondTokenId], + [firstTokenAmount, secondTokenAmount], '0x', ); - await this.token.$_burnBatch( - holder, - [ firstTokenId, secondTokenId ], - [ firstTokenAmount, secondTokenAmount ], - ); + await this.token.$_burnBatch(holder, [firstTokenId, secondTokenId], [firstTokenAmount, secondTokenAmount]); }); it('exist', async function () { diff --git a/test/token/ERC1155/extensions/ERC1155URIStorage.test.js b/test/token/ERC1155/extensions/ERC1155URIStorage.test.js index a12a5c972..95d9c18f7 100644 --- a/test/token/ERC1155/extensions/ERC1155URIStorage.test.js +++ b/test/token/ERC1155/extensions/ERC1155URIStorage.test.js @@ -6,7 +6,7 @@ const { artifacts } = require('hardhat'); const ERC1155URIStorage = artifacts.require('$ERC1155URIStorage'); contract(['ERC1155URIStorage'], function (accounts) { - const [ holder ] = accounts; + const [holder] = accounts; const erc1155Uri = 'https://token.com/nfts/'; const baseUri = 'https://token.com/'; diff --git a/test/token/ERC1155/presets/ERC1155PresetMinterPauser.test.js b/test/token/ERC1155/presets/ERC1155PresetMinterPauser.test.js index a8d83d123..12d2594d6 100644 --- a/test/token/ERC1155/presets/ERC1155PresetMinterPauser.test.js +++ b/test/token/ERC1155/presets/ERC1155PresetMinterPauser.test.js @@ -7,7 +7,7 @@ const { expect } = require('chai'); const ERC1155PresetMinterPauser = artifacts.require('ERC1155PresetMinterPauser'); contract('ERC1155PresetMinterPauser', function (accounts) { - const [ deployer, other ] = accounts; + const [deployer, other] = accounts; const firstTokenId = new BN('845'); const firstTokenIdAmount = new BN('5000'); @@ -50,9 +50,13 @@ contract('ERC1155PresetMinterPauser', function (accounts) { describe('minting', function () { it('deployer can mint tokens', async function () { const receipt = await this.token.mint(other, firstTokenId, firstTokenIdAmount, '0x', { from: deployer }); - expectEvent(receipt, 'TransferSingle', - { operator: deployer, from: ZERO_ADDRESS, to: other, value: firstTokenIdAmount, id: firstTokenId }, - ); + expectEvent(receipt, 'TransferSingle', { + operator: deployer, + from: ZERO_ADDRESS, + to: other, + value: firstTokenIdAmount, + id: firstTokenId, + }); expect(await this.token.balanceOf(other, firstTokenId)).to.be.bignumber.equal(firstTokenIdAmount); }); @@ -68,21 +72,23 @@ contract('ERC1155PresetMinterPauser', function (accounts) { describe('batched minting', function () { it('deployer can batch mint tokens', async function () { const receipt = await this.token.mintBatch( - other, [firstTokenId, secondTokenId], [firstTokenIdAmount, secondTokenIdAmount], '0x', { from: deployer }, + other, + [firstTokenId, secondTokenId], + [firstTokenIdAmount, secondTokenIdAmount], + '0x', + { from: deployer }, ); - expectEvent(receipt, 'TransferBatch', - { operator: deployer, from: ZERO_ADDRESS, to: other }, - ); + expectEvent(receipt, 'TransferBatch', { operator: deployer, from: ZERO_ADDRESS, to: other }); expect(await this.token.balanceOf(other, firstTokenId)).to.be.bignumber.equal(firstTokenIdAmount); }); it('other accounts cannot batch mint tokens', async function () { await expectRevert( - this.token.mintBatch( - other, [firstTokenId, secondTokenId], [firstTokenIdAmount, secondTokenIdAmount], '0x', { from: other }, - ), + this.token.mintBatch(other, [firstTokenId, secondTokenId], [firstTokenIdAmount, secondTokenIdAmount], '0x', { + from: other, + }), 'ERC1155PresetMinterPauser: must have minter role to mint', ); }); @@ -136,9 +142,13 @@ contract('ERC1155PresetMinterPauser', function (accounts) { await this.token.mint(other, firstTokenId, firstTokenIdAmount, '0x', { from: deployer }); const receipt = await this.token.burn(other, firstTokenId, firstTokenIdAmount.subn(1), { from: other }); - expectEvent(receipt, 'TransferSingle', - { operator: other, from: other, to: ZERO_ADDRESS, value: firstTokenIdAmount.subn(1), id: firstTokenId }, - ); + expectEvent(receipt, 'TransferSingle', { + operator: other, + from: other, + to: ZERO_ADDRESS, + value: firstTokenIdAmount.subn(1), + id: firstTokenId, + }); expect(await this.token.balanceOf(other, firstTokenId)).to.be.bignumber.equal('1'); }); diff --git a/test/token/ERC1155/utils/ERC1155Holder.test.js b/test/token/ERC1155/utils/ERC1155Holder.test.js index 736925bd6..864e89b50 100644 --- a/test/token/ERC1155/utils/ERC1155Holder.test.js +++ b/test/token/ERC1155/utils/ERC1155Holder.test.js @@ -32,8 +32,9 @@ contract('ERC1155Holder', function (accounts) { { from: creator }, ); - expect(await this.multiToken.balanceOf(this.holder.address, multiTokenIds[0])) - .to.be.bignumber.equal(multiTokenAmounts[0]); + expect(await this.multiToken.balanceOf(this.holder.address, multiTokenIds[0])).to.be.bignumber.equal( + multiTokenAmounts[0], + ); for (let i = 1; i < multiTokenIds.length; i++) { expect(await this.multiToken.balanceOf(this.holder.address, multiTokenIds[i])).to.be.bignumber.equal(new BN(0)); @@ -43,7 +44,7 @@ contract('ERC1155Holder', function (accounts) { it('receives ERC1155 tokens from a multiple IDs', async function () { for (let i = 0; i < multiTokenIds.length; i++) { expect(await this.multiToken.balanceOf(this.holder.address, multiTokenIds[i])).to.be.bignumber.equal(new BN(0)); - }; + } await this.multiToken.safeBatchTransferFrom( creator, @@ -55,8 +56,9 @@ contract('ERC1155Holder', function (accounts) { ); for (let i = 0; i < multiTokenIds.length; i++) { - expect(await this.multiToken.balanceOf(this.holder.address, multiTokenIds[i])) - .to.be.bignumber.equal(multiTokenAmounts[i]); + expect(await this.multiToken.balanceOf(this.holder.address, multiTokenIds[i])).to.be.bignumber.equal( + multiTokenAmounts[i], + ); } }); }); diff --git a/test/token/ERC20/ERC20.behavior.js b/test/token/ERC20/ERC20.behavior.js index 8bc54762a..41e47f065 100644 --- a/test/token/ERC20/ERC20.behavior.js +++ b/test/token/ERC20/ERC20.behavior.js @@ -2,7 +2,7 @@ const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test const { expect } = require('chai'); const { ZERO_ADDRESS, MAX_UINT256 } = constants; -function shouldBehaveLikeERC20 (errorPrefix, initialSupply, initialHolder, recipient, anotherAccount) { +function shouldBehaveLikeERC20(errorPrefix, initialSupply, initialHolder, recipient, anotherAccount) { describe('total supply', function () { it('returns the total amount of tokens', async function () { expect(await this.token.totalSupply()).to.be.bignumber.equal(initialSupply); @@ -24,11 +24,9 @@ function shouldBehaveLikeERC20 (errorPrefix, initialSupply, initialHolder, recip }); describe('transfer', function () { - shouldBehaveLikeERC20Transfer(errorPrefix, initialHolder, recipient, initialSupply, - function (from, to, value) { - return this.token.transfer(to, value, { from }); - }, - ); + shouldBehaveLikeERC20Transfer(errorPrefix, initialHolder, recipient, initialSupply, function (from, to, value) { + return this.token.transfer(to, value, { from }); + }); }); describe('transfer from', function () { @@ -63,19 +61,19 @@ function shouldBehaveLikeERC20 (errorPrefix, initialSupply, initialHolder, recip }); it('emits a transfer event', async function () { - expectEvent( - await this.token.transferFrom(tokenOwner, to, amount, { from: spender }), - 'Transfer', - { from: tokenOwner, to: to, value: amount }, - ); + expectEvent(await this.token.transferFrom(tokenOwner, to, amount, { from: spender }), 'Transfer', { + from: tokenOwner, + to: to, + value: amount, + }); }); it('emits an approval event', async function () { - expectEvent( - await this.token.transferFrom(tokenOwner, to, amount, { from: spender }), - 'Approval', - { owner: tokenOwner, spender: spender, value: await this.token.allowance(tokenOwner, spender) }, - ); + expectEvent(await this.token.transferFrom(tokenOwner, to, amount, { from: spender }), 'Approval', { + owner: tokenOwner, + spender: spender, + value: await this.token.allowance(tokenOwner, spender), + }); }); }); @@ -141,10 +139,7 @@ function shouldBehaveLikeERC20 (errorPrefix, initialSupply, initialHolder, recip }); it('does not emit an approval event', async function () { - expectEvent.notEmitted( - await this.token.transferFrom(tokenOwner, to, 1, { from: spender }), - 'Approval', - ); + expectEvent.notEmitted(await this.token.transferFrom(tokenOwner, to, 1, { from: spender }), 'Approval'); }); }); }); @@ -158,8 +153,9 @@ function shouldBehaveLikeERC20 (errorPrefix, initialSupply, initialHolder, recip }); it('reverts', async function () { - await expectRevert(this.token.transferFrom( - tokenOwner, to, amount, { from: spender }), `${errorPrefix}: transfer to the zero address`, + await expectRevert( + this.token.transferFrom(tokenOwner, to, amount, { from: spender }), + `${errorPrefix}: transfer to the zero address`, ); }); }); @@ -171,16 +167,17 @@ function shouldBehaveLikeERC20 (errorPrefix, initialSupply, initialHolder, recip const to = recipient; it('reverts', async function () { - await expectRevert( - this.token.transferFrom(tokenOwner, to, amount, { from: spender }), - 'from the zero address', - ); + await expectRevert(this.token.transferFrom(tokenOwner, to, amount, { from: spender }), 'from the zero address'); }); }); }); describe('approve', function () { - shouldBehaveLikeERC20Approve(errorPrefix, initialHolder, recipient, initialSupply, + shouldBehaveLikeERC20Approve( + errorPrefix, + initialHolder, + recipient, + initialSupply, function (owner, spender, amount) { return this.token.approve(spender, amount, { from: owner }); }, @@ -188,15 +185,13 @@ function shouldBehaveLikeERC20 (errorPrefix, initialSupply, initialHolder, recip }); } -function shouldBehaveLikeERC20Transfer (errorPrefix, from, to, balance, transfer) { +function shouldBehaveLikeERC20Transfer(errorPrefix, from, to, balance, transfer) { describe('when the recipient is not the zero address', function () { describe('when the sender does not have enough balance', function () { const amount = balance.addn(1); it('reverts', async function () { - await expectRevert(transfer.call(this, from, to, amount), - `${errorPrefix}: transfer amount exceeds balance`, - ); + await expectRevert(transfer.call(this, from, to, amount), `${errorPrefix}: transfer amount exceeds balance`); }); }); @@ -212,11 +207,7 @@ function shouldBehaveLikeERC20Transfer (errorPrefix, from, to, balance, transfer }); it('emits a transfer event', async function () { - expectEvent( - await transfer.call(this, from, to, amount), - 'Transfer', - { from, to, value: amount }, - ); + expectEvent(await transfer.call(this, from, to, amount), 'Transfer', { from, to, value: amount }); }); }); @@ -232,35 +223,32 @@ function shouldBehaveLikeERC20Transfer (errorPrefix, from, to, balance, transfer }); it('emits a transfer event', async function () { - expectEvent( - await transfer.call(this, from, to, amount), - 'Transfer', - { from, to, value: amount }, - ); + expectEvent(await transfer.call(this, from, to, amount), 'Transfer', { from, to, value: amount }); }); }); }); describe('when the recipient is the zero address', function () { it('reverts', async function () { - await expectRevert(transfer.call(this, from, ZERO_ADDRESS, balance), + await expectRevert( + transfer.call(this, from, ZERO_ADDRESS, balance), `${errorPrefix}: transfer to the zero address`, ); }); }); } -function shouldBehaveLikeERC20Approve (errorPrefix, owner, spender, supply, approve) { +function shouldBehaveLikeERC20Approve(errorPrefix, owner, spender, supply, approve) { describe('when the spender is not the zero address', function () { describe('when the sender has enough balance', function () { const amount = supply; it('emits an approval event', async function () { - expectEvent( - await approve.call(this, owner, spender, amount), - 'Approval', - { owner: owner, spender: spender, value: amount }, - ); + expectEvent(await approve.call(this, owner, spender, amount), 'Approval', { + owner: owner, + spender: spender, + value: amount, + }); }); describe('when there was no approved amount before', function () { @@ -288,11 +276,11 @@ function shouldBehaveLikeERC20Approve (errorPrefix, owner, spender, supply, appr const amount = supply.addn(1); it('emits an approval event', async function () { - expectEvent( - await approve.call(this, owner, spender, amount), - 'Approval', - { owner: owner, spender: spender, value: amount }, - ); + expectEvent(await approve.call(this, owner, spender, amount), 'Approval', { + owner: owner, + spender: spender, + value: amount, + }); }); describe('when there was no approved amount before', function () { @@ -319,7 +307,8 @@ function shouldBehaveLikeERC20Approve (errorPrefix, owner, spender, supply, appr describe('when the spender is the zero address', function () { it('reverts', async function () { - await expectRevert(approve.call(this, owner, ZERO_ADDRESS, supply), + await expectRevert( + approve.call(this, owner, ZERO_ADDRESS, supply), `${errorPrefix}: approve to the zero address`, ); }); diff --git a/test/token/ERC20/ERC20.test.js b/test/token/ERC20/ERC20.test.js index 10d86e4b4..6971eede9 100644 --- a/test/token/ERC20/ERC20.test.js +++ b/test/token/ERC20/ERC20.test.js @@ -12,7 +12,7 @@ const ERC20 = artifacts.require('$ERC20'); const ERC20Decimals = artifacts.require('$ERC20DecimalsMock'); contract('ERC20', function (accounts) { - const [ initialHolder, recipient, anotherAccount ] = accounts; + const [initialHolder, recipient, anotherAccount] = accounts; const name = 'My Token'; const symbol = 'MTKN'; @@ -51,11 +51,12 @@ contract('ERC20', function (accounts) { describe('when the spender is not the zero address', function () { const spender = recipient; - function shouldDecreaseApproval (amount) { + function shouldDecreaseApproval(amount) { describe('when there was no approved amount before', function () { it('reverts', async function () { - await expectRevert(this.token.decreaseAllowance( - spender, amount, { from: initialHolder }), 'ERC20: decreased allowance below zero', + await expectRevert( + this.token.decreaseAllowance(spender, amount, { from: initialHolder }), + 'ERC20: decreased allowance below zero', ); }); }); @@ -113,8 +114,9 @@ contract('ERC20', function (accounts) { const spender = ZERO_ADDRESS; it('reverts', async function () { - await expectRevert(this.token.decreaseAllowance( - spender, amount, { from: initialHolder }), 'ERC20: decreased allowance below zero', + await expectRevert( + this.token.decreaseAllowance(spender, amount, { from: initialHolder }), + 'ERC20: decreased allowance below zero', ); }); }); @@ -128,11 +130,11 @@ contract('ERC20', function (accounts) { describe('when the sender has enough balance', function () { it('emits an approval event', async function () { - expectEvent( - await this.token.increaseAllowance(spender, amount, { from: initialHolder }), - 'Approval', - { owner: initialHolder, spender: spender, value: amount }, - ); + expectEvent(await this.token.increaseAllowance(spender, amount, { from: initialHolder }), 'Approval', { + owner: initialHolder, + spender: spender, + value: amount, + }); }); describe('when there was no approved amount before', function () { @@ -160,11 +162,11 @@ contract('ERC20', function (accounts) { const amount = initialSupply.addn(1); it('emits an approval event', async function () { - expectEvent( - await this.token.increaseAllowance(spender, amount, { from: initialHolder }), - 'Approval', - { owner: initialHolder, spender: spender, value: amount }, - ); + expectEvent(await this.token.increaseAllowance(spender, amount, { from: initialHolder }), 'Approval', { + owner: initialHolder, + spender: spender, + value: amount, + }); }); describe('when there was no approved amount before', function () { @@ -194,7 +196,8 @@ contract('ERC20', function (accounts) { it('reverts', async function () { await expectRevert( - this.token.increaseAllowance(spender, amount, { from: initialHolder }), 'ERC20: approve to the zero address', + this.token.increaseAllowance(spender, amount, { from: initialHolder }), + 'ERC20: approve to the zero address', ); }); }); @@ -203,9 +206,7 @@ contract('ERC20', function (accounts) { describe('_mint', function () { 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', - ); + await expectRevert(this.token.$_mint(ZERO_ADDRESS, amount), 'ERC20: mint to the zero address'); }); describe('for a non zero account', function () { @@ -223,11 +224,7 @@ contract('ERC20', function (accounts) { }); it('emits Transfer event', async function () { - const event = expectEvent( - this.receipt, - 'Transfer', - { from: ZERO_ADDRESS, to: recipient }, - ); + const event = expectEvent(this.receipt, 'Transfer', { from: ZERO_ADDRESS, to: recipient }); expect(event.args.value).to.be.bignumber.equal(amount); }); @@ -236,14 +233,14 @@ contract('ERC20', function (accounts) { describe('_burn', function () { it('rejects a null account', async function () { - await expectRevert(this.token.$_burn(ZERO_ADDRESS, new BN(1)), - 'ERC20: burn from the zero address'); + 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( - initialHolder, initialSupply.addn(1)), 'ERC20: burn amount exceeds balance', + await expectRevert( + this.token.$_burn(initialHolder, initialSupply.addn(1)), + 'ERC20: burn amount exceeds balance', ); }); @@ -264,11 +261,7 @@ contract('ERC20', function (accounts) { }); it('emits Transfer event', async function () { - const event = expectEvent( - this.receipt, - 'Transfer', - { from: initialHolder, to: ZERO_ADDRESS }, - ); + const event = expectEvent(this.receipt, 'Transfer', { from: initialHolder, to: ZERO_ADDRESS }); expect(event.args.value).to.be.bignumber.equal(amount); }); @@ -287,7 +280,8 @@ contract('ERC20', function (accounts) { describe('when the sender is the zero address', function () { it('reverts', async function () { - await expectRevert(this.token.$_transfer(ZERO_ADDRESS, recipient, initialSupply), + await expectRevert( + this.token.$_transfer(ZERO_ADDRESS, recipient, initialSupply), 'ERC20: transfer from the zero address', ); }); @@ -301,7 +295,8 @@ contract('ERC20', function (accounts) { describe('when the owner is the zero address', function () { it('reverts', async function () { - await expectRevert(this.token.$_approve(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.behavior.js b/test/token/ERC20/extensions/ERC20Burnable.behavior.js index a931bf60d..2edabc4bf 100644 --- a/test/token/ERC20/extensions/ERC20Burnable.behavior.js +++ b/test/token/ERC20/extensions/ERC20Burnable.behavior.js @@ -3,7 +3,7 @@ const { ZERO_ADDRESS } = constants; const { expect } = require('chai'); -function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { +function shouldBehaveLikeERC20Burnable(owner, initialBalance, [burner]) { describe('burn', function () { describe('when the given amount is not greater than balance of the sender', function () { context('for a zero amount', function () { @@ -14,9 +14,9 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { shouldBurn(new BN(100)); }); - function shouldBurn (amount) { + function shouldBurn(amount) { beforeEach(async function () { - (this.receipt = await this.token.burn(amount, { from: owner })); + this.receipt = await this.token.burn(amount, { from: owner }); }); it('burns the requested amount', async function () { @@ -37,9 +37,7 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { const amount = initialBalance.addn(1); it('reverts', async function () { - await expectRevert(this.token.burn(amount, { from: owner }), - 'ERC20: burn amount exceeds balance', - ); + await expectRevert(this.token.burn(amount, { from: owner }), 'ERC20: burn amount exceeds balance'); }); }); }); @@ -54,7 +52,7 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { shouldBurnFrom(new BN(100)); }); - function shouldBurnFrom (amount) { + function shouldBurnFrom(amount) { const originalAllowance = amount.muln(3); beforeEach(async function () { @@ -85,9 +83,7 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { it('reverts', async function () { await this.token.approve(burner, amount, { from: owner }); - await expectRevert(this.token.burnFrom(owner, amount, { from: burner }), - 'ERC20: burn amount exceeds balance', - ); + await expectRevert(this.token.burnFrom(owner, amount, { from: burner }), 'ERC20: burn amount exceeds balance'); }); }); @@ -96,7 +92,8 @@ function shouldBehaveLikeERC20Burnable (owner, initialBalance, [burner]) { it('reverts', async function () { await this.token.approve(burner, allowance, { from: owner }); - await expectRevert(this.token.burnFrom(owner, allowance.addn(1), { from: burner }), + await expectRevert( + this.token.burnFrom(owner, allowance.addn(1), { from: burner }), 'ERC20: insufficient allowance', ); }); diff --git a/test/token/ERC20/extensions/ERC20Burnable.test.js b/test/token/ERC20/extensions/ERC20Burnable.test.js index 45264b774..00acc81ed 100644 --- a/test/token/ERC20/extensions/ERC20Burnable.test.js +++ b/test/token/ERC20/extensions/ERC20Burnable.test.js @@ -4,7 +4,7 @@ const { shouldBehaveLikeERC20Burnable } = require('./ERC20Burnable.behavior'); const ERC20Burnable = artifacts.require('$ERC20Burnable'); contract('ERC20Burnable', function (accounts) { - const [ owner, ...otherAccounts ] = accounts; + const [owner, ...otherAccounts] = accounts; const initialBalance = new BN(1000); diff --git a/test/token/ERC20/extensions/ERC20Capped.behavior.js b/test/token/ERC20/extensions/ERC20Capped.behavior.js index fe8c3a4ff..97bad1db1 100644 --- a/test/token/ERC20/extensions/ERC20Capped.behavior.js +++ b/test/token/ERC20/extensions/ERC20Capped.behavior.js @@ -2,7 +2,7 @@ const { expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -function shouldBehaveLikeERC20Capped (accounts, cap) { +function shouldBehaveLikeERC20Capped(accounts, cap) { describe('capped token', function () { const user = accounts[0]; diff --git a/test/token/ERC20/extensions/ERC20FlashMint.test.js b/test/token/ERC20/extensions/ERC20FlashMint.test.js index 86326f95d..76d66ff7a 100644 --- a/test/token/ERC20/extensions/ERC20FlashMint.test.js +++ b/test/token/ERC20/extensions/ERC20FlashMint.test.js @@ -52,10 +52,25 @@ contract('ERC20FlashMint', function (accounts) { const receiver = await ERC3156FlashBorrowerMock.new(true, true); const { tx } = await this.token.flashLoan(receiver.address, this.token.address, loanAmount, '0x'); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: ZERO_ADDRESS, to: receiver.address, value: loanAmount }); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: receiver.address, to: ZERO_ADDRESS, value: loanAmount }); - await expectEvent.inTransaction(tx, receiver, 'BalanceOf', { token: this.token.address, account: receiver.address, value: loanAmount }); - await expectEvent.inTransaction(tx, receiver, 'TotalSupply', { token: this.token.address, value: initialSupply.add(loanAmount) }); + await expectEvent.inTransaction(tx, this.token, 'Transfer', { + from: ZERO_ADDRESS, + to: receiver.address, + value: loanAmount, + }); + await expectEvent.inTransaction(tx, this.token, 'Transfer', { + from: receiver.address, + to: ZERO_ADDRESS, + value: loanAmount, + }); + await expectEvent.inTransaction(tx, receiver, 'BalanceOf', { + token: this.token.address, + account: receiver.address, + value: loanAmount, + }); + await expectEvent.inTransaction(tx, receiver, 'TotalSupply', { + token: this.token.address, + value: initialSupply.add(loanAmount), + }); expect(await this.token.totalSupply()).to.be.bignumber.equal(initialSupply); expect(await this.token.balanceOf(receiver.address)).to.be.bignumber.equal('0'); @@ -101,7 +116,11 @@ 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); - await expectEvent(receipt, 'Transfer', { from: ZERO_ADDRESS, to: this.receiver.address, value: 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); await this.token.setFlashFee(flashFee); @@ -110,13 +129,32 @@ contract('ERC20FlashMint', function (accounts) { it('default flash fee receiver', async function () { const { tx } = await this.token.flashLoan(this.receiver.address, this.token.address, loanAmount, '0x'); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: ZERO_ADDRESS, to: this.receiver.address, value: loanAmount }); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: this.receiver.address, to: ZERO_ADDRESS, value: loanAmount.add(flashFee) }); - await expectEvent.inTransaction(tx, this.receiver, 'BalanceOf', { token: this.token.address, account: this.receiver.address, value: receiverInitialBalance.add(loanAmount) }); - await expectEvent.inTransaction(tx, this.receiver, 'TotalSupply', { token: this.token.address, value: initialSupply.add(receiverInitialBalance).add(loanAmount) }); + await expectEvent.inTransaction(tx, this.token, 'Transfer', { + from: ZERO_ADDRESS, + to: this.receiver.address, + value: loanAmount, + }); + await expectEvent.inTransaction(tx, this.token, 'Transfer', { + from: this.receiver.address, + to: ZERO_ADDRESS, + value: loanAmount.add(flashFee), + }); + await expectEvent.inTransaction(tx, this.receiver, 'BalanceOf', { + token: this.token.address, + account: this.receiver.address, + value: receiverInitialBalance.add(loanAmount), + }); + await expectEvent.inTransaction(tx, this.receiver, 'TotalSupply', { + token: this.token.address, + value: initialSupply.add(receiverInitialBalance).add(loanAmount), + }); - 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.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.allowance(this.receiver.address, this.token.address)).to.be.bignumber.equal('0'); }); @@ -129,14 +167,35 @@ contract('ERC20FlashMint', function (accounts) { expect(await this.token.balanceOf(flashFeeReceiverAddress)).to.be.bignumber.equal('0'); const { tx } = await this.token.flashLoan(this.receiver.address, this.token.address, loanAmount, '0x'); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: ZERO_ADDRESS, to: this.receiver.address, value: loanAmount }); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: this.receiver.address, to: ZERO_ADDRESS, value: loanAmount }); - await expectEvent.inTransaction(tx, this.token, 'Transfer', { from: this.receiver.address, to: flashFeeReceiverAddress, value: flashFee }); - await expectEvent.inTransaction(tx, this.receiver, 'BalanceOf', { token: this.token.address, account: this.receiver.address, value: receiverInitialBalance.add(loanAmount) }); - await expectEvent.inTransaction(tx, this.receiver, 'TotalSupply', { token: this.token.address, value: initialSupply.add(receiverInitialBalance).add(loanAmount) }); + await expectEvent.inTransaction(tx, this.token, 'Transfer', { + from: ZERO_ADDRESS, + to: this.receiver.address, + value: loanAmount, + }); + await expectEvent.inTransaction(tx, this.token, 'Transfer', { + from: this.receiver.address, + to: ZERO_ADDRESS, + value: loanAmount, + }); + await expectEvent.inTransaction(tx, this.token, 'Transfer', { + from: this.receiver.address, + to: flashFeeReceiverAddress, + value: flashFee, + }); + await expectEvent.inTransaction(tx, this.receiver, 'BalanceOf', { + token: this.token.address, + account: this.receiver.address, + value: receiverInitialBalance.add(loanAmount), + }); + await expectEvent.inTransaction(tx, this.receiver, 'TotalSupply', { + token: this.token.address, + value: initialSupply.add(receiverInitialBalance).add(loanAmount), + }); expect(await this.token.totalSupply()).to.be.bignumber.equal(initialSupply.add(receiverInitialBalance)); - expect(await this.token.balanceOf(this.receiver.address)).to.be.bignumber.equal(receiverInitialBalance.sub(flashFee)); + expect(await this.token.balanceOf(this.receiver.address)).to.be.bignumber.equal( + receiverInitialBalance.sub(flashFee), + ); expect(await this.token.balanceOf(flashFeeReceiverAddress)).to.be.bignumber.equal(flashFee); expect(await this.token.allowance(this.receiver.address, 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 03c630451..ead442b99 100644 --- a/test/token/ERC20/extensions/ERC20Pausable.test.js +++ b/test/token/ERC20/extensions/ERC20Pausable.test.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const ERC20Pausable = artifacts.require('$ERC20Pausable'); contract('ERC20Pausable', function (accounts) { - const [ holder, recipient, anotherAccount ] = accounts; + const [holder, recipient, anotherAccount] = accounts; const initialSupply = new BN(100); @@ -39,7 +39,8 @@ contract('ERC20Pausable', function (accounts) { it('reverts when trying to transfer when paused', async function () { await this.token.$_pause(); - await expectRevert(this.token.transfer(recipient, initialSupply, { from: holder }), + await expectRevert( + this.token.transfer(recipient, initialSupply, { from: holder }), 'ERC20Pausable: token transfer while paused', ); }); @@ -72,8 +73,9 @@ contract('ERC20Pausable', function (accounts) { it('reverts when trying to transfer from when paused', async function () { await this.token.$_pause(); - await expectRevert(this.token.transferFrom( - holder, recipient, allowance, { from: anotherAccount }), 'ERC20Pausable: token transfer while paused', + await expectRevert( + this.token.transferFrom(holder, recipient, allowance, { from: anotherAccount }), + 'ERC20Pausable: token transfer while paused', ); }); }); @@ -99,9 +101,7 @@ contract('ERC20Pausable', function (accounts) { it('reverts when trying to mint when paused', async function () { await this.token.$_pause(); - await expectRevert(this.token.$_mint(recipient, amount), - 'ERC20Pausable: token transfer while paused', - ); + await expectRevert(this.token.$_mint(recipient, amount), 'ERC20Pausable: token transfer while paused'); }); }); @@ -126,9 +126,7 @@ contract('ERC20Pausable', function (accounts) { it('reverts when trying to burn when paused', async function () { await this.token.$_pause(); - await expectRevert(this.token.$_burn(holder, amount), - 'ERC20Pausable: token transfer while paused', - ); + 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 6f7646d77..fb0bb31d3 100644 --- a/test/token/ERC20/extensions/ERC20Snapshot.test.js +++ b/test/token/ERC20/extensions/ERC20Snapshot.test.js @@ -4,7 +4,7 @@ const ERC20Snapshot = artifacts.require('$ERC20Snapshot'); const { expect } = require('chai'); contract('ERC20Snapshot', function (accounts) { - const [ initialHolder, recipient, other ] = accounts; + const [initialHolder, recipient, other] = accounts; const initialSupply = new BN(100); @@ -123,8 +123,9 @@ contract('ERC20Snapshot', function (accounts) { context('with no balance changes after the snapshot', function () { it('returns the current balance for all accounts', async function () { - expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)) - .to.be.bignumber.equal(initialSupply); + expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)).to.be.bignumber.equal( + initialSupply, + ); expect(await this.token.balanceOfAt(recipient, this.initialSnapshotId)).to.be.bignumber.equal('0'); expect(await this.token.balanceOfAt(other, this.initialSnapshotId)).to.be.bignumber.equal('0'); }); @@ -138,8 +139,9 @@ contract('ERC20Snapshot', function (accounts) { }); it('returns the balances before the changes', async function () { - expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)) - .to.be.bignumber.equal(initialSupply); + expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)).to.be.bignumber.equal( + initialSupply, + ); expect(await this.token.balanceOfAt(recipient, this.initialSnapshotId)).to.be.bignumber.equal('0'); expect(await this.token.balanceOfAt(other, this.initialSnapshotId)).to.be.bignumber.equal('0'); }); @@ -153,8 +155,9 @@ contract('ERC20Snapshot', function (accounts) { }); it('snapshots return the balances before and after the changes', async function () { - expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)) - .to.be.bignumber.equal(initialSupply); + expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)).to.be.bignumber.equal( + initialSupply, + ); expect(await this.token.balanceOfAt(recipient, this.initialSnapshotId)).to.be.bignumber.equal('0'); expect(await this.token.balanceOfAt(other, this.initialSnapshotId)).to.be.bignumber.equal('0'); @@ -181,8 +184,9 @@ contract('ERC20Snapshot', function (accounts) { }); it('all posterior snapshots return the supply after the changes', async function () { - expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)) - .to.be.bignumber.equal(initialSupply); + expect(await this.token.balanceOfAt(initialHolder, this.initialSnapshotId)).to.be.bignumber.equal( + initialSupply, + ); expect(await this.token.balanceOfAt(recipient, this.initialSnapshotId)).to.be.bignumber.equal('0'); expect(await this.token.balanceOfAt(other, this.initialSnapshotId)).to.be.bignumber.equal('0'); @@ -193,9 +197,7 @@ contract('ERC20Snapshot', function (accounts) { expect(await this.token.balanceOfAt(recipient, id)).to.be.bignumber.equal( await this.token.balanceOf(recipient), ); - expect(await this.token.balanceOfAt(other, id)).to.be.bignumber.equal( - await this.token.balanceOf(other), - ); + expect(await this.token.balanceOfAt(other, id)).to.be.bignumber.equal(await this.token.balanceOf(other)); } }); }); diff --git a/test/token/ERC20/extensions/ERC20Votes.test.js b/test/token/ERC20/extensions/ERC20Votes.test.js index 18d3011cd..a340e71a7 100644 --- a/test/token/ERC20/extensions/ERC20Votes.test.js +++ b/test/token/ERC20/extensions/ERC20Votes.test.js @@ -21,7 +21,7 @@ const Delegation = [ ]; contract('ERC20Votes', function (accounts) { - const [ holder, recipient, holderDelegatee, other1, other2 ] = accounts; + const [holder, recipient, holderDelegatee, other1, other2] = accounts; const name = 'My Token'; const symbol = 'MTKN'; @@ -38,19 +38,14 @@ contract('ERC20Votes', function (accounts) { }); it('domain separator', async function () { - expect( - await this.token.DOMAIN_SEPARATOR(), - ).to.equal( + expect(await this.token.DOMAIN_SEPARATOR()).to.equal( 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), - 'ERC20Votes: total supply risks overflowing votes', - ); + await expectRevert(this.token.$_mint(holder, amount), 'ERC20Votes: total supply risks overflowing votes'); }); it('recent checkpoints', async function () { @@ -112,26 +107,30 @@ contract('ERC20Votes', function (accounts) { const delegatorAddress = web3.utils.toChecksumAddress(delegator.getAddressString()); const nonce = 0; - const buildData = (chainId, verifyingContract, message) => ({ data: { - primaryType: 'Delegation', - types: { EIP712Domain, Delegation }, - domain: { name, version, chainId, verifyingContract }, - message, - }}); + const buildData = (chainId, verifyingContract, message) => ({ + data: { + primaryType: 'Delegation', + types: { EIP712Domain, Delegation }, + domain: { name, version, chainId, verifyingContract }, + message, + }, + }); beforeEach(async function () { await this.token.$_mint(delegatorAddress, supply); }); it('accept signed delegation', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.token.address, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); expect(await this.token.delegates(delegatorAddress)).to.be.equal(ZERO_ADDRESS); @@ -156,14 +155,16 @@ contract('ERC20Votes', function (accounts) { }); it('rejects reused signature', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.token.address, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); await this.token.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); @@ -174,14 +175,16 @@ contract('ERC20Votes', function (accounts) { }); it('rejects bad delegatee', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.token.address, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); const receipt = await this.token.delegateBySig(holderDelegatee, nonce, MAX_UINT256, v, r, s); const { args } = receipt.logs.find(({ event }) => event == 'DelegateChanged'); @@ -191,14 +194,16 @@ contract('ERC20Votes', function (accounts) { }); it('rejects bad nonce', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.token.address, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); await expectRevert( this.token.delegateBySig(delegatorAddress, nonce + 1, MAX_UINT256, v, r, s), 'ERC20Votes: invalid nonce', @@ -207,14 +212,16 @@ contract('ERC20Votes', function (accounts) { it('rejects expired permit', async function () { const expiry = (await time.latest()) - time.duration.weeks(1); - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.token.address, { + delegatee: delegatorAddress, + nonce, + expiry, + }), + ), + ); await expectRevert( this.token.delegateBySig(delegatorAddress, nonce, expiry, v, r, s), @@ -281,10 +288,18 @@ contract('ERC20Votes', function (accounts) { const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: holder, previousBalance: supply, newBalance: supply.subn(1) }); + expectEvent(receipt, 'DelegateVotesChanged', { + delegate: holder, + previousBalance: supply, + newBalance: supply.subn(1), + }); const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); + expect( + receipt.logs + .filter(({ event }) => event == 'DelegateVotesChanged') + .every(({ logIndex }) => transferLogIndex < logIndex), + ).to.be.equal(true); this.holderVotes = supply.subn(1); this.recipientVotes = '0'; @@ -298,7 +313,11 @@ contract('ERC20Votes', function (accounts) { expectEvent(receipt, 'DelegateVotesChanged', { delegate: recipient, previousBalance: '0', newBalance: '1' }); const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); + expect( + receipt.logs + .filter(({ event }) => event == 'DelegateVotesChanged') + .every(({ logIndex }) => transferLogIndex < logIndex), + ).to.be.equal(true); this.holderVotes = '0'; this.recipientVotes = '1'; @@ -310,11 +329,19 @@ contract('ERC20Votes', function (accounts) { const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: holder, previousBalance: supply, newBalance: supply.subn(1) }); + expectEvent(receipt, 'DelegateVotesChanged', { + delegate: holder, + previousBalance: supply, + newBalance: supply.subn(1), + }); expectEvent(receipt, 'DelegateVotesChanged', { delegate: recipient, previousBalance: '0', newBalance: '1' }); const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); + expect( + receipt.logs + .filter(({ event }) => event == 'DelegateVotesChanged') + .every(({ logIndex }) => transferLogIndex < logIndex), + ).to.be.equal(true); this.holderVotes = supply.subn(1); this.recipientVotes = '1'; @@ -361,10 +388,10 @@ contract('ERC20Votes', function (accounts) { const t4 = await this.token.transfer(recipient, 20, { from: holder }); expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('4'); - expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([ t1.receipt.blockNumber.toString(), '100' ]); - expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ t2.receipt.blockNumber.toString(), '90' ]); - expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([ t3.receipt.blockNumber.toString(), '80' ]); - expect(await this.token.checkpoints(other1, 3)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]); + expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([t1.receipt.blockNumber.toString(), '100']); + expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([t2.receipt.blockNumber.toString(), '90']); + expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([t3.receipt.blockNumber.toString(), '80']); + expect(await this.token.checkpoints(other1, 3)).to.be.deep.equal([t4.receipt.blockNumber.toString(), '100']); await time.advanceBlock(); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('100'); @@ -377,28 +404,25 @@ contract('ERC20Votes', function (accounts) { await this.token.transfer(recipient, '100', { from: holder }); expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('0'); - const [ t1, t2, t3 ] = await batchInBlock([ + const [t1, t2, t3] = await batchInBlock([ () => this.token.delegate(other1, { from: recipient, gas: 100000 }), () => this.token.transfer(other2, 10, { from: recipient, gas: 100000 }), () => this.token.transfer(other2, 10, { from: recipient, gas: 100000 }), ]); expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('1'); - expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([ t1.receipt.blockNumber.toString(), '80' ]); + expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([t1.receipt.blockNumber.toString(), '80']); // expectReve(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ '0', '0' ]); // Reverts due to array overflow check // expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([ '0', '0' ]); // Reverts due to array overflow check const t4 = await this.token.transfer(recipient, 20, { from: holder }); expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('2'); - expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]); + expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([t4.receipt.blockNumber.toString(), '100']); }); }); describe('getPastVotes', function () { it('reverts if block number >= current block', async function () { - await expectRevert( - this.token.getPastVotes(other1, 5e10), - 'ERC20Votes: block not yet mined', - ); + await expectRevert(this.token.getPastVotes(other1, 5e10), 'ERC20Votes: block not yet mined'); }); it('returns 0 if there are no checkpoints', async function () { @@ -410,8 +434,12 @@ contract('ERC20Votes', function (accounts) { await time.advanceBlock(); await time.advanceBlock(); - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); + expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); }); it('returns zero if < first checkpoint block', async function () { @@ -421,7 +449,9 @@ contract('ERC20Votes', function (accounts) { await time.advanceBlock(); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); + expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); }); it('generally returns the voting balance at the appropriate checkpoint', async function () { @@ -439,14 +469,30 @@ contract('ERC20Votes', function (accounts) { await time.advanceBlock(); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); + expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPastVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal( + '9999999999999999999999990', + ); + expect(await this.token.getPastVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal( + '9999999999999999999999990', + ); + expect(await this.token.getPastVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal( + '9999999999999999999999980', + ); + expect(await this.token.getPastVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal( + '9999999999999999999999980', + ); + expect(await this.token.getPastVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPastVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); }); }); }); @@ -457,10 +503,7 @@ contract('ERC20Votes', function (accounts) { }); it('reverts if block number >= current block', async function () { - await expectRevert( - this.token.getPastTotalSupply(5e10), - 'ERC20Votes: block not yet mined', - ); + await expectRevert(this.token.getPastTotalSupply(5e10), 'ERC20Votes: block not yet mined'); }); it('returns 0 if there are no checkpoints', async function () { @@ -484,7 +527,9 @@ contract('ERC20Votes', function (accounts) { await time.advanceBlock(); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); + expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); }); it('generally returns the voting balance at the appropriate checkpoint', async function () { @@ -502,14 +547,30 @@ contract('ERC20Votes', function (accounts) { await time.advanceBlock(); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); + expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal( + '9999999999999999999999990', + ); + expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal( + '9999999999999999999999990', + ); + expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal( + '9999999999999999999999980', + ); + expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal( + '9999999999999999999999980', + ); + expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); }); }); }); diff --git a/test/token/ERC20/extensions/ERC20VotesComp.test.js b/test/token/ERC20/extensions/ERC20VotesComp.test.js index 5efaa5561..6a7c00013 100644 --- a/test/token/ERC20/extensions/ERC20VotesComp.test.js +++ b/test/token/ERC20/extensions/ERC20VotesComp.test.js @@ -21,7 +21,7 @@ const Delegation = [ ]; contract('ERC20VotesComp', function (accounts) { - const [ holder, recipient, holderDelegatee, other1, other2 ] = accounts; + const [holder, recipient, holderDelegatee, other1, other2] = accounts; const name = 'My Token'; const symbol = 'MTKN'; @@ -38,19 +38,14 @@ contract('ERC20VotesComp', function (accounts) { }); it('domain separator', async function () { - expect( - await this.token.DOMAIN_SEPARATOR(), - ).to.equal( + expect(await this.token.DOMAIN_SEPARATOR()).to.equal( 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), - 'ERC20Votes: total supply risks overflowing votes', - ); + await expectRevert(this.token.$_mint(holder, amount), 'ERC20Votes: total supply risks overflowing votes'); }); describe('set delegation', function () { @@ -99,26 +94,30 @@ contract('ERC20VotesComp', function (accounts) { const delegatorAddress = web3.utils.toChecksumAddress(delegator.getAddressString()); const nonce = 0; - const buildData = (chainId, verifyingContract, message) => ({ data: { - primaryType: 'Delegation', - types: { EIP712Domain, Delegation }, - domain: { name, version, chainId, verifyingContract }, - message, - }}); + const buildData = (chainId, verifyingContract, message) => ({ + data: { + primaryType: 'Delegation', + types: { EIP712Domain, Delegation }, + domain: { name, version, chainId, verifyingContract }, + message, + }, + }); beforeEach(async function () { await this.token.$_mint(delegatorAddress, supply); }); it('accept signed delegation', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.token.address, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); expect(await this.token.delegates(delegatorAddress)).to.be.equal(ZERO_ADDRESS); @@ -143,14 +142,16 @@ contract('ERC20VotesComp', function (accounts) { }); it('rejects reused signature', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.token.address, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); await this.token.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); @@ -161,14 +162,16 @@ contract('ERC20VotesComp', function (accounts) { }); it('rejects bad delegatee', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.token.address, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); const receipt = await this.token.delegateBySig(holderDelegatee, nonce, MAX_UINT256, v, r, s); const { args } = receipt.logs.find(({ event }) => event == 'DelegateChanged'); @@ -178,14 +181,16 @@ contract('ERC20VotesComp', function (accounts) { }); it('rejects bad nonce', async function () { - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry: MAX_UINT256, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.token.address, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + ), + ); await expectRevert( this.token.delegateBySig(delegatorAddress, nonce + 1, MAX_UINT256, v, r, s), 'ERC20Votes: invalid nonce', @@ -194,14 +199,16 @@ contract('ERC20VotesComp', function (accounts) { it('rejects expired permit', async function () { const expiry = (await time.latest()) - time.duration.weeks(1); - const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( - delegator.getPrivateKey(), - buildData(this.chainId, this.token.address, { - delegatee: delegatorAddress, - nonce, - expiry, - }), - )); + const { v, r, s } = fromRpcSig( + ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.token.address, { + delegatee: delegatorAddress, + nonce, + expiry, + }), + ), + ); await expectRevert( this.token.delegateBySig(delegatorAddress, nonce, expiry, v, r, s), @@ -268,7 +275,11 @@ contract('ERC20VotesComp', function (accounts) { const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: holder, previousBalance: supply, newBalance: supply.subn(1) }); + expectEvent(receipt, 'DelegateVotesChanged', { + delegate: holder, + previousBalance: supply, + newBalance: supply.subn(1), + }); this.holderVotes = supply.subn(1); this.recipientVotes = '0'; @@ -291,7 +302,11 @@ contract('ERC20VotesComp', function (accounts) { const { receipt } = await this.token.transfer(recipient, 1, { from: holder }); expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: holder, previousBalance: supply, newBalance: supply.subn(1) }); + expectEvent(receipt, 'DelegateVotesChanged', { + delegate: holder, + previousBalance: supply, + newBalance: supply.subn(1), + }); expectEvent(receipt, 'DelegateVotesChanged', { delegate: recipient, previousBalance: '0', newBalance: '1' }); this.holderVotes = supply.subn(1); @@ -339,10 +354,10 @@ contract('ERC20VotesComp', function (accounts) { const t4 = await this.token.transfer(recipient, 20, { from: holder }); expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('4'); - expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([ t1.receipt.blockNumber.toString(), '100' ]); - expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ t2.receipt.blockNumber.toString(), '90' ]); - expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([ t3.receipt.blockNumber.toString(), '80' ]); - expect(await this.token.checkpoints(other1, 3)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]); + expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([t1.receipt.blockNumber.toString(), '100']); + expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([t2.receipt.blockNumber.toString(), '90']); + expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([t3.receipt.blockNumber.toString(), '80']); + expect(await this.token.checkpoints(other1, 3)).to.be.deep.equal([t4.receipt.blockNumber.toString(), '100']); await time.advanceBlock(); expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('100'); @@ -355,28 +370,25 @@ contract('ERC20VotesComp', function (accounts) { await this.token.transfer(recipient, '100', { from: holder }); expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('0'); - const [ t1, t2, t3 ] = await batchInBlock([ + const [t1, t2, t3] = await batchInBlock([ () => this.token.delegate(other1, { from: recipient, gas: 100000 }), () => this.token.transfer(other2, 10, { from: recipient, gas: 100000 }), () => this.token.transfer(other2, 10, { from: recipient, gas: 100000 }), ]); expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('1'); - expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([ t1.receipt.blockNumber.toString(), '80' ]); + expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([t1.receipt.blockNumber.toString(), '80']); // expectReve(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ '0', '0' ]); // Reverts due to array overflow check // expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([ '0', '0' ]); // Reverts due to array overflow check const t4 = await this.token.transfer(recipient, 20, { from: holder }); expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('2'); - expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]); + expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([t4.receipt.blockNumber.toString(), '100']); }); }); describe('getPriorVotes', function () { it('reverts if block number >= current block', async function () { - await expectRevert( - this.token.getPriorVotes(other1, 5e10), - 'ERC20Votes: block not yet mined', - ); + await expectRevert(this.token.getPriorVotes(other1, 5e10), 'ERC20Votes: block not yet mined'); }); it('returns 0 if there are no checkpoints', async function () { @@ -388,8 +400,12 @@ contract('ERC20VotesComp', function (accounts) { await time.advanceBlock(); await time.advanceBlock(); - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); + expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); }); it('returns zero if < first checkpoint block', async function () { @@ -399,7 +415,9 @@ contract('ERC20VotesComp', function (accounts) { await time.advanceBlock(); expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); + expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); }); it('generally returns the voting balance at the appropriate checkpoint', async function () { @@ -417,14 +435,30 @@ contract('ERC20VotesComp', function (accounts) { await time.advanceBlock(); expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); + expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal( + '9999999999999999999999990', + ); + expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal( + '9999999999999999999999990', + ); + expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal( + '9999999999999999999999980', + ); + expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal( + '9999999999999999999999980', + ); + expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); }); }); }); @@ -435,10 +469,7 @@ contract('ERC20VotesComp', function (accounts) { }); it('reverts if block number >= current block', async function () { - await expectRevert( - this.token.getPastTotalSupply(5e10), - 'ERC20Votes: block not yet mined', - ); + await expectRevert(this.token.getPastTotalSupply(5e10), 'ERC20Votes: block not yet mined'); }); it('returns 0 if there are no checkpoints', async function () { @@ -462,7 +493,9 @@ contract('ERC20VotesComp', function (accounts) { await time.advanceBlock(); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); + expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); }); it('generally returns the voting balance at the appropriate checkpoint', async function () { @@ -480,14 +513,30 @@ contract('ERC20VotesComp', function (accounts) { await time.advanceBlock(); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990'); - expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980'); - expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); - expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); + expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal( + '9999999999999999999999990', + ); + expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal( + '9999999999999999999999990', + ); + expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal( + '9999999999999999999999980', + ); + expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal( + '9999999999999999999999980', + ); + expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal( + '10000000000000000000000000', + ); + expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal( + '10000000000000000000000000', + ); }); }); }); diff --git a/test/token/ERC20/extensions/ERC20Wrapper.test.js b/test/token/ERC20/extensions/ERC20Wrapper.test.js index a82164cdf..cfb47bfa2 100644 --- a/test/token/ERC20/extensions/ERC20Wrapper.test.js +++ b/test/token/ERC20/extensions/ERC20Wrapper.test.js @@ -9,7 +9,7 @@ const ERC20Decimals = artifacts.require('$ERC20DecimalsMock'); const ERC20Wrapper = artifacts.require('$ERC20Wrapper'); contract('ERC20', function (accounts) { - const [ initialHolder, recipient, anotherAccount ] = accounts; + const [initialHolder, recipient, anotherAccount] = accounts; const name = 'My Token'; const symbol = 'MTKN'; diff --git a/test/token/ERC20/extensions/ERC4626.test.js b/test/token/ERC20/extensions/ERC4626.test.js index d095fb9d9..f85ffd56d 100644 --- a/test/token/ERC20/extensions/ERC4626.test.js +++ b/test/token/ERC20/extensions/ERC4626.test.js @@ -5,11 +5,11 @@ 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')); +const parseToken = token => new BN(token).mul(new BN('1000000000000')); +const parseShare = share => new BN(share).mul(new BN('1000000000000000000')); contract('ERC4626', function (accounts) { - const [ holder, recipient, spender, other, user1, user2 ] = accounts; + const [holder, recipient, spender, other, user1, user2] = accounts; const name = 'My Token'; const symbol = 'MTKN'; @@ -31,7 +31,7 @@ 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)) { + for (const decimals of [0, 9, 12, 18, 36].map(web3.utils.toBN)) { const token = await ERC20Decimals.new('', '', decimals); const vault = await ERC4626.new('', '', token.address); expect(await vault.decimals()).to.be.bignumber.equal(decimals); diff --git a/test/token/ERC20/extensions/draft-ERC20Permit.test.js b/test/token/ERC20/extensions/draft-ERC20Permit.test.js index 0c6b0982d..eb6737826 100644 --- a/test/token/ERC20/extensions/draft-ERC20Permit.test.js +++ b/test/token/ERC20/extensions/draft-ERC20Permit.test.js @@ -14,7 +14,7 @@ const { EIP712Domain, Permit, domainSeparator } = require('../../../helpers/eip7 const { getChainId } = require('../../../helpers/chainid'); contract('ERC20Permit', function (accounts) { - const [ initialHolder, spender ] = accounts; + const [initialHolder, spender] = accounts; const name = 'My Token'; const symbol = 'MTKN'; @@ -34,9 +34,7 @@ contract('ERC20Permit', function (accounts) { }); it('domain separator', async function () { - expect( - await this.token.DOMAIN_SEPARATOR(), - ).to.equal( + expect(await this.token.DOMAIN_SEPARATOR()).to.equal( await domainSeparator({ name, version, chainId: this.chainId, verifyingContract: this.token.address }), ); }); @@ -99,10 +97,7 @@ contract('ERC20Permit', function (accounts) { const signature = ethSigUtil.signTypedMessage(wallet.getPrivateKey(), { data }); const { v, r, s } = fromRpcSig(signature); - await expectRevert( - this.token.permit(owner, spender, value, deadline, v, r, s), - 'ERC20Permit: expired deadline', - ); + await expectRevert(this.token.permit(owner, spender, value, deadline, v, r, s), 'ERC20Permit: expired deadline'); }); }); }); diff --git a/test/token/ERC20/presets/ERC20PresetMinterPauser.test.js b/test/token/ERC20/presets/ERC20PresetMinterPauser.test.js index c143790f4..ad9ff29c5 100644 --- a/test/token/ERC20/presets/ERC20PresetMinterPauser.test.js +++ b/test/token/ERC20/presets/ERC20PresetMinterPauser.test.js @@ -6,7 +6,7 @@ const { expect } = require('chai'); const ERC20PresetMinterPauser = artifacts.require('ERC20PresetMinterPauser'); contract('ERC20PresetMinterPauser', function (accounts) { - const [ deployer, other ] = accounts; + const [deployer, other] = accounts; const name = 'MinterPauserToken'; const symbol = 'DRT'; @@ -84,10 +84,7 @@ contract('ERC20PresetMinterPauser', function (accounts) { }); it('other accounts cannot pause', async function () { - await expectRevert( - this.token.pause({ from: other }), - 'ERC20PresetMinterPauser: must have pauser role to pause', - ); + await expectRevert(this.token.pause({ from: other }), 'ERC20PresetMinterPauser: must have pauser role to pause'); }); it('other accounts cannot unpause', async function () { diff --git a/test/token/ERC20/utils/SafeERC20.test.js b/test/token/ERC20/utils/SafeERC20.test.js index dab116131..878989cb1 100644 --- a/test/token/ERC20/utils/SafeERC20.test.js +++ b/test/token/ERC20/utils/SafeERC20.test.js @@ -14,7 +14,7 @@ const ethSigUtil = require('eth-sig-util'); const Wallet = require('ethereumjs-wallet').default; contract('SafeERC20', function (accounts) { - const [ hasNoCode ] = accounts; + const [hasNoCode] = accounts; before(async function () { this.mock = await SafeERC20.new(); @@ -52,7 +52,7 @@ contract('SafeERC20', function (accounts) { shouldOnlyRevertOnErrors(); }); - describe('with token that doesn\'t revert on invalid permit', function () { + describe("with token that doesn't revert on invalid permit", function () { const wallet = Wallet.generate(); const owner = wallet.getAddressString(); const spender = hasNoCode; @@ -169,12 +169,9 @@ contract('SafeERC20', function (accounts) { }); }); -function shouldRevertOnAllCalls (reason) { +function shouldRevertOnAllCalls(reason) { it('reverts on transfer', async function () { - await expectRevert( - this.mock.$safeTransfer(this.token.address, constants.ZERO_ADDRESS, 0), - reason, - ); + await expectRevert(this.mock.$safeTransfer(this.token.address, constants.ZERO_ADDRESS, 0), reason); }); it('reverts on transferFrom', async function () { @@ -185,10 +182,7 @@ function shouldRevertOnAllCalls (reason) { }); it('reverts on approve', async function () { - await expectRevert( - this.mock.$safeApprove(this.token.address, constants.ZERO_ADDRESS, 0), - reason, - ); + await expectRevert(this.mock.$safeApprove(this.token.address, constants.ZERO_ADDRESS, 0), reason); }); it('reverts on increaseAllowance', async function () { @@ -202,12 +196,12 @@ function shouldRevertOnAllCalls (reason) { }); } -function shouldOnlyRevertOnErrors () { - it('doesn\'t revert on transfer', async function () { +function shouldOnlyRevertOnErrors() { + it("doesn't revert on transfer", async function () { await this.mock.$safeTransfer(this.token.address, constants.ZERO_ADDRESS, 0); }); - it('doesn\'t revert on transferFrom', async function () { + it("doesn't revert on transferFrom", async function () { await this.mock.$safeTransferFrom(this.token.address, this.mock.address, constants.ZERO_ADDRESS, 0); }); @@ -217,15 +211,15 @@ function shouldOnlyRevertOnErrors () { await this.token.setAllowance(this.mock.address, 0); }); - it('doesn\'t revert when approving a non-zero allowance', async function () { + it("doesn't revert when approving a non-zero allowance", async function () { await this.mock.$safeApprove(this.token.address, constants.ZERO_ADDRESS, 100); }); - it('doesn\'t revert when approving a zero allowance', async function () { + it("doesn't revert when approving a zero allowance", async function () { await this.mock.$safeApprove(this.token.address, constants.ZERO_ADDRESS, 0); }); - it('doesn\'t revert when increasing the allowance', async function () { + it("doesn't revert when increasing the allowance", async function () { await this.mock.$safeIncreaseAllowance(this.token.address, constants.ZERO_ADDRESS, 10); }); @@ -249,15 +243,15 @@ function shouldOnlyRevertOnErrors () { ); }); - it('doesn\'t revert when approving a zero allowance', async function () { + it("doesn't revert when approving a zero allowance", async function () { await this.mock.$safeApprove(this.token.address, constants.ZERO_ADDRESS, 0); }); - it('doesn\'t revert when increasing the allowance', async function () { + it("doesn't revert when increasing the allowance", async function () { 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 () { + it("doesn't revert when decreasing the allowance to a positive value", async function () { await this.mock.$safeDecreaseAllowance(this.token.address, constants.ZERO_ADDRESS, 50); }); diff --git a/test/token/ERC20/utils/TokenTimelock.test.js b/test/token/ERC20/utils/TokenTimelock.test.js index 4e0dc0a84..22e8071eb 100644 --- a/test/token/ERC20/utils/TokenTimelock.test.js +++ b/test/token/ERC20/utils/TokenTimelock.test.js @@ -6,7 +6,7 @@ const ERC20 = artifacts.require('$ERC20'); const TokenTimelock = artifacts.require('TokenTimelock'); contract('TokenTimelock', function (accounts) { - const [ beneficiary ] = accounts; + const [beneficiary] = accounts; const name = 'My Token'; const symbol = 'MTKN'; diff --git a/test/token/ERC721/ERC721.behavior.js b/test/token/ERC721/ERC721.behavior.js index 436841a25..c09479572 100644 --- a/test/token/ERC721/ERC721.behavior.js +++ b/test/token/ERC721/ERC721.behavior.js @@ -6,8 +6,10 @@ const { shouldSupportInterfaces } = require('../../utils/introspection/SupportsI const ERC721ReceiverMock = artifacts.require('ERC721ReceiverMock'); -const Error = [ 'None', 'RevertWithMessage', 'RevertWithoutMessage', 'Panic' ] - .reduce((acc, entry, idx) => Object.assign({ [entry]: idx }, acc), {}); +const Error = ['None', 'RevertWithMessage', 'RevertWithoutMessage', 'Panic'].reduce( + (acc, entry, idx) => Object.assign({ [entry]: idx }, acc), + {}, +); const firstTokenId = new BN('5042'); const secondTokenId = new BN('79217'); @@ -17,11 +19,8 @@ const baseURI = 'https://api.example.com/v1/'; const RECEIVER_MAGIC_VALUE = '0x150b7a02'; -function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, anotherApproved, operator, other) { - shouldSupportInterfaces([ - 'ERC165', - 'ERC721', - ]); +function shouldBehaveLikeERC721(errorPrefix, owner, newOwner, approved, anotherApproved, operator, other) { + shouldSupportInterfaces(['ERC165', 'ERC721']); context('with minted tokens', function () { beforeEach(async function () { @@ -45,9 +44,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('when querying the zero address', function () { it('throws', async function () { - await expectRevert( - this.token.balanceOf(ZERO_ADDRESS), 'ERC721: address zero is not a valid owner', - ); + await expectRevert(this.token.balanceOf(ZERO_ADDRESS), 'ERC721: address zero is not a valid owner'); }); }); }); @@ -65,9 +62,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another const tokenId = nonExistentTokenId; it('reverts', async function () { - await expectRevert( - this.token.ownerOf(tokenId), 'ERC721: invalid token ID', - ); + await expectRevert(this.token.ownerOf(tokenId), 'ERC721: invalid token ID'); }); }); }); @@ -112,21 +107,21 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another const shouldTransferTokensByUsers = function (transferFunction) { context('when called by the owner', function () { beforeEach(async function () { - (receipt = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: owner })); + receipt = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: owner }); }); transferWasSuccessful({ owner, tokenId, approved }); }); context('when called by the approved individual', function () { beforeEach(async function () { - (receipt = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: approved })); + receipt = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: approved }); }); transferWasSuccessful({ owner, tokenId, approved }); }); context('when called by the operator', function () { beforeEach(async function () { - (receipt = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: operator })); + receipt = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: operator }); }); transferWasSuccessful({ owner, tokenId, approved }); }); @@ -134,14 +129,14 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('when called by the owner without an approved user', function () { beforeEach(async function () { await this.token.approve(ZERO_ADDRESS, tokenId, { from: owner }); - (receipt = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: operator })); + receipt = await transferFunction.call(this, owner, this.toWhom, tokenId, { from: operator }); }); transferWasSuccessful({ owner, tokenId, approved: null }); }); context('when sent to the owner', function () { beforeEach(async function () { - (receipt = await transferFunction.call(this, owner, owner, tokenId, { from: owner })); + receipt = await transferFunction.call(this, owner, owner, tokenId, { from: owner }); }); it('keeps ownership of the token', async function () { @@ -166,12 +161,11 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another it('keeps same tokens by index', async function () { if (!this.token.tokenOfOwnerByIndex) return; - const tokensListed = await Promise.all( - [0, 1].map(i => this.token.tokenOfOwnerByIndex(owner, i)), - ); - expect(tokensListed.map(t => t.toNumber())).to.have.members( - [firstTokenId.toNumber(), secondTokenId.toNumber()], - ); + const tokensListed = await Promise.all([0, 1].map(i => this.token.tokenOfOwnerByIndex(owner, i))); + expect(tokensListed.map(t => t.toNumber())).to.have.members([ + firstTokenId.toNumber(), + secondTokenId.toNumber(), + ]); }); }); @@ -265,13 +259,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another describe('with an invalid token id', function () { it('reverts', async function () { await expectRevert( - transferFun.call( - this, - owner, - this.receiver.address, - nonExistentTokenId, - { from: owner }, - ), + transferFun.call(this, owner, this.receiver.address, nonExistentTokenId, { from: owner }), 'ERC721: invalid token ID', ); }); @@ -342,7 +330,8 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another const tokenId = fourthTokenId; const data = '0x42'; - describe('via safeMint', function () { // regular minting is tested in ERC721Mintable.test.js and others + 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); @@ -397,9 +386,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('to a receiver contract that panics', function () { it('reverts', async function () { const revertingReceiver = await ERC721ReceiverMock.new(RECEIVER_MAGIC_VALUE, Error.Panic); - await expectRevert.unspecified( - this.token.$_safeMint(revertingReceiver.address, tokenId), - ); + await expectRevert.unspecified(this.token.$_safeMint(revertingReceiver.address, tokenId)); }); }); @@ -445,7 +432,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('when clearing approval', function () { context('when there was no prior approval', function () { beforeEach(async function () { - (receipt = await this.token.approve(ZERO_ADDRESS, tokenId, { from: owner })); + receipt = await this.token.approve(ZERO_ADDRESS, tokenId, { from: owner }); }); itClearsApproval(); @@ -455,7 +442,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('when there was a prior approval', function () { beforeEach(async function () { await this.token.approve(approved, tokenId, { from: owner }); - (receipt = await this.token.approve(ZERO_ADDRESS, tokenId, { from: owner })); + receipt = await this.token.approve(ZERO_ADDRESS, tokenId, { from: owner }); }); itClearsApproval(); @@ -466,7 +453,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('when approving a non-zero address', function () { context('when there was no prior approval', function () { beforeEach(async function () { - (receipt = await this.token.approve(approved, tokenId, { from: owner })); + receipt = await this.token.approve(approved, tokenId, { from: owner }); }); itApproves(approved); @@ -476,7 +463,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('when there was a prior approval to the same address', function () { beforeEach(async function () { await this.token.approve(approved, tokenId, { from: owner }); - (receipt = await this.token.approve(approved, tokenId, { from: owner })); + receipt = await this.token.approve(approved, tokenId, { from: owner }); }); itApproves(approved); @@ -486,7 +473,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('when there was a prior approval to a different address', function () { beforeEach(async function () { await this.token.approve(anotherApproved, tokenId, { from: owner }); - (receipt = await this.token.approve(anotherApproved, tokenId, { from: owner })); + receipt = await this.token.approve(anotherApproved, tokenId, { from: owner }); }); itApproves(anotherApproved); @@ -496,31 +483,33 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('when the address that receives the approval is the owner', function () { it('reverts', async function () { - await expectRevert( - this.token.approve(owner, tokenId, { from: owner }), 'ERC721: approval to current owner', - ); + await expectRevert(this.token.approve(owner, tokenId, { from: owner }), 'ERC721: approval to current owner'); }); }); context('when the sender does not own the given token ID', function () { it('reverts', async function () { - await expectRevert(this.token.approve(approved, tokenId, { from: other }), - 'ERC721: approve caller is not token owner or approved'); + await expectRevert( + this.token.approve(approved, tokenId, { from: other }), + 'ERC721: approve caller is not token owner or approved', + ); }); }); context('when the sender is approved for the given token ID', function () { it('reverts', async function () { await this.token.approve(approved, tokenId, { from: owner }); - await expectRevert(this.token.approve(anotherApproved, tokenId, { from: approved }), - 'ERC721: approve caller is not token owner or approved for all'); + await expectRevert( + this.token.approve(anotherApproved, tokenId, { from: approved }), + 'ERC721: approve caller is not token owner or approved for all', + ); }); }); context('when the sender is an operator', function () { beforeEach(async function () { await this.token.setApprovalForAll(operator, true, { from: owner }); - (receipt = await this.token.approve(approved, tokenId, { from: operator })); + receipt = await this.token.approve(approved, tokenId, { from: operator }); }); itApproves(approved); @@ -529,8 +518,10 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('when the given token ID does not exist', function () { it('reverts', async function () { - await expectRevert(this.token.approve(approved, nonExistentTokenId, { from: operator }), - 'ERC721: invalid token ID'); + await expectRevert( + this.token.approve(approved, nonExistentTokenId, { from: operator }), + 'ERC721: invalid token ID', + ); }); }); }); @@ -608,8 +599,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another context('when the operator is the owner', function () { it('reverts', async function () { - await expectRevert(this.token.setApprovalForAll(owner, true, { from: owner }), - 'ERC721: approve to caller'); + await expectRevert(this.token.setApprovalForAll(owner, true, { from: owner }), 'ERC721: approve to caller'); }); }); }); @@ -617,18 +607,13 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another describe('getApproved', async function () { context('when token is not minted', async function () { it('reverts', async function () { - await expectRevert( - this.token.getApproved(nonExistentTokenId), - 'ERC721: invalid token ID', - ); + await expectRevert(this.token.getApproved(nonExistentTokenId), 'ERC721: invalid token ID'); }); }); context('when token has been minted ', async function () { it('should return the zero address', async function () { - expect(await this.token.getApproved(firstTokenId)).to.be.equal( - ZERO_ADDRESS, - ); + expect(await this.token.getApproved(firstTokenId)).to.be.equal(ZERO_ADDRESS); }); context('when account has been approved', async function () { @@ -646,14 +631,12 @@ 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', - ); + await expectRevert(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 () { @@ -673,9 +656,7 @@ 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', - ); + await expectRevert(this.token.$_burn(nonExistentTokenId), 'ERC721: invalid token ID'); }); context('with minted tokens', function () { @@ -686,7 +667,7 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another 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 () { @@ -695,25 +676,19 @@ function shouldBehaveLikeERC721 (errorPrefix, owner, newOwner, approved, another it('deletes the token', async function () { expect(await this.token.balanceOf(owner)).to.be.bignumber.equal('1'); - await expectRevert( - this.token.ownerOf(firstTokenId), 'ERC721: invalid token ID', - ); + await expectRevert(this.token.ownerOf(firstTokenId), 'ERC721: invalid token ID'); }); it('reverts when burning a token id that has been deleted', async function () { - await expectRevert( - this.token.$_burn(firstTokenId), 'ERC721: invalid token ID', - ); + await expectRevert(this.token.$_burn(firstTokenId), 'ERC721: invalid token ID'); }); }); }); }); } -function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approved, anotherApproved, operator, other) { - shouldSupportInterfaces([ - 'ERC721Enumerable', - ]); +function shouldBehaveLikeERC721Enumerable(errorPrefix, owner, newOwner, approved, anotherApproved, operator, other) { + shouldSupportInterfaces(['ERC721Enumerable']); context('with minted tokens', function () { beforeEach(async function () { @@ -737,17 +712,13 @@ function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approve describe('when the index is greater than or equal to the total tokens owned by the given address', function () { it('reverts', async function () { - await expectRevert( - this.token.tokenOfOwnerByIndex(owner, 2), 'ERC721Enumerable: owner index out of bounds', - ); + await expectRevert(this.token.tokenOfOwnerByIndex(owner, 2), 'ERC721Enumerable: owner index out of bounds'); }); }); describe('when the given address does not own any token', function () { it('reverts', async function () { - await expectRevert( - this.token.tokenOfOwnerByIndex(other, 0), 'ERC721Enumerable: owner index out of bounds', - ); + await expectRevert(this.token.tokenOfOwnerByIndex(other, 0), 'ERC721Enumerable: owner index out of bounds'); }); }); @@ -759,35 +730,31 @@ function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approve it('returns correct token IDs for target', async function () { expect(await this.token.balanceOf(other)).to.be.bignumber.equal('2'); - const tokensListed = await Promise.all( - [0, 1].map(i => this.token.tokenOfOwnerByIndex(other, i)), - ); - expect(tokensListed.map(t => t.toNumber())).to.have.members([firstTokenId.toNumber(), - secondTokenId.toNumber()]); + const tokensListed = await Promise.all([0, 1].map(i => this.token.tokenOfOwnerByIndex(other, i))); + expect(tokensListed.map(t => t.toNumber())).to.have.members([ + firstTokenId.toNumber(), + secondTokenId.toNumber(), + ]); }); it('returns empty collection for original owner', async function () { expect(await this.token.balanceOf(owner)).to.be.bignumber.equal('0'); - await expectRevert( - this.token.tokenOfOwnerByIndex(owner, 0), 'ERC721Enumerable: owner index out of bounds', - ); + await expectRevert(this.token.tokenOfOwnerByIndex(owner, 0), 'ERC721Enumerable: owner index out of bounds'); }); }); }); describe('tokenByIndex', function () { it('returns all tokens', async function () { - const tokensListed = await Promise.all( - [0, 1].map(i => this.token.tokenByIndex(i)), - ); - expect(tokensListed.map(t => t.toNumber())).to.have.members([firstTokenId.toNumber(), - secondTokenId.toNumber()]); + const tokensListed = await Promise.all([0, 1].map(i => this.token.tokenByIndex(i))); + expect(tokensListed.map(t => t.toNumber())).to.have.members([ + firstTokenId.toNumber(), + secondTokenId.toNumber(), + ]); }); it('reverts if index is greater than supply', async function () { - await expectRevert( - this.token.tokenByIndex(2), 'ERC721Enumerable: global index out of bounds', - ); + await expectRevert(this.token.tokenByIndex(2), 'ERC721Enumerable: global index out of bounds'); }); [firstTokenId, secondTokenId].forEach(function (tokenId) { @@ -801,11 +768,9 @@ function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approve expect(await this.token.totalSupply()).to.be.bignumber.equal('3'); - const tokensListed = await Promise.all( - [0, 1, 2].map(i => this.token.tokenByIndex(i)), - ); + const tokensListed = await Promise.all([0, 1, 2].map(i => this.token.tokenByIndex(i))); const expectedTokens = [firstTokenId, secondTokenId, newTokenId, anotherNewTokenId].filter( - x => (x !== tokenId), + x => x !== tokenId, ); expect(tokensListed.map(t => t.toNumber())).to.have.members(expectedTokens.map(t => t.toNumber())); }); @@ -815,14 +780,12 @@ 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', - ); + await expectRevert(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 () { @@ -837,9 +800,7 @@ 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', - ); + await expectRevert(this.token.$_burn(firstTokenId), 'ERC721: invalid token ID'); }); context('with minted tokens', function () { @@ -850,7 +811,7 @@ function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approve 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 () { @@ -864,19 +825,15 @@ function shouldBehaveLikeERC721Enumerable (errorPrefix, owner, newOwner, approve it('burns all tokens', async function () { 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', - ); + await expectRevert(this.token.tokenByIndex(0), 'ERC721Enumerable: global index out of bounds'); }); }); }); }); } -function shouldBehaveLikeERC721Metadata (errorPrefix, name, symbol, owner) { - shouldSupportInterfaces([ - 'ERC721Metadata', - ]); +function shouldBehaveLikeERC721Metadata(errorPrefix, name, symbol, owner) { + shouldSupportInterfaces(['ERC721Metadata']); describe('metadata', function () { it('has a name', async function () { @@ -897,9 +854,7 @@ function shouldBehaveLikeERC721Metadata (errorPrefix, name, symbol, owner) { }); it('reverts when queried for non existent token id', async function () { - await expectRevert( - this.token.tokenURI(nonExistentTokenId), 'ERC721: invalid token ID', - ); + await expectRevert(this.token.tokenURI(nonExistentTokenId), 'ERC721: invalid token ID'); }); describe('base URI', function () { diff --git a/test/token/ERC721/ERC721.test.js b/test/token/ERC721/ERC721.test.js index 6e72e02bd..312430cb9 100644 --- a/test/token/ERC721/ERC721.test.js +++ b/test/token/ERC721/ERC721.test.js @@ -1,7 +1,4 @@ -const { - shouldBehaveLikeERC721, - shouldBehaveLikeERC721Metadata, -} = require('./ERC721.behavior'); +const { shouldBehaveLikeERC721, shouldBehaveLikeERC721Metadata } = require('./ERC721.behavior'); const ERC721 = artifacts.require('$ERC721'); diff --git a/test/token/ERC721/extensions/ERC721Burnable.test.js b/test/token/ERC721/extensions/ERC721Burnable.test.js index 75a5603fb..6a4bc6dbc 100644 --- a/test/token/ERC721/extensions/ERC721Burnable.test.js +++ b/test/token/ERC721/extensions/ERC721Burnable.test.js @@ -34,10 +34,7 @@ contract('ERC721Burnable', function (accounts) { }); it('burns the given token ID and adjusts the balance of the owner', async function () { - await expectRevert( - this.token.ownerOf(tokenId), - 'ERC721: invalid token ID', - ); + await expectRevert(this.token.ownerOf(tokenId), 'ERC721: invalid token ID'); expect(await this.token.balanceOf(owner)).to.be.bignumber.equal('1'); }); @@ -58,18 +55,14 @@ contract('ERC721Burnable', function (accounts) { context('getApproved', function () { it('reverts', async function () { - await expectRevert( - this.token.getApproved(tokenId), 'ERC721: invalid token ID', - ); + await expectRevert(this.token.getApproved(tokenId), 'ERC721: invalid token ID'); }); }); }); describe('when the given token ID was not tracked by this contract', function () { it('reverts', async function () { - await expectRevert( - this.token.burn(unknownTokenId, { from: owner }), 'ERC721: invalid token ID', - ); + await expectRevert(this.token.burn(unknownTokenId, { from: owner }), 'ERC721: invalid token ID'); }); }); }); diff --git a/test/token/ERC721/extensions/ERC721Consecutive.test.js b/test/token/ERC721/extensions/ERC721Consecutive.test.js index 17df12ea1..3d4922846 100644 --- a/test/token/ERC721/extensions/ERC721Consecutive.test.js +++ b/test/token/ERC721/extensions/ERC721Consecutive.test.js @@ -6,7 +6,7 @@ const ERC721ConsecutiveEnumerableMock = artifacts.require('$ERC721ConsecutiveEnu const ERC721ConsecutiveNoConstructorMintMock = artifacts.require('$ERC721ConsecutiveNoConstructorMintMock'); contract('ERC721Consecutive', function (accounts) { - const [ user1, user2, user3, receiver ] = accounts; + const [user1, user2, user3, receiver] = accounts; const name = 'Non Fungible Token'; const symbol = 'NFT'; @@ -17,7 +17,7 @@ contract('ERC721Consecutive', function (accounts) { { receiver: user3, amount: 0 }, { receiver: user1, amount: 7 }, ]; - const delegates = [ user1, user3 ]; + const delegates = [user1, user3]; describe('with valid batches', function () { beforeEach(async function () { @@ -53,8 +53,7 @@ contract('ERC721Consecutive', function (accounts) { const owners = batches.flatMap(({ receiver, amount }) => Array(amount).fill(receiver)); for (const tokenId in owners) { - expect(await this.token.ownerOf(tokenId)) - .to.be.equal(owners[tokenId]); + expect(await this.token.ownerOf(tokenId)).to.be.equal(owners[tokenId]); } }); @@ -65,20 +64,17 @@ contract('ERC721Consecutive', function (accounts) { .map(({ amount }) => amount) .reduce((a, b) => a + b, 0); - expect(await this.token.balanceOf(account)) - .to.be.bignumber.equal(web3.utils.toBN(balance)); + expect(await this.token.balanceOf(account)).to.be.bignumber.equal(web3.utils.toBN(balance)); // If not delegated at construction, check before + do delegation if (!delegates.includes(account)) { - expect(await this.token.getVotes(account)) - .to.be.bignumber.equal(web3.utils.toBN(0)); + expect(await this.token.getVotes(account)).to.be.bignumber.equal(web3.utils.toBN(0)); await this.token.delegate(account, { from: account }); } // At this point all accounts should have delegated - expect(await this.token.getVotes(account)) - .to.be.bignumber.equal(web3.utils.toBN(balance)); + expect(await this.token.getVotes(account)).to.be.bignumber.equal(web3.utils.toBN(balance)); } }); }); @@ -96,11 +92,11 @@ contract('ERC721Consecutive', function (accounts) { expect(await this.token.$_exists(tokenId)).to.be.equal(false); - expectEvent( - await this.token.$_mint(user1, tokenId), - 'Transfer', - { from: constants.ZERO_ADDRESS, to: user1, tokenId: tokenId.toString() }, - ); + expectEvent(await this.token.$_mint(user1, tokenId), 'Transfer', { + from: constants.ZERO_ADDRESS, + to: user1, + tokenId: tokenId.toString(), + }); }); it('cannot mint a token that has been batched minted', async function () { @@ -108,10 +104,7 @@ contract('ERC721Consecutive', function (accounts) { expect(await this.token.$_exists(tokenId)).to.be.equal(true); - await expectRevert( - this.token.$_mint(user1, tokenId), - 'ERC721: token already minted', - ); + await expectRevert(this.token.$_mint(user1, tokenId), 'ERC721: token already minted'); }); }); @@ -123,19 +116,19 @@ contract('ERC721Consecutive', function (accounts) { }); it('tokens can be burned and re-minted #1', async function () { - expectEvent( - await this.token.$_burn(1, { from: user1 }), - 'Transfer', - { from: user1, to: constants.ZERO_ADDRESS, tokenId: '1' }, - ); + expectEvent(await this.token.$_burn(1, { from: user1 }), 'Transfer', { + from: user1, + to: constants.ZERO_ADDRESS, + tokenId: '1', + }); await expectRevert(this.token.ownerOf(1), 'ERC721: invalid token ID'); - expectEvent( - await this.token.$_mint(user2, 1), - 'Transfer', - { from: constants.ZERO_ADDRESS, to: user2, tokenId: '1' }, - ); + expectEvent(await this.token.$_mint(user2, 1), 'Transfer', { + from: constants.ZERO_ADDRESS, + to: user2, + tokenId: '1', + }); expect(await this.token.ownerOf(1)).to.be.equal(user2); }); @@ -153,21 +146,21 @@ contract('ERC721Consecutive', function (accounts) { expect(await this.token.ownerOf(tokenId), user1); // burn - expectEvent( - await this.token.$_burn(tokenId, { from: user1 }), - 'Transfer', - { from: user1, to: constants.ZERO_ADDRESS, tokenId }, - ); + expectEvent(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); await expectRevert(this.token.ownerOf(tokenId), 'ERC721: invalid token ID'); // re-mint - expectEvent( - await this.token.$_mint(user2, tokenId), - 'Transfer', - { from: constants.ZERO_ADDRESS, to: user2, tokenId }, - ); + expectEvent(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.ownerOf(tokenId), user2); @@ -178,34 +171,22 @@ contract('ERC721Consecutive', function (accounts) { describe('invalid use', function () { it('cannot mint a batch larger than 5000', async function () { await expectRevert( - ERC721ConsecutiveMock.new( - name, - symbol, - [], - [user1], - ['5001'], - ), + ERC721ConsecutiveMock.new(name, symbol, [], [user1], ['5001']), 'ERC721Consecutive: batch too large', ); }); it('cannot use single minting during construction', async function () { await expectRevert( - ERC721ConsecutiveNoConstructorMintMock.new( - name, - symbol, - ), - 'ERC721Consecutive: can\'t mint during construction', + ERC721ConsecutiveNoConstructorMintMock.new(name, symbol), + "ERC721Consecutive: can't mint during construction", ); }); it('cannot use single minting during construction', async function () { await expectRevert( - ERC721ConsecutiveNoConstructorMintMock.new( - name, - symbol, - ), - 'ERC721Consecutive: can\'t mint during construction', + ERC721ConsecutiveNoConstructorMintMock.new(name, symbol), + "ERC721Consecutive: can't mint during construction", ); }); diff --git a/test/token/ERC721/extensions/ERC721Pausable.test.js b/test/token/ERC721/extensions/ERC721Pausable.test.js index 04dd520a3..c7fc8233f 100644 --- a/test/token/ERC721/extensions/ERC721Pausable.test.js +++ b/test/token/ERC721/extensions/ERC721Pausable.test.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const ERC721Pausable = artifacts.require('$ERC721Pausable'); contract('ERC721Pausable', function (accounts) { - const [ owner, receiver, operator ] = accounts; + const [owner, receiver, operator] = accounts; const name = 'Non Fungible Token'; const symbol = 'NFT'; @@ -41,24 +41,19 @@ contract('ERC721Pausable', function (accounts) { it('reverts when trying to safeTransferFrom with data', async function () { await expectRevert( - this.token.methods['safeTransferFrom(address,address,uint256,bytes)']( - owner, receiver, firstTokenId, mockData, { from: owner }, - ), 'ERC721Pausable: token transfer while paused', + this.token.methods['safeTransferFrom(address,address,uint256,bytes)'](owner, receiver, firstTokenId, mockData, { + from: owner, + }), + 'ERC721Pausable: token transfer while paused', ); }); it('reverts when trying to mint', async function () { - await expectRevert( - this.token.$_mint(receiver, secondTokenId), - 'ERC721Pausable: token transfer while paused', - ); + await expectRevert(this.token.$_mint(receiver, secondTokenId), 'ERC721Pausable: token transfer while paused'); }); it('reverts when trying to burn', async function () { - await expectRevert( - this.token.$_burn(firstTokenId), - 'ERC721Pausable: token transfer while paused', - ); + await expectRevert(this.token.$_burn(firstTokenId), 'ERC721Pausable: token transfer while paused'); }); describe('getApproved', function () { diff --git a/test/token/ERC721/extensions/ERC721Royalty.test.js b/test/token/ERC721/extensions/ERC721Royalty.test.js index 9d38071e3..1c0536bf5 100644 --- a/test/token/ERC721/extensions/ERC721Royalty.test.js +++ b/test/token/ERC721/extensions/ERC721Royalty.test.js @@ -5,7 +5,7 @@ const { shouldBehaveLikeERC2981 } = require('../../common/ERC2981.behavior'); const ERC721Royalty = artifacts.require('$ERC721Royalty'); contract('ERC721Royalty', function (accounts) { - const [ account1, account2 ] = accounts; + const [account1, account2] = accounts; const tokenId1 = new BN('1'); const tokenId2 = new BN('2'); const royalty = new BN('200'); diff --git a/test/token/ERC721/extensions/ERC721URIStorage.test.js b/test/token/ERC721/extensions/ERC721URIStorage.test.js index a27b5f658..c0274c669 100644 --- a/test/token/ERC721/extensions/ERC721URIStorage.test.js +++ b/test/token/ERC721/extensions/ERC721URIStorage.test.js @@ -5,7 +5,7 @@ const { expect } = require('chai'); const ERC721URIStorageMock = artifacts.require('$ERC721URIStorageMock'); contract('ERC721URIStorage', function (accounts) { - const [ owner ] = accounts; + const [owner] = accounts; const name = 'Non Fungible Token'; const symbol = 'NFT'; @@ -30,9 +30,7 @@ contract('ERC721URIStorage', function (accounts) { }); it('reverts when queried for non existent token id', async function () { - await expectRevert( - this.token.tokenURI(nonExistentTokenId), 'ERC721: invalid token ID', - ); + await expectRevert(this.token.tokenURI(nonExistentTokenId), 'ERC721: invalid token ID'); }); it('can be set for a token id', async function () { @@ -42,7 +40,8 @@ contract('ERC721URIStorage', function (accounts) { 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', ); }); @@ -77,9 +76,7 @@ contract('ERC721URIStorage', function (accounts) { await this.token.$_burn(firstTokenId, { from: owner }); expect(await this.token.$_exists(firstTokenId)).to.equal(false); - await expectRevert( - this.token.tokenURI(firstTokenId), 'ERC721: invalid token ID', - ); + await expectRevert(this.token.tokenURI(firstTokenId), 'ERC721: invalid token ID'); }); it('tokens with URI can be burnt ', async function () { @@ -88,9 +85,7 @@ contract('ERC721URIStorage', function (accounts) { await this.token.$_burn(firstTokenId, { from: owner }); expect(await this.token.$_exists(firstTokenId)).to.equal(false); - await expectRevert( - this.token.tokenURI(firstTokenId), 'ERC721: invalid token ID', - ); + 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 8d9cb701e..f7baef4c1 100644 --- a/test/token/ERC721/extensions/ERC721Votes.test.js +++ b/test/token/ERC721/extensions/ERC721Votes.test.js @@ -10,7 +10,7 @@ const { shouldBehaveLikeVotes } = require('../../../governance/utils/Votes.behav const ERC721Votes = artifacts.require('$ERC721Votes'); contract('ERC721Votes', function (accounts) { - const [ account1, account2, account1Delegatee, other1, other2 ] = accounts; + const [account1, account2, account1Delegatee, other1, other2] = accounts; const name = 'My Vote'; const symbol = 'MTKN'; @@ -18,7 +18,7 @@ contract('ERC721Votes', function (accounts) { beforeEach(async function () { this.chainId = await getChainId(); - this.votes = await ERC721Votes.new(name, symbol, name, "1"); + this.votes = await ERC721Votes.new(name, symbol, name, '1'); this.NFT0 = new BN('10000000000000000000000000'); this.NFT1 = new BN('10'); @@ -61,7 +61,11 @@ contract('ERC721Votes', function (accounts) { expectEvent(receipt, 'DelegateVotesChanged', { delegate: account1, previousBalance: '1', newBalance: '0' }); const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); + expect( + receipt.logs + .filter(({ event }) => event == 'DelegateVotesChanged') + .every(({ logIndex }) => transferLogIndex < logIndex), + ).to.be.equal(true); this.account1Votes = '0'; this.account2Votes = '0'; @@ -75,7 +79,11 @@ contract('ERC721Votes', function (accounts) { expectEvent(receipt, 'DelegateVotesChanged', { delegate: account2, previousBalance: '0', newBalance: '1' }); const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); + expect( + receipt.logs + .filter(({ event }) => event == 'DelegateVotesChanged') + .every(({ logIndex }) => transferLogIndex < logIndex), + ).to.be.equal(true); this.account1Votes = '0'; this.account2Votes = '1'; @@ -87,11 +95,15 @@ contract('ERC721Votes', function (accounts) { const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); expectEvent(receipt, 'Transfer', { from: account1, to: account2, tokenId: this.NFT0 }); - expectEvent(receipt, 'DelegateVotesChanged', { delegate: account1, previousBalance: '1', newBalance: '0'}); + expectEvent(receipt, 'DelegateVotesChanged', { delegate: account1, previousBalance: '1', newBalance: '0' }); expectEvent(receipt, 'DelegateVotesChanged', { delegate: account2, previousBalance: '0', newBalance: '1' }); const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); - expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); + expect( + receipt.logs + .filter(({ event }) => event == 'DelegateVotesChanged') + .every(({ logIndex }) => transferLogIndex < logIndex), + ).to.be.equal(true); this.account1Votes = '0'; this.account2Votes = '1'; diff --git a/test/token/ERC721/presets/ERC721PresetMinterPauserAutoId.test.js b/test/token/ERC721/presets/ERC721PresetMinterPauserAutoId.test.js index 4ad73552a..0af614bd1 100644 --- a/test/token/ERC721/presets/ERC721PresetMinterPauserAutoId.test.js +++ b/test/token/ERC721/presets/ERC721PresetMinterPauserAutoId.test.js @@ -7,7 +7,7 @@ const { expect } = require('chai'); const ERC721PresetMinterPauserAutoId = artifacts.require('ERC721PresetMinterPauserAutoId'); contract('ERC721PresetMinterPauserAutoId', function (accounts) { - const [ deployer, other ] = accounts; + const [deployer, other] = accounts; const name = 'MinterAutoIDToken'; const symbol = 'MAIT'; @@ -85,10 +85,7 @@ contract('ERC721PresetMinterPauserAutoId', function (accounts) { it('cannot mint while paused', async function () { await this.token.pause({ from: deployer }); - await expectRevert( - this.token.mint(other, { from: deployer }), - 'ERC721Pausable: token transfer while paused', - ); + await expectRevert(this.token.mint(other, { from: deployer }), 'ERC721Pausable: token transfer while paused'); }); it('other accounts cannot pause', async function () { diff --git a/test/token/ERC721/utils/ERC721Holder.test.js b/test/token/ERC721/utils/ERC721Holder.test.js index e821f32dd..0fd822280 100644 --- a/test/token/ERC721/utils/ERC721Holder.test.js +++ b/test/token/ERC721/utils/ERC721Holder.test.js @@ -4,7 +4,7 @@ const ERC721Holder = artifacts.require('ERC721Holder'); const ERC721 = artifacts.require('$ERC721'); contract('ERC721Holder', function (accounts) { - const [ owner ] = accounts; + const [owner] = accounts; const name = 'Non Fungible Token'; const symbol = 'NFT'; diff --git a/test/token/ERC777/ERC777.behavior.js b/test/token/ERC777/ERC777.behavior.js index be104f467..b1585bc91 100644 --- a/test/token/ERC777/ERC777.behavior.js +++ b/test/token/ERC777/ERC777.behavior.js @@ -5,22 +5,22 @@ const { expect } = require('chai'); const ERC777SenderRecipientMock = artifacts.require('ERC777SenderRecipientMock'); -function shouldBehaveLikeERC777DirectSendBurn (holder, recipient, data) { +function shouldBehaveLikeERC777DirectSendBurn(holder, recipient, data) { shouldBehaveLikeERC777DirectSend(holder, recipient, data); shouldBehaveLikeERC777DirectBurn(holder, data); } -function shouldBehaveLikeERC777OperatorSendBurn (holder, recipient, operator, data, operatorData) { +function shouldBehaveLikeERC777OperatorSendBurn(holder, recipient, operator, data, operatorData) { shouldBehaveLikeERC777OperatorSend(holder, recipient, operator, data, operatorData); shouldBehaveLikeERC777OperatorBurn(holder, operator, data, operatorData); } -function shouldBehaveLikeERC777UnauthorizedOperatorSendBurn (holder, recipient, operator, data, operatorData) { +function shouldBehaveLikeERC777UnauthorizedOperatorSendBurn(holder, recipient, operator, data, operatorData) { shouldBehaveLikeERC777UnauthorizedOperatorSend(holder, recipient, operator, data, operatorData); shouldBehaveLikeERC777UnauthorizedOperatorBurn(holder, operator, data, operatorData); } -function shouldBehaveLikeERC777DirectSend (holder, recipient, data) { +function shouldBehaveLikeERC777DirectSend(holder, recipient, data) { describe('direct send', function () { context('when the sender has tokens', function () { shouldDirectSendTokens(holder, recipient, new BN('0'), data); @@ -48,7 +48,7 @@ function shouldBehaveLikeERC777DirectSend (holder, recipient, data) { }); } -function shouldBehaveLikeERC777OperatorSend (holder, recipient, operator, data, operatorData) { +function shouldBehaveLikeERC777OperatorSend(holder, recipient, operator, data, operatorData) { describe('operator send', function () { context('when the sender has tokens', async function () { shouldOperatorSendTokens(holder, operator, recipient, new BN('0'), data, operatorData); @@ -63,9 +63,7 @@ function shouldBehaveLikeERC777OperatorSend (holder, recipient, operator, data, it('reverts when sending to the zero address', async function () { await expectRevert.unspecified( - this.token.operatorSend( - holder, ZERO_ADDRESS, new BN('1'), data, operatorData, { from: operator }, - ), + this.token.operatorSend(holder, ZERO_ADDRESS, new BN('1'), data, operatorData, { from: operator }), ); }); }); @@ -84,16 +82,14 @@ function shouldBehaveLikeERC777OperatorSend (holder, recipient, operator, data, it('reverts when sending from the zero address', async function () { // This is not yet reflected in the spec await expectRevert.unspecified( - this.token.operatorSend( - ZERO_ADDRESS, recipient, new BN('0'), data, operatorData, { from: operator }, - ), + this.token.operatorSend(ZERO_ADDRESS, recipient, new BN('0'), data, operatorData, { from: operator }), ); }); }); }); } -function shouldBehaveLikeERC777UnauthorizedOperatorSend (holder, recipient, operator, data, operatorData) { +function shouldBehaveLikeERC777UnauthorizedOperatorSend(holder, recipient, operator, data, operatorData) { describe('operator send', function () { it('reverts', async function () { await expectRevert.unspecified(this.token.operatorSend(holder, recipient, new BN('0'), data, operatorData)); @@ -101,7 +97,7 @@ function shouldBehaveLikeERC777UnauthorizedOperatorSend (holder, recipient, oper }); } -function shouldBehaveLikeERC777DirectBurn (holder, data) { +function shouldBehaveLikeERC777DirectBurn(holder, data) { describe('direct burn', function () { context('when the sender has tokens', function () { shouldDirectBurnTokens(holder, new BN('0'), data); @@ -125,7 +121,7 @@ function shouldBehaveLikeERC777DirectBurn (holder, data) { }); } -function shouldBehaveLikeERC777OperatorBurn (holder, operator, data, operatorData) { +function shouldBehaveLikeERC777OperatorBurn(holder, operator, data, operatorData) { describe('operator burn', function () { context('when the sender has tokens', async function () { shouldOperatorBurnTokens(holder, operator, new BN('0'), data, operatorData); @@ -153,16 +149,14 @@ function shouldBehaveLikeERC777OperatorBurn (holder, operator, data, operatorDat it('reverts when burning from the zero address', async function () { // This is not yet reflected in the spec await expectRevert.unspecified( - this.token.operatorBurn( - ZERO_ADDRESS, new BN('0'), data, operatorData, { from: operator }, - ), + this.token.operatorBurn(ZERO_ADDRESS, new BN('0'), data, operatorData, { from: operator }), ); }); }); }); } -function shouldBehaveLikeERC777UnauthorizedOperatorBurn (holder, operator, data, operatorData) { +function shouldBehaveLikeERC777UnauthorizedOperatorBurn(holder, operator, data, operatorData) { describe('operator burn', function () { it('reverts', async function () { await expectRevert.unspecified(this.token.operatorBurn(holder, new BN('0'), data, operatorData)); @@ -170,15 +164,15 @@ function shouldBehaveLikeERC777UnauthorizedOperatorBurn (holder, operator, data, }); } -function shouldDirectSendTokens (from, to, amount, data) { +function shouldDirectSendTokens(from, to, amount, data) { shouldSendTokens(from, null, to, amount, data, null); } -function shouldOperatorSendTokens (from, operator, to, amount, data, operatorData) { +function shouldOperatorSendTokens(from, operator, to, amount, data, operatorData) { shouldSendTokens(from, operator, to, amount, data, operatorData); } -function shouldSendTokens (from, operator, to, amount, data, operatorData) { +function shouldSendTokens(from, operator, to, amount, data, operatorData) { const operatorCall = operator !== null; it(`${operatorCall ? 'operator ' : ''}can send an amount of ${amount}`, async function () { @@ -188,7 +182,7 @@ function shouldSendTokens (from, operator, to, amount, data, operatorData) { let receipt; if (!operatorCall) { - (receipt = await this.token.send(to, amount, data, { from })); + receipt = await this.token.send(to, amount, data, { from }); expectEvent(receipt, 'Sent', { operator: from, from, @@ -198,7 +192,7 @@ function shouldSendTokens (from, operator, to, amount, data, operatorData) { operatorData: null, }); } else { - (receipt = await this.token.operatorSend(from, to, amount, data, operatorData, { from: operator })); + receipt = await this.token.operatorSend(from, to, amount, data, operatorData, { from: operator }); expectEvent(receipt, 'Sent', { operator, from, @@ -225,15 +219,15 @@ function shouldSendTokens (from, operator, to, amount, data, operatorData) { }); } -function shouldDirectBurnTokens (from, amount, data) { +function shouldDirectBurnTokens(from, amount, data) { shouldBurnTokens(from, null, amount, data, null); } -function shouldOperatorBurnTokens (from, operator, amount, data, operatorData) { +function shouldOperatorBurnTokens(from, operator, amount, data, operatorData) { shouldBurnTokens(from, operator, amount, data, operatorData); } -function shouldBurnTokens (from, operator, amount, data, operatorData) { +function shouldBurnTokens(from, operator, amount, data, operatorData) { const operatorCall = operator !== null; it(`${operatorCall ? 'operator ' : ''}can burn an amount of ${amount}`, async function () { @@ -242,7 +236,7 @@ function shouldBurnTokens (from, operator, amount, data, operatorData) { let receipt; if (!operatorCall) { - (receipt = await this.token.burn(amount, data, { from })); + receipt = await this.token.burn(amount, data, { from }); expectEvent(receipt, 'Burned', { operator: from, from, @@ -251,7 +245,7 @@ function shouldBurnTokens (from, operator, amount, data, operatorData) { operatorData: null, }); } else { - (receipt = await this.token.operatorBurn(from, amount, data, operatorData, { from: operator })); + receipt = await this.token.operatorBurn(from, amount, data, operatorData, { from: operator }); expectEvent(receipt, 'Burned', { operator, from, @@ -275,7 +269,7 @@ function shouldBurnTokens (from, operator, amount, data, operatorData) { }); } -function shouldBehaveLikeERC777InternalMint (recipient, operator, amount, data, operatorData) { +function shouldBehaveLikeERC777InternalMint(recipient, operator, amount, data, operatorData) { shouldInternalMintTokens(operator, recipient, new BN('0'), data, operatorData); shouldInternalMintTokens(operator, recipient, amount, data, operatorData); @@ -286,7 +280,7 @@ function shouldBehaveLikeERC777InternalMint (recipient, operator, amount, data, }); } -function shouldInternalMintTokens (operator, to, amount, data, operatorData) { +function shouldInternalMintTokens(operator, to, amount, data, operatorData) { it(`can (internal) mint an amount of ${amount}`, async function () { const initialTotalSupply = await this.token.totalSupply(); const initialToBalance = await this.token.balanceOf(to); @@ -315,7 +309,7 @@ function shouldInternalMintTokens (operator, to, amount, data, operatorData) { }); } -function shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook (operator, amount, data, operatorData) { +function shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook(operator, amount, data, operatorData) { context('when TokensRecipient reverts', function () { beforeEach(async function () { await this.tokensRecipientImplementer.setShouldRevertReceive(true); @@ -364,10 +358,9 @@ function shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook (operator, am }); it('TokensRecipient receives operatorSend data and is called after state mutation', async function () { - const { tx } = await this.token.operatorSend( - this.sender, this.recipient, amount, data, operatorData, - { from: operator }, - ); + const { tx } = await this.token.operatorSend(this.sender, this.recipient, amount, data, operatorData, { + from: operator, + }); const postSenderBalance = await this.token.balanceOf(this.sender); const postRecipientBalance = await this.token.balanceOf(this.recipient); @@ -407,7 +400,7 @@ function shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook (operator, am }); } -function shouldBehaveLikeERC777SendBurnWithSendHook (operator, amount, data, operatorData) { +function shouldBehaveLikeERC777SendBurnWithSendHook(operator, amount, data, operatorData) { context('when TokensSender reverts', function () { beforeEach(async function () { await this.tokensSenderImplementer.setShouldRevertSend(true); @@ -463,10 +456,9 @@ function shouldBehaveLikeERC777SendBurnWithSendHook (operator, amount, data, ope const preSenderBalance = await this.token.balanceOf(this.sender); const preRecipientBalance = await this.token.balanceOf(this.recipient); - const { tx } = await this.token.operatorSend( - this.sender, this.recipient, amount, data, operatorData, - { from: operator }, - ); + const { tx } = await this.token.operatorSend(this.sender, this.recipient, amount, data, operatorData, { + from: operator, + }); await assertTokensToSendCalled( this.token, @@ -488,7 +480,15 @@ function shouldBehaveLikeERC777SendBurnWithSendHook (operator, amount, data, ope const { tx } = await burnFromHolder(this.token, this.sender, amount, data, { from: this.sender }); await assertTokensToSendCalled( - this.token, tx, this.sender, this.sender, ZERO_ADDRESS, amount, data, null, preSenderBalance, + this.token, + tx, + this.sender, + this.sender, + ZERO_ADDRESS, + amount, + data, + null, + preSenderBalance, ); }); @@ -498,34 +498,78 @@ function shouldBehaveLikeERC777SendBurnWithSendHook (operator, amount, data, ope const { tx } = await this.token.operatorBurn(this.sender, amount, data, operatorData, { from: operator }); await assertTokensToSendCalled( - this.token, tx, operator, this.sender, ZERO_ADDRESS, amount, data, operatorData, preSenderBalance, + this.token, + tx, + operator, + this.sender, + ZERO_ADDRESS, + amount, + data, + operatorData, + preSenderBalance, ); }); }); } -function removeBalance (holder) { +function removeBalance(holder) { beforeEach(async function () { await this.token.burn(await this.token.balanceOf(holder), '0x', { from: holder }); expect(await this.token.balanceOf(holder)).to.be.bignumber.equal('0'); }); } -async function assertTokensReceivedCalled (token, txHash, operator, from, to, amount, data, operatorData, fromBalance, - toBalance = '0') { +async function assertTokensReceivedCalled( + token, + txHash, + operator, + from, + to, + amount, + data, + operatorData, + fromBalance, + toBalance = '0', +) { await expectEvent.inTransaction(txHash, ERC777SenderRecipientMock, 'TokensReceivedCalled', { - operator, from, to, amount, data, operatorData, token: token.address, fromBalance, toBalance, + operator, + from, + to, + amount, + data, + operatorData, + token: token.address, + fromBalance, + toBalance, }); } -async function assertTokensToSendCalled (token, txHash, operator, from, to, amount, data, operatorData, fromBalance, - toBalance = '0') { +async function assertTokensToSendCalled( + token, + txHash, + operator, + from, + to, + amount, + data, + operatorData, + fromBalance, + toBalance = '0', +) { await expectEvent.inTransaction(txHash, ERC777SenderRecipientMock, 'TokensToSendCalled', { - operator, from, to, amount, data, operatorData, token: token.address, fromBalance, toBalance, + operator, + from, + to, + amount, + data, + operatorData, + token: token.address, + fromBalance, + toBalance, }); } -async function sendFromHolder (token, holder, to, amount, data) { +async function sendFromHolder(token, holder, to, amount, data) { if ((await web3.eth.getCode(holder)).length <= '0x'.length) { return token.send(to, amount, data, { from: holder }); } else { @@ -534,7 +578,7 @@ async function sendFromHolder (token, holder, to, amount, data) { } } -async function burnFromHolder (token, holder, amount, data) { +async function burnFromHolder(token, holder, amount, data) { if ((await web3.eth.getCode(holder)).length <= '0x'.length) { return token.burn(amount, data, { from: holder }); } else { diff --git a/test/token/ERC777/ERC777.test.js b/test/token/ERC777/ERC777.test.js index efb8eae43..44bc25351 100644 --- a/test/token/ERC777/ERC777.test.js +++ b/test/token/ERC777/ERC777.test.js @@ -12,16 +12,13 @@ const { shouldBehaveLikeERC777SendBurnWithSendHook, } = require('./ERC777.behavior'); -const { - shouldBehaveLikeERC20, - shouldBehaveLikeERC20Approve, -} = require('../ERC20/ERC20.behavior'); +const { shouldBehaveLikeERC20, shouldBehaveLikeERC20Approve } = require('../ERC20/ERC20.behavior'); const ERC777 = artifacts.require('$ERC777Mock'); const ERC777SenderRecipientMock = artifacts.require('$ERC777SenderRecipientMock'); contract('ERC777', function (accounts) { - const [ registryFunder, holder, defaultOperatorA, defaultOperatorB, newOperator, anyone ] = accounts; + const [registryFunder, holder, defaultOperatorA, defaultOperatorB, newOperator, anyone] = accounts; const initialSupply = new BN('10000'); const name = 'ERC777Test'; @@ -51,7 +48,8 @@ contract('ERC777', function (accounts) { describe('when the owner is the zero address', function () { it('reverts', async function () { - await expectRevert(this.token.$_approve(ZERO_ADDRESS, anyone, initialSupply), + await expectRevert( + this.token.$_approve(ZERO_ADDRESS, anyone, initialSupply), 'ERC777: approve from the zero address', ); }); @@ -95,13 +93,15 @@ contract('ERC777', function (accounts) { }); it('the ERC777Token interface is registered in the registry', async function () { - expect(await this.erc1820.getInterfaceImplementer(this.token.address, web3.utils.soliditySha3('ERC777Token'))) - .to.equal(this.token.address); + expect( + await this.erc1820.getInterfaceImplementer(this.token.address, web3.utils.soliditySha3('ERC777Token')), + ).to.equal(this.token.address); }); it('the ERC20Token interface is registered in the registry', async function () { - expect(await this.erc1820.getInterfaceImplementer(this.token.address, web3.utils.soliditySha3('ERC20Token'))) - .to.equal(this.token.address); + expect( + await this.erc1820.getInterfaceImplementer(this.token.address, web3.utils.soliditySha3('ERC20Token')), + ).to.equal(this.token.address); }); }); @@ -185,25 +185,11 @@ contract('ERC777', function (accounts) { const operator = defaultOperatorA; it('without requireReceptionAck', async function () { - await this.token.$_mint( - this.recipient, - amount, - data, - operatorData, - false, - { from: operator }, - ); + await this.token.$_mint(this.recipient, amount, data, operatorData, false, { from: operator }); }); it('with requireReceptionAck', async function () { - await this.token.$_mint( - this.recipient, - amount, - data, - operatorData, - true, - { from: operator }, - ); + await this.token.$_mint(this.recipient, amount, data, operatorData, true, { from: operator }); }); }); @@ -211,25 +197,11 @@ contract('ERC777', function (accounts) { const operator = newOperator; it('without requireReceptionAck', async function () { - await this.token.$_mint( - this.recipient, - amount, - data, - operatorData, - false, - { from: operator }, - ); + await this.token.$_mint(this.recipient, amount, data, operatorData, false, { from: operator }); }); it('with requireReceptionAck', async function () { - await this.token.$_mint( - this.recipient, - amount, - data, - operatorData, - true, - { from: operator }, - ); + await this.token.$_mint(this.recipient, amount, data, operatorData, true, { from: operator }); }); }); }); @@ -244,26 +216,12 @@ contract('ERC777', function (accounts) { const operator = defaultOperatorA; it('without requireReceptionAck', async function () { - await this.token.$_mint( - this.recipient, - amount, - data, - operatorData, - false, - { from: operator }, - ); + await this.token.$_mint(this.recipient, amount, data, operatorData, false, { from: operator }); }); it('with requireReceptionAck', async function () { await expectRevert( - this.token.$_mint( - this.recipient, - amount, - data, - operatorData, - true, - { from: operator }, - ), + this.token.$_mint(this.recipient, amount, data, operatorData, true, { from: operator }), 'ERC777: token recipient contract has no implementer for ERC777TokensRecipient', ); }); @@ -273,26 +231,12 @@ contract('ERC777', function (accounts) { const operator = newOperator; it('without requireReceptionAck', async function () { - await this.token.$_mint( - this.recipient, - amount, - data, - operatorData, - false, - { from: operator }, - ); + await this.token.$_mint(this.recipient, amount, data, operatorData, false, { from: operator }); }); it('with requireReceptionAck', async function () { await expectRevert( - this.token.$_mint( - this.recipient, - amount, - data, - operatorData, - true, - { from: operator }, - ), + this.token.$_mint(this.recipient, amount, data, operatorData, true, { from: operator }), 'ERC777: token recipient contract has no implementer for ERC777TokensRecipient', ); }); @@ -308,14 +252,13 @@ contract('ERC777', function (accounts) { it('reverts when self-authorizing', async function () { await expectRevert( - this.token.authorizeOperator(holder, { from: holder }), 'ERC777: authorizing self as operator', + this.token.authorizeOperator(holder, { from: holder }), + 'ERC777: authorizing self as operator', ); }); it('reverts when self-revoking', async function () { - await expectRevert( - this.token.revokeOperator(holder, { from: holder }), 'ERC777: revoking self as operator', - ); + await expectRevert(this.token.revokeOperator(holder, { from: holder }), 'ERC777: revoking self as operator'); }); it('non-operators can be revoked', async function () { @@ -471,7 +414,8 @@ contract('ERC777', function (accounts) { await this.erc1820.setInterfaceImplementer( this.recipient, - web3.utils.soliditySha3('ERC777TokensRecipient'), this.tokensRecipientImplementer.address, + web3.utils.soliditySha3('ERC777TokensRecipient'), + this.tokensRecipientImplementer.address, { from: this.recipient }, ); }); @@ -519,7 +463,8 @@ contract('ERC777', function (accounts) { await this.erc1820.setInterfaceImplementer( this.sender, - web3.utils.soliditySha3('ERC777TokensSender'), this.tokensSenderImplementer.address, + web3.utils.soliditySha3('ERC777TokensSender'), + this.tokensSenderImplementer.address, { from: this.sender }, ); }); diff --git a/test/token/common/ERC2981.behavior.js b/test/token/common/ERC2981.behavior.js index aea5e52f0..5d0f67715 100644 --- a/test/token/common/ERC2981.behavior.js +++ b/test/token/common/ERC2981.behavior.js @@ -4,7 +4,7 @@ const { ZERO_ADDRESS } = constants; const { shouldSupportInterfaces } = require('../../utils/introspection/SupportsInterface.behavior'); -function shouldBehaveLikeERC2981 () { +function shouldBehaveLikeERC2981() { const royaltyFraction = new BN('10'); shouldSupportInterfaces(['ERC2981']); @@ -60,10 +60,7 @@ function shouldBehaveLikeERC2981 () { }); it('reverts if invalid parameters', async function () { - await expectRevert( - this.token.$_setDefaultRoyalty(ZERO_ADDRESS, royaltyFraction), - 'ERC2981: invalid receiver', - ); + await expectRevert(this.token.$_setDefaultRoyalty(ZERO_ADDRESS, royaltyFraction), 'ERC2981: invalid receiver'); await expectRevert( this.token.$_setDefaultRoyalty(this.account1, new BN('11000')), diff --git a/test/utils/Address.test.js b/test/utils/Address.test.js index 135a7f96d..a78ae14e6 100644 --- a/test/utils/Address.test.js +++ b/test/utils/Address.test.js @@ -6,7 +6,7 @@ const EtherReceiver = artifacts.require('EtherReceiverMock'); const CallReceiverMock = artifacts.require('CallReceiverMock'); contract('Address', function (accounts) { - const [ recipient, other ] = accounts; + const [recipient, other] = accounts; beforeEach(async function () { this.mock = await Address.new(); @@ -35,10 +35,7 @@ contract('Address', function (accounts) { }); 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'); }); }); @@ -65,10 +62,7 @@ contract('Address', function (accounts) { }); 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 () { @@ -107,11 +101,9 @@ contract('Address', function (accounts) { const receipt = await this.mock.$functionCall(this.target.address, abiEncodedCall); - expectEvent( - receipt, - 'return$functionCall_address_bytes', - { ret0: web3.eth.abi.encodeParameters(['string'], [ '0x1234' ]) }, - ); + expectEvent(receipt, 'return$functionCall_address_bytes', { + ret0: web3.eth.abi.encodeParameters(['string'], ['0x1234']), + }); await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); }); @@ -127,10 +119,7 @@ contract('Address', function (accounts) { it('reverts when the called function reverts, bubbling up the revert reason', async function () { const abiEncodedCall = this.target.contract.methods.mockFunctionRevertsReason().encodeABI(); - await expectRevert( - this.mock.$functionCall(this.target.address, abiEncodedCall), - 'CallReceiverMock: reverting', - ); + await expectRevert(this.mock.$functionCall(this.target.address, abiEncodedCall), 'CallReceiverMock: reverting'); }); it('reverts when the called function runs out of gas', async function () { @@ -145,17 +134,18 @@ contract('Address', function (accounts) { it('reverts when the called function throws', async function () { const abiEncodedCall = this.target.contract.methods.mockFunctionThrows().encodeABI(); - await expectRevert.unspecified( - this.mock.$functionCall(this.target.address, abiEncodedCall), - ); + await expectRevert.unspecified(this.mock.$functionCall(this.target.address, abiEncodedCall)); }); it('reverts when function does not exist', async function () { - const abiEncodedCall = web3.eth.abi.encodeFunctionCall({ - name: 'mockFunctionDoesNotExist', - type: 'function', - inputs: [], - }, []); + const abiEncodedCall = web3.eth.abi.encodeFunctionCall( + { + name: 'mockFunctionDoesNotExist', + type: 'function', + inputs: [], + }, + [], + ); await expectRevert( this.mock.$functionCall(this.target.address, abiEncodedCall), @@ -166,13 +156,10 @@ contract('Address', function (accounts) { context('with non-contract receiver', function () { it('reverts when address is not a contract', async function () { - const [ recipient ] = accounts; + const [recipient] = accounts; const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); - await expectRevert( - this.mock.$functionCall(recipient, abiEncodedCall), - 'Address: call to non-contract', - ); + await expectRevert(this.mock.$functionCall(recipient, abiEncodedCall), 'Address: call to non-contract'); }); }); }); @@ -187,11 +174,9 @@ contract('Address', function (accounts) { const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); 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' ]) }, - ); + expectEvent(receipt, 'return$functionCallWithValue_address_bytes_uint256', { + ret0: web3.eth.abi.encodeParameters(['string'], ['0x1234']), + }); await expectEvent.inTransaction(receipt.tx, CallReceiverMock, 'MockFunctionCalled'); }); }); @@ -216,11 +201,9 @@ contract('Address', function (accounts) { await send.ether(other, this.mock.address, 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' ]) }, - ); + 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); @@ -233,17 +216,13 @@ contract('Address', function (accounts) { expect(await balance.current(this.mock.address)).to.be.bignumber.equal('0'); - 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' ]) }, - ); + 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); @@ -269,8 +248,9 @@ contract('Address', function (accounts) { it('calls the requested function', async function () { const abiEncodedCall = this.target.contract.methods.mockStaticFunction().encodeABI(); - expect(await this.mock.$functionStaticCall(this.target.address, abiEncodedCall)) - .to.be.equal(web3.eth.abi.encodeParameters(['string'], [ '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 () { @@ -292,13 +272,10 @@ contract('Address', function (accounts) { }); it('reverts when address is not a contract', async function () { - const [ recipient ] = accounts; + const [recipient] = accounts; const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); - await expectRevert( - this.mock.$functionStaticCall(recipient, abiEncodedCall), - 'Address: call to non-contract', - ); + await expectRevert(this.mock.$functionStaticCall(recipient, abiEncodedCall), 'Address: call to non-contract'); }); }); @@ -319,7 +296,7 @@ contract('Address', function (accounts) { expectEvent( await this.mock.$functionDelegateCall(this.target.address, abiEncodedCall), 'return$functionDelegateCall_address_bytes', - { ret0: web3.eth.abi.encodeParameters(['string'], [ '0x1234' ]) }, + { ret0: web3.eth.abi.encodeParameters(['string'], ['0x1234']) }, ); expect(await web3.eth.getStorageAt(this.mock.address, slot)).to.be.equal(value); @@ -335,13 +312,10 @@ contract('Address', function (accounts) { }); it('reverts when address is not a contract', async function () { - const [ recipient ] = accounts; + const [recipient] = accounts; const abiEncodedCall = this.target.contract.methods.mockFunction().encodeABI(); - await expectRevert( - this.mock.$functionDelegateCall(recipient, abiEncodedCall), - 'Address: call to non-contract', - ); + await expectRevert(this.mock.$functionDelegateCall(recipient, abiEncodedCall), 'Address: call to non-contract'); }); }); }); diff --git a/test/utils/Arrays.test.js b/test/utils/Arrays.test.js index 5d32e510a..d939d59bd 100644 --- a/test/utils/Arrays.test.js +++ b/test/utils/Arrays.test.js @@ -89,9 +89,27 @@ contract('Arrays', function () { describe('unsafeAccess', function () { for (const { type, artifact, elements } of [ - { type: 'address', artifact: AddressArraysMock, elements: Array(10).fill().map(() => web3.utils.randomHex(20)) }, - { type: 'bytes32', artifact: Bytes32ArraysMock, elements: Array(10).fill().map(() => web3.utils.randomHex(32)) }, - { type: 'uint256', artifact: Uint256ArraysMock, elements: Array(10).fill().map(() => web3.utils.randomHex(32)) }, + { + type: 'address', + artifact: AddressArraysMock, + elements: Array(10) + .fill() + .map(() => web3.utils.randomHex(20)), + }, + { + type: 'bytes32', + artifact: Bytes32ArraysMock, + elements: Array(10) + .fill() + .map(() => web3.utils.randomHex(32)), + }, + { + type: 'uint256', + artifact: Uint256ArraysMock, + elements: Array(10) + .fill() + .map(() => web3.utils.randomHex(32)), + }, ]) { it(type, async function () { const contract = await artifact.new(elements); diff --git a/test/utils/Checkpoints.test.js b/test/utils/Checkpoints.test.js index 520cf4fd0..d43d469cc 100644 --- a/test/utils/Checkpoints.test.js +++ b/test/utils/Checkpoints.test.js @@ -6,8 +6,8 @@ const { batchInBlock } = require('../helpers/txpool'); const $Checkpoints = artifacts.require('$Checkpoints'); -const first = (array) => array.length ? array[0] : undefined; -const last = (array) => array.length ? array[array.length - 1] : undefined; +const first = array => (array.length ? array[0] : undefined); +const last = array => (array.length ? array[array.length - 1] : undefined); contract('Checkpoints', function () { beforeEach(async function () { @@ -15,18 +15,13 @@ contract('Checkpoints', function () { }); describe('History checkpoints', function () { - const latest = (self, ...args) => - self.methods['$latest_Checkpoints_History(uint256)'](0, ...args); + 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); + 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 () { @@ -40,8 +35,8 @@ contract('Checkpoints', function () { it('returns zero as past value', async function () { await time.advanceBlock(); - 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'); + 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'); }); }); @@ -64,7 +59,7 @@ contract('Checkpoints', function () { expect(ckpt[2]).to.be.bignumber.equal(web3.utils.toBN('3')); }); - for (const getAtBlockVariant of [ getAtBlock, getAtRecentBlock ]) { + for (const getAtBlockVariant of [getAtBlock, getAtRecentBlock]) { describe(`lookup: ${getAtBlockVariant}`, function () { it('returns past values', async function () { expect(await getAtBlockVariant(this.mock, this.tx1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); @@ -82,7 +77,7 @@ contract('Checkpoints', function () { ); await expectRevert( - getAtBlockVariant(this.mock, await web3.eth.getBlockNumber() + 1), + getAtBlockVariant(this.mock, (await web3.eth.getBlockNumber()) + 1), 'Checkpoints: block not yet mined', ); }); @@ -118,18 +113,13 @@ contract('Checkpoints', function () { for (const length of [160, 224]) { describe(`Trace${length}`, function () { - const latest = (self, ...args) => - self.methods[`$latest_Checkpoints_Trace${length}(uint256)`](0, ...args); + 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); + 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 () { @@ -162,8 +152,7 @@ contract('Checkpoints', function () { }); it('length', async function () { - expect(await getLength(this.mock)) - .to.be.bignumber.equal(this.checkpoints.length.toString()); + expect(await getLength(this.mock)).to.be.bignumber.equal(this.checkpoints.length.toString()); }); it('returns latest value', async function () { diff --git a/test/utils/Context.behavior.js b/test/utils/Context.behavior.js index 8728e1021..08f7558d7 100644 --- a/test/utils/Context.behavior.js +++ b/test/utils/Context.behavior.js @@ -2,7 +2,7 @@ const { BN, expectEvent } = require('@openzeppelin/test-helpers'); const ContextMock = artifacts.require('ContextMock'); -function shouldBehaveLikeRegularContext (sender) { +function shouldBehaveLikeRegularContext(sender) { describe('msgSender', function () { it('returns the transaction sender when called from an EOA', async function () { const receipt = await this.context.msgSender({ from: sender }); diff --git a/test/utils/Context.test.js b/test/utils/Context.test.js index 709aa87d4..f372f7420 100644 --- a/test/utils/Context.test.js +++ b/test/utils/Context.test.js @@ -6,7 +6,7 @@ const ContextMockCaller = artifacts.require('ContextMockCaller'); const { shouldBehaveLikeRegularContext } = require('./Context.behavior'); contract('Context', function (accounts) { - const [ sender ] = accounts; + const [sender] = accounts; beforeEach(async function () { this.context = await ContextMock.new(); diff --git a/test/utils/Create2.test.js b/test/utils/Create2.test.js index 121630265..2fc27dc15 100644 --- a/test/utils/Create2.test.js +++ b/test/utils/Create2.test.js @@ -7,15 +7,12 @@ const VestingWallet = artifacts.require('VestingWallet'); const ERC1820Implementer = artifacts.require('$ERC1820Implementer'); contract('Create2', function (accounts) { - const [ deployerAccount, other ] = accounts; + const [deployerAccount, other] = accounts; const salt = 'salt message'; const saltHex = web3.utils.soliditySha3(salt); - const encodedParams = web3.eth.abi.encodeParameters( - [ 'address', 'uint64', 'uint64' ], - [ other, 0, 0 ], - ).slice(2); + const encodedParams = web3.eth.abi.encodeParameters(['address', 'uint64', 'uint64'], [other, 0, 0]).slice(2); const constructorByteCode = `${VestingWallet.bytecode}${encodedParams}`; @@ -24,18 +21,18 @@ contract('Create2', function (accounts) { }); describe('computeAddress', function () { it('computes the correct contract address', async function () { - const onChainComputed = - await this.factory.$computeAddress(saltHex, web3.utils.keccak256(constructorByteCode)); - const offChainComputed = - computeCreate2Address(saltHex, constructorByteCode, this.factory.address); + 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.$computeAddress(saltHex, web3.utils.keccak256(constructorByteCode), deployerAccount); - const offChainComputed = - computeCreate2Address(saltHex, 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); }); }); @@ -44,11 +41,9 @@ contract('Create2', function (accounts) { it('deploys a ERC1820Implementer from inline assembly code', async function () { const offChainComputed = computeCreate2Address(saltHex, ERC1820Implementer.bytecode, this.factory.address); - expectEvent( - await this.factory.$deploy(0, saltHex, ERC1820Implementer.bytecode), - 'return$deploy', - { addr: offChainComputed }, - ); + 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)); }); @@ -56,11 +51,9 @@ contract('Create2', function (accounts) { it('deploys a contract with constructor arguments', async function () { const offChainComputed = computeCreate2Address(saltHex, constructorByteCode, this.factory.address); - expectEvent( - await this.factory.$deploy(0, saltHex, constructorByteCode), - 'return$deploy', - { addr: offChainComputed }, - ); + expectEvent(await this.factory.$deploy(0, saltHex, constructorByteCode), 'return$deploy', { + addr: offChainComputed, + }); expect(await VestingWallet.at(offChainComputed).then(instance => instance.beneficiary())).to.be.equal(other); }); @@ -72,39 +65,25 @@ contract('Create2', function (accounts) { const offChainComputed = computeCreate2Address(saltHex, constructorByteCode, this.factory.address); - expectEvent( - await this.factory.$deploy(deposit, saltHex, constructorByteCode), - 'return$deploy', - { addr: offChainComputed }, - ); + 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 () { - expectEvent( - await this.factory.$deploy(0, saltHex, constructorByteCode), - 'return$deploy', - ); + expectEvent(await this.factory.$deploy(0, saltHex, constructorByteCode), 'return$deploy'); - await expectRevert( - this.factory.$deploy(0, saltHex, constructorByteCode), - 'Create2: Failed on deploy', - ); + await expectRevert(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'), - 'Create2: bytecode length is zero', - ); + await expectRevert(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), - 'Create2: insufficient balance', - ); + await expectRevert(this.factory.$deploy(1, saltHex, constructorByteCode), 'Create2: insufficient balance'); }); }); }); diff --git a/test/utils/Multicall.test.js b/test/utils/Multicall.test.js index 95cdddc92..cfb800769 100644 --- a/test/utils/Multicall.test.js +++ b/test/utils/Multicall.test.js @@ -3,7 +3,7 @@ const { BN, expectRevert } = require('@openzeppelin/test-helpers'); const ERC20MulticallMock = artifacts.require('$ERC20MulticallMock'); contract('Multicall', function (accounts) { - const [ deployer, alice, bob ] = accounts; + const [deployer, alice, bob] = accounts; const amount = 12000; beforeEach(async function () { @@ -15,10 +15,13 @@ contract('Multicall', function (accounts) { expect(await this.multicallToken.balanceOf(alice)).to.be.bignumber.equal(new BN('0')); expect(await this.multicallToken.balanceOf(bob)).to.be.bignumber.equal(new BN('0')); - await this.multicallToken.multicall([ - this.multicallToken.contract.methods.transfer(alice, amount / 2).encodeABI(), - this.multicallToken.contract.methods.transfer(bob, amount / 3).encodeABI(), - ], { from: deployer }); + await this.multicallToken.multicall( + [ + this.multicallToken.contract.methods.transfer(alice, amount / 2).encodeABI(), + this.multicallToken.contract.methods.transfer(bob, amount / 3).encodeABI(), + ], + { from: deployer }, + ); expect(await this.multicallToken.balanceOf(alice)).to.be.bignumber.equal(new BN(amount / 2)); expect(await this.multicallToken.balanceOf(bob)).to.be.bignumber.equal(new BN(amount / 3)); @@ -39,20 +42,26 @@ contract('Multicall', function (accounts) { it('reverts previous calls', async function () { expect(await this.multicallToken.balanceOf(alice)).to.be.bignumber.equal(new BN('0')); - const call = this.multicallToken.multicall([ - this.multicallToken.contract.methods.transfer(alice, amount).encodeABI(), - this.multicallToken.contract.methods.transfer(bob, amount).encodeABI(), - ], { from: deployer }); + const call = this.multicallToken.multicall( + [ + this.multicallToken.contract.methods.transfer(alice, amount).encodeABI(), + this.multicallToken.contract.methods.transfer(bob, amount).encodeABI(), + ], + { from: deployer }, + ); await expectRevert(call, 'ERC20: transfer amount exceeds balance'); expect(await this.multicallToken.balanceOf(alice)).to.be.bignumber.equal(new BN('0')); }); it('bubbles up revert reasons', async function () { - const call = this.multicallToken.multicall([ - this.multicallToken.contract.methods.transfer(alice, amount).encodeABI(), - this.multicallToken.contract.methods.transfer(bob, amount).encodeABI(), - ], { from: deployer }); + const call = this.multicallToken.multicall( + [ + this.multicallToken.contract.methods.transfer(alice, amount).encodeABI(), + this.multicallToken.contract.methods.transfer(bob, amount).encodeABI(), + ], + { from: deployer }, + ); await expectRevert(call, 'ERC20: transfer amount exceeds balance'); }); diff --git a/test/utils/Strings.test.js b/test/utils/Strings.test.js index 11f3e7270..6658871a0 100644 --- a/test/utils/Strings.test.js +++ b/test/utils/Strings.test.js @@ -78,15 +78,17 @@ contract('Strings', function () { }); it('converts MAX_UINT256', async function () { - expect(await this.strings.methods['$toHexString(uint256)'](constants.MAX_UINT256)) - .to.equal(web3.utils.toHex(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)) - .to.equal('0x0000000000000000000000000000000000000000000000000000000000004132'); + expect(await this.strings.methods['$toHexString(uint256,uint256)'](0x4132, 32)).to.equal( + '0x0000000000000000000000000000000000000000000000000000000000004132', + ); }); it('converts a positive number (short)', async function () { @@ -97,8 +99,9 @@ contract('Strings', function () { }); it('converts MAX_UINT256', async function () { - expect(await this.strings.methods['$toHexString(uint256,uint256)'](constants.MAX_UINT256, 32)) - .to.equal(web3.utils.toHex(constants.MAX_UINT256)); + expect(await this.strings.methods['$toHexString(uint256,uint256)'](constants.MAX_UINT256, 32)).to.equal( + web3.utils.toHex(constants.MAX_UINT256), + ); }); }); diff --git a/test/utils/cryptography/ECDSA.test.js b/test/utils/cryptography/ECDSA.test.js index fc3df0db4..3b19cde60 100644 --- a/test/utils/cryptography/ECDSA.test.js +++ b/test/utils/cryptography/ECDSA.test.js @@ -9,40 +9,40 @@ const TEST_MESSAGE = web3.utils.sha3('OpenZeppelin'); const WRONG_MESSAGE = web3.utils.sha3('Nope'); const NON_HASH_MESSAGE = '0x' + Buffer.from('abcd').toString('hex'); -function to2098Format (signature) { +function to2098Format(signature) { const long = web3.utils.hexToBytes(signature); if (long.length !== 65) { throw new Error('invalid signature length (expected long format)'); } if (long[32] >> 7 === 1) { - throw new Error('invalid signature \'s\' value'); + throw new Error("invalid signature 's' value"); } const short = long.slice(0, 64); - short[32] |= (long[64] % 27) << 7; // set the first bit of the 32nd byte to the v parity bit + short[32] |= long[64] % 27 << 7; // set the first bit of the 32nd byte to the v parity bit return web3.utils.bytesToHex(short); } -function split (signature) { +function split(signature) { const raw = web3.utils.hexToBytes(signature); switch (raw.length) { - case 64: - return [ - web3.utils.bytesToHex(raw.slice(0, 32)), // r - web3.utils.bytesToHex(raw.slice(32, 64)), // vs - ]; - case 65: - return [ - raw[64], // v - web3.utils.bytesToHex(raw.slice(0, 32)), // r - web3.utils.bytesToHex(raw.slice(32, 64)), // s - ]; - default: - expect.fail('Invalid signature length, cannot split'); + case 64: + return [ + web3.utils.bytesToHex(raw.slice(0, 32)), // r + web3.utils.bytesToHex(raw.slice(32, 64)), // vs + ]; + case 65: + return [ + raw[64], // v + web3.utils.bytesToHex(raw.slice(0, 32)), // r + web3.utils.bytesToHex(raw.slice(32, 64)), // s + ]; + default: + expect.fail('Invalid signature length, cannot split'); } } contract('ECDSA', function (accounts) { - const [ other ] = accounts; + const [other] = accounts; beforeEach(async function () { this.ecdsa = await ECDSA.new(); @@ -56,7 +56,10 @@ contract('ECDSA', function (accounts) { 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,10 +72,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( - toEthSignedMessageHash(TEST_MESSAGE), - signature, - )).to.equal(other); + expect(await this.ecdsa.$recover(toEthSignedMessageHash(TEST_MESSAGE), signature)).to.equal(other); }); it('returns signer address with correct signature for arbitrary length message', async function () { @@ -80,10 +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( - toEthSignedMessageHash(NON_HASH_MESSAGE), - signature, - )).to.equal(other); + expect(await this.ecdsa.$recover(toEthSignedMessageHash(NON_HASH_MESSAGE), signature)).to.equal(other); }); it('returns a different address', async function () { @@ -93,7 +90,8 @@ contract('ECDSA', function (accounts) { it('reverts with invalid signature', async function () { // eslint-disable-next-line max-len - const signature = '0x332ce75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e01c'; + const signature = + '0x332ce75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e01c'; await expectRevert(this.ecdsa.$recover(TEST_MESSAGE, signature), 'ECDSA: invalid signature'); }); }); @@ -102,53 +100,47 @@ contract('ECDSA', function (accounts) { // Signature generated outside ganache with method web3.eth.sign(signer, message) const signer = '0x2cc1166f6212628A0deEf2B33BEFB2187D35b86c'; // eslint-disable-next-line max-len - const signatureWithoutV = '0x5d99b6f7f6d1f73d1a26497f2b1c89b24c0993913f86e9a2d02cd69887d9c94f3c880358579d811b21dd1b7fd9bb01c1d81d10e69f0384e675c32b39643be892'; + const signatureWithoutV = + '0x5d99b6f7f6d1f73d1a26497f2b1c89b24c0993913f86e9a2d02cd69887d9c94f3c880358579d811b21dd1b7fd9bb01c1d81d10e69f0384e675c32b39643be892'; 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(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,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); + 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(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,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); + 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(TEST_MESSAGE, signature), 'ECDSA: invalid signature'); await expectRevert( this.ecdsa.methods['$recover(bytes32,uint8,bytes32,bytes32)'](TEST_MESSAGE, ...split(signature)), @@ -170,53 +162,47 @@ contract('ECDSA', function (accounts) { context('with v=28 signature', function () { const signer = '0x1E318623aB09Fe6de3C9b8672098464Aeda9100E'; // eslint-disable-next-line max-len - const signatureWithoutV = '0x331fe75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e0'; + const signatureWithoutV = + '0x331fe75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e0'; 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(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,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); + 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(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,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); + 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(TEST_MESSAGE, signature), 'ECDSA: invalid signature'); await expectRevert( this.ecdsa.methods['$recover(bytes32,uint8,bytes32,bytes32)'](TEST_MESSAGE, ...split(signature)), @@ -238,25 +224,28 @@ contract('ECDSA', function (accounts) { it('reverts with high-s value signature', async function () { const message = '0xb94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'; // eslint-disable-next-line max-len - const highSSignature = '0xe742ff452d41413616a5bf43fe15dd88294e983d3d36206c2712f39083d638bde0a0fc89be718fbc1033e1d30d78be1c68081562ed2e97af876f286f3453231d1b'; - await expectRevert(this.ecdsa.$recover(message, highSSignature), 'ECDSA: invalid signature \'s\' value'); + const highSSignature = + '0xe742ff452d41413616a5bf43fe15dd88294e983d3d36206c2712f39083d638bde0a0fc89be718fbc1033e1d30d78be1c68081562ed2e97af876f286f3453231d1b'; + await expectRevert(this.ecdsa.$recover(message, highSSignature), "ECDSA: invalid signature 's' value"); await expectRevert( this.ecdsa.methods['$recover(bytes32,uint8,bytes32,bytes32)'](TEST_MESSAGE, ...split(highSSignature)), - 'ECDSA: invalid signature \'s\' value', + "ECDSA: invalid signature 's' value", ); - expect(() => to2098Format(highSSignature)).to.throw('invalid signature \'s\' value'); + expect(() => to2098Format(highSSignature)).to.throw("invalid signature 's' value"); }); }); context('toEthSignedMessageHash', function () { it('prefixes bytes32 data correctly', async function () { - expect(await this.ecdsa.methods['$toEthSignedMessageHash(bytes32)'](TEST_MESSAGE)) - .to.equal(toEthSignedMessageHash(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)) - .to.equal(toEthSignedMessageHash(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/MerkleProof.test.js b/test/utils/cryptography/MerkleProof.test.js index 70271eea1..62157b56a 100644 --- a/test/utils/cryptography/MerkleProof.test.js +++ b/test/utils/cryptography/MerkleProof.test.js @@ -92,10 +92,10 @@ contract('MerkleProof', function () { const badProof = badMerkleTree.getMultiProof(badProofLeaves); const badProofFlags = badMerkleTree.getProofFlags(badProofLeaves, badProof); - expect(await this.merkleProof.$multiProofVerify(badProof, badProofFlags, root, badProofLeaves)) - .to.equal(false); - expect(await this.merkleProof.$multiProofVerifyCalldata(badProof, badProofFlags, root, badProofLeaves)) - .to.equal(false); + expect(await this.merkleProof.$multiProofVerify(badProof, badProofFlags, root, badProofLeaves)).to.equal(false); + expect(await this.merkleProof.$multiProofVerifyCalldata(badProof, badProofFlags, root, badProofLeaves)).to.equal( + false, + ); }); it('revert with invalid multi proof #1', async function () { @@ -108,19 +108,19 @@ contract('MerkleProof', function () { await expectRevert( this.merkleProof.$multiProofVerify( - [ leaves[1], fill, merkleTree.layers[1][1] ], - [ false, false, false ], + [leaves[1], fill, merkleTree.layers[1][1]], + [false, false, false], root, - [ leaves[0], badLeaf ], // A, E + [leaves[0], badLeaf], // A, E ), 'MerkleProof: invalid multiproof', ); await expectRevert( this.merkleProof.$multiProofVerifyCalldata( - [ leaves[1], fill, merkleTree.layers[1][1] ], - [ false, false, false ], + [leaves[1], fill, merkleTree.layers[1][1]], + [false, false, false], root, - [ leaves[0], badLeaf ], // A, E + [leaves[0], badLeaf], // A, E ), 'MerkleProof: invalid multiproof', ); @@ -136,20 +136,20 @@ contract('MerkleProof', function () { await expectRevert( this.merkleProof.$multiProofVerify( - [ leaves[1], fill, merkleTree.layers[1][1] ], - [ false, false, false, false ], + [leaves[1], fill, merkleTree.layers[1][1]], + [false, false, false, false], root, - [ badLeaf, leaves[0] ], // A, E + [badLeaf, leaves[0]], // A, E ), 'reverted with panic code 0x32', ); await expectRevert( this.merkleProof.$multiProofVerifyCalldata( - [ leaves[1], fill, merkleTree.layers[1][1] ], - [ false, false, false, false ], + [leaves[1], fill, merkleTree.layers[1][1]], + [false, false, false, false], root, - [ badLeaf, leaves[0] ], // A, E + [badLeaf, leaves[0]], // A, E ), 'reverted with panic code 0x32', ); @@ -173,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 55ba75af0..11054c3e1 100644 --- a/test/utils/cryptography/SignatureChecker.test.js +++ b/test/utils/cryptography/SignatureChecker.test.js @@ -21,61 +21,63 @@ contract('SignatureChecker (ERC1271)', function (accounts) { context('EOA account', function () { it('with matching signer and signature', async function () { - expect(await this.signaturechecker.$isValidSignatureNow( - signer, - toEthSignedMessageHash(TEST_MESSAGE), - this.signature, - )).to.equal(true); + expect( + await this.signaturechecker.$isValidSignatureNow(signer, toEthSignedMessageHash(TEST_MESSAGE), this.signature), + ).to.equal(true); }); it('with invalid signer', async function () { - expect(await this.signaturechecker.$isValidSignatureNow( - other, - toEthSignedMessageHash(TEST_MESSAGE), - this.signature, - )).to.equal(false); + expect( + await this.signaturechecker.$isValidSignatureNow(other, toEthSignedMessageHash(TEST_MESSAGE), this.signature), + ).to.equal(false); }); it('with invalid signature', async function () { - expect(await this.signaturechecker.$isValidSignatureNow( - signer, - toEthSignedMessageHash(WRONG_MESSAGE), - this.signature, - )).to.equal(false); + expect( + await this.signaturechecker.$isValidSignatureNow(signer, toEthSignedMessageHash(WRONG_MESSAGE), this.signature), + ).to.equal(false); }); }); context('ERC1271 wallet', function () { it('with matching signer and signature', async function () { - expect(await this.signaturechecker.$isValidSignatureNow( - this.wallet.address, - toEthSignedMessageHash(TEST_MESSAGE), - this.signature, - )).to.equal(true); + expect( + await this.signaturechecker.$isValidSignatureNow( + this.wallet.address, + toEthSignedMessageHash(TEST_MESSAGE), + this.signature, + ), + ).to.equal(true); }); it('with invalid signer', async function () { - expect(await this.signaturechecker.$isValidSignatureNow( - this.signaturechecker.address, - toEthSignedMessageHash(TEST_MESSAGE), - this.signature, - )).to.equal(false); + expect( + await this.signaturechecker.$isValidSignatureNow( + this.signaturechecker.address, + toEthSignedMessageHash(TEST_MESSAGE), + this.signature, + ), + ).to.equal(false); }); it('with invalid signature', async function () { - expect(await this.signaturechecker.$isValidSignatureNow( - this.wallet.address, - toEthSignedMessageHash(WRONG_MESSAGE), - this.signature, - )).to.equal(false); + expect( + await this.signaturechecker.$isValidSignatureNow( + this.wallet.address, + toEthSignedMessageHash(WRONG_MESSAGE), + this.signature, + ), + ).to.equal(false); }); it('with malicious wallet', async function () { - expect(await this.signaturechecker.$isValidSignatureNow( - this.malicious.address, - toEthSignedMessageHash(TEST_MESSAGE), - this.signature, - )).to.equal(false); + expect( + await this.signaturechecker.$isValidSignatureNow( + this.malicious.address, + toEthSignedMessageHash(TEST_MESSAGE), + this.signature, + ), + ).to.equal(false); }); }); }); diff --git a/test/utils/escrow/ConditionalEscrow.test.js b/test/utils/escrow/ConditionalEscrow.test.js index 3386ca55c..9e17a8bce 100644 --- a/test/utils/escrow/ConditionalEscrow.test.js +++ b/test/utils/escrow/ConditionalEscrow.test.js @@ -4,7 +4,7 @@ const { shouldBehaveLikeEscrow } = require('./Escrow.behavior'); const ConditionalEscrowMock = artifacts.require('ConditionalEscrowMock'); contract('ConditionalEscrow', function (accounts) { - const [ owner, payee, ...otherAccounts ] = accounts; + const [owner, payee, ...otherAccounts] = accounts; beforeEach(async function () { this.escrow = await ConditionalEscrowMock.new({ from: owner }); @@ -28,7 +28,8 @@ contract('ConditionalEscrow', function (accounts) { it('reverts on withdrawals', async function () { await this.escrow.deposit(payee, { from: owner, value: amount }); - await expectRevert(this.escrow.withdraw(payee, { from: owner }), + await expectRevert( + this.escrow.withdraw(payee, { from: owner }), 'ConditionalEscrow: payee is not allowed to withdraw', ); }); diff --git a/test/utils/escrow/Escrow.behavior.js b/test/utils/escrow/Escrow.behavior.js index ab5905994..f2059ed62 100644 --- a/test/utils/escrow/Escrow.behavior.js +++ b/test/utils/escrow/Escrow.behavior.js @@ -2,7 +2,7 @@ const { balance, ether, expectEvent, expectRevert } = require('@openzeppelin/tes const { expect } = require('chai'); -function shouldBehaveLikeEscrow (owner, [payee1, payee2]) { +function shouldBehaveLikeEscrow(owner, [payee1, payee2]) { const amount = ether('42'); describe('as an escrow', function () { @@ -20,9 +20,7 @@ function shouldBehaveLikeEscrow (owner, [payee1, payee2]) { }); it('only the owner can deposit', async function () { - await expectRevert(this.escrow.deposit(payee1, { from: payee2 }), - 'Ownable: caller is not the owner', - ); + await expectRevert(this.escrow.deposit(payee1, { from: payee2 }), 'Ownable: caller is not the owner'); }); it('emits a deposited event', async function () { @@ -72,9 +70,7 @@ function shouldBehaveLikeEscrow (owner, [payee1, payee2]) { }); it('only the owner can withdraw', async function () { - await expectRevert(this.escrow.withdraw(payee1, { from: payee1 }), - 'Ownable: caller is not the owner', - ); + await expectRevert(this.escrow.withdraw(payee1, { from: payee1 }), 'Ownable: caller is not the owner'); }); it('emits a withdrawn event', async function () { diff --git a/test/utils/escrow/Escrow.test.js b/test/utils/escrow/Escrow.test.js index 025a2a936..47627904b 100644 --- a/test/utils/escrow/Escrow.test.js +++ b/test/utils/escrow/Escrow.test.js @@ -4,7 +4,7 @@ const { shouldBehaveLikeEscrow } = require('./Escrow.behavior'); const Escrow = artifacts.require('Escrow'); contract('Escrow', function (accounts) { - const [ owner, ...otherAccounts ] = accounts; + const [owner, ...otherAccounts] = accounts; beforeEach(async function () { this.escrow = await Escrow.new({ from: owner }); diff --git a/test/utils/escrow/RefundEscrow.test.js b/test/utils/escrow/RefundEscrow.test.js index 26c19b366..c5344db16 100644 --- a/test/utils/escrow/RefundEscrow.test.js +++ b/test/utils/escrow/RefundEscrow.test.js @@ -6,14 +6,15 @@ const { expect } = require('chai'); const RefundEscrow = artifacts.require('RefundEscrow'); contract('RefundEscrow', function (accounts) { - const [ owner, beneficiary, refundee1, refundee2 ] = accounts; + const [owner, beneficiary, refundee1, refundee2] = accounts; const amount = ether('54'); const refundees = [refundee1, refundee2]; it('requires a non-null beneficiary', async function () { await expectRevert( - RefundEscrow.new(ZERO_ADDRESS, { from: owner }), 'RefundEscrow: beneficiary is the zero address', + RefundEscrow.new(ZERO_ADDRESS, { from: owner }), + 'RefundEscrow: beneficiary is the zero address', ); }); @@ -36,23 +37,20 @@ contract('RefundEscrow', function (accounts) { it('does not refund refundees', async function () { await this.escrow.deposit(refundee1, { from: owner, value: amount }); - await expectRevert(this.escrow.withdraw(refundee1), - 'ConditionalEscrow: payee is not allowed to withdraw', - ); + await expectRevert(this.escrow.withdraw(refundee1), 'ConditionalEscrow: payee is not allowed to withdraw'); }); it('does not allow beneficiary withdrawal', async function () { await this.escrow.deposit(refundee1, { from: owner, value: amount }); - await expectRevert(this.escrow.beneficiaryWithdraw(), + await expectRevert( + this.escrow.beneficiaryWithdraw(), 'RefundEscrow: beneficiary can only withdraw while closed', ); }); }); it('only the owner can enter closed state', async function () { - await expectRevert(this.escrow.close({ from: beneficiary }), - 'Ownable: caller is not the owner', - ); + await expectRevert(this.escrow.close({ from: beneficiary }), 'Ownable: caller is not the owner'); const receipt = await this.escrow.close({ from: owner }); expectEvent(receipt, 'RefundsClosed'); @@ -66,15 +64,14 @@ contract('RefundEscrow', function (accounts) { }); it('rejects deposits', async function () { - await expectRevert(this.escrow.deposit(refundee1, { from: owner, value: amount }), + await expectRevert( + this.escrow.deposit(refundee1, { from: owner, value: amount }), 'RefundEscrow: can only deposit while active', ); }); it('does not refund refundees', async function () { - await expectRevert(this.escrow.withdraw(refundee1), - 'ConditionalEscrow: payee is not allowed to withdraw', - ); + await expectRevert(this.escrow.withdraw(refundee1), 'ConditionalEscrow: payee is not allowed to withdraw'); }); it('allows beneficiary withdrawal', async function () { @@ -84,22 +81,19 @@ contract('RefundEscrow', function (accounts) { }); it('prevents entering the refund state', async function () { - await expectRevert(this.escrow.enableRefunds({ from: owner }), + await expectRevert( + this.escrow.enableRefunds({ from: owner }), 'RefundEscrow: can only enable refunds while active', ); }); it('prevents re-entering the closed state', async function () { - await expectRevert(this.escrow.close({ from: owner }), - 'RefundEscrow: can only close while active', - ); + await expectRevert(this.escrow.close({ from: owner }), 'RefundEscrow: can only close while active'); }); }); it('only the owner can enter refund state', async function () { - await expectRevert(this.escrow.enableRefunds({ from: beneficiary }), - 'Ownable: caller is not the owner', - ); + await expectRevert(this.escrow.enableRefunds({ from: beneficiary }), 'Ownable: caller is not the owner'); const receipt = await this.escrow.enableRefunds({ from: owner }); expectEvent(receipt, 'RefundsEnabled'); @@ -113,7 +107,8 @@ contract('RefundEscrow', function (accounts) { }); it('rejects deposits', async function () { - await expectRevert(this.escrow.deposit(refundee1, { from: owner, value: amount }), + await expectRevert( + this.escrow.deposit(refundee1, { from: owner, value: amount }), 'RefundEscrow: can only deposit while active', ); }); @@ -127,19 +122,19 @@ contract('RefundEscrow', function (accounts) { }); it('does not allow beneficiary withdrawal', async function () { - await expectRevert(this.escrow.beneficiaryWithdraw(), + await expectRevert( + this.escrow.beneficiaryWithdraw(), 'RefundEscrow: beneficiary can only withdraw while closed', ); }); it('prevents entering the closed state', async function () { - await expectRevert(this.escrow.close({ from: owner }), - 'RefundEscrow: can only close while active', - ); + await expectRevert(this.escrow.close({ from: owner }), 'RefundEscrow: can only close while active'); }); it('prevents re-entering the refund state', async function () { - await expectRevert(this.escrow.enableRefunds({ from: owner }), + await expectRevert( + this.escrow.enableRefunds({ from: owner }), 'RefundEscrow: can only enable refunds while active', ); }); diff --git a/test/utils/introspection/ERC165.test.js b/test/utils/introspection/ERC165.test.js index c1db67768..6d531c16d 100644 --- a/test/utils/introspection/ERC165.test.js +++ b/test/utils/introspection/ERC165.test.js @@ -7,7 +7,5 @@ contract('ERC165', function () { this.mock = await ERC165.new(); }); - shouldSupportInterfaces([ - 'ERC165', - ]); + shouldSupportInterfaces(['ERC165']); }); diff --git a/test/utils/introspection/ERC165Checker.test.js b/test/utils/introspection/ERC165Checker.test.js index baa344a7f..bb6842812 100644 --- a/test/utils/introspection/ERC165Checker.test.js +++ b/test/utils/introspection/ERC165Checker.test.js @@ -184,7 +184,7 @@ contract('ERC165Checker', function () { context('ERC165 and many interfaces supported', function () { beforeEach(async function () { - this.supportedInterfaces = [ DUMMY_ID, DUMMY_ID_2, DUMMY_ID_3 ]; + 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))); }); @@ -198,7 +198,7 @@ contract('ERC165Checker', function () { for (const interfaceId of this.supportedInterfaces) { const supported = await this.mock.$supportsInterface(this.target.address, interfaceId); expect(supported).to.equal(true); - }; + } }); it('supports all interfaceIds via supportsAllInterfaces', async function () { @@ -252,7 +252,7 @@ contract('ERC165Checker', function () { for (const interfaceId of this.supportedInterfaces) { const supported = await this.mock.$supportsERC165InterfaceUnchecked(this.target.address, interfaceId); expect(supported).to.equal(true); - }; + } }); }); @@ -290,16 +290,13 @@ contract('ERC165Checker', function () { 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( - this.target.address, - [ - DUMMY_ID, - DUMMY_ID_2, - DUMMY_ID_3, - DUMMY_UNSUPPORTED_ID, - DUMMY_UNSUPPORTED_ID_2, - ], - ); + const tx2 = await this.mock.$getSupportedInterfaces.sendTransaction(this.target.address, [ + DUMMY_ID, + DUMMY_ID_2, + DUMMY_ID_3, + DUMMY_UNSUPPORTED_ID, + DUMMY_UNSUPPORTED_ID_2, + ]); expect(tx2.receipt.gasUsed).to.be.lessThan(250000); // (2+5)*30k + 21k + some margin }); }); diff --git a/test/utils/introspection/ERC165Storage.test.js b/test/utils/introspection/ERC165Storage.test.js index 278f4ae18..c78caf812 100644 --- a/test/utils/introspection/ERC165Storage.test.js +++ b/test/utils/introspection/ERC165Storage.test.js @@ -19,7 +19,5 @@ contract('ERC165Storage', function () { await expectRevert(this.mock.$_registerInterface('0xffffffff'), 'ERC165: invalid interface id'); }); - shouldSupportInterfaces([ - 'ERC165', - ]); + shouldSupportInterfaces(['ERC165']); }); diff --git a/test/utils/introspection/ERC1820Implementer.test.js b/test/utils/introspection/ERC1820Implementer.test.js index ba0304625..83d0a6534 100644 --- a/test/utils/introspection/ERC1820Implementer.test.js +++ b/test/utils/introspection/ERC1820Implementer.test.js @@ -6,7 +6,7 @@ const { expect } = require('chai'); const ERC1820Implementer = artifacts.require('$ERC1820Implementer'); contract('ERC1820Implementer', function (accounts) { - const [ registryFunder, implementee, other ] = accounts; + const [registryFunder, implementee, other] = accounts; const ERC1820_ACCEPT_MAGIC = bufferToHex(keccakFromString('ERC1820_ACCEPT_MAGIC')); @@ -20,15 +20,16 @@ contract('ERC1820Implementer', function (accounts) { context('with no registered interfaces', function () { it('returns false when interface implementation is queried', async function () { - expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceA, implementee)) - .to.not.equal(ERC1820_ACCEPT_MAGIC); + expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceA, implementee)).to.not.equal( + ERC1820_ACCEPT_MAGIC, + ); }); it('reverts when attempting to set as implementer in the registry', async function () { await expectRevert( - this.registry.setInterfaceImplementer( - implementee, this.interfaceA, this.implementer.address, { from: implementee }, - ), + this.registry.setInterfaceImplementer(implementee, this.interfaceA, this.implementer.address, { + from: implementee, + }), 'Does not implement the interface', ); }); @@ -40,27 +41,31 @@ contract('ERC1820Implementer', function (accounts) { }); it('returns true when interface implementation is queried', async function () { - expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceA, implementee)) - .to.equal(ERC1820_ACCEPT_MAGIC); + expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceA, implementee)).to.equal( + ERC1820_ACCEPT_MAGIC, + ); }); it('returns false when interface implementation for non-supported interfaces is queried', async function () { - expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceB, implementee)) - .to.not.equal(ERC1820_ACCEPT_MAGIC); + expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceB, implementee)).to.not.equal( + ERC1820_ACCEPT_MAGIC, + ); }); it('returns false when interface implementation for non-supported addresses is queried', async function () { - expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceA, other)) - .to.not.equal(ERC1820_ACCEPT_MAGIC); + expect(await this.implementer.canImplementInterfaceForAddress(this.interfaceA, other)).to.not.equal( + ERC1820_ACCEPT_MAGIC, + ); }); it('can be set as an implementer for supported interfaces in the registry', async function () { - await this.registry.setInterfaceImplementer( - implementee, this.interfaceA, this.implementer.address, { from: implementee }, - ); + await this.registry.setInterfaceImplementer(implementee, this.interfaceA, this.implementer.address, { + from: implementee, + }); - expect(await this.registry.getInterfaceImplementer(implementee, this.interfaceA)) - .to.equal(this.implementer.address); + expect(await this.registry.getInterfaceImplementer(implementee, this.interfaceA)).to.equal( + this.implementer.address, + ); }); }); }); diff --git a/test/utils/introspection/SupportsInterface.behavior.js b/test/utils/introspection/SupportsInterface.behavior.js index 78e327248..ba5aca2fc 100644 --- a/test/utils/introspection/SupportsInterface.behavior.js +++ b/test/utils/introspection/SupportsInterface.behavior.js @@ -3,9 +3,7 @@ const { makeInterfaceId } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); const INTERFACES = { - ERC165: [ - 'supportsInterface(bytes4)', - ], + ERC165: ['supportsInterface(bytes4)'], ERC721: [ 'balanceOf(address)', 'ownerOf(uint256)', @@ -17,16 +15,8 @@ const INTERFACES = { 'safeTransferFrom(address,address,uint256)', 'safeTransferFrom(address,address,uint256,bytes)', ], - ERC721Enumerable: [ - 'totalSupply()', - 'tokenOfOwnerByIndex(address,uint256)', - 'tokenByIndex(uint256)', - ], - ERC721Metadata: [ - 'name()', - 'symbol()', - 'tokenURI(uint256)', - ], + ERC721Enumerable: ['totalSupply()', 'tokenOfOwnerByIndex(address,uint256)', 'tokenByIndex(uint256)'], + ERC721Metadata: ['name()', 'symbol()', 'tokenURI(uint256)'], ERC1155: [ 'balanceOf(address,uint256)', 'balanceOfBatch(address[],uint256[])', @@ -46,10 +36,7 @@ const INTERFACES = { 'revokeRole(bytes32,address)', 'renounceRole(bytes32,address)', ], - AccessControlEnumerable: [ - 'getRoleMember(bytes32,uint256)', - 'getRoleMemberCount(bytes32)', - ], + AccessControlEnumerable: ['getRoleMember(bytes32,uint256)', 'getRoleMemberCount(bytes32)'], Governor: [ 'name()', 'version()', @@ -91,14 +78,8 @@ const INTERFACES = { 'castVoteBySig(uint256,uint8,uint8,bytes32,bytes32)', 'castVoteWithReasonAndParamsBySig(uint256,uint8,string,bytes,uint8,bytes32,bytes32)', ], - GovernorTimelock: [ - 'timelock()', - 'proposalEta(uint256)', - 'queue(address[],uint256[],bytes[],bytes32)', - ], - ERC2981: [ - 'royaltyInfo(uint256,uint256)', - ], + GovernorTimelock: ['timelock()', 'proposalEta(uint256)', 'queue(address[],uint256[],bytes[],bytes32)'], + ERC2981: ['royaltyInfo(uint256,uint256)'], }; const INTERFACE_IDS = {}; @@ -111,7 +92,7 @@ for (const k of Object.getOwnPropertyNames(INTERFACES)) { } } -function shouldSupportInterfaces (interfaces = []) { +function shouldSupportInterfaces(interfaces = []) { describe('ERC165', function () { beforeEach(function () { this.contractUnderTest = this.mock || this.token || this.holder || this.accessControl; diff --git a/test/utils/math/Math.test.js b/test/utils/math/Math.test.js index 63cfa186c..6b97a646f 100644 --- a/test/utils/math/Math.test.js +++ b/test/utils/math/Math.test.js @@ -36,7 +36,7 @@ contract('Math', function () { }); describe('average', function () { - function bnAverage (a, b) { + function bnAverage(a, b) { return a.add(b).divn(2); } @@ -101,40 +101,25 @@ contract('Math', function () { }); it('large values', async function () { - 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(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'), - MAX_UINT256, - MAX_UINT256, - Rounding.Down, - )).to.be.bignumber.equal(new BN('17')); + ); - 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(MAX_UINT256_SUB1, MAX_UINT256_SUB1, MAX_UINT256, Rounding.Down), + ).to.be.bignumber.equal(MAX_UINT256_SUB2); - 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(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, Rounding.Down)).to.be.bignumber.equal( MAX_UINT256, - MAX_UINT256, - MAX_UINT256, - Rounding.Down, - )).to.be.bignumber.equal(MAX_UINT256); + ); }); }); @@ -145,40 +130,25 @@ contract('Math', function () { }); 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'), - 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'), - MAX_UINT256, - MAX_UINT256, - Rounding.Up, - )).to.be.bignumber.equal(new BN('17')); + ); - 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(MAX_UINT256_SUB1, MAX_UINT256_SUB1, MAX_UINT256, Rounding.Up), + ).to.be.bignumber.equal(MAX_UINT256_SUB1); - expect(await this.math.$mulDiv( - MAX_UINT256, + expect(await this.math.$mulDiv(MAX_UINT256, MAX_UINT256_SUB1, MAX_UINT256, Rounding.Up)).to.be.bignumber.equal( 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, Rounding.Up)).to.be.bignumber.equal( MAX_UINT256, - MAX_UINT256, - MAX_UINT256, - Rounding.Up, - )).to.be.bignumber.equal(MAX_UINT256); + ); }); }); }); @@ -196,8 +166,9 @@ contract('Math', function () { 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'); + expect(await this.math.$sqrt(MAX_UINT256, Rounding.Down)).to.be.bignumber.equal( + '340282366920938463463374607431768211455', + ); }); it('rounds up', async function () { @@ -212,8 +183,9 @@ contract('Math', function () { 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'); + expect(await this.math.$sqrt(MAX_UINT256, Rounding.Up)).to.be.bignumber.equal( + '340282366920938463463374607431768211456', + ); }); }); @@ -231,8 +203,9 @@ contract('Math', function () { 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'); + expect(await this.math.methods['$log2(uint256,uint8)'](MAX_UINT256, Rounding.Down)).to.be.bignumber.equal( + '255', + ); }); it('rounds up', async function () { @@ -247,8 +220,7 @@ contract('Math', function () { 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'); + expect(await this.math.methods['$log2(uint256,uint8)'](MAX_UINT256, Rounding.Up)).to.be.bignumber.equal('256'); }); }); diff --git a/test/utils/math/SafeCast.test.js b/test/utils/math/SafeCast.test.js index 38374e500..63223f5d1 100644 --- a/test/utils/math/SafeCast.test.js +++ b/test/utils/math/SafeCast.test.js @@ -9,7 +9,7 @@ contract('SafeCast', async function () { this.safeCast = await SafeCast.new(); }); - function testToUint (bits) { + function testToUint(bits) { describe(`toUint${bits}`, () => { const maxValue = new BN('2').pow(new BN(bits)).subn(1); @@ -60,21 +60,15 @@ contract('SafeCast', async function () { }); it('reverts when casting -1', async function () { - await expectRevert( - this.safeCast.$toUint256(-1), - 'SafeCast: value must be positive', - ); + await expectRevert(this.safeCast.$toUint256(-1), 'SafeCast: value must be positive'); }); it(`reverts when casting INT256_MIN (${minInt256})`, async function () { - await expectRevert( - this.safeCast.$toUint256(minInt256), - 'SafeCast: value must be positive', - ); + await expectRevert(this.safeCast.$toUint256(minInt256), 'SafeCast: value must be positive'); }); }); - function testToInt (bits) { + function testToInt(bits) { describe(`toInt${bits}`, () => { const minValue = new BN('-2').pow(new BN(bits - 1)); const maxValue = new BN('2').pow(new BN(bits - 1)).subn(1); @@ -148,17 +142,11 @@ contract('SafeCast', async function () { }); it(`reverts when casting INT256_MAX + 1 (${maxInt256.addn(1)})`, async function () { - await expectRevert( - this.safeCast.$toInt256(maxInt256.addn(1)), - 'SafeCast: value doesn\'t fit in an int256', - ); + await expectRevert(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), - 'SafeCast: value doesn\'t fit in an int256', - ); + await expectRevert(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 a74d7fb96..9598ac57c 100644 --- a/test/utils/math/SafeMath.test.js +++ b/test/utils/math/SafeMath.test.js @@ -6,7 +6,7 @@ const { expect } = require('chai'); const SafeMath = artifacts.require('$SafeMath'); const SafeMathMemoryCheck = artifacts.require('$SafeMathMemoryCheck'); -function expectStruct (value, expected) { +function expectStruct(value, expected) { for (const key in expected) { if (BN.isBN(value[key])) { expect(value[key]).to.be.bignumber.equal(expected[key]); @@ -21,12 +21,12 @@ contract('SafeMath', function () { this.safeMath = await SafeMath.new(); }); - async function testCommutative (fn, lhs, rhs, expected, ...extra) { + async function testCommutative(fn, lhs, rhs, expected, ...extra) { expect(await fn(lhs, rhs, ...extra)).to.be.bignumber.equal(expected); expect(await fn(rhs, lhs, ...extra)).to.be.bignumber.equal(expected); } - async function testFailsCommutative (fn, lhs, rhs, reason, ...extra) { + async function testFailsCommutative(fn, lhs, rhs, reason, ...extra) { if (reason === undefined) { await expectRevert.unspecified(fn(lhs, rhs, ...extra)); await expectRevert.unspecified(fn(rhs, lhs, ...extra)); @@ -36,7 +36,7 @@ contract('SafeMath', function () { } } - async function testCommutativeIterable (fn, lhs, rhs, expected, ...extra) { + async function testCommutativeIterable(fn, lhs, rhs, expected, ...extra) { expectStruct(await fn(lhs, rhs, ...extra), expected); expectStruct(await fn(rhs, lhs, ...extra), expected); } @@ -47,14 +47,14 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('1234'); - testCommutativeIterable(this.safeMath.$tryAdd, a, b, [ true, 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, [ false, '0' ]); + testCommutativeIterable(this.safeMath.$tryAdd, a, b, [false, '0']); }); }); @@ -63,14 +63,14 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('1234'); - expectStruct(await this.safeMath.$trySub(a, b), [ true, 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), [ false, '0' ]); + expectStruct(await this.safeMath.$trySub(a, b), [false, '0']); }); }); @@ -79,21 +79,21 @@ contract('SafeMath', function () { const a = new BN('1234'); const b = new BN('5678'); - testCommutativeIterable(this.safeMath.$tryMul, a, b, [ true, 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, [ true, 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, [ false, '0' ]); + testCommutativeIterable(this.safeMath.$tryMul, a, b, [false, '0']); }); }); @@ -102,28 +102,28 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('5678'); - expectStruct(await this.safeMath.$tryDiv(a, b), [ true, 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), [ true, 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), [ true, 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), [ false, '0' ]); + expectStruct(await this.safeMath.$tryDiv(a, b), [false, '0']); }); }); @@ -133,28 +133,28 @@ contract('SafeMath', function () { const a = new BN('284'); const b = new BN('5678'); - expectStruct(await this.safeMath.$tryMod(a, b), [ true, 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), [ true, 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), [ true, 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), [ true, a.mod(b) ]); + expectStruct(await this.safeMath.$tryMod(a, b), [true, a.mod(b)]); }); }); @@ -162,7 +162,7 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('0'); - expectStruct(await this.safeMath.$tryMod(a, b), [ false, '0' ]); + expectStruct(await this.safeMath.$tryMod(a, b), [false, '0']); }); }); }); @@ -299,8 +299,9 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('1234'); - expect(await this.safeMath.methods['$sub(uint256,uint256,string)'](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 () { @@ -319,24 +320,27 @@ contract('SafeMath', function () { const a = new BN('5678'); const b = new BN('5678'); - expect(await this.safeMath.methods['$div(uint256,uint256,string)'](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.methods['$div(uint256,uint256,string)'](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.methods['$div(uint256,uint256,string)'](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 () { @@ -356,32 +360,36 @@ contract('SafeMath', function () { const a = new BN('284'); const b = new BN('5678'); - expect(await this.safeMath.methods['$mod(uint256,uint256,string)'](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.methods['$mod(uint256,uint256,string)'](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.methods['$mod(uint256,uint256,string)'](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.methods['$mod(uint256,uint256,string)'](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)); }); }); diff --git a/test/utils/math/SignedMath.test.js b/test/utils/math/SignedMath.test.js index bbf492b20..c014e22ba 100644 --- a/test/utils/math/SignedMath.test.js +++ b/test/utils/math/SignedMath.test.js @@ -33,7 +33,7 @@ contract('SignedMath', function () { }); describe('average', function () { - function bnAverage (a, b) { + function bnAverage(a, b) { return a.add(b).divn(2); } @@ -68,8 +68,10 @@ contract('SignedMath', function () { for (const x of valuesX) { for (const y of valuesY) { - expect(await this.math.$average(x, y)) - .to.be.bignumber.equal(bnAverage(x, y), `Bad result for average(${x}, ${y})`); + expect(await this.math.$average(x, y)).to.be.bignumber.equal( + bnAverage(x, y), + `Bad result for average(${x}, ${y})`, + ); } } }); diff --git a/test/utils/math/SignedSafeMath.test.js b/test/utils/math/SignedSafeMath.test.js index 5702a4330..3b6530cf5 100644 --- a/test/utils/math/SignedSafeMath.test.js +++ b/test/utils/math/SignedSafeMath.test.js @@ -10,12 +10,12 @@ contract('SignedSafeMath', function () { this.safeMath = await SignedSafeMath.new(); }); - async function testCommutative (fn, lhs, rhs, expected) { + async function testCommutative(fn, lhs, rhs, expected) { expect(await fn(lhs, rhs)).to.be.bignumber.equal(expected); expect(await fn(rhs, lhs)).to.be.bignumber.equal(expected); } - async function testFailsCommutative (fn, lhs, rhs) { + async function testFailsCommutative(fn, lhs, rhs) { await expectRevert.unspecified(fn(lhs, rhs)); await expectRevert.unspecified(fn(rhs, lhs)); } diff --git a/test/utils/structs/DoubleEndedQueue.test.js b/test/utils/structs/DoubleEndedQueue.test.js index 8900663d8..2fbb8dc25 100644 --- a/test/utils/structs/DoubleEndedQueue.test.js +++ b/test/utils/structs/DoubleEndedQueue.test.js @@ -4,9 +4,14 @@ const { expectRevertCustomError } = require('../../helpers/customError'); const DoubleEndedQueue = artifacts.require('$DoubleEndedQueue'); /** Rebuild the content of the deque as a JS array. */ -const getContent = (deque) => deque.$length(0).then(bn => - Promise.all(Array(bn.toNumber()).fill().map((_, i) => deque.$at(0, i))), -); +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'); @@ -37,7 +42,7 @@ contract('DoubleEndedQueue', function () { await this.deque.$pushBack(0, bytesB); await this.deque.$pushFront(0, bytesA); await this.deque.$pushBack(0, bytesC); - this.content = [ bytesA, bytesB, bytesC ]; + this.content = [bytesA, bytesB, bytesC]; }); it('getters', async function () { diff --git a/test/utils/structs/EnumerableMap.behavior.js b/test/utils/structs/EnumerableMap.behavior.js index 25ae84215..b4b5ee372 100644 --- a/test/utils/structs/EnumerableMap.behavior.js +++ b/test/utils/structs/EnumerableMap.behavior.js @@ -3,46 +3,39 @@ const { expect } = require('chai'); const zip = require('lodash.zip'); -function shouldBehaveLikeMap ( - keys, - values, - zeroValue, - methods, - events, -) { - 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) { + async function expectMembersMatch(map, keys, values) { expect(keys.length).to.equal(values.length); - await Promise.all(keys.map(async key => - expect(await methods.contains(map, key)).to.equal(true), - )); + await Promise.all(keys.map(async key => expect(await methods.contains(map, key)).to.equal(true))); expect(await methods.length(map)).to.bignumber.equal(keys.length.toString()); - expect( - (await Promise.all(keys.map(key => methods.get(map, key)))).map(k => k.toString()), - ).to.have.same.members( + expect((await Promise.all(keys.map(key => methods.get(map, key)))).map(k => k.toString())).to.have.same.members( values.map(value => value.toString()), ); // 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 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())), + expect( + await Promise.all( + [...Array(keys.length).keys()].map(async index => { + 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()), + ), ); // This also checks that both arrays have the same length - expect( - (await methods.keys(map)).map(k => k.toString()), - ).to.have.same.members( - keys.map(key => key.toString()), - ); + expect((await methods.keys(map)).map(k => k.toString())).to.have.same.members(keys.map(key => key.toString())); } it('starts empty', async function () { @@ -154,29 +147,21 @@ function shouldBehaveLikeMap ( describe('get', function () { it('existing value', async function () { - expect( - await methods.get(this.map, keyA).then(r => r.toString()), - ).to.be.equal(valueA.toString()); + expect(await methods.get(this.map, keyA).then(r => r.toString())).to.be.equal(valueA.toString()); }); it('missing value', async function () { - await expectRevert( - methods.get(this.map, 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 methods.getWithMessage(this.map, keyA, 'custom error string').then(r => r.toString()), - ).to.be.equal(valueA.toString()); + expect(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( - methods.getWithMessage(this.map, keyB, 'custom error string'), - 'custom error string', - ); + await expectRevert(methods.getWithMessage(this.map, keyB, 'custom error string'), 'custom error string'); }); }); diff --git a/test/utils/structs/EnumerableMap.test.js b/test/utils/structs/EnumerableMap.test.js index 14f31b429..548e73775 100644 --- a/test/utils/structs/EnumerableMap.test.js +++ b/test/utils/structs/EnumerableMap.test.js @@ -5,12 +5,17 @@ const EnumerableMap = artifacts.require('$EnumerableMap'); const { shouldBehaveLikeMap } = require('./EnumerableMap.behavior'); -const getMethods = (ms) => { - return mapValues(ms, m => (self, ...args) => self.methods[m](0, ...args)); +const getMethods = ms => { + return mapValues( + ms, + m => + (self, ...args) => + self.methods[m](0, ...args), + ); }; contract('EnumerableMap', function (accounts) { - const [ accountA, accountB, accountC ] = accounts; + const [accountA, accountB, accountC] = accounts; const keyA = new BN('7891'); const keyB = new BN('451'); @@ -27,8 +32,8 @@ contract('EnumerableMap', function (accounts) { // AddressToUintMap describe('AddressToUintMap', function () { shouldBehaveLikeMap( - [ accountA, accountB, accountC ], - [ keyA, keyB, keyC ], + [accountA, accountB, accountC], + [keyA, keyB, keyC], new BN('0'), getMethods({ set: '$set(uint256,address,uint256)', @@ -51,8 +56,8 @@ contract('EnumerableMap', function (accounts) { // UintToAddressMap describe('UintToAddressMap', function () { shouldBehaveLikeMap( - [ keyA, keyB, keyC ], - [ accountA, accountB, accountC ], + [keyA, keyB, keyC], + [accountA, accountB, accountC], constants.ZERO_ADDRESS, getMethods({ set: '$set(uint256,uint256,address)', @@ -75,8 +80,8 @@ contract('EnumerableMap', function (accounts) { // Bytes32ToBytes32Map describe('Bytes32ToBytes32Map', function () { shouldBehaveLikeMap( - [ keyA, keyB, keyC ].map(k => '0x' + k.toString(16).padEnd(64, '0')), - [ bytesA, bytesB, bytesC ], + [keyA, keyB, keyC].map(k => '0x' + k.toString(16).padEnd(64, '0')), + [bytesA, bytesB, bytesC], constants.ZERO_BYTES32, getMethods({ set: '$set(uint256,bytes32,bytes32)', @@ -99,8 +104,8 @@ contract('EnumerableMap', function (accounts) { // UintToUintMap describe('UintToUintMap', function () { shouldBehaveLikeMap( - [ keyA, keyB, keyC ], - [ keyA, keyB, keyC ].map(k => k.add(new BN('1332'))), + [keyA, keyB, keyC], + [keyA, keyB, keyC].map(k => k.add(new BN('1332'))), new BN('0'), getMethods({ set: '$set(uint256,uint256,uint256)', @@ -123,8 +128,8 @@ contract('EnumerableMap', function (accounts) { // Bytes32ToUintMap describe('Bytes32ToUintMap', function () { shouldBehaveLikeMap( - [ bytesA, bytesB, bytesC ], - [ keyA, keyB, keyC ], + [bytesA, bytesB, bytesC], + [keyA, keyB, keyC], new BN('0'), getMethods({ set: '$set(uint256,bytes32,uint256)', diff --git a/test/utils/structs/EnumerableSet.behavior.js b/test/utils/structs/EnumerableSet.behavior.js index db56a2eca..f80eb8169 100644 --- a/test/utils/structs/EnumerableSet.behavior.js +++ b/test/utils/structs/EnumerableSet.behavior.js @@ -1,14 +1,10 @@ const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); -function shouldBehaveLikeSet ( - values, - methods, - events, -) { - const [ valueA, valueB, valueC ] = values; +function shouldBehaveLikeSet(values, methods, events) { + const [valueA, valueB, valueC] = values; - async function expectMembersMatch (set, values) { + async function expectMembersMatch(set, values) { const contains = await Promise.all(values.map(value => methods.contains(set, value))); expect(contains.every(Boolean)).to.be.equal(true); @@ -17,19 +13,15 @@ function shouldBehaveLikeSet ( // 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) => methods.at(set, index))); - expect( - indexedValues.map(v => v.toString()), - ).to.have.same.members( - values.map(v => v.toString()), + 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 methods.values(set); - expect( - returnedValues.map(v => v.toString()), - ).to.have.same.members( - values.map(v => v.toString()), - ); + expect(returnedValues.map(v => v.toString())).to.have.same.members(values.map(v => v.toString())); } it('starts empty', async function () { diff --git a/test/utils/structs/EnumerableSet.test.js b/test/utils/structs/EnumerableSet.test.js index 27f1c731e..862cb6d9e 100644 --- a/test/utils/structs/EnumerableSet.test.js +++ b/test/utils/structs/EnumerableSet.test.js @@ -3,8 +3,13 @@ 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)); +const getMethods = ms => { + return mapValues( + ms, + m => + (self, ...args) => + self.methods[m](0, ...args), + ); }; contract('EnumerableSet', function (accounts) { @@ -15,7 +20,7 @@ contract('EnumerableSet', function (accounts) { // Bytes32Set describe('EnumerableBytes32Set', function () { shouldBehaveLikeSet( - [ '0xdeadbeef', '0x0123456789', '0x42424242' ].map(e => e.padEnd(66, '0')), + ['0xdeadbeef', '0x0123456789', '0x42424242'].map(e => e.padEnd(66, '0')), getMethods({ add: '$add(uint256,bytes32)', remove: '$remove(uint256,bytes32)', @@ -53,7 +58,7 @@ contract('EnumerableSet', function (accounts) { // UintSet describe('EnumerableUintSet', function () { shouldBehaveLikeSet( - [ 1234, 5678, 9101112 ].map(e => web3.utils.toBN(e)), + [1234, 5678, 9101112].map(e => web3.utils.toBN(e)), getMethods({ add: '$add(uint256,uint256)', remove: '$remove(uint256,uint256)', From d59306bd06a241083841c2e4a39db08e1f3722cc Mon Sep 17 00:00:00 2001 From: Francisco Date: Fri, 6 Jan 2023 10:09:02 -0300 Subject: [PATCH 21/29] Improve ERC20.decimals documentation (#3933) --- contracts/token/ERC20/ERC20.sol | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/contracts/token/ERC20/ERC20.sol b/contracts/token/ERC20/ERC20.sol index dfca5a79b..7c53c6962 100644 --- a/contracts/token/ERC20/ERC20.sol +++ b/contracts/token/ERC20/ERC20.sol @@ -18,6 +18,9 @@ import "../../utils/Context.sol"; * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * + * The default value of {decimals} is 18. To change this, you should override + * this function so it returns a different value. + * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 @@ -45,9 +48,6 @@ contract ERC20 is Context, IERC20, IERC20Metadata { /** * @dev Sets the values for {name} and {symbol}. * - * The default value of {decimals} is 18. To select a different value for - * {decimals} you should overload it. - * * All two of these values are immutable: they can only be set once during * construction. */ @@ -77,8 +77,8 @@ contract ERC20 is Context, IERC20, IERC20Metadata { * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between - * Ether and Wei. This is the value {ERC20} uses, unless this function is - * overridden; + * Ether and Wei. This is the default value returned by this function, unless + * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including From 86de1e8b6c3fa6b4efa4a5435869d2521be0f5f5 Mon Sep 17 00:00:00 2001 From: Francisco Date: Thu, 12 Jan 2023 05:50:06 -0300 Subject: [PATCH 22/29] Pin Slither to 0.9.1 (#3949) --- .github/workflows/checks.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 81b0b8f46..ae660661e 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -78,6 +78,8 @@ jobs: uses: ./.github/actions/setup - run: rm foundry.toml - uses: crytic/slither-action@v0.2.0 + with: + slither-version: 0.9.1 codespell: if: github.repository != 'OpenZeppelin/openzeppelin-contracts-upgradeable' From 5dbde1a5c954a79338959d4eb9c7e716a217d6a1 Mon Sep 17 00:00:00 2001 From: Owen Date: Thu, 12 Jan 2023 05:43:29 -0800 Subject: [PATCH 23/29] Fix governance tutorial contract (#3948) Co-authored-by: Francisco Giordano Co-authored-by: Hadrien Croubois --- docs/modules/ROOT/pages/governance.adoc | 28 +++++-------------------- 1 file changed, 5 insertions(+), 23 deletions(-) diff --git a/docs/modules/ROOT/pages/governance.adoc b/docs/modules/ROOT/pages/governance.adoc index 00a997db5..aa27c0ba8 100644 --- a/docs/modules/ROOT/pages/governance.adoc +++ b/docs/modules/ROOT/pages/governance.adoc @@ -145,11 +145,11 @@ We can optionally set a proposal threshold as well. This restricts proposal crea // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; -import "./governance/Governor.sol"; -import "./governance/compatibility/GovernorCompatibilityBravo.sol"; -import "./governance/extensions/GovernorVotes.sol"; -import "./governance/extensions/GovernorVotesQuorumFraction.sol"; -import "./governance/extensions/GovernorTimelockControl.sol"; +import "@openzeppelin/contracts/governance/Governor.sol"; +import "@openzeppelin/contracts/governance/compatibility/GovernorCompatibilityBravo.sol"; +import "@openzeppelin/contracts/governance/extensions/GovernorVotes.sol"; +import "@openzeppelin/contracts/governance/extensions/GovernorVotesQuorumFraction.sol"; +import "@openzeppelin/contracts/governance/extensions/GovernorTimelockControl.sol"; contract MyGovernor is Governor, GovernorCompatibilityBravo, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockControl { constructor(IVotes _token, TimelockController _timelock) @@ -173,24 +173,6 @@ contract MyGovernor is Governor, GovernorCompatibilityBravo, GovernorVotes, Gove // The functions below are overrides required by Solidity. - function quorum(uint256 blockNumber) - public - view - override(IGovernor, GovernorVotesQuorumFraction) - returns (uint256) - { - return super.quorum(blockNumber); - } - - function getVotes(address account, uint256 blockNumber) - public - view - override(IGovernor, GovernorVotes) - returns (uint256) - { - return super.getVotes(account, blockNumber); - } - function state(uint256 proposalId) public view From 6b17b334300f8268acdfc88b77b87395f6aa5174 Mon Sep 17 00:00:00 2001 From: Hadrien Croubois Date: Thu, 12 Jan 2023 16:33:15 +0100 Subject: [PATCH 24/29] Use a staticcall to fetch ERC20.decimals in ERC4626 (#3943) Co-authored-by: Francisco --- CHANGELOG.md | 4 ++++ contracts/token/ERC20/extensions/ERC4626.sol | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f6a9be40..eb23ca8ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,10 @@ * `ERC20Permit`: Added the file `IERC20Permit.sol` and `ERC20Permit.sol` and deprecated `draft-IERC20Permit.sol` and `draft-ERC20Permit.sol` since [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612) is no longer a Draft. Developers are encouraged to update their imports. ([#3793](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3793)) +## 4.8.1 + + * `ERC4626`: Use staticcall instead of call when fetching underlying ERC-20 decimals. ([#3943](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3943)) + ## 4.8.0 (2022-11-08) * `TimelockController`: Added a new `admin` constructor parameter that is assigned the admin role instead of the deployer account. ([#3722](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3722)) diff --git a/contracts/token/ERC20/extensions/ERC4626.sol b/contracts/token/ERC20/extensions/ERC4626.sol index 9b26aefeb..663377dad 100644 --- a/contracts/token/ERC20/extensions/ERC4626.sol +++ b/contracts/token/ERC20/extensions/ERC4626.sol @@ -45,8 +45,8 @@ abstract contract ERC4626 is ERC20, IERC4626 { /** * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way. */ - function _tryGetAssetDecimals(IERC20 asset_) private returns (bool, uint8) { - (bool success, bytes memory encodedDecimals) = address(asset_).call( + function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) { + (bool success, bytes memory encodedDecimals) = address(asset_).staticcall( abi.encodeWithSelector(IERC20Metadata.decimals.selector) ); if (success && encodedDecimals.length >= 32) { From 42fab12584d2f446b7e013dd9f1cf260e5a9d747 Mon Sep 17 00:00:00 2001 From: Francisco Giordano Date: Thu, 12 Jan 2023 17:43:43 -0300 Subject: [PATCH 25/29] Remove unnecessary CI cache --- .github/actions/setup/action.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml index 9e562eb71..680fba0c6 100644 --- a/.github/actions/setup/action.yml +++ b/.github/actions/setup/action.yml @@ -6,14 +6,13 @@ runs: - uses: actions/setup-node@v3 with: node-version: 14.x - cache: npm - uses: actions/cache@v3 id: cache with: path: '**/node_modules' key: npm-v3-${{ hashFiles('**/package-lock.json') }} - name: Install dependencies - run: npm ci --prefer-offline + run: npm ci shell: bash if: steps.cache.outputs.cache-hit != 'true' env: From ac30219a6a0eb9f98798da39ddef7fe554e43616 Mon Sep 17 00:00:00 2001 From: Francisco Giordano Date: Thu, 12 Jan 2023 20:55:53 -0300 Subject: [PATCH 26/29] Add explicit permissions to docs workflow --- .github/workflows/docs.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 526fe608c..4b54ea6ee 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -4,6 +4,9 @@ on: push: branches: [release-v*] +permissions: + contents: write + jobs: build: runs-on: ubuntu-latest From 717fbc45cbc05a034fd98050e6537499a81a25fb Mon Sep 17 00:00:00 2001 From: Francisco Date: Fri, 13 Jan 2023 07:17:38 -0300 Subject: [PATCH 27/29] Add docs on non-stability of internal function use (#3952) --- docs/modules/ROOT/pages/extending-contracts.adoc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/modules/ROOT/pages/extending-contracts.adoc b/docs/modules/ROOT/pages/extending-contracts.adoc index 6ae68a858..7330fc997 100644 --- a/docs/modules/ROOT/pages/extending-contracts.adoc +++ b/docs/modules/ROOT/pages/extending-contracts.adoc @@ -126,4 +126,6 @@ That's it! Enjoy simpler code using hooks! The maintainers of OpenZeppelin Contracts are mainly concerned with the correctness and security of the code as published in the library, and the combinations of base contracts with the official extensions from the library. -Custom overrides, and those of hooks in particular, may break some important assumptions and introduce vulnerabilities in otherwise secure code. While we try to ensure the contracts remain secure in the face of a wide range of potential customizations, this is done in a best-effort manner. Similarly, while we try to document all important assumptions, this should not be relied upon. Custom overrides should be carefully reviewed and checked against the source code of the contract they are customizing so as to fully understand their impact and guarantee their security. +Custom overrides, and those of hooks in particular, may break some important assumptions and introduce vulnerabilities in otherwise secure code. While we try to ensure the contracts remain secure in the face of a wide range of potential customizations, this is done in a best-effort manner. While we try to document all important assumptions, this should not be relied upon. Custom overrides should be carefully reviewed and checked against the source code of the contract they are customizing so as to fully understand their impact and guarantee their security. + +The way functions interact internally should not be assumed to stay stable across releases of the library. For example, a function that is used in one context in a particular release may not be used in the same context in the next release. Contracts that override functions should revalidate their assumptions when updating the version of OpenZeppelin Contracts they are built on. From d89e51ac4249eb6ff31451aa191fabc73954d638 Mon Sep 17 00:00:00 2001 From: Francisco Date: Fri, 13 Jan 2023 11:05:13 -0300 Subject: [PATCH 28/29] Use actionlint on GitHub Actions workflows (#3953) --- .github/workflows/actionlint.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .github/workflows/actionlint.yml diff --git a/.github/workflows/actionlint.yml b/.github/workflows/actionlint.yml new file mode 100644 index 000000000..8193109cf --- /dev/null +++ b/.github/workflows/actionlint.yml @@ -0,0 +1,18 @@ +name: lint workflows + +on: + pull_request: + paths: + - '.github/**/*.ya?ml' + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Add problem matchers + run: | + # https://github.com/rhysd/actionlint/blob/3a2f2c7/docs/usage.md#problem-matchers + curl -LO https://raw.githubusercontent.com/rhysd/actionlint/main/.github/actionlint-matcher.json + echo "::add-matcher::actionlint-matcher.json" + - uses: docker://rhysd/actionlint:latest From a5af0adce4276cc0931083d612e31c7319a78a1d Mon Sep 17 00:00:00 2001 From: alpharush <0xalpharush@protonmail.com> Date: Fri, 13 Jan 2023 11:29:53 -0600 Subject: [PATCH 29/29] Ignore reentrancy in`executeBatch` and update Slither config (#3955) Co-authored-by: Francisco --- .github/workflows/checks.yml | 3 --- contracts/governance/TimelockController.sol | 3 +++ slither.config.json | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index ae660661e..4e92c1043 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -76,10 +76,7 @@ jobs: - uses: actions/checkout@v3 - name: Set up environment uses: ./.github/actions/setup - - run: rm foundry.toml - uses: crytic/slither-action@v0.2.0 - with: - slither-version: 0.9.1 codespell: if: github.repository != 'OpenZeppelin/openzeppelin-contracts-upgradeable' diff --git a/contracts/governance/TimelockController.sol b/contracts/governance/TimelockController.sol index da7143499..dac55d858 100644 --- a/contracts/governance/TimelockController.sol +++ b/contracts/governance/TimelockController.sol @@ -311,6 +311,9 @@ contract TimelockController is AccessControl, IERC721Receiver, IERC1155Receiver * * - the caller must have the 'executor' role. */ + // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, + // thus any modifications to the operation during reentrancy should be caught. + // slither-disable-next-line reentrancy-eth function executeBatch( address[] calldata targets, uint256[] calldata values, diff --git a/slither.config.json b/slither.config.json index e52e3f5d5..2b618794a 100644 --- a/slither.config.json +++ b/slither.config.json @@ -1,4 +1,5 @@ { "detectors_to_run": "reentrancy-eth,reentrancy-no-eth,reentrancy-unlimited-gas", - "filter_paths": "contracts/mocks" + "filter_paths": "contracts/mocks", + "compile_force_framework": "hardhat" } \ No newline at end of file