From a28aafdc85a592776544f7978c6b1a462d28ede2 Mon Sep 17 00:00:00 2001 From: Francisco Date: Wed, 4 Jan 2023 11:03:40 -0300 Subject: [PATCH] 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 | 95 +++--- 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 | 89 +++--- 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 | 64 ++-- 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 | 95 ++++-- .../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 | 193 ++++++------ 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 | 67 ++-- test/utils/structs/EnumerableMap.test.js | 31 +- test/utils/structs/EnumerableSet.behavior.js | 28 +- test/utils/structs/EnumerableSet.test.js | 13 +- 135 files changed, 2754 insertions(+), 3138 deletions(-) diff --git a/.prettierrc b/.prettierrc index 923a710a6ad..e08e2427368 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 6cf991ef170..e0dea5e2c9b 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 8c94d757c6a..0d587caa8b7 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 5dde3a4710a..99bdf88b260 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 1722faf9163..74f40c4d173 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 c9d3c36a4c5..8e3e34340fb 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 b8030288d30..965ba37c39e 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 172fa094457..c847f2c928f 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 3ea1d73010f..41d1131bb41 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 5e3a0e7cd20..ca99dea0dc9 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 3ade7409a7a..45c707e6fcd 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 b39d23e0d61..de3d0daba18 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 e1f1823e834..fa3d6b120d8 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 51ddba33994..a3482322301 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 858ddb4aa27..afac259917a 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 22178ecca7d..a3af2c30479 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 8cf174206bf..3e2b148fda3 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 '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 '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 5c26c682111..9221f7c21c9 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 cbd0e01e3b5..26d0a2baad2 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 04ebce76ca3..f6044190331 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 15915a1c829..c17ad614dfd 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 c368eb7b063..b1a4a177faf 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 7baf8c2b4a9..da2028c6869 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 2ef27889960..f3e45b8d1b2 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 82bb7e0606c..4e94ba6b1a7 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 310ac369356..a935609830e 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 a462d5e541c..90efad3d013 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 5146848edbf..d5a41076b0b 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 b8ca81d28a4..dc308f98f65 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 bff95588256..9e7d26308da 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 ef74d4f69c1..1408c9f51a5 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, 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, 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, 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 5ab6233ca83..afd4c0495e5 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 81a1e228a45..5b90a691671 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 e5dd04cf0be..cc3cc17ef45 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 3b31f818972..83352ef8512 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 1c25be36aa1..231d57b2799 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 d32480ec16f..8d48b4ddca2 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 4c402737b4d..b0babbd37f8 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 b179e26f7ba..ffec8ace6fb 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 3e8e10b103e..334659e07cb 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 167734e9b19..2e8c7588815 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 763f0306828..84d36f926d4 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 981fe0715dd..26e94854439 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 fc3af64dd58..5062a9c9701 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 e9b50b0a3c3..7cf998b2dc5 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 f67b91bda1d..58757eb80f9 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 3e57764c8e4..afe07dae385 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 d4d25d1a15c..9e6ff9610a5 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 '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 'Optimism': - return BridgeOptimismMock.new(); - - case 'Polygon-Child': - return BridgePolygonChildMock.new(); - - default: - throw new Error(`CrossChain: ${type} is not supported`); + case 'AMB': + return BridgeAMBMock.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 'Optimism': + return BridgeOptimismMock.new(); + + case 'Polygon-Child': + return BridgePolygonChildMock.new(); + + default: + throw new Error(`CrossChain: ${type} is not supported`); } } diff --git a/test/helpers/customError.js b/test/helpers/customError.js index 8fea43426cd..3cfcd7277ea 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 26e2218bbcd..9851df66205 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 26825de337e..ced6c3858dc 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 aab0e2288a3..9abbcc8b9e5 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 66a479b5263..ff341aa12f3 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 4c14d1f1d62..417ef591dbb 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 895246b72d8..ecdba546214 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 15778505e09..24de1719d31 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 639767c256d..7ec9a97ab10 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 81c5ee35f94..b5fd3c51b21 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 09f719cec48..947b2ed957f 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 435792f2302..0867b93c9c9 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 0a4a8d0cfb9..968f00be802 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 0c49906d6c3..d65f3e0a534 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 07adba6ad69..811dc5671f0 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 33fef6f4119..da8f21bee18 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 20324e67b42..b0c1b3f6f4b 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 86701bcfdf2..5cca11e47de 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 1552ed9947d..5bf72bbe699 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 172a29b1f49..1a80bc86005 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 37afea0aa7a..96d448a9e2c 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 4e295d59ea5..ff432d37c85 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 2c854e2e885..f80d9935ac6 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 e7ace3c2c27..f4d5cedec57 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 0eb4952abe3..721d5a782ee 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 a12a5c9724f..95d9c18f74e 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 a8d83d12374..12d2594d622 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 736925bd6f3..864e89b5049 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 8bc54762ac8..41e47f06528 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 10d86e4b46c..6971eede981 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 a931bf60d4f..2edabc4bfd9 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 45264b77452..00acc81edfc 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 fe8c3a4ff0d..97bad1db192 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 86326f95dc7..76d66ff7a37 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) }); - - 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)); + 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.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 03c63045171..ead442b9929 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 6f7646d7718..fb0bb31d34d 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 18d3011cdd8..a340e71a775 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 5efaa556168..6a7c0001344 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 a82164cdfd9..cfb47bfa289 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 d095fb9d9d2..f85ffd56d8b 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 0c6b0982db8..eb673782699 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 c143790f45f..ad9ff29c501 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 dab116131ea..878989cb171 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 4e0dc0a841e..22e8071eb7e 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 436841a25c4..c0947957207 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 6e72e02bd1f..312430cb973 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 75a5603fb4f..6a4bc6dbc4f 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 17df12ea10d..3d492284606 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 04dd520a32b..c7fc8233f13 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 9d38071e317..1c0536bf5ff 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 a27b5f65866..c0274c669e2 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 8d9cb701ea6..f7baef4c111 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 4ad73552a59..0af614bd1ee 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 e821f32dd1e..0fd82228035 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 be104f467bf..b1585bc9154 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 efb8eae4333..44bc2535149 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 aea5e52f053..5d0f677152c 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 135a7f96d82..a78ae14e641 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 5d32e510af8..d939d59bdf2 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 520cf4fd0f2..d43d469cc17 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 8728e102153..08f7558d78b 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 709aa87d439..f372f7420c2 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 1216302650d..2fc27dc15a6 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 95cdddc9281..cfb80076956 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 11f3e72703f..6658871a00c 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 fc3df0db4d5..3b19cde60dd 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.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.$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.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.$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(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.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.$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.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.$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(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 70271eea1a3..62157b56a84 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 55ba75af092..11054c3e1b4 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 3386ca55c70..9e17a8bcebe 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 ab59059942d..f2059ed62c0 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 025a2a936ad..47627904bed 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 26c19b3662e..c5344db16ca 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 c1db67768b6..6d531c16d40 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 baa344a7f7e..bb68428125d 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 278f4ae1817..c78caf81244 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 ba030462574..83d0a6534c7 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 78e32724823..ba5aca2fc06 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 63cfa186cdc..6b97a646f0e 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( - MAX_UINT256, + expect(await this.math.$mulDiv(MAX_UINT256, MAX_UINT256, MAX_UINT256, Rounding.Down)).to.be.bignumber.equal( 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( - MAX_UINT256, - MAX_UINT256, + expect(await this.math.$mulDiv(MAX_UINT256, MAX_UINT256, MAX_UINT256, Rounding.Up)).to.be.bignumber.equal( 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 38374e5000a..63223f5d1ba 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 a74d7fb9631..9598ac57c5d 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 bbf492b20f3..c014e22ba9d 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 5702a4330f5..3b6530cf523 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 8900663d8aa..2fbb8dc2580 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 25ae8421580..b4b5ee37219 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; - - async function expectMembersMatch (map, keys, 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 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 14f31b4294b..548e73775cd 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 db56a2eca47..f80eb816984 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; - - async function expectMembersMatch (set, values) { +function shouldBehaveLikeSet(values, methods, events) { + const [valueA, valueB, valueC] = 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 27f1c731e74..862cb6d9eb4 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)',