From 71f9547f7418e5eab0a1deed6e84bfb9eeacc8ca Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Tue, 21 Feb 2023 18:34:15 +0200 Subject: [PATCH 01/14] =?UTF-8?q?=F0=9F=A4=96:=20prettier=20config?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .editorconfig | 5 +++++ .prettierrc | 17 +++-------------- package.json | 1 - yarn.lock | 44 +------------------------------------------- 4 files changed, 9 insertions(+), 58 deletions(-) diff --git a/.editorconfig b/.editorconfig index b3b682a97..abda0feff 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,4 +9,9 @@ indent_style = space indent_size = 4 [*.{js,yml}] +charset = utf-8 +insert_final_newline = true +end_of_line = lf +indent_style = space indent_size = 2 +max_line_length = 120 diff --git a/.prettierrc b/.prettierrc index d4ae4e317..c8c5e7306 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,20 +1,9 @@ { "singleQuote": true, "semi": false, - "trailingComma": "none", "bracketSpacing": true, "jsxBracketSameLine": false, - "printWidth": 120, - "overrides": [ - { - "files": "*.sol", - "options": { - "printWidth": 120, - "tabWidth": 4, - "useTabs": false, - "singleQuote": false, - "bracketSpacing": false - } - } - ] + "options": { + "editorconfig": true + } } diff --git a/package.json b/package.json index 6a3ea0df0..881548417 100644 --- a/package.json +++ b/package.json @@ -110,7 +110,6 @@ "lerna": "^3.22.1", "lint-staged": ">=10", "prettier": "^2.8.1", - "prettier-plugin-solidity": "^1.1.0", "solhint": "^3.3.7", "solhint-plugin-lido": "^0.0.4", "solidity-coverage": "^0.8.2", diff --git a/yarn.lock b/yarn.lock index 48d24ce95..0ad8cb66e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3579,7 +3579,6 @@ __metadata: node-gyp: ^8.4.1 openzeppelin-solidity: 2.0.0 prettier: ^2.8.1 - prettier-plugin-solidity: ^1.1.0 solhint: ^3.3.7 solhint-plugin-lido: ^0.0.4 solidity-coverage: ^0.8.2 @@ -4637,7 +4636,7 @@ __metadata: languageName: node linkType: hard -"@solidity-parser/parser@npm:^0.14.1, @solidity-parser/parser@npm:^0.14.5": +"@solidity-parser/parser@npm:^0.14.1": version: 0.14.5 resolution: "@solidity-parser/parser@npm:0.14.5" dependencies: @@ -10716,13 +10715,6 @@ __metadata: languageName: node linkType: hard -"emoji-regex@npm:^10.2.1": - version: 10.2.1 - resolution: "emoji-regex@npm:10.2.1" - checksum: 6a15ddd92b5782a99dec6a0700c4caab9ebc92bdcc90d1fc59e298a1628a694c465739f18a9103446687192bec89406b2910b6f22f4de48cf74f82f86194a3d8 - languageName: node - linkType: hard - "emoji-regex@npm:^7.0.1": version: 7.0.3 resolution: "emoji-regex@npm:7.0.3" @@ -21765,22 +21757,6 @@ fsevents@~2.3.2: languageName: node linkType: hard -"prettier-plugin-solidity@npm:^1.1.0": - version: 1.1.0 - resolution: "prettier-plugin-solidity@npm:1.1.0" - dependencies: - "@solidity-parser/parser": ^0.14.5 - emoji-regex: ^10.2.1 - escape-string-regexp: ^4.0.0 - semver: ^7.3.8 - solidity-comments-extractor: ^0.0.7 - string-width: ^4.2.3 - peerDependencies: - prettier: ^2.3.0 - checksum: 5abaf1480a46b270e6fca948768cc1fd203b8a142ca8efd5ee4687d8599cfbe8fa5991c84ac66aefebe924ea425b4f69b5662277cc7d6d0ce99350f490aa7d1c - languageName: node - linkType: hard - "prettier@npm:^1.14.3": version: 1.19.1 resolution: "prettier@npm:1.19.1" @@ -23684,17 +23660,6 @@ resolve@1.1.x: languageName: node linkType: hard -"semver@npm:^7.3.8": - version: 7.3.8 - resolution: "semver@npm:7.3.8" - dependencies: - lru-cache: ^6.0.0 - bin: - semver: bin/semver.js - checksum: cfb9c2101dae4ee93c415471f48797c750174d65def4e06ff691bf910194cc6ca92793e597be8302175ceb640100a3da36451e7656320da53b51167eeaf11eb5 - languageName: node - linkType: hard - "semver@npm:~5.4.1": version: 5.4.1 resolution: "semver@npm:5.4.1" @@ -24256,13 +24221,6 @@ resolve@1.1.x: languageName: node linkType: hard -"solidity-comments-extractor@npm:^0.0.7": - version: 0.0.7 - resolution: "solidity-comments-extractor@npm:0.0.7" - checksum: b3a463999290067e87f65335e0397d5932b21734c3b0867cad7dc710968120ec58e9f9a633001724b60a2bfb0c5d2aa90a7038fe2234fb130563564c5526200d - languageName: node - linkType: hard - "solidity-comments-freebsd-x64@npm:0.0.2": version: 0.0.2 resolution: "solidity-comments-freebsd-x64@npm:0.0.2" From f3962aa6ed81944359f779213f59850fbfb4eee8 Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Tue, 21 Feb 2023 18:53:41 +0200 Subject: [PATCH 02/14] =?UTF-8?q?=F0=9F=A4=96:=20tune=20eslint=20a=20bit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 2 -- 1 file changed, 2 deletions(-) diff --git a/.eslintrc b/.eslintrc index 9885e9214..52fd7e3a8 100644 --- a/.eslintrc +++ b/.eslintrc @@ -17,14 +17,12 @@ "rules": { "prettier/prettier": "error", - "max-len": ["warn", { "code": 140, "ignoreComments": true, "ignoreUrls": true }], "no-undef": "warn", "no-unused-vars": "warn", "prefer-const": "warn", "camelcase": "off", "eol-last": "warn", "no-multiple-empty-lines": "warn", - "comma-dangle": "warn", "quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }], "jsx-quotes": ["error", "prefer-single"], "no-useless-escape": "off", From c4b1426048edbc6d5144e527d0ac49c566ac88ad Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Tue, 21 Feb 2023 19:33:45 +0200 Subject: [PATCH 03/14] =?UTF-8?q?=F0=9F=A4=96:=20update=20eslint=20and=20p?= =?UTF-8?q?rettier?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 4 +- apps/lido/app/package.json | 18 +- apps/node-operators-registry/app/package.json | 18 +- package.json | 21 +- yarn.lock | 1713 +++++++++++++---- 5 files changed, 1369 insertions(+), 405 deletions(-) diff --git a/.eslintrc b/.eslintrc index 52fd7e3a8..26d9bc447 100644 --- a/.eslintrc +++ b/.eslintrc @@ -3,8 +3,8 @@ "node": true, "es2020": true }, - "extends": ["standard", "plugin:prettier/recommended", "prettier", "prettier/standard"], - "parser": "babel-eslint", + "extends": ["standard", "plugin:prettier/recommended"], + "parser": "@babel/eslint-parser", "parserOptions": { "ecmaVersion": 8, "sourceType": "module", diff --git a/apps/lido/app/package.json b/apps/lido/app/package.json index 4fd67bb1d..dc14dec61 100644 --- a/apps/lido/app/package.json +++ b/apps/lido/app/package.json @@ -19,25 +19,25 @@ "yup": "^0.29.3" }, "devDependencies": { - "@babel/core": "^7.11.6", + "@babel/core": "^7.21.0", "@babel/preset-env": "^7.11.5", "@babel/preset-react": "^7.10.1", "babel-eslint": "^10.1.0", "babel-plugin-styled-components": "^1.11.1", "copyfiles": "^2.3.0", - "eslint": "^7.9.0", - "eslint-config-prettier": "^6.11.0", - "eslint-config-standard": "^14.1.1", + "eslint": "^8.34.0", + "eslint-config-prettier": "^8.6.0", + "eslint-config-standard": "^17.0.0", "eslint-config-standard-react": "^9.2.0", - "eslint-plugin-import": "^2.22.0", + "eslint-plugin-import": "^2.27.5", "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^3.1.4", - "eslint-plugin-promise": "^4.2.1", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-promise": "^6.1.1", "eslint-plugin-react": "^7.20.6", "eslint-plugin-react-hooks": "^4.1.2", - "eslint-plugin-standard": "^4.0.1", + "eslint-plugin-standard": "^5.0.0", "parcel-bundler": "^1.12.4", - "prettier": "^2.1.2" + "prettier": "^2.8.4" }, "scripts": { "build": "yarn sync-assets && yarn build:app && yarn build:script", diff --git a/apps/node-operators-registry/app/package.json b/apps/node-operators-registry/app/package.json index 9ad4e2335..1b626b0a6 100644 --- a/apps/node-operators-registry/app/package.json +++ b/apps/node-operators-registry/app/package.json @@ -15,25 +15,25 @@ "yup": "^0.29.3" }, "devDependencies": { - "@babel/core": "^7.11.6", + "@babel/core": "^7.21.0", "@babel/preset-env": "^7.11.5", "@babel/preset-react": "^7.10.1", "babel-eslint": "^10.1.0", "babel-plugin-styled-components": "^1.11.1", "copyfiles": "^2.3.0", - "eslint": "^7.9.0", - "eslint-config-prettier": "^6.11.0", - "eslint-config-standard": "^14.1.1", + "eslint": "^8.34.0", + "eslint-config-prettier": "^8.6.0", + "eslint-config-standard": "^17.0.0", "eslint-config-standard-react": "^9.2.0", - "eslint-plugin-import": "^2.22.0", + "eslint-plugin-import": "^2.27.5", "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^3.1.4", - "eslint-plugin-promise": "^4.2.1", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-promise": "^6.1.1", "eslint-plugin-react": "^7.20.6", "eslint-plugin-react-hooks": "^4.1.2", - "eslint-plugin-standard": "^4.0.1", + "eslint-plugin-standard": "^5.0.0", "parcel-bundler": "^1.12.4", - "prettier": "^2.1.2" + "prettier": "^2.8.4" }, "scripts": { "build": "yarn sync-assets && yarn build:app && yarn build:script", diff --git a/package.json b/package.json index 881548417..ecf2455e6 100644 --- a/package.json +++ b/package.json @@ -75,7 +75,8 @@ "@aragon/id": "^2.0.3", "@aragon/minime": "1.0.0", "@aragon/test-helpers": "^2.1.0", - "@babel/core": "^7.12.3", + "@babel/core": "^7.21.0", + "@babel/eslint-parser": "^7.19.1", "@babel/node": "^7.12.1", "@babel/preset-env": "^7.11.5", "@babel/register": "^7.12.1", @@ -91,14 +92,14 @@ "chai": "^4.2.0", "dotenv": "^8.2.0", "electron": "^22.0.0", - "eslint": "^7.10.0", - "eslint-config-prettier": "^6.12.0", - "eslint-config-standard": "^14.1.1", - "eslint-plugin-import": "^2.22.1", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^3.1.4", - "eslint-plugin-promise": "^4.2.1", - "eslint-plugin-standard": "^4.0.1", + "eslint": "^8.34.0", + "eslint-config-prettier": "^8.6.0", + "eslint-config-standard": "^17.0.0", + "eslint-plugin-import": "^2.27.5", + "eslint-plugin-n": "^15.6.1", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-promise": "^6.1.1", + "eslint-plugin-standard": "^5.0.0", "eth-ens-namehash": "^2.0.8", "ethereumjs-testrpc-sc": "^6.5.1-sc.1", "hardhat": "2.12.7", @@ -109,7 +110,7 @@ "ipfs-http-client": "^55.0.0", "lerna": "^3.22.1", "lint-staged": ">=10", - "prettier": "^2.8.1", + "prettier": "^2.8.4", "solhint": "^3.3.7", "solhint-plugin-lido": "^0.0.4", "solidity-coverage": "^0.8.2", diff --git a/yarn.lock b/yarn.lock index 0ad8cb66e..480ff498e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5,6 +5,16 @@ __metadata: version: 4 cacheKey: 7 +"@ampproject/remapping@npm:^2.2.0": + version: 2.2.0 + resolution: "@ampproject/remapping@npm:2.2.0" + dependencies: + "@jridgewell/gen-mapping": ^0.1.0 + "@jridgewell/trace-mapping": ^0.3.9 + checksum: db5a84e3297235d6d1664f39456f6ae628c7c48256c0e73206f70f0e9f7092b5dc14a8a6db6508b056b8651fe3c1b7a09b6430cf48a780655452f341ac20c38f + languageName: node + linkType: hard + "@aragon/api-react@npm:^2.0.0": version: 2.0.0 resolution: "@aragon/api-react@npm:2.0.0" @@ -237,6 +247,15 @@ __metadata: languageName: node linkType: hard +"@babel/code-frame@npm:^7.18.6": + version: 7.18.6 + resolution: "@babel/code-frame@npm:7.18.6" + dependencies: + "@babel/highlight": ^7.18.6 + checksum: 7bc86ea4d6bf6792f0f5629b1a7addbb8e3160a39c03becffe62ac1f49482ab820eb74143427b877e087c6a28feda697487f0e84e6bdb3ab6aa54976ca5ac5e3 + languageName: node + linkType: hard + "@babel/compat-data@npm:^7.10.4, @babel/compat-data@npm:^7.11.0": version: 7.11.0 resolution: "@babel/compat-data@npm:7.11.0" @@ -248,7 +267,37 @@ __metadata: languageName: node linkType: hard -"@babel/core@npm:^7.11.6, @babel/core@npm:^7.4.4, @babel/core@npm:^7.7.5": +"@babel/compat-data@npm:^7.20.5": + version: 7.21.0 + resolution: "@babel/compat-data@npm:7.21.0" + checksum: 4ed0769daab7d2961cf03cd9dacd0f4c1f8931172e1cc2f2bf08e0ecd7cb0da2e317c0ea986dba3d979f9029ada8e5642b422a543b2725c89e4a2124522470a2 + languageName: node + linkType: hard + +"@babel/core@npm:7.21.0, @babel/core@npm:^7.21.0": + version: 7.21.0 + resolution: "@babel/core@npm:7.21.0" + dependencies: + "@ampproject/remapping": ^2.2.0 + "@babel/code-frame": ^7.18.6 + "@babel/generator": ^7.21.0 + "@babel/helper-compilation-targets": ^7.20.7 + "@babel/helper-module-transforms": ^7.21.0 + "@babel/helpers": ^7.21.0 + "@babel/parser": ^7.21.0 + "@babel/template": ^7.20.7 + "@babel/traverse": ^7.21.0 + "@babel/types": ^7.21.0 + convert-source-map: ^1.7.0 + debug: ^4.1.0 + gensync: ^1.0.0-beta.2 + json5: ^2.2.2 + semver: ^6.3.0 + checksum: 40940706ee1ad4672a7674902ea39e86e9e497786bba2c06fea1297147cdb209b3c898af01fa65288e5feb7a081c9c51bf704f986e3be5bc46b4cee812be06fe + languageName: node + linkType: hard + +"@babel/core@npm:^7.4.4, @babel/core@npm:^7.7.5": version: 7.11.6 resolution: "@babel/core@npm:7.11.6" dependencies: @@ -272,27 +321,17 @@ __metadata: languageName: node linkType: hard -"@babel/core@npm:^7.12.3": - version: 7.12.3 - resolution: "@babel/core@npm:7.12.3" +"@babel/eslint-parser@npm:^7.19.1": + version: 7.19.1 + resolution: "@babel/eslint-parser@npm:7.19.1" dependencies: - "@babel/code-frame": ^7.10.4 - "@babel/generator": ^7.12.1 - "@babel/helper-module-transforms": ^7.12.1 - "@babel/helpers": ^7.12.1 - "@babel/parser": ^7.12.3 - "@babel/template": ^7.10.4 - "@babel/traverse": ^7.12.1 - "@babel/types": ^7.12.1 - convert-source-map: ^1.7.0 - debug: ^4.1.0 - gensync: ^1.0.0-beta.1 - json5: ^2.1.2 - lodash: ^4.17.19 - resolve: ^1.3.2 - semver: ^5.4.1 - source-map: ^0.5.0 - checksum: 110eb092da34c8061db81647d3110e72438a805418195238ac0bb5ab5aec0fa9be9a1ce6350d442865254e088c7ee6edafafc2fbb72f105eb70414ac211e0995 + "@nicolo-ribaudo/eslint-scope-5-internals": 5.1.1-v1 + eslint-visitor-keys: ^2.1.0 + semver: ^6.3.0 + peerDependencies: + "@babel/core": ">=7.11.0" + eslint: ^7.5.0 || ^8.0.0 + checksum: e7bbcdd8b61bc7040af63e8b1abf109224085ccf3e72ef08cc00647b9fae4a74df54cfc0860218ce38f7520938494cdeeb3b1824b989366a733551faf7048667 languageName: node linkType: hard @@ -307,14 +346,15 @@ __metadata: languageName: node linkType: hard -"@babel/generator@npm:^7.12.1": - version: 7.12.1 - resolution: "@babel/generator@npm:7.12.1" +"@babel/generator@npm:^7.21.0": + version: 7.21.1 + resolution: "@babel/generator@npm:7.21.1" dependencies: - "@babel/types": ^7.12.1 + "@babel/types": ^7.21.0 + "@jridgewell/gen-mapping": ^0.3.2 + "@jridgewell/trace-mapping": ^0.3.17 jsesc: ^2.5.1 - source-map: ^0.5.0 - checksum: e0f5f9af4f5e1ed3afd02a57b1f15a85c7adb7e4deafbda2534bb49d889d6443b1fb5494e4543e31525788db20e1426e4a89c8cbd0c55289a8fdc6da0a9700cf + checksum: 86da188dd1727c624faf8bbba602c5549f787aaf2181ff4196f0e80b065df24fc6614ed3ed93868ce286499c8956ae26742ae5c0808a0a8ddba647f63bb9710e languageName: node linkType: hard @@ -373,6 +413,21 @@ __metadata: languageName: node linkType: hard +"@babel/helper-compilation-targets@npm:^7.20.7": + version: 7.20.7 + resolution: "@babel/helper-compilation-targets@npm:7.20.7" + dependencies: + "@babel/compat-data": ^7.20.5 + "@babel/helper-validator-option": ^7.18.6 + browserslist: ^4.21.3 + lru-cache: ^5.1.1 + semver: ^6.3.0 + peerDependencies: + "@babel/core": ^7.0.0 + checksum: ce4c22ffc09913e0b7ebe6c6ba082dcd5b832a36cb619e4b5fa31afe3ce5fbc462b824b6462c66798a5e10187d81ce718bf3099af5b29c5506f38377f588fbf4 + languageName: node + linkType: hard + "@babel/helper-create-class-features-plugin@npm:^7.10.4": version: 7.10.5 resolution: "@babel/helper-create-class-features-plugin@npm:7.10.5" @@ -413,6 +468,13 @@ __metadata: languageName: node linkType: hard +"@babel/helper-environment-visitor@npm:^7.18.9": + version: 7.18.9 + resolution: "@babel/helper-environment-visitor@npm:7.18.9" + checksum: b6f8963ee52b96786eb7bdc2fc7194ddf8fd13e47be7f06eddd144a1e8f91637fcaae129795be20bcde2a30abccdfc9a46bd9b253af718172941e87e1f3f5be2 + languageName: node + linkType: hard + "@babel/helper-explode-assignable-expression@npm:^7.10.4": version: 7.11.4 resolution: "@babel/helper-explode-assignable-expression@npm:7.11.4" @@ -433,6 +495,16 @@ __metadata: languageName: node linkType: hard +"@babel/helper-function-name@npm:^7.21.0": + version: 7.21.0 + resolution: "@babel/helper-function-name@npm:7.21.0" + dependencies: + "@babel/template": ^7.20.7 + "@babel/types": ^7.21.0 + checksum: eda46e999621468b933f91ae025a0d7a6aa129ea23b28d5421f21e7765aa9b7c9d989c5eb772be96d6317fd1dfdc2508e457f2ce41b8afa392334e189b725c58 + languageName: node + linkType: hard + "@babel/helper-get-function-arity@npm:^7.10.4": version: 7.10.4 resolution: "@babel/helper-get-function-arity@npm:7.10.4" @@ -451,6 +523,15 @@ __metadata: languageName: node linkType: hard +"@babel/helper-hoist-variables@npm:^7.18.6": + version: 7.18.6 + resolution: "@babel/helper-hoist-variables@npm:7.18.6" + dependencies: + "@babel/types": ^7.18.6 + checksum: afb9f3a3a9745f251c68bb375c4aff7a3eef5916bdaaf3f22b381aeafaa2dba7177607b595ce22558135023e0185f43f02f86efa292f5c388e33f58a8888cea5 + languageName: node + linkType: hard + "@babel/helper-member-expression-to-functions@npm:^7.10.4, @babel/helper-member-expression-to-functions@npm:^7.10.5": version: 7.11.0 resolution: "@babel/helper-member-expression-to-functions@npm:7.11.0" @@ -460,15 +541,6 @@ __metadata: languageName: node linkType: hard -"@babel/helper-member-expression-to-functions@npm:^7.12.1": - version: 7.12.1 - resolution: "@babel/helper-member-expression-to-functions@npm:7.12.1" - dependencies: - "@babel/types": ^7.12.1 - checksum: ae0cd0594bcc0343663747b28aa3433a312164eab259f919d184d39aed60dc2602b4cf0c7e287a22583c244cfc467b9097a289c1c4fd383f435ad10642c6a3d6 - languageName: node - linkType: hard - "@babel/helper-module-imports@npm:^7.0.0, @babel/helper-module-imports@npm:^7.10.4": version: 7.10.4 resolution: "@babel/helper-module-imports@npm:7.10.4" @@ -478,12 +550,12 @@ __metadata: languageName: node linkType: hard -"@babel/helper-module-imports@npm:^7.12.1": - version: 7.12.1 - resolution: "@babel/helper-module-imports@npm:7.12.1" +"@babel/helper-module-imports@npm:^7.18.6": + version: 7.18.6 + resolution: "@babel/helper-module-imports@npm:7.18.6" dependencies: - "@babel/types": ^7.12.1 - checksum: 261205f2e2c8da282af7c402089af49add550116b330cc2e9191af349da5f7930893bf147fcb1324ce71f515a287899d67ca3e644a4c94b5a1487d9dbfcda3b0 + "@babel/types": ^7.18.6 + checksum: 1f2c66c1653102d20dcc79aa56116e2ba11856f230f7b2b8fc43e2714e68683007c41b32591895400e3c8cc7eb04679bc40cbdc8f120053a7914d3c778eb9051 languageName: node linkType: hard @@ -502,20 +574,19 @@ __metadata: languageName: node linkType: hard -"@babel/helper-module-transforms@npm:^7.12.1": - version: 7.12.1 - resolution: "@babel/helper-module-transforms@npm:7.12.1" +"@babel/helper-module-transforms@npm:^7.21.0": + version: 7.21.0 + resolution: "@babel/helper-module-transforms@npm:7.21.0" dependencies: - "@babel/helper-module-imports": ^7.12.1 - "@babel/helper-replace-supers": ^7.12.1 - "@babel/helper-simple-access": ^7.12.1 - "@babel/helper-split-export-declaration": ^7.11.0 - "@babel/helper-validator-identifier": ^7.10.4 - "@babel/template": ^7.10.4 - "@babel/traverse": ^7.12.1 - "@babel/types": ^7.12.1 - lodash: ^4.17.19 - checksum: 902ed2b8e9ff45d33d20379f84b2269741a3a6108eb6c5e9e139186fd72e5bb405fac84bdcb7fae135c0cf4a5464d30bfb78ad00fc163b329aa9caa3630e7dd2 + "@babel/helper-environment-visitor": ^7.18.9 + "@babel/helper-module-imports": ^7.18.6 + "@babel/helper-simple-access": ^7.20.2 + "@babel/helper-split-export-declaration": ^7.18.6 + "@babel/helper-validator-identifier": ^7.19.1 + "@babel/template": ^7.20.7 + "@babel/traverse": ^7.21.0 + "@babel/types": ^7.21.0 + checksum: 508a0e0b504dedfc0a5da1b78f5f37ec7c5bd819126c77b3306dc38c77f00893b9e1dc85f7a5559c3f62309c3b023b5394ff35af9807749c5d1f48abb631bd1d languageName: node linkType: hard @@ -568,18 +639,6 @@ __metadata: languageName: node linkType: hard -"@babel/helper-replace-supers@npm:^7.12.1": - version: 7.12.1 - resolution: "@babel/helper-replace-supers@npm:7.12.1" - dependencies: - "@babel/helper-member-expression-to-functions": ^7.12.1 - "@babel/helper-optimise-call-expression": ^7.10.4 - "@babel/traverse": ^7.12.1 - "@babel/types": ^7.12.1 - checksum: e745f78b48647975392517c64df9311308f1badec3ca911d21126ba2f3f4aa36b4c31ad42f4cba4813d5b44f6c0417b2649d2d9991332f881d59ff25ab32c2a2 - languageName: node - linkType: hard - "@babel/helper-simple-access@npm:^7.10.4": version: 7.10.4 resolution: "@babel/helper-simple-access@npm:7.10.4" @@ -590,12 +649,12 @@ __metadata: languageName: node linkType: hard -"@babel/helper-simple-access@npm:^7.12.1": - version: 7.12.1 - resolution: "@babel/helper-simple-access@npm:7.12.1" +"@babel/helper-simple-access@npm:^7.20.2": + version: 7.20.2 + resolution: "@babel/helper-simple-access@npm:7.20.2" dependencies: - "@babel/types": ^7.12.1 - checksum: ca44e3f694957d4026e2837905cd4f4ec60d73f49f8d65d8592afa6d797cb000f261ce7db1ed3e14b51200467f4c04917cb84ebe395f3d153462ccce1b980322 + "@babel/types": ^7.20.2 + checksum: 73719cbb173148988e4bd74fb4fa5d133e56706e85c2f0722b14a1179e1eca7983e4d066f0cc70729f5dd4c5af2f1ff85f14c7e4dabd3d58ad8e8900251dada1 languageName: node linkType: hard @@ -617,6 +676,22 @@ __metadata: languageName: node linkType: hard +"@babel/helper-split-export-declaration@npm:^7.18.6": + version: 7.18.6 + resolution: "@babel/helper-split-export-declaration@npm:7.18.6" + dependencies: + "@babel/types": ^7.18.6 + checksum: 7d189c3998cbcc22a138e573b61f081877b4941e539fdc2fd2d73caa0ce1a9a7b1bdc2749d8d9ae3f81abf4aaaed9a87245a26f507d97489011848c0e5821e6a + languageName: node + linkType: hard + +"@babel/helper-string-parser@npm:^7.19.4": + version: 7.19.4 + resolution: "@babel/helper-string-parser@npm:7.19.4" + checksum: e9e9747c1b1b5991a5b4f31214055bd2997d3e0cd0b0c25f249862a6a891727762d62a8d79a09e94f2eb30d56af7fa2d00f90e97d50664bc75ac3316b42e2ea7 + languageName: node + linkType: hard + "@babel/helper-validator-identifier@npm:^7.10.4": version: 7.10.4 resolution: "@babel/helper-validator-identifier@npm:7.10.4" @@ -624,6 +699,20 @@ __metadata: languageName: node linkType: hard +"@babel/helper-validator-identifier@npm:^7.18.6, @babel/helper-validator-identifier@npm:^7.19.1": + version: 7.19.1 + resolution: "@babel/helper-validator-identifier@npm:7.19.1" + checksum: 4167919e3518fdec9c8fb087b0f62d4ba86a0e983d4b8294e13f75983244bf89c06f2c0ba8abf096e122adb49ecb69702a19c9b3e6dfb2abad5d4ad49c0348ba + languageName: node + linkType: hard + +"@babel/helper-validator-option@npm:^7.18.6": + version: 7.21.0 + resolution: "@babel/helper-validator-option@npm:7.21.0" + checksum: fbf7fa6f2d539a65ae1cd78d72666cdd160fb6cc04551b39f2acea8be44de872ca7e5f36bb527e28eeecdeafde233cd1569ad173ae3e041b91779a55e62b2d43 + languageName: node + linkType: hard + "@babel/helper-wrap-function@npm:^7.10.4": version: 7.10.4 resolution: "@babel/helper-wrap-function@npm:7.10.4" @@ -647,14 +736,14 @@ __metadata: languageName: node linkType: hard -"@babel/helpers@npm:^7.12.1": - version: 7.12.1 - resolution: "@babel/helpers@npm:7.12.1" +"@babel/helpers@npm:^7.21.0": + version: 7.21.0 + resolution: "@babel/helpers@npm:7.21.0" dependencies: - "@babel/template": ^7.10.4 - "@babel/traverse": ^7.12.1 - "@babel/types": ^7.12.1 - checksum: bbea976e6900dfe1c55bd8425ef982839650a1190859eae9a7cae737332b71375ea74e83863399d2941800142bdbe876829827907096d36685d7a980511c1d86 + "@babel/template": ^7.20.7 + "@babel/traverse": ^7.21.0 + "@babel/types": ^7.21.0 + checksum: 76a87b643c047fae5d512afee8cdf058153f7a5e032d480cdb8d24c63a1a54ccf2a286a71884f34932743857b3014bc74be8ec071715b5b31ac6e4395ad1c819 languageName: node linkType: hard @@ -669,6 +758,17 @@ __metadata: languageName: node linkType: hard +"@babel/highlight@npm:^7.18.6": + version: 7.18.6 + resolution: "@babel/highlight@npm:7.18.6" + dependencies: + "@babel/helper-validator-identifier": ^7.18.6 + chalk: ^2.0.0 + js-tokens: ^4.0.0 + checksum: 40e315e64afcdc30300368f136dd879f2bef862178e8c3f8ff69aa112ada58e77a80432f0a65ac2eb1baf26106d535d48758a3a4b8383ed2caf699d264d05496 + languageName: node + linkType: hard + "@babel/node@npm:^7.12.1": version: 7.12.1 resolution: "@babel/node@npm:7.12.1" @@ -698,12 +798,12 @@ __metadata: languageName: node linkType: hard -"@babel/parser@npm:^7.12.1, @babel/parser@npm:^7.12.3": - version: 7.12.3 - resolution: "@babel/parser@npm:7.12.3" +"@babel/parser@npm:^7.20.7, @babel/parser@npm:^7.21.0": + version: 7.21.1 + resolution: "@babel/parser@npm:7.21.1" bin: parser: ./bin/babel-parser.js - checksum: 3605bcf97e956ef36506ccb7e0ca4432025d8992c7e1f5d5b03976750a1198a0b27f461ab9304dbc5319a154b5ea19c09e72f87bfc5c08dd2780428734e13339 + checksum: c01ba012beb55a22fd31a1f6db99c052191928c7f7743d560abbd38773eef7ae3e5da553dcd8642c8b77d6acc87df70ec6dc66cad7242124e2e8b8f384d49e53 languageName: node linkType: hard @@ -1644,6 +1744,17 @@ __metadata: languageName: node linkType: hard +"@babel/template@npm:^7.20.7": + version: 7.20.7 + resolution: "@babel/template@npm:7.20.7" + dependencies: + "@babel/code-frame": ^7.18.6 + "@babel/parser": ^7.20.7 + "@babel/types": ^7.20.7 + checksum: 4a145d27a0e012310201ac8aec109dfa997f7e08efbca4b5955fce284bd54edb230a2569c00f8e7d9aab9a9c2f4a12d24ae987b2eaad15dd63ad6901104ae4c2 + languageName: node + linkType: hard + "@babel/traverse@npm:^7.10.4, @babel/traverse@npm:^7.11.5, @babel/traverse@npm:^7.4.4, @babel/traverse@npm:^7.4.5, @babel/traverse@npm:^7.7.0": version: 7.11.5 resolution: "@babel/traverse@npm:7.11.5" @@ -1661,20 +1772,21 @@ __metadata: languageName: node linkType: hard -"@babel/traverse@npm:^7.12.1": - version: 7.12.1 - resolution: "@babel/traverse@npm:7.12.1" +"@babel/traverse@npm:^7.21.0": + version: 7.21.0 + resolution: "@babel/traverse@npm:7.21.0" dependencies: - "@babel/code-frame": ^7.10.4 - "@babel/generator": ^7.12.1 - "@babel/helper-function-name": ^7.10.4 - "@babel/helper-split-export-declaration": ^7.11.0 - "@babel/parser": ^7.12.1 - "@babel/types": ^7.12.1 + "@babel/code-frame": ^7.18.6 + "@babel/generator": ^7.21.0 + "@babel/helper-environment-visitor": ^7.18.9 + "@babel/helper-function-name": ^7.21.0 + "@babel/helper-hoist-variables": ^7.18.6 + "@babel/helper-split-export-declaration": ^7.18.6 + "@babel/parser": ^7.21.0 + "@babel/types": ^7.21.0 debug: ^4.1.0 globals: ^11.1.0 - lodash: ^4.17.19 - checksum: a3040d94b72ba4214dc63b3d5f3517874dc8a72991a4c6916f48b756567e20c53c796feca6340db6edad9d48e7a9075e351c9b8daa0ed179d498cb80865be9da + checksum: 4d6d111c1efca0eb8bf0598f3526b136e4e0f273386a78093b6ce34748b29139b795b7b40e54d7b99f1255ed79c503ee354a24c5987cf0d3f78f9da7f8249a99 languageName: node linkType: hard @@ -1689,14 +1801,14 @@ __metadata: languageName: node linkType: hard -"@babel/types@npm:^7.12.1": - version: 7.12.1 - resolution: "@babel/types@npm:7.12.1" +"@babel/types@npm:^7.18.6, @babel/types@npm:^7.20.2, @babel/types@npm:^7.20.7, @babel/types@npm:^7.21.0": + version: 7.21.0 + resolution: "@babel/types@npm:7.21.0" dependencies: - "@babel/helper-validator-identifier": ^7.10.4 - lodash: ^4.17.19 + "@babel/helper-string-parser": ^7.19.4 + "@babel/helper-validator-identifier": ^7.19.1 to-fast-properties: ^2.0.0 - checksum: 0747b064093126e3ceba410c78e8ea438ed84cd68ad8abb2f98ffe88e2b600406096553bb5ef28cd40b29e68122820fe98e31ddfd0318fbb0efc2f4080d3417a + checksum: 724d90d1afe3f8f9cacac0f48751d63f972d70a3eebadb75bdccfb0b3aa04671533f8646a3669d430f4f0b80f1fa554c947bea3698ba2a1688d34885f9a87750 languageName: node linkType: hard @@ -1769,21 +1881,20 @@ __metadata: languageName: node linkType: hard -"@eslint/eslintrc@npm:^0.1.3": - version: 0.1.3 - resolution: "@eslint/eslintrc@npm:0.1.3" +"@eslint/eslintrc@npm:^1.4.1": + version: 1.4.1 + resolution: "@eslint/eslintrc@npm:1.4.1" dependencies: ajv: ^6.12.4 - debug: ^4.1.1 - espree: ^7.3.0 - globals: ^12.1.0 - ignore: ^4.0.6 + debug: ^4.3.2 + espree: ^9.4.0 + globals: ^13.19.0 + ignore: ^5.2.0 import-fresh: ^3.2.1 - js-yaml: ^3.13.1 - lodash: ^4.17.19 - minimatch: ^3.0.4 + js-yaml: ^4.1.0 + minimatch: ^3.1.2 strip-json-comments: ^3.1.1 - checksum: e9c5eaa5e706bcedbba6e7e1a2bc85faa7e3a9edbe71375e07240d1b6540fbb88d907bd5e5841b42c2a7a9683dcf031ea052c447c3c9d81ba4d0b74f0dd67e5f + checksum: cc5841156bcdb1642a438eaee459120b3c4f6bbe478f947034cfac355996299d8dea4c86acd081e2f1e8442b4e659bd48e48d53af0900e663ce9250a1a5572c9 languageName: node linkType: hard @@ -2662,6 +2773,31 @@ __metadata: languageName: node linkType: hard +"@humanwhocodes/config-array@npm:^0.11.8": + version: 0.11.8 + resolution: "@humanwhocodes/config-array@npm:0.11.8" + dependencies: + "@humanwhocodes/object-schema": ^1.2.1 + debug: ^4.1.1 + minimatch: ^3.0.5 + checksum: 3f6f4b8a6944d17b4cc426917e23d2b9dc7a02f92204d6c65075c1c0f8b8d4d0c49cf6e037d9ad1a6cc9b72f4aa1f1483ed05800e0ab9b773f4f29c9be0caa0e + languageName: node + linkType: hard + +"@humanwhocodes/module-importer@npm:^1.0.1": + version: 1.0.1 + resolution: "@humanwhocodes/module-importer@npm:1.0.1" + checksum: 4a2e3f2866153b0587679ebb74dc08908ca9c7e23fe499633b30f79019ad8f6e83ab85ebe6f6dd57f23c5ea61fdbd2dbe117b13d3356c109219511028828ba28 + languageName: node + linkType: hard + +"@humanwhocodes/object-schema@npm:^1.2.1": + version: 1.2.1 + resolution: "@humanwhocodes/object-schema@npm:1.2.1" + checksum: 5fc0c8672c9f0a3fcb9f71004e386fbbe6ff443309dfebfdbae4646536a416ed7d11fd2ce34be2b90dc4033e75922f4b4cde2f387a389d0462b1eb6034342c16 + languageName: node + linkType: hard + "@iarna/toml@npm:^2.2.0": version: 2.2.5 resolution: "@iarna/toml@npm:2.2.5" @@ -2718,6 +2854,58 @@ __metadata: languageName: node linkType: hard +"@jridgewell/gen-mapping@npm:^0.1.0": + version: 0.1.1 + resolution: "@jridgewell/gen-mapping@npm:0.1.1" + dependencies: + "@jridgewell/set-array": ^1.0.0 + "@jridgewell/sourcemap-codec": ^1.4.10 + checksum: 655d1e0cf4b93d3911979a3060280b5a3c1558f82733f78726320dc000a6d61eca9d4ec8cd156d7a2d7a0ccf9a39e1d1cf138d8a5e5aae4ddd718b4be1f174af + languageName: node + linkType: hard + +"@jridgewell/gen-mapping@npm:^0.3.2": + version: 0.3.2 + resolution: "@jridgewell/gen-mapping@npm:0.3.2" + dependencies: + "@jridgewell/set-array": ^1.0.1 + "@jridgewell/sourcemap-codec": ^1.4.10 + "@jridgewell/trace-mapping": ^0.3.9 + checksum: 9a5cb819d4b9c88580a95cd9ef5230ba6d8774589ac4fb9d52bf06e15182f70adae88fbe05972fc9e2e4b7f5b6452f282a9b7eba66fbbc0b98f979953e33c946 + languageName: node + linkType: hard + +"@jridgewell/resolve-uri@npm:3.1.0": + version: 3.1.0 + resolution: "@jridgewell/resolve-uri@npm:3.1.0" + checksum: e244743192d930084e0df6ad9e8eccd243326e09d258132a65ce003db3d89cf7d572dc77b49e3141f70ca6cc21fcead158da5e41e4f85b22e29f7632c7ec8086 + languageName: node + linkType: hard + +"@jridgewell/set-array@npm:^1.0.0, @jridgewell/set-array@npm:^1.0.1": + version: 1.1.2 + resolution: "@jridgewell/set-array@npm:1.1.2" + checksum: 1013d307699d2ccf04bcd7298e2c1f0932014cc55393ce56f9835925935a91c863e660013c5b2faed3b499518bb6c2918b1b7474112ee0122495980f36d35a22 + languageName: node + linkType: hard + +"@jridgewell/sourcemap-codec@npm:1.4.14, @jridgewell/sourcemap-codec@npm:^1.4.10": + version: 1.4.14 + resolution: "@jridgewell/sourcemap-codec@npm:1.4.14" + checksum: bc601cc782f385eac186a0151003e1de615b610282d294fa30840cd2382b8e657ea854bff4fe3e8e6107c81533bac0a8bd003d87eee4a7ffe839fba3a07e2969 + languageName: node + linkType: hard + +"@jridgewell/trace-mapping@npm:^0.3.17, @jridgewell/trace-mapping@npm:^0.3.9": + version: 0.3.17 + resolution: "@jridgewell/trace-mapping@npm:0.3.17" + dependencies: + "@jridgewell/resolve-uri": 3.1.0 + "@jridgewell/sourcemap-codec": 1.4.14 + checksum: 6e0a7c0c3c01087aab753f8ee9fde419dcf5f20f10665726b21a26325b29e76f240683041b240d2f055ada333d82c74a49b4012731ff403ea0a7037c78586474 + languageName: node + linkType: hard + "@lerna/add@npm:3.21.0": version: 3.21.0 resolution: "@lerna/add@npm:3.21.0" @@ -3535,7 +3723,8 @@ __metadata: "@aragon/minime": 1.0.0 "@aragon/os": ^4.4.0 "@aragon/test-helpers": ^2.1.0 - "@babel/core": ^7.12.3 + "@babel/core": ^7.21.0 + "@babel/eslint-parser": ^7.19.1 "@babel/node": ^7.12.1 "@babel/preset-env": ^7.11.5 "@babel/register": ^7.12.1 @@ -3555,14 +3744,14 @@ __metadata: concurrently: ^6.4.0 dotenv: ^8.2.0 electron: ^22.0.0 - eslint: ^7.10.0 - eslint-config-prettier: ^6.12.0 - eslint-config-standard: ^14.1.1 - eslint-plugin-import: ^2.22.1 - eslint-plugin-node: ^11.1.0 - eslint-plugin-prettier: ^3.1.4 - eslint-plugin-promise: ^4.2.1 - eslint-plugin-standard: ^4.0.1 + eslint: ^8.34.0 + eslint-config-prettier: ^8.6.0 + eslint-config-standard: ^17.0.0 + eslint-plugin-import: ^2.27.5 + eslint-plugin-n: ^15.6.1 + eslint-plugin-prettier: ^4.2.1 + eslint-plugin-promise: ^6.1.1 + eslint-plugin-standard: ^5.0.0 eth-ens-namehash: ^2.0.8 ethereumjs-testrpc-sc: ^6.5.1-sc.1 ethereumjs-util: ^7.0.8 @@ -3578,7 +3767,7 @@ __metadata: minimatch: ^6.2.0 node-gyp: ^8.4.1 openzeppelin-solidity: 2.0.0 - prettier: ^2.8.1 + prettier: ^2.8.4 solhint: ^3.3.7 solhint-plugin-lido: ^0.0.4 solidity-coverage: ^0.8.2 @@ -3631,6 +3820,15 @@ __metadata: languageName: node linkType: hard +"@nicolo-ribaudo/eslint-scope-5-internals@npm:5.1.1-v1": + version: 5.1.1-v1 + resolution: "@nicolo-ribaudo/eslint-scope-5-internals@npm:5.1.1-v1" + dependencies: + eslint-scope: 5.1.1 + checksum: 0d166bdbda46fe9c4f42ad1df1ae6a943b118cda138590cec21db92e383c02136b9a20152bc6736dd84a315dc3459dcd9be20072c7d2c36a5648be1f21d115da + languageName: node + linkType: hard + "@noble/hashes@npm:1.1.2": version: 1.1.2 resolution: "@noble/hashes@npm:1.1.2" @@ -3662,6 +3860,16 @@ __metadata: languageName: node linkType: hard +"@nodelib/fs.scandir@npm:2.1.5": + version: 2.1.5 + resolution: "@nodelib/fs.scandir@npm:2.1.5" + dependencies: + "@nodelib/fs.stat": 2.0.5 + run-parallel: ^1.1.9 + checksum: 91b3de88d9ba843b74057ebec53d97bb1ca006fcb794f1eb2becfe6faf114cb575c90b10fc20f7390358106ffa5e6bbc493506c24f2263a33aa69f90c1e77f74 + languageName: node + linkType: hard + "@nodelib/fs.stat@npm:2.0.3, @nodelib/fs.stat@npm:^2.0.2": version: 2.0.3 resolution: "@nodelib/fs.stat@npm:2.0.3" @@ -3669,6 +3877,13 @@ __metadata: languageName: node linkType: hard +"@nodelib/fs.stat@npm:2.0.5": + version: 2.0.5 + resolution: "@nodelib/fs.stat@npm:2.0.5" + checksum: a4fcf7408f2a1e11737856629b1259fb9ed658c464fabb17f77db1069fea5dd47abd5e92325b217617dbc116138d82ea6d33ffc07a426de940c5f6e08603da88 + languageName: node + linkType: hard + "@nodelib/fs.stat@npm:^1.1.2": version: 1.1.3 resolution: "@nodelib/fs.stat@npm:1.1.3" @@ -3686,6 +3901,16 @@ __metadata: languageName: node linkType: hard +"@nodelib/fs.walk@npm:^1.2.8": + version: 1.2.8 + resolution: "@nodelib/fs.walk@npm:1.2.8" + dependencies: + "@nodelib/fs.scandir": 2.1.5 + fastq: ^1.6.0 + checksum: f7870cf3f1071f53441c008c22e7e47a37c9d8138b55981d018a8fd8a28fc094a835bf03c917ef98bc08badbfaa063c3140af455a03274bbeec9094ec96afac7 + languageName: node + linkType: hard + "@nomicfoundation/ethereumjs-block@npm:^4.0.0": version: 4.0.0 resolution: "@nomicfoundation/ethereumjs-block@npm:4.0.0" @@ -5455,7 +5680,7 @@ __metadata: languageName: node linkType: hard -"acorn-jsx@npm:^5.0.0, acorn-jsx@npm:^5.2.0": +"acorn-jsx@npm:^5.0.0": version: 5.3.1 resolution: "acorn-jsx@npm:5.3.1" peerDependencies: @@ -5464,6 +5689,15 @@ __metadata: languageName: node linkType: hard +"acorn-jsx@npm:^5.3.2": + version: 5.3.2 + resolution: "acorn-jsx@npm:5.3.2" + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + checksum: 41c748fd26345f63fd27508c61596ffba5c4f23a8c98fffd2e75cf650c3928bb35af8658bf40d1ed18e56630cc9f4aa34d82bd5a3f53476df27d768eb03e9281 + languageName: node + linkType: hard + "acorn-walk@npm:^6.0.1": version: 6.2.0 resolution: "acorn-walk@npm:6.2.0" @@ -5487,7 +5721,7 @@ __metadata: languageName: node linkType: hard -"acorn@npm:^7.1.1, acorn@npm:^7.4.0": +"acorn@npm:^7.1.1": version: 7.4.1 resolution: "acorn@npm:7.4.1" bin: @@ -5505,6 +5739,15 @@ __metadata: languageName: node linkType: hard +"acorn@npm:^8.8.0": + version: 8.8.2 + resolution: "acorn@npm:8.8.2" + bin: + acorn: bin/acorn + checksum: ff4058b23372a00dbd1a32ebbe029b53e22198cf2dd70aed99a7715b07eb98c2f669f3ac27e969fcb3b15dbade7a6654e72dd4b845996ce5698520b122d1cc8c + languageName: node + linkType: hard + "address@npm:^1.0.1": version: 1.1.2 resolution: "address@npm:1.1.2" @@ -6007,6 +6250,19 @@ __metadata: languageName: node linkType: hard +"array-includes@npm:^3.1.6": + version: 3.1.6 + resolution: "array-includes@npm:3.1.6" + dependencies: + call-bind: ^1.0.2 + define-properties: ^1.1.4 + es-abstract: ^1.20.4 + get-intrinsic: ^1.1.3 + is-string: ^1.0.7 + checksum: 857edac24e17b5f5c06f00c35351a3d90c81015f5d802f17bc2b669a9f4854711126ce61efe916917e448274149a8f0c8ffa459441f4cd8224c586adfaf1f0f5 + languageName: node + linkType: hard + "array-union@npm:^1.0.1, array-union@npm:^1.0.2": version: 1.0.2 resolution: "array-union@npm:1.0.2" @@ -6047,13 +6303,15 @@ __metadata: languageName: node linkType: hard -"array.prototype.flat@npm:^1.2.3": - version: 1.2.3 - resolution: "array.prototype.flat@npm:1.2.3" +"array.prototype.flat@npm:^1.3.1": + version: 1.3.1 + resolution: "array.prototype.flat@npm:1.3.1" dependencies: - define-properties: ^1.1.3 - es-abstract: ^1.17.0-next.1 - checksum: f88a474d1cb3bfb2cfa44a5d36047bad146324f1beabbc743689d34fa36f29fab277008446ab56601c48721e1d50c5f47e5b3fae2583cc3724d1e6073cbdd901 + call-bind: ^1.0.2 + define-properties: ^1.1.4 + es-abstract: ^1.20.4 + es-shim-unscopables: ^1.0.0 + checksum: 17f1b9162c3de7be9206bac186cf38c42cf0d5b10fb32c3b41aa76946acbb7eefccf3d9759ff98c8fe08da30379478140880270e03614ee1718a7b04d71793b3 languageName: node linkType: hard @@ -6068,6 +6326,18 @@ __metadata: languageName: node linkType: hard +"array.prototype.flatmap@npm:^1.3.1": + version: 1.3.1 + resolution: "array.prototype.flatmap@npm:1.3.1" + dependencies: + call-bind: ^1.0.2 + define-properties: ^1.1.4 + es-abstract: ^1.20.4 + es-shim-unscopables: ^1.0.0 + checksum: cc430cf501f24032bddca17a94b0c06eaca91d45d9455806af72f8a66ebdbacd0e7d162c838a392eedc2e828a2706c18506bc951cac5df0e86700d3357e4b121 + languageName: node + linkType: hard + "array.prototype.map@npm:^1.0.1": version: 1.0.2 resolution: "array.prototype.map@npm:1.0.2" @@ -6353,6 +6623,13 @@ __metadata: languageName: node linkType: hard +"available-typed-arrays@npm:^1.0.5": + version: 1.0.5 + resolution: "available-typed-arrays@npm:1.0.5" + checksum: d08c9a44c1b5963395418ad32aff318eb70f368336338d2a6d81e5bcca2bc51ddd29103be15c0c468de7eb2df525af3f3dbc1fdc9a905161771967f305ee2a95 + languageName: node + linkType: hard + "await-semaphore@npm:^0.1.3": version: 0.1.3 resolution: "await-semaphore@npm:0.1.3" @@ -7649,6 +7926,20 @@ __metadata: languageName: node linkType: hard +"browserslist@npm:4.21.5, browserslist@npm:^4.21.3": + version: 4.21.5 + resolution: "browserslist@npm:4.21.5" + dependencies: + caniuse-lite: ^1.0.30001449 + electron-to-chromium: ^1.4.284 + node-releases: ^2.0.8 + update-browserslist-db: ^1.0.10 + bin: + browserslist: cli.js + checksum: 497c3b4a825452f1041da2d21da8e408886329ac1a75f64bef4a450c204475c7f35585080692e51a0ff57d1786cd18e0ff5527e4a4b5d9d1fb4aeb64a770c92e + languageName: node + linkType: hard + "browserslist@npm:^3.2.6": version: 3.2.8 resolution: "browserslist@npm:3.2.8" @@ -7834,6 +8125,15 @@ __metadata: languageName: node linkType: hard +"builtins@npm:^5.0.1": + version: 5.0.1 + resolution: "builtins@npm:5.0.1" + dependencies: + semver: ^7.0.0 + checksum: 84f830260b5388a0d058aa693f0d8b256edebf10049cf40e40cca999dfdfd698c6d75d909d8c03acfe006ea1f3b2499a0f7bef389b10afcad968449c79056c84 + languageName: node + linkType: hard + "busboy@npm:^1.6.0": version: 1.6.0 resolution: "busboy@npm:1.6.0" @@ -8011,6 +8311,16 @@ __metadata: languageName: node linkType: hard +"call-bind@npm:^1.0.0, call-bind@npm:^1.0.2": + version: 1.0.2 + resolution: "call-bind@npm:1.0.2" + dependencies: + function-bind: ^1.1.1 + get-intrinsic: ^1.0.2 + checksum: 18cc6107a1f028247f2b505dae73ad1c63b737addfcd43ff75159f072c5c827300c1fb66f26ee0ec70fc2fdd005ce68d65c05a2a34b74bab08c3b1921954ada9 + languageName: node + linkType: hard + "call-me-maybe@npm:^1.0.1": version: 1.0.1 resolution: "call-me-maybe@npm:1.0.1" @@ -8143,6 +8453,13 @@ __metadata: languageName: node linkType: hard +"caniuse-lite@npm:^1.0.30001449": + version: 1.0.30001457 + resolution: "caniuse-lite@npm:1.0.30001457" + checksum: 54d3bc005c033fe55c6ef2d0f50934e057d1d54e05a4d03eb76911963a3f74e0e35413bef8740cd32578306f0ee8e09bfa860b9fbf6e0630b6a47956d009e026 + languageName: node + linkType: hard + "caseless@npm:^0.12.0, caseless@npm:~0.12.0": version: 0.12.0 resolution: "caseless@npm:0.12.0" @@ -9075,13 +9392,6 @@ __metadata: languageName: node linkType: hard -"contains-path@npm:^0.1.0": - version: 0.1.0 - resolution: "contains-path@npm:0.1.0" - checksum: 59920a59a0c7d1244235d76b8cfd2b2e7a8dcc463fa578ef9d4d5a5a73eeb14d75dada6b21188e0b35f2474ae9efd10c3698372e674db9c6a904b281998b97d6 - languageName: node - linkType: hard - "content-disposition@npm:0.5.3, content-disposition@npm:^0.5.2": version: 0.5.3 resolution: "content-disposition@npm:0.5.3" @@ -9897,7 +10207,7 @@ __metadata: languageName: node linkType: hard -"debug@npm:4.3.4": +"debug@npm:4.3.4, debug@npm:^4.3.2": version: 4.3.4 resolution: "debug@npm:4.3.4" dependencies: @@ -9909,6 +10219,15 @@ __metadata: languageName: node linkType: hard +"debug@npm:^3.2.7": + version: 3.2.7 + resolution: "debug@npm:3.2.7" + dependencies: + ms: ^2.1.1 + checksum: 9fc1277e666db3af31df89e9e41f5c83da6e9de56d4a95b37e095d47ba1958238b8c7b49d4327b516465d46b6340bee723a97a7b2f28c5c7563f8b0a8fc9458a + languageName: node + linkType: hard + "debug@npm:^4.3.1, debug@npm:^4.3.3": version: 4.3.3 resolution: "debug@npm:4.3.3" @@ -10142,6 +10461,16 @@ __metadata: languageName: node linkType: hard +"define-properties@npm:^1.1.4": + version: 1.2.0 + resolution: "define-properties@npm:1.2.0" + dependencies: + has-property-descriptors: ^1.0.0 + object-keys: ^1.1.1 + checksum: 5d593089ff8eeca20baa9eed9f1dff22ecd229df25c8041d7b57642091b6d636fa71f07cd17ceb4591457f6ca421e0653f065526febf9375333cb00f393d1aa2 + languageName: node + linkType: hard + "define-property@npm:^0.2.5": version: 0.2.5 resolution: "define-property@npm:0.2.5" @@ -10383,16 +10712,6 @@ __metadata: languageName: node linkType: hard -"doctrine@npm:1.5.0": - version: 1.5.0 - resolution: "doctrine@npm:1.5.0" - dependencies: - esutils: ^2.0.2 - isarray: ^1.0.0 - checksum: aaffea02f963b8b07a78b1e27d7cef29be65d31be2c6681cb2872c2fb3781e14615bd05d4dff6036f75dcf3f191216058409fbfec805d3a7277a8647cd5bdee1 - languageName: node - linkType: hard - "doctrine@npm:^2.1.0": version: 2.1.0 resolution: "doctrine@npm:2.1.0" @@ -10646,6 +10965,13 @@ __metadata: languageName: node linkType: hard +"electron-to-chromium@npm:^1.4.284": + version: 1.4.304 + resolution: "electron-to-chromium@npm:1.4.304" + checksum: 0d06cef5df12f50667e000300e97a2f655173913907b4a81a8cd7b3a67c0853bbad8fa14dc02b79167970f9e0352320292f38b9d34cd13147cf1c23c721c66f2 + languageName: node + linkType: hard + "electron@npm:^22.0.0": version: 22.0.0 resolution: "electron@npm:22.0.0" @@ -10774,7 +11100,7 @@ __metadata: languageName: node linkType: hard -"enquirer@npm:^2.3.0, enquirer@npm:^2.3.5, enquirer@npm:^2.3.6": +"enquirer@npm:^2.3.0, enquirer@npm:^2.3.6": version: 2.3.6 resolution: "enquirer@npm:2.3.6" dependencies: @@ -10900,6 +11226,47 @@ __metadata: languageName: node linkType: hard +"es-abstract@npm:^1.19.0, es-abstract@npm:^1.20.4": + version: 1.21.1 + resolution: "es-abstract@npm:1.21.1" + dependencies: + available-typed-arrays: ^1.0.5 + call-bind: ^1.0.2 + es-set-tostringtag: ^2.0.1 + es-to-primitive: ^1.2.1 + function-bind: ^1.1.1 + function.prototype.name: ^1.1.5 + get-intrinsic: ^1.1.3 + get-symbol-description: ^1.0.0 + globalthis: ^1.0.3 + gopd: ^1.0.1 + has: ^1.0.3 + has-property-descriptors: ^1.0.0 + has-proto: ^1.0.1 + has-symbols: ^1.0.3 + internal-slot: ^1.0.4 + is-array-buffer: ^3.0.1 + is-callable: ^1.2.7 + is-negative-zero: ^2.0.2 + is-regex: ^1.1.4 + is-shared-array-buffer: ^1.0.2 + is-string: ^1.0.7 + is-typed-array: ^1.1.10 + is-weakref: ^1.0.2 + object-inspect: ^1.12.2 + object-keys: ^1.1.1 + object.assign: ^4.1.4 + regexp.prototype.flags: ^1.4.3 + safe-regex-test: ^1.0.0 + string.prototype.trimend: ^1.0.6 + string.prototype.trimstart: ^1.0.6 + typed-array-length: ^1.0.4 + unbox-primitive: ^1.0.2 + which-typed-array: ^1.1.9 + checksum: a7b1cf71b9e296aae354c293a6678944accab1a0b0ef30235524b340e6b02e814635bc74fcbbf36c174d1582ed5df34a8947a5081b4e06442e203998ebc4253c + languageName: node + linkType: hard + "es-array-method-boxes-properly@npm:^1.0.0": version: 1.0.0 resolution: "es-array-method-boxes-properly@npm:1.0.0" @@ -10922,6 +11289,26 @@ __metadata: languageName: node linkType: hard +"es-set-tostringtag@npm:^2.0.1": + version: 2.0.1 + resolution: "es-set-tostringtag@npm:2.0.1" + dependencies: + get-intrinsic: ^1.1.3 + has: ^1.0.3 + has-tostringtag: ^1.0.0 + checksum: 88b2e1c31d943fad46578d4f4c9e27bc7686ca4b1047e5f535ce086c4089e33162c0862c21aad2da17c4bb60a5eca4f434fc676d372be2818696e59c4adeab15 + languageName: node + linkType: hard + +"es-shim-unscopables@npm:^1.0.0": + version: 1.0.0 + resolution: "es-shim-unscopables@npm:1.0.0" + dependencies: + has: ^1.0.3 + checksum: 4d61eb7732ddd8480113e4914bfc190e2678489f126560c7e7cf1bad62115a38099d95522469c4b12ab4998236341f5f63951bdc0726d555590c422f0b0b9ca2 + languageName: node + linkType: hard + "es-to-primitive@npm:^1.2.1": version: 1.2.1 resolution: "es-to-primitive@npm:1.2.1" @@ -11087,29 +11474,14 @@ __metadata: languageName: node linkType: hard -"eslint-config-prettier@npm:^6.11.0": - version: 6.12.0 - resolution: "eslint-config-prettier@npm:6.12.0" - dependencies: - get-stdin: ^6.0.0 - peerDependencies: - eslint: ">=3.14.1" - bin: - eslint-config-prettier-check: bin/cli.js - checksum: 9371c0a8d05df36f3698247e703118a8eb95fa887aabc4b1e189c21e248ab9c49c3b8e5621f42826b89bbfd05aa52493ffddf0c41219db9b6e4df20e46e21da0 - languageName: node - linkType: hard - -"eslint-config-prettier@npm:^6.12.0": - version: 6.13.0 - resolution: "eslint-config-prettier@npm:6.13.0" - dependencies: - get-stdin: ^6.0.0 +"eslint-config-prettier@npm:^8.6.0": + version: 8.6.0 + resolution: "eslint-config-prettier@npm:8.6.0" peerDependencies: - eslint: ">=3.14.1" + eslint: ">=7.0.0" bin: - eslint-config-prettier-check: bin/cli.js - checksum: fe88da82a493da579fe57cc7b0be0cac5c84bfb5148d5e35abda99a73e6a0ab1125aa24ceae52144c9382c958f1f33efaadb4b86455cd28fef72172d9046a683 + eslint-config-prettier: bin/cli.js + checksum: 410fefb9747543acfd4f2c214b2d9f9dfde3f7a76c1c51367a772b2fc31e24aa6320f369e9d2ec18476822495774a18535fe6ea463f5b6fa529f6d8cb6eb48a1 languageName: node linkType: hard @@ -11135,36 +11507,38 @@ __metadata: languageName: node linkType: hard -"eslint-config-standard@npm:^14.1.1": - version: 14.1.1 - resolution: "eslint-config-standard@npm:14.1.1" +"eslint-config-standard@npm:^17.0.0": + version: 17.0.0 + resolution: "eslint-config-standard@npm:17.0.0" peerDependencies: - eslint: ">=6.2.2" - eslint-plugin-import: ">=2.18.0" - eslint-plugin-node: ">=9.1.0" - eslint-plugin-promise: ">=4.2.1" - eslint-plugin-standard: ">=4.0.0" - checksum: 779f599c458425ac453dcfe32c50384e093415fcbf6a90be2501914bccc287aa90de90fd5a914585b1810317a5c13600c157f4cbea4f82a4be09692e91eb9051 + eslint: ^8.0.1 + eslint-plugin-import: ^2.25.2 + eslint-plugin-n: ^15.0.0 + eslint-plugin-promise: ^6.0.0 + checksum: 3c80b161317f9c0c606c4e28030ddea3d5199485f5ab970c8f7f2f6bf00249ac271b18c92c77264d2893d48eb0265e9f1c4237fea2625bab0010a53911ef162a languageName: node linkType: hard -"eslint-import-resolver-node@npm:^0.3.4": - version: 0.3.4 - resolution: "eslint-import-resolver-node@npm:0.3.4" +"eslint-import-resolver-node@npm:^0.3.7": + version: 0.3.7 + resolution: "eslint-import-resolver-node@npm:0.3.7" dependencies: - debug: ^2.6.9 - resolve: ^1.13.1 - checksum: 825e34e662c988ece8229e6956a95f12d2fa19265b429e3e3db14e58bfe72e270c999cda0cfc690793ed6e6a3e49ffa8df0e0a8842d668a1f0f7de5ae1aa36f9 + debug: ^3.2.7 + is-core-module: ^2.11.0 + resolve: ^1.22.1 + checksum: 58e1fb09e7f11ea610ad85264d5caffcc62be6032f98badde1427b90f87522a8312a0a3390629742dae68c4a421422e6a522935c8dfc820e4baba46112c0a5b1 languageName: node linkType: hard -"eslint-module-utils@npm:^2.6.0": - version: 2.6.0 - resolution: "eslint-module-utils@npm:2.6.0" +"eslint-module-utils@npm:^2.7.4": + version: 2.7.4 + resolution: "eslint-module-utils@npm:2.7.4" dependencies: - debug: ^2.6.9 - pkg-dir: ^2.0.0 - checksum: f584af176480a702eedcdb3f610797f8b8d1293c3835ed71fadb579ec28400b91ded5283729418f63d48dc27c6358bd66f2bd839614d565a1b78d3c3440ee8f7 + debug: ^3.2.7 + peerDependenciesMeta: + eslint: + optional: true + checksum: 7b49c0f986602d3db779a41212e482bc45b15d4ace6f872b5b7e69146acae32a2caeab1b7f60a25e918862823c25381108e0c6c46385c7ed0f3c60988f323581 languageName: node linkType: hard @@ -11180,26 +11554,58 @@ __metadata: languageName: node linkType: hard -"eslint-plugin-import@npm:^2.22.0, eslint-plugin-import@npm:^2.22.1": - version: 2.22.1 - resolution: "eslint-plugin-import@npm:2.22.1" +"eslint-plugin-es@npm:^4.1.0": + version: 4.1.0 + resolution: "eslint-plugin-es@npm:4.1.0" dependencies: - array-includes: ^3.1.1 - array.prototype.flat: ^1.2.3 - contains-path: ^0.1.0 - debug: ^2.6.9 - doctrine: 1.5.0 - eslint-import-resolver-node: ^0.3.4 - eslint-module-utils: ^2.6.0 + eslint-utils: ^2.0.0 + regexpp: ^3.0.0 + peerDependencies: + eslint: ">=4.19.1" + checksum: ad9de9606447182056d1ec769afe4dca18a974d1124f3f76b2c5784fd957b6e8ec8c3028ecd8546a47e362c7c46cd1e71a1308a44adbb81c1d548c688ba1b641 + languageName: node + linkType: hard + +"eslint-plugin-import@npm:^2.27.5": + version: 2.27.5 + resolution: "eslint-plugin-import@npm:2.27.5" + dependencies: + array-includes: ^3.1.6 + array.prototype.flat: ^1.3.1 + array.prototype.flatmap: ^1.3.1 + debug: ^3.2.7 + doctrine: ^2.1.0 + eslint-import-resolver-node: ^0.3.7 + eslint-module-utils: ^2.7.4 has: ^1.0.3 - minimatch: ^3.0.4 - object.values: ^1.1.1 - read-pkg-up: ^2.0.0 - resolve: ^1.17.0 - tsconfig-paths: ^3.9.0 + is-core-module: ^2.11.0 + is-glob: ^4.0.3 + minimatch: ^3.1.2 + object.values: ^1.1.6 + resolve: ^1.22.1 + semver: ^6.3.0 + tsconfig-paths: ^3.14.1 peerDependencies: - eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 - checksum: 35ae09ceae6f0fe239f6b72e134d58d74762ad1ed0f57aa989affb856354e46bc082bb6df9399b624989107efb9ab9af2c91c08f03c0c70c5cb46a37676591ec + eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 + checksum: b7fb1bb5246965ac82cf08d8e71c5c3d269bdf0cc035347c6079d84293b57d5e85198b371267dc03262f9fcd196c2ab917973453e619f589a447e89fb3906668 + languageName: node + linkType: hard + +"eslint-plugin-n@npm:^15.6.1": + version: 15.6.1 + resolution: "eslint-plugin-n@npm:15.6.1" + dependencies: + builtins: ^5.0.1 + eslint-plugin-es: ^4.1.0 + eslint-utils: ^3.0.0 + ignore: ^5.1.1 + is-core-module: ^2.11.0 + minimatch: ^3.1.2 + resolve: ^1.22.1 + semver: ^7.3.8 + peerDependencies: + eslint: ">=7.0.0" + checksum: eeadc78e1ce25e549fc229302f66c14b49cdc3d19a74cacb9886e677c5ff0df0e820c3c06732b8360b105df99521c32fa165f59ed35d9492fec9ef536ef6bce1 languageName: node linkType: hard @@ -11219,22 +11625,27 @@ __metadata: languageName: node linkType: hard -"eslint-plugin-prettier@npm:^3.1.4": - version: 3.1.4 - resolution: "eslint-plugin-prettier@npm:3.1.4" +"eslint-plugin-prettier@npm:^4.2.1": + version: 4.2.1 + resolution: "eslint-plugin-prettier@npm:4.2.1" dependencies: prettier-linter-helpers: ^1.0.0 peerDependencies: - eslint: ">=5.0.0" - prettier: ">=1.13.0" - checksum: 4e4df155790a20a7ceef9008bbc22a677a8f7e790e9ef613a049a78dfe0b5dc3726afcd4bfd2a8ce41abc88c9a11db029819a722f70b940da32a03629e7f7832 + eslint: ">=7.28.0" + prettier: ">=2.0.0" + peerDependenciesMeta: + eslint-config-prettier: + optional: true + checksum: ff1b4155f247f09e1560ec13981ea6f512e858af13b9378f9d80fb1fe9fa89d0ffbc031c1f8390492e4579e79c278a34f361f2a7d4ffd80e677b4b80afb96056 languageName: node linkType: hard -"eslint-plugin-promise@npm:^4.2.1": - version: 4.2.1 - resolution: "eslint-plugin-promise@npm:4.2.1" - checksum: 8c233a0b5f5646e08709e999aa75973481ee46c45255ec4b4d1577915f68d79ae52f6f84e361af5b761971294bdb38ec86021515fa4cff178f57c989226dd671 +"eslint-plugin-promise@npm:^6.1.1": + version: 6.1.1 + resolution: "eslint-plugin-promise@npm:6.1.1" + peerDependencies: + eslint: ^7.0.0 || ^8.0.0 + checksum: fa6f418bcc402683c573f6cfb4a8816fec1f2c34323c575bfe12dbf31e78bd4b85cb28c7efa5d6412812896ec23b612449a4f37587650336f03e504109a18b1a languageName: node linkType: hard @@ -11268,12 +11679,22 @@ __metadata: languageName: node linkType: hard -"eslint-plugin-standard@npm:^4.0.1": - version: 4.0.1 - resolution: "eslint-plugin-standard@npm:4.0.1" +"eslint-plugin-standard@npm:^5.0.0": + version: 5.0.0 + resolution: "eslint-plugin-standard@npm:5.0.0" peerDependencies: eslint: ">=5.0.0" - checksum: f08e162e5826c376b39dde8c015c32389e2a8430525ec645e16d8f0be141d9e1b8377c1f0af020db962ec07b8e9341519d07f1ca79a7e8ab6a6481a217c37be4 + checksum: b51a7e87ae38d2ddd4e04b546fb72ca4e93c14789f028c751a0b31375ec40619281e84d386833419c3ded8911dafa56d0a2645f88510abbd37edaac7d77337a0 + languageName: node + linkType: hard + +"eslint-scope@npm:5.1.1": + version: 5.1.1 + resolution: "eslint-scope@npm:5.1.1" + dependencies: + esrecurse: ^4.3.0 + estraverse: ^4.1.1 + checksum: 79465cf5082f4216176f6d49c7d088de89ee890f912eb87b831f23ee9a5e17ed0f3f2ab6108fb8fefa0474ba5ebeaa9bdefbe49ba704bd879b73f2445e23ee10 languageName: node linkType: hard @@ -11287,13 +11708,13 @@ __metadata: languageName: node linkType: hard -"eslint-scope@npm:^5.1.1": - version: 5.1.1 - resolution: "eslint-scope@npm:5.1.1" +"eslint-scope@npm:^7.1.1": + version: 7.1.1 + resolution: "eslint-scope@npm:7.1.1" dependencies: esrecurse: ^4.3.0 - estraverse: ^4.1.1 - checksum: 79465cf5082f4216176f6d49c7d088de89ee890f912eb87b831f23ee9a5e17ed0f3f2ab6108fb8fefa0474ba5ebeaa9bdefbe49ba704bd879b73f2445e23ee10 + estraverse: ^5.2.0 + checksum: 86c4f451b36f0074692bc298291a01cc39b4da2df20bf14fc0bea72c2a86c14b22c6da79a01eb686b612752af124079b31fea9761a8f678de785dced7081e4a7 languageName: node linkType: hard @@ -11306,7 +11727,7 @@ __metadata: languageName: node linkType: hard -"eslint-utils@npm:^2.0.0, eslint-utils@npm:^2.1.0": +"eslint-utils@npm:^2.0.0": version: 2.1.0 resolution: "eslint-utils@npm:2.1.0" dependencies: @@ -11315,7 +11736,18 @@ __metadata: languageName: node linkType: hard -"eslint-visitor-keys@npm:^1.0.0, eslint-visitor-keys@npm:^1.1.0, eslint-visitor-keys@npm:^1.3.0": +"eslint-utils@npm:^3.0.0": + version: 3.0.0 + resolution: "eslint-utils@npm:3.0.0" + dependencies: + eslint-visitor-keys: ^2.0.0 + peerDependencies: + eslint: ">=5" + checksum: 035451529f016e28edd26e8951f15e28a6a4e58adff67bd0cb494879f360080750b9c779e46561369aec0657ac2b89dd8b0aa38476e8cdf50e635aa872fa27b6 + languageName: node + linkType: hard + +"eslint-visitor-keys@npm:^1.0.0, eslint-visitor-keys@npm:^1.1.0": version: 1.3.0 resolution: "eslint-visitor-keys@npm:1.3.0" checksum: 58ab7a0107621d8a0fe19142a5e1306fd527c0f36b65d5c79033639e80278d8060264804f42c56f68e5541c4cc83d9175f9143083774cec8222f6cd5a695306e @@ -11329,6 +11761,69 @@ __metadata: languageName: node linkType: hard +"eslint-visitor-keys@npm:^2.1.0": + version: 2.1.0 + resolution: "eslint-visitor-keys@npm:2.1.0" + checksum: 75eaae9006f5bcb9d1e09641719b840b83c4758f5f25bc06a0e94918d78658d0f19691bdc2e3b100604d0fe2d1eb94a2aab287ba24ad2f02f87cacdccb86c2e4 + languageName: node + linkType: hard + +"eslint-visitor-keys@npm:^3.3.0": + version: 3.3.0 + resolution: "eslint-visitor-keys@npm:3.3.0" + checksum: dd2991ba803154def4bc16eed8990360268e54ae48d6acce467cec71d8e670d494097e568eed3be2028c6e56aea1e2be57c90c536f7a94eb5bcf33f86098d9f2 + languageName: node + linkType: hard + +"eslint@npm:8.34.0, eslint@npm:^8.34.0": + version: 8.34.0 + resolution: "eslint@npm:8.34.0" + dependencies: + "@eslint/eslintrc": ^1.4.1 + "@humanwhocodes/config-array": ^0.11.8 + "@humanwhocodes/module-importer": ^1.0.1 + "@nodelib/fs.walk": ^1.2.8 + ajv: ^6.10.0 + chalk: ^4.0.0 + cross-spawn: ^7.0.2 + debug: ^4.3.2 + doctrine: ^3.0.0 + escape-string-regexp: ^4.0.0 + eslint-scope: ^7.1.1 + eslint-utils: ^3.0.0 + eslint-visitor-keys: ^3.3.0 + espree: ^9.4.0 + esquery: ^1.4.0 + esutils: ^2.0.2 + fast-deep-equal: ^3.1.3 + file-entry-cache: ^6.0.1 + find-up: ^5.0.0 + glob-parent: ^6.0.2 + globals: ^13.19.0 + grapheme-splitter: ^1.0.4 + ignore: ^5.2.0 + import-fresh: ^3.0.0 + imurmurhash: ^0.1.4 + is-glob: ^4.0.0 + is-path-inside: ^3.0.3 + js-sdsl: ^4.1.4 + js-yaml: ^4.1.0 + json-stable-stringify-without-jsonify: ^1.0.1 + levn: ^0.4.1 + lodash.merge: ^4.6.2 + minimatch: ^3.1.2 + natural-compare: ^1.4.0 + optionator: ^0.9.1 + regexpp: ^3.2.0 + strip-ansi: ^6.0.1 + strip-json-comments: ^3.1.0 + text-table: ^0.2.0 + bin: + eslint: bin/eslint.js + checksum: d64a438bb73eedd598d002dadb0b429749ef59c58a58ef391c094667b4b255408f4cf6a3d0467cfa686fda708530cc931f613c02e9114336b1ae523b6da12c17 + languageName: node + linkType: hard + "eslint@npm:^5.6.0": version: 5.16.0 resolution: "eslint@npm:5.16.0" @@ -11375,53 +11870,6 @@ __metadata: languageName: node linkType: hard -"eslint@npm:^7.10.0, eslint@npm:^7.9.0": - version: 7.11.0 - resolution: "eslint@npm:7.11.0" - dependencies: - "@babel/code-frame": ^7.0.0 - "@eslint/eslintrc": ^0.1.3 - ajv: ^6.10.0 - chalk: ^4.0.0 - cross-spawn: ^7.0.2 - debug: ^4.0.1 - doctrine: ^3.0.0 - enquirer: ^2.3.5 - eslint-scope: ^5.1.1 - eslint-utils: ^2.1.0 - eslint-visitor-keys: ^2.0.0 - espree: ^7.3.0 - esquery: ^1.2.0 - esutils: ^2.0.2 - file-entry-cache: ^5.0.1 - functional-red-black-tree: ^1.0.1 - glob-parent: ^5.0.0 - globals: ^12.1.0 - ignore: ^4.0.6 - import-fresh: ^3.0.0 - imurmurhash: ^0.1.4 - is-glob: ^4.0.0 - js-yaml: ^3.13.1 - json-stable-stringify-without-jsonify: ^1.0.1 - levn: ^0.4.1 - lodash: ^4.17.19 - minimatch: ^3.0.4 - natural-compare: ^1.4.0 - optionator: ^0.9.1 - progress: ^2.0.0 - regexpp: ^3.1.0 - semver: ^7.2.1 - strip-ansi: ^6.0.0 - strip-json-comments: ^3.1.0 - table: ^5.2.3 - text-table: ^0.2.0 - v8-compile-cache: ^2.0.3 - bin: - eslint: bin/eslint.js - checksum: 45ef6dc7b31684ca0f383ed9c6224e763197e1d49745542f4440e37286c947973388a6a7ebbf103eeee91ddb4af2652c5d22718f4130bfbbf4bd16a04103f82a - languageName: node - linkType: hard - "espree@npm:^5.0.1": version: 5.0.1 resolution: "espree@npm:5.0.1" @@ -11433,14 +11881,14 @@ __metadata: languageName: node linkType: hard -"espree@npm:^7.3.0": - version: 7.3.0 - resolution: "espree@npm:7.3.0" +"espree@npm:^9.4.0": + version: 9.4.1 + resolution: "espree@npm:9.4.1" dependencies: - acorn: ^7.4.0 - acorn-jsx: ^5.2.0 - eslint-visitor-keys: ^1.3.0 - checksum: dd2543c293e091532f3d6eda4a09ae49039ac65e69bc072aec952a5db6eb23eeee7617e99cde11414367104208c2dec13f709bbede0528d4f6854ce5cb734960 + acorn: ^8.8.0 + acorn-jsx: ^5.3.2 + eslint-visitor-keys: ^3.3.0 + checksum: 1f93d9b2a54186a79765521e3308181a049bc2ebc93ceee36c0d3645a49608c6cfcda439d8d982a6266dbc51db1889e19766419d74d6dda33d7a772620371ee7 languageName: node linkType: hard @@ -11474,7 +11922,7 @@ __metadata: languageName: node linkType: hard -"esquery@npm:^1.0.1, esquery@npm:^1.2.0": +"esquery@npm:^1.0.1": version: 1.3.1 resolution: "esquery@npm:1.3.1" dependencies: @@ -11483,6 +11931,15 @@ __metadata: languageName: node linkType: hard +"esquery@npm:^1.4.0": + version: 1.4.2 + resolution: "esquery@npm:1.4.2" + dependencies: + estraverse: ^5.1.0 + checksum: 40a124e8d64fd78faa4d6862a9d2797f195da170a0fbd7932928f4d3870b8a61ae2163323ad47c9c9b691a5db9977ae2e2f657e9820c501959c5163511d03780 + languageName: node + linkType: hard + "esrecurse@npm:^4.1.0, esrecurse@npm:^4.3.0": version: 4.3.0 resolution: "esrecurse@npm:4.3.0" @@ -12754,7 +13211,7 @@ __metadata: languageName: node linkType: hard -"fast-deep-equal@npm:^3.1.1": +"fast-deep-equal@npm:^3.1.1, fast-deep-equal@npm:^3.1.3": version: 3.1.3 resolution: "fast-deep-equal@npm:3.1.3" checksum: 451526766b219503131d11e823eaadd1533080b0be4860e316670b039dcaf31cd1007c2fe036a9b922abba7c040dfad5e942ed79d21f2ff849e50049f36e0fb7 @@ -12908,6 +13365,15 @@ __metadata: languageName: node linkType: hard +"file-entry-cache@npm:^6.0.1": + version: 6.0.1 + resolution: "file-entry-cache@npm:6.0.1" + dependencies: + flat-cache: ^3.0.4 + checksum: af83a412143100405a995bb7d9a31982ebcfabe6c545dac2e787fc5580b2da74e253ef62968057fa5bbfaf0811a8b85623aeea776e16c77e3ce4c2488b0e4821 + languageName: node + linkType: hard + "file-type@npm:^3.8.0": version: 3.9.0 resolution: "file-type@npm:3.9.0" @@ -13031,7 +13497,7 @@ __metadata: languageName: node linkType: hard -"find-up@npm:5.0.0": +"find-up@npm:5.0.0, find-up@npm:^5.0.0": version: 5.0.0 resolution: "find-up@npm:5.0.0" dependencies: @@ -13091,6 +13557,16 @@ __metadata: languageName: node linkType: hard +"flat-cache@npm:^3.0.4": + version: 3.0.4 + resolution: "flat-cache@npm:3.0.4" + dependencies: + flatted: ^3.1.0 + rimraf: ^3.0.2 + checksum: 72d86ccdf840e70227168a20bb908db8bc382360f0b241efd4c2e5cf2d17a7d566c0849dc4c5d2e8e6d7838e052539dcc319f0cf295c0bb9f47b71844c1de78d + languageName: node + linkType: hard + "flat@npm:^4.1.0": version: 4.1.0 resolution: "flat@npm:4.1.0" @@ -13118,6 +13594,13 @@ __metadata: languageName: node linkType: hard +"flatted@npm:^3.1.0": + version: 3.2.7 + resolution: "flatted@npm:3.2.7" + checksum: 9a4de5f058d3709e5ed362aed746c5847a34c645c88d756d101143720d7ea95b36f307ed4d0b0e7d19aefc8b58f36b7b9f7c261bbf7d37e18ed8f64c5a663b98 + languageName: node + linkType: hard + "flow-stoplight@npm:^1.0.0": version: 1.0.0 resolution: "flow-stoplight@npm:1.0.0" @@ -13163,7 +13646,7 @@ __metadata: languageName: node linkType: hard -"for-each@npm:~0.3.3": +"for-each@npm:^0.3.3, for-each@npm:~0.3.3": version: 0.3.3 resolution: "for-each@npm:0.3.3" dependencies: @@ -13474,6 +13957,18 @@ fsevents@~2.3.2: languageName: node linkType: hard +"function.prototype.name@npm:^1.1.5": + version: 1.1.5 + resolution: "function.prototype.name@npm:1.1.5" + dependencies: + call-bind: ^1.0.2 + define-properties: ^1.1.3 + es-abstract: ^1.19.0 + functions-have-names: ^1.2.2 + checksum: b9a1d5c1f157d7f222ef3ad5caa9a7999ae3c873bc66b26135041085c306ea3efd64db82aee9d18bbe23b0f8f15758f02f4e0b5a118ce3ca6bd327dcc320fe5f + languageName: node + linkType: hard + "functional-red-black-tree@npm:^1.0.1, functional-red-black-tree@npm:~1.0.1": version: 1.0.1 resolution: "functional-red-black-tree@npm:1.0.1" @@ -13488,6 +13983,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"functions-have-names@npm:^1.2.2": + version: 1.2.3 + resolution: "functions-have-names@npm:1.2.3" + checksum: c3133492123c2bfb8e5ec8ffa885518b1bacc31a0169db6f180dfa9cecd24cae9041c0f31f2733db382d1585ddb0b2226937488ce892cf7f2339d6a5687708f3 + languageName: node + linkType: hard + "ganache-cli@npm:^6.12.0": version: 6.12.1 resolution: "ganache-cli@npm:6.12.1" @@ -13647,6 +14149,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"gensync@npm:^1.0.0-beta.2": + version: 1.0.0-beta.2 + resolution: "gensync@npm:1.0.0-beta.2" + checksum: d523437689c97b3aba9c5cdeca4677d5fff9a29d620db693fea40d852bad63563110f16979d0170248439dbcd2ecee0780fb2533d3f0519f019081aa10767c60 + languageName: node + linkType: hard + "get-caller-file@npm:^1.0.1": version: 1.0.3 resolution: "get-caller-file@npm:1.0.3" @@ -13668,6 +14177,17 @@ fsevents@~2.3.2: languageName: node linkType: hard +"get-intrinsic@npm:^1.0.2, get-intrinsic@npm:^1.1.1, get-intrinsic@npm:^1.1.3, get-intrinsic@npm:^1.2.0": + version: 1.2.0 + resolution: "get-intrinsic@npm:1.2.0" + dependencies: + function-bind: ^1.1.1 + has: ^1.0.3 + has-symbols: ^1.0.3 + checksum: 7c2e9c764ac1e8ea854d467e5a6cc85e3e2b9e67b68b076bda6551ca40cbbc1e2cfe3825eef0e34c5efa6dfc7d8ac663757c56df0354f609c2abb7e33ac8e633 + languageName: node + linkType: hard + "get-iterator@npm:^1.0.2": version: 1.0.2 resolution: "get-iterator@npm:1.0.2" @@ -13734,13 +14254,6 @@ fsevents@~2.3.2: languageName: node linkType: hard -"get-stdin@npm:^6.0.0": - version: 6.0.0 - resolution: "get-stdin@npm:6.0.0" - checksum: b51d664838aef7f8353dc57371ce59cea54d8d584fec015a9d89d24561e95b97806d5b5ba120bc81574c9ed63cb3e210176ffa0ff9263c7e7ba4d56d0fe54913 - languageName: node - linkType: hard - "get-stream@npm:3.0.0, get-stream@npm:^3.0.0": version: 3.0.0 resolution: "get-stream@npm:3.0.0" @@ -13783,6 +14296,16 @@ fsevents@~2.3.2: languageName: node linkType: hard +"get-symbol-description@npm:^1.0.0": + version: 1.0.0 + resolution: "get-symbol-description@npm:1.0.0" + dependencies: + call-bind: ^1.0.2 + get-intrinsic: ^1.1.1 + checksum: 18f90e08b5f8ef01ec109a50b0ef44d24382439388678e82808f0699ea57863eb0242b805f12db5afed2447d90f3db36ea2fd676d9776eb57844ebda4a285db7 + languageName: node + linkType: hard + "get-value@npm:^2.0.3, get-value@npm:^2.0.6": version: 2.0.6 resolution: "get-value@npm:2.0.6" @@ -13895,6 +14418,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"glob-parent@npm:^6.0.2": + version: 6.0.2 + resolution: "glob-parent@npm:6.0.2" + dependencies: + is-glob: ^4.0.3 + checksum: 226293dc9d952acbe87d89eb4d87a1901a3eb64d9ec7338a65cb4dc8b337fe129d695e0bd5903b64f70c5044c6c3dfd5736fa18904f1d43d0136a752cb4d988f + languageName: node + linkType: hard + "glob-parent@npm:~5.1.2": version: 5.1.2 resolution: "glob-parent@npm:5.1.2" @@ -14035,12 +14567,12 @@ fsevents@~2.3.2: languageName: node linkType: hard -"globals@npm:^12.1.0": - version: 12.4.0 - resolution: "globals@npm:12.4.0" +"globals@npm:^13.19.0": + version: 13.20.0 + resolution: "globals@npm:13.20.0" dependencies: - type-fest: ^0.8.1 - checksum: 0b9764bdeab0bc9762dea8954a0d4c5db029420bd8bf693df9098ce7e045ccaf9b2d259185396fd048b051d42fdc8dc7ab02af62e3dbeb2324a78a05aac8d33c + type-fest: ^0.20.2 + checksum: 745fb2105fb9cffc40f2d4fc4a0af3bd6a951452d3ece66198834123fb6cfdf9a8992eac55534a8688608f7b7ea8e7f536d256fa9c93b3cde20f52089f7897a2 languageName: node linkType: hard @@ -14051,7 +14583,7 @@ fsevents@~2.3.2: languageName: node linkType: hard -"globalthis@npm:^1.0.1": +"globalthis@npm:^1.0.1, globalthis@npm:^1.0.3": version: 1.0.3 resolution: "globalthis@npm:1.0.3" dependencies: @@ -14120,6 +14652,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"gopd@npm:^1.0.1": + version: 1.0.1 + resolution: "gopd@npm:1.0.1" + dependencies: + get-intrinsic: ^1.1.3 + checksum: e3e651934e1915cb9dede75440b08542e6232aee55fd4718a432f9a9a341a090842533e202f12b60093adeaad47069dd22713ee5bca5fb63c6ea0ad4f5481c4c + languageName: node + linkType: hard + "got@npm:9.6.0, got@npm:^9.6.0": version: 9.6.0 resolution: "got@npm:9.6.0" @@ -14229,6 +14770,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"grapheme-splitter@npm:^1.0.4": + version: 1.0.4 + resolution: "grapheme-splitter@npm:1.0.4" + checksum: 6875e94add80360364a609e1fd0fe325e3b82326db2278dd36c1011a6bfc0e098811e791dedf9a88d4ae3f9d17a5c6a8d684948dd7b097f1f8d5ff905676e2b2 + languageName: node + linkType: hard + "growl@npm:1.10.5": version: 1.10.5 resolution: "growl@npm:1.10.5" @@ -14391,6 +14939,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"has-bigints@npm:^1.0.1, has-bigints@npm:^1.0.2": + version: 1.0.2 + resolution: "has-bigints@npm:1.0.2" + checksum: e85980d35de03b0b4d945526b01c354d0ee63b02ae92b448f3707ee1de19b002b821d2f493736b89be4aadb6a6fa6cbcbad4cb7530fff2285356096216e8f2e9 + languageName: node + linkType: hard + "has-flag@npm:^1.0.0": version: 1.0.0 resolution: "has-flag@npm:1.0.0" @@ -14412,6 +14967,22 @@ fsevents@~2.3.2: languageName: node linkType: hard +"has-property-descriptors@npm:^1.0.0": + version: 1.0.0 + resolution: "has-property-descriptors@npm:1.0.0" + dependencies: + get-intrinsic: ^1.1.1 + checksum: b80993daa0ef66fdeb44881d45dc352abb6627b8c9872534c6e8313a1438c936cfce3adf3eb6f5b0ccc8263ff3a0322851ed8858fbcac102f9e0bee1801c6b05 + languageName: node + linkType: hard + +"has-proto@npm:^1.0.1": + version: 1.0.1 + resolution: "has-proto@npm:1.0.1" + checksum: 9007a6cd8965598d62c710804e1f01b623dd91cf05a40f265e9dee36c1e4ee311c69fcf8c5063c608ccbd5cefedbd3e60f1d939ef32096631a447101b125c5c5 + languageName: node + linkType: hard + "has-symbol-support-x@npm:^1.4.1": version: 1.4.2 resolution: "has-symbol-support-x@npm:1.4.2" @@ -14426,6 +14997,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"has-symbols@npm:^1.0.2, has-symbols@npm:^1.0.3": + version: 1.0.3 + resolution: "has-symbols@npm:1.0.3" + checksum: 4b7e882feed6c1f53c8a01ec7a55ec0fe7654ebeeee76093916f8b0ccc3e1a6a115def0053e9113a353439c6276a90a5b9623fbed668bab660f65b04af25da2e + languageName: node + linkType: hard + "has-to-string-tag-x@npm:^1.2.0": version: 1.4.1 resolution: "has-to-string-tag-x@npm:1.4.1" @@ -14435,6 +15013,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"has-tostringtag@npm:^1.0.0": + version: 1.0.0 + resolution: "has-tostringtag@npm:1.0.0" + dependencies: + has-symbols: ^1.0.2 + checksum: f66b738e6b641f47a67f75a39afbdc7e2505bf174ea5fbab97082ad4d3ece66201508ea768775b2b72cdb849de63f3fedb2f005aac390d268db9f273a779df4a + languageName: node + linkType: hard + "has-unicode@npm:^2.0.0, has-unicode@npm:^2.0.1": version: 2.0.1 resolution: "has-unicode@npm:2.0.1" @@ -15008,6 +15595,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"ignore@npm:^5.2.0": + version: 5.2.4 + resolution: "ignore@npm:5.2.4" + checksum: 3d88da8802f9f5d4777f3db81b787508d97ef7d49ab8c04502ec4cda2dc467ebea641835965f97006633f6b9c7b9c048e6c89182e934396cc4addf9d62c66f4b + languageName: node + linkType: hard + "immediate@npm:^3.2.3": version: 3.3.0 resolution: "immediate@npm:3.3.0" @@ -15264,6 +15858,17 @@ fsevents@~2.3.2: languageName: node linkType: hard +"internal-slot@npm:^1.0.4": + version: 1.0.5 + resolution: "internal-slot@npm:1.0.5" + dependencies: + get-intrinsic: ^1.2.0 + has: ^1.0.3 + side-channel: ^1.0.4 + checksum: 16bcbe8c115729f169270ad031d15ab7bc02e092b80767db80ce04b2f37c48983cc21ce686a19fa9f03386abb2324f0f6d62bafc8dd0d4142fe238c5fe102ee1 + languageName: node + linkType: hard + "interpret@npm:^1.0.0": version: 1.4.0 resolution: "interpret@npm:1.4.0" @@ -15757,6 +16362,17 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-array-buffer@npm:^3.0.1": + version: 3.0.1 + resolution: "is-array-buffer@npm:3.0.1" + dependencies: + call-bind: ^1.0.2 + get-intrinsic: ^1.1.3 + is-typed-array: ^1.1.10 + checksum: 39cf488d58a4484904445aaaff717f46143594cd3682698abf259ff4a131fbe03df1f45ac73e6758b755de7e2cd6ec37ae6ffa0321d447caa5bbf904adfa4a7c + languageName: node + linkType: hard + "is-arrayish@npm:^0.2.1": version: 0.2.1 resolution: "is-arrayish@npm:0.2.1" @@ -15771,6 +16387,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-bigint@npm:^1.0.1": + version: 1.0.4 + resolution: "is-bigint@npm:1.0.4" + dependencies: + has-bigints: ^1.0.1 + checksum: 213e652ee9382a185b97e1c33956bdaa44a50eb466bec5d3a5c89d53bfca397e970ae70a75f5989332bb2790c6356f35ac1be5181f3622a84d8b8401dae13dad + languageName: node + linkType: hard + "is-binary-path@npm:^1.0.0": version: 1.0.1 resolution: "is-binary-path@npm:1.0.1" @@ -15789,6 +16414,16 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-boolean-object@npm:^1.1.0": + version: 1.1.2 + resolution: "is-boolean-object@npm:1.1.2" + dependencies: + call-bind: ^1.0.2 + has-tostringtag: ^1.0.0 + checksum: 2ce475fb2a4993a27a128054646a848e51c4864469dd9a6a1a077f19cc292fc0454b0bf73a9614b3b87614b7facbc100ce004920d206f7097563283bba5fcee3 + languageName: node + linkType: hard + "is-buffer@npm:^1.1.5": version: 1.1.6 resolution: "is-buffer@npm:1.1.6" @@ -15817,6 +16452,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-callable@npm:^1.2.7": + version: 1.2.7 + resolution: "is-callable@npm:1.2.7" + checksum: b7693ef4c5f0b1259952339d8cccacbe198eb34538372c70a290d35f3f73e0fe3eb88d3e942a17b53d6abf7b2add6c245654959c71e60923a649220a50b3588c + languageName: node + linkType: hard + "is-ci@npm:^1.0.10": version: 1.2.1 resolution: "is-ci@npm:1.2.1" @@ -15860,6 +16502,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-core-module@npm:^2.11.0, is-core-module@npm:^2.9.0": + version: 2.11.0 + resolution: "is-core-module@npm:2.11.0" + dependencies: + has: ^1.0.3 + checksum: a17868d944c75682438e638a6dd79fc1485f9ca34ba63d83c070d46504e079749fed241267952ac69f18097fd50cac5d9406704d4667d94fb9debbff4aa3d263 + languageName: node + linkType: hard + "is-data-descriptor@npm:^0.1.4": version: 0.1.4 resolution: "is-data-descriptor@npm:0.1.4" @@ -16022,6 +16673,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-glob@npm:^4.0.3": + version: 4.0.3 + resolution: "is-glob@npm:4.0.3" + dependencies: + is-extglob: ^2.1.1 + checksum: 8f6b4c42b78ece93a17dc6c83cd7e6f104319d6381ab24c8ba5643fcc14bec97dbdf6f8a5739d6333572557cb54e58a41c1edc89ffdb61d0277ec88ca9c3d6e3 + languageName: node + linkType: hard + "is-hex-prefixed@npm:1.0.0": version: 1.0.0 resolution: "is-hex-prefixed@npm:1.0.0" @@ -16102,6 +16762,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-negative-zero@npm:^2.0.2": + version: 2.0.2 + resolution: "is-negative-zero@npm:2.0.2" + checksum: 34aa0e6d7bf919ae3833591100ee371f21b33f602bc2af4fd85b77ee3f65b78611387791e47e9ce653a2b5a2062c21649c53824973f7858b4f8e045bb8846752 + languageName: node + linkType: hard + "is-npm@npm:^4.0.0": version: 4.0.0 resolution: "is-npm@npm:4.0.0" @@ -16109,6 +16776,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-number-object@npm:^1.0.4": + version: 1.0.7 + resolution: "is-number-object@npm:1.0.7" + dependencies: + has-tostringtag: ^1.0.0 + checksum: 99951ef179e651df5931a663e22e9f65bcb14cc141cfab94927cb9c165a2a29ec9564092b4533f725f85c7f6e6f89c94be31d5390e41e802fcd264d3ffcd1d7e + languageName: node + linkType: hard + "is-number@npm:^3.0.0": version: 3.0.0 resolution: "is-number@npm:3.0.0" @@ -16194,6 +16870,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-path-inside@npm:^3.0.3": + version: 3.0.3 + resolution: "is-path-inside@npm:3.0.3" + checksum: b19a2937441131e68b9eb9931ec8933bc87743a8f5364f6f7e1b8fc6c1403386ecf305835fb781e3986332fada456d71ff95af77ccda5806b35aac58234f9080 + languageName: node + linkType: hard + "is-plain-obj@npm:^1.0.0, is-plain-obj@npm:^1.1.0": version: 1.1.0 resolution: "is-plain-obj@npm:1.1.0" @@ -16240,6 +16923,16 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-regex@npm:^1.1.4": + version: 1.1.4 + resolution: "is-regex@npm:1.1.4" + dependencies: + call-bind: ^1.0.2 + has-tostringtag: ^1.0.0 + checksum: a9c466f93191ec306c5293d9d61a4360178bcdad0b642ef24d612a7392176c0f217498fde1e7c8e1cb3c520ac5c1b6d59da4b9148c23afbdd4374dec33127d0e + languageName: node + linkType: hard + "is-regex@npm:~1.0.5": version: 1.0.5 resolution: "is-regex@npm:1.0.5" @@ -16277,6 +16970,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-shared-array-buffer@npm:^1.0.2": + version: 1.0.2 + resolution: "is-shared-array-buffer@npm:1.0.2" + dependencies: + call-bind: ^1.0.2 + checksum: 9a7220da6df141880838f9e4ba766aa162e7d666e1d3e711486fd6da741aad5a19a346cb36976f282de6b3ac399b5b4f8f9b610093b3f916afd9802bf24eaf9a + languageName: node + linkType: hard + "is-ssh@npm:^1.3.0": version: 1.3.2 resolution: "is-ssh@npm:1.3.2" @@ -16307,6 +17009,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-string@npm:^1.0.7": + version: 1.0.7 + resolution: "is-string@npm:1.0.7" + dependencies: + has-tostringtag: ^1.0.0 + checksum: 29acb230cceafc33005a9710e1a25161c601282afc61fa2109cb60cf28f78ef0ef0b3ec20b1833f7b572f32ddf5034a0efa0c118af1a8ec58c277423c9d63418 + languageName: node + linkType: hard + "is-svg@npm:^3.0.0": version: 3.0.0 resolution: "is-svg@npm:3.0.0" @@ -16325,6 +17036,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-symbol@npm:^1.0.3": + version: 1.0.4 + resolution: "is-symbol@npm:1.0.4" + dependencies: + has-symbols: ^1.0.2 + checksum: 2794e0b9c3d6ca760b2f46c0132917746ce95fe034556e0e4da341e59f6171c9b733d2f0942475ecdee2e5b6d80a6e021eba200076fefcc79348ac48d56ad4b5 + languageName: node + linkType: hard + "is-text-path@npm:^1.0.1": version: 1.0.1 resolution: "is-text-path@npm:1.0.1" @@ -16334,6 +17054,19 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-typed-array@npm:^1.1.10, is-typed-array@npm:^1.1.9": + version: 1.1.10 + resolution: "is-typed-array@npm:1.1.10" + dependencies: + available-typed-arrays: ^1.0.5 + call-bind: ^1.0.2 + for-each: ^0.3.3 + gopd: ^1.0.1 + has-tostringtag: ^1.0.0 + checksum: 4d87e976b6f34c60dae9b79c7bcfde27bb7a3e1f845f274cecddd847151873729a9244850b5966fe9999aa507c5861991e12f2421824781f3e98f37bf9a54152 + languageName: node + linkType: hard + "is-typedarray@npm:^1.0.0, is-typedarray@npm:~1.0.0": version: 1.0.0 resolution: "is-typedarray@npm:1.0.0" @@ -16362,6 +17095,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"is-weakref@npm:^1.0.2": + version: 1.0.2 + resolution: "is-weakref@npm:1.0.2" + dependencies: + call-bind: ^1.0.2 + checksum: 0d54eb2c58d79060feec60937eb38b2071e70fdc9746df5804fcdda263ad0bb62813d35b297dddf319ae05121d14cd9dc12ba4f591a3577d4876f46202a4fa19 + languageName: node + linkType: hard + "is-windows@npm:^1.0.0, is-windows@npm:^1.0.2": version: 1.0.2 resolution: "is-windows@npm:1.0.2" @@ -16728,6 +17470,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"js-sdsl@npm:^4.1.4": + version: 4.3.0 + resolution: "js-sdsl@npm:4.3.0" + checksum: 09415cf28a6b7425f2cb5a9e36f22cbbb84d8ba222cd5f3717021a1565c03420adfb77c3b4d8f1a59bec3d18c304a441aa981d61f91d07542c06c627e479b049 + languageName: node + linkType: hard + "js-sha3@npm:0.5.5": version: 0.5.5 resolution: "js-sha3@npm:0.5.5" @@ -16794,7 +17543,7 @@ fsevents@~2.3.2: languageName: node linkType: hard -"js-yaml@npm:4.1.0": +"js-yaml@npm:4.1.0, js-yaml@npm:^4.1.0": version: 4.1.0 resolution: "js-yaml@npm:4.1.0" dependencies: @@ -17034,6 +17783,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"json5@npm:^2.2.2": + version: 2.2.3 + resolution: "json5@npm:2.2.3" + bin: + json5: lib/cli.js + checksum: c6ab786b232e576477f63d9b672ee4b546a181ac732e8cba0603e3e7352ac1fe9287344af1132c76c71613b5f69ce4f9b92ec41a10f51030ab764e015087932a + languageName: node + linkType: hard + "jsonfile@npm:^2.1.0": version: 2.4.0 resolution: "jsonfile@npm:2.4.0" @@ -17523,7 +18281,7 @@ fsevents@~2.3.2: "@aragon/api": ^2.0.0 "@aragon/api-react": ^2.0.0 "@aragon/ui": ^1.7.0 - "@babel/core": ^7.11.6 + "@babel/core": ^7.21.0 "@babel/preset-env": ^7.11.5 "@babel/preset-react": ^7.10.1 "@openzeppelin/contracts": 3.1.0 @@ -17532,20 +18290,20 @@ fsevents@~2.3.2: bn.js: ^5.1.3 copyfiles: ^2.3.0 core-js: ^3.6.5 - eslint: ^7.9.0 - eslint-config-prettier: ^6.11.0 - eslint-config-standard: ^14.1.1 + eslint: ^8.34.0 + eslint-config-prettier: ^8.6.0 + eslint-config-standard: ^17.0.0 eslint-config-standard-react: ^9.2.0 - eslint-plugin-import: ^2.22.0 + eslint-plugin-import: ^2.27.5 eslint-plugin-node: ^11.1.0 - eslint-plugin-prettier: ^3.1.4 - eslint-plugin-promise: ^4.2.1 + eslint-plugin-prettier: ^4.2.1 + eslint-plugin-promise: ^6.1.1 eslint-plugin-react: ^7.20.6 eslint-plugin-react-hooks: ^4.1.2 - eslint-plugin-standard: ^4.0.1 + eslint-plugin-standard: ^5.0.0 formik: ^2.2.0 parcel-bundler: ^1.12.4 - prettier: ^2.1.2 + prettier: ^2.8.4 react: ^16.13.1 react-copy-to-clipboard: ^5.0.2 react-dom: ^16.13.1 @@ -17642,18 +18400,6 @@ fsevents@~2.3.2: languageName: node linkType: hard -"load-json-file@npm:^2.0.0": - version: 2.0.0 - resolution: "load-json-file@npm:2.0.0" - dependencies: - graceful-fs: ^4.1.2 - parse-json: ^2.2.0 - pify: ^2.0.0 - strip-bom: ^3.0.0 - checksum: c6ea93d36099dd6e778c6c018c9e184ad65d278a9538c2280f959b040b1a9a756d8856bdaf8a38c8f1454eca19bf4798ea59f79ccd8bb1c33aa8b7ecbe157f0c - languageName: node - linkType: hard - "load-json-file@npm:^4.0.0": version: 4.0.0 resolution: "load-json-file@npm:4.0.0" @@ -18635,6 +19381,15 @@ fsevents@~2.3.2: languageName: node linkType: hard +"minimatch@npm:^3.0.5, minimatch@npm:^3.1.2": + version: 3.1.2 + resolution: "minimatch@npm:3.1.2" + dependencies: + brace-expansion: ^1.1.7 + checksum: 1a7584a6de279285a62c3b0ab2f3effde12566a5df983fb2a4f2eb9262f44238c7e2c692f202b075dc3df79c9a8479a22833cc28c841e98fa3ef989b1ceb264e + languageName: node + linkType: hard + "minimatch@npm:^5.1.0": version: 5.1.6 resolution: "minimatch@npm:5.1.6" @@ -18688,6 +19443,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"minimist@npm:^1.2.6": + version: 1.2.8 + resolution: "minimist@npm:1.2.8" + checksum: e3f8b422f9bff709afffa75fc87a8949b26a85bac5b69327f9ac03e5b826e6c7265945435848f23da6e54e78da5063734c2e0060bb1212bdfff4ad3ed6d23f52 + languageName: node + linkType: hard + "minipass-collect@npm:^1.0.2": version: 1.0.2 resolution: "minipass-collect@npm:1.0.2" @@ -19696,27 +20458,27 @@ fsevents@~2.3.2: "@aragon/api": ^2.0.0 "@aragon/api-react": ^2.0.0 "@aragon/ui": ^1.7.0 - "@babel/core": ^7.11.6 + "@babel/core": ^7.21.0 "@babel/preset-env": ^7.11.5 "@babel/preset-react": ^7.10.1 babel-eslint: ^10.1.0 babel-plugin-styled-components: ^1.11.1 copyfiles: ^2.3.0 core-js: ^3.6.5 - eslint: ^7.9.0 - eslint-config-prettier: ^6.11.0 - eslint-config-standard: ^14.1.1 + eslint: ^8.34.0 + eslint-config-prettier: ^8.6.0 + eslint-config-standard: ^17.0.0 eslint-config-standard-react: ^9.2.0 - eslint-plugin-import: ^2.22.0 + eslint-plugin-import: ^2.27.5 eslint-plugin-node: ^11.1.0 - eslint-plugin-prettier: ^3.1.4 - eslint-plugin-promise: ^4.2.1 + eslint-plugin-prettier: ^4.2.1 + eslint-plugin-promise: ^6.1.1 eslint-plugin-react: ^7.20.6 eslint-plugin-react-hooks: ^4.1.2 - eslint-plugin-standard: ^4.0.1 + eslint-plugin-standard: ^5.0.0 formik: ^2.2.0 parcel-bundler: ^1.12.4 - prettier: ^2.1.2 + prettier: ^2.8.4 react: ^16.13.1 react-dom: ^16.13.1 regenerator-runtime: ^0.13.7 @@ -19732,6 +20494,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"node-releases@npm:^2.0.8": + version: 2.0.10 + resolution: "node-releases@npm:2.0.10" + checksum: bf25020704d8406dc59d98c946479d509cc628deb5259ff16e31a3dc1f6d51f337af919502a31b21aba4735b208558341aee086318530065d1331b0800fc9157 + languageName: node + linkType: hard + "nofilter@npm:^1.0.4": version: 1.0.4 resolution: "nofilter@npm:1.0.4" @@ -20033,6 +20802,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"object-inspect@npm:^1.12.2, object-inspect@npm:^1.9.0": + version: 1.12.3 + resolution: "object-inspect@npm:1.12.3" + checksum: 554721848053312494b5e9e7b48999377292f6443966b189aab8b3f8a9a7bf42e38a68f80fa61fdbfbf10525bd4dbc7855cb907f5870a6faf842b1f9cb6b00b7 + languageName: node + linkType: hard + "object-inspect@npm:^1.8.0": version: 1.8.0 resolution: "object-inspect@npm:1.8.0" @@ -20111,6 +20887,18 @@ fsevents@~2.3.2: languageName: node linkType: hard +"object.assign@npm:^4.1.4": + version: 4.1.4 + resolution: "object.assign@npm:4.1.4" + dependencies: + call-bind: ^1.0.2 + define-properties: ^1.1.4 + has-symbols: ^1.0.3 + object-keys: ^1.1.1 + checksum: 0bf916575905dd41926472f857b02669700657b5c5b8fcd305d3c07d9ada74ac39b3980ebbbd6d4bcf3997cfdba0801862aa15b9fa2d087343f8376c38ba91fb + languageName: node + linkType: hard + "object.entries@npm:^1.1.2": version: 1.1.2 resolution: "object.entries@npm:1.1.2" @@ -20165,6 +20953,17 @@ fsevents@~2.3.2: languageName: node linkType: hard +"object.values@npm:^1.1.6": + version: 1.1.6 + resolution: "object.values@npm:1.1.6" + dependencies: + call-bind: ^1.0.2 + define-properties: ^1.1.4 + es-abstract: ^1.20.4 + checksum: 87fbbf75d66bc3bef66ada4e168d16fe63f79e5a922167a4b74d01b90234295cf0633899d9de87e88c680108225b2897c17de30708e499a64d581937af8b8b01 + languageName: node + linkType: hard + "obliterator@npm:^2.0.0": version: 2.0.1 resolution: "obliterator@npm:2.0.1" @@ -21025,6 +21824,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"path-parse@npm:^1.0.7": + version: 1.0.7 + resolution: "path-parse@npm:1.0.7" + checksum: 6de0bfa37b4f09af465ff3900fb4104ca9cb1e1fa5cbe869c40cedd10d5d625d04c284afc34967830eee780bf83fd69c017d72a23ffd35718ec861192ec91dd9 + languageName: node + linkType: hard + "path-to-regexp@npm:0.1.7": version: 0.1.7 resolution: "path-to-regexp@npm:0.1.7" @@ -21043,15 +21849,6 @@ fsevents@~2.3.2: languageName: node linkType: hard -"path-type@npm:^2.0.0": - version: 2.0.0 - resolution: "path-type@npm:2.0.0" - dependencies: - pify: ^2.0.0 - checksum: d028f828dffe48a0062dc4370d5118a0c45f5fb075b013a1dfb13eadd1426eba0c8c2a13fa78f19fc4fd8771ef2012e9d062f8f970c8e56df36d4fbbe5073b26 - languageName: node - linkType: hard - "path-type@npm:^3.0.0": version: 3.0.0 resolution: "path-type@npm:3.0.0" @@ -21118,6 +21915,13 @@ fsevents@~2.3.2: languageName: node linkType: hard +"picocolors@npm:^1.0.0": + version: 1.0.0 + resolution: "picocolors@npm:1.0.0" + checksum: 6616d34dd03bde8881c63402dea34f0b5972845b04b791b234446d4a408bc3d7f932acea3970a6b671d8f5c5aae1b1ce9fc1f89b0ed9a363469cf9da8e916b71 + languageName: node + linkType: hard + "picomatch@npm:^2.0.4, picomatch@npm:^2.0.5, picomatch@npm:^2.2.1, picomatch@npm:^2.2.2": version: 2.2.2 resolution: "picomatch@npm:2.2.2" @@ -21181,15 +21985,6 @@ fsevents@~2.3.2: languageName: node linkType: hard -"pkg-dir@npm:^2.0.0": - version: 2.0.0 - resolution: "pkg-dir@npm:2.0.0" - dependencies: - find-up: ^2.1.0 - checksum: f8ae3a151714c61283aeb24385b10355a238732fab822a560145c670c21350da2024f01918231222bcdfce53ec5d69056681be2c2cffe3f3a06e462b9ef2ac29 - languageName: node - linkType: hard - "pkg-dir@npm:^3.0.0": version: 3.0.0 resolution: "pkg-dir@npm:3.0.0" @@ -21766,12 +22561,12 @@ fsevents@~2.3.2: languageName: node linkType: hard -"prettier@npm:^2.1.2, prettier@npm:^2.8.1": - version: 2.8.2 - resolution: "prettier@npm:2.8.2" +"prettier@npm:^2.8.4": + version: 2.8.4 + resolution: "prettier@npm:2.8.4" bin: prettier: bin-prettier.js - checksum: 6f85fc14fb0cbdc8b247edff2168fcc5a2bc79fc58b7e9433e245f959781f56dd62202857c896c33e6c20a6d465baabd395201af91dcbb3023bedda07c728f31 + checksum: 59758930b2ad33f9335c2bb2c154faa2826c230c2bf21e83d6b1ddf07f66c880a0603a8bdf4cc91cbe24b7fcdd7927bcaadbeab012794e0ff5f171b9993b3573 languageName: node linkType: hard @@ -22504,16 +23299,6 @@ fsevents@~2.3.2: languageName: node linkType: hard -"read-pkg-up@npm:^2.0.0": - version: 2.0.0 - resolution: "read-pkg-up@npm:2.0.0" - dependencies: - find-up: ^2.0.0 - read-pkg: ^2.0.0 - checksum: f35e4cb4577b994fc9497886672c748de766ab034e24f029111b6bbbfe757b2e27b6d2b82a28a38f45d9d89ea8a9b1d3c04854e5f991d5deed48f4c9ff7baeb9 - languageName: node - linkType: hard - "read-pkg-up@npm:^3.0.0": version: 3.0.0 resolution: "read-pkg-up@npm:3.0.0" @@ -22546,17 +23331,6 @@ fsevents@~2.3.2: languageName: node linkType: hard -"read-pkg@npm:^2.0.0": - version: 2.0.0 - resolution: "read-pkg@npm:2.0.0" - dependencies: - load-json-file: ^2.0.0 - normalize-package-data: ^2.3.2 - path-type: ^2.0.0 - checksum: ddf911317fba54abb447b1d76dd1785c37e1360f7b1e39d83201f6f3807572391ab7392f11727a9c4d90600ebc6616d22e72514d2291688c89ebd440148840b4 - languageName: node - linkType: hard - "read-pkg@npm:^3.0.0": version: 3.0.0 resolution: "read-pkg@npm:3.0.0" @@ -22838,6 +23612,17 @@ fsevents@~2.3.2: languageName: node linkType: hard +"regexp.prototype.flags@npm:^1.4.3": + version: 1.4.3 + resolution: "regexp.prototype.flags@npm:1.4.3" + dependencies: + call-bind: ^1.0.2 + define-properties: ^1.1.3 + functions-have-names: ^1.2.2 + checksum: 0490e98e3b503368bd75cf3cd855c593b827db47978672e9d57a5a0ba72c0a14ef007f841ff85e2cb38f8d821b210d592c4d447e28db186bf2ee43c72335a872 + languageName: node + linkType: hard + "regexpp@npm:^2.0.1": version: 2.0.1 resolution: "regexpp@npm:2.0.1" @@ -22845,13 +23630,20 @@ fsevents@~2.3.2: languageName: node linkType: hard -"regexpp@npm:^3.0.0, regexpp@npm:^3.1.0": +"regexpp@npm:^3.0.0": version: 3.1.0 resolution: "regexpp@npm:3.1.0" checksum: 69d0ce6b449cf35d3732d6341a1e70850360ffc619f8eef10629871c462e614853fffb80d3f00fc17cd0bb5b8f34b0cde5be4b434e72c0eb3fbba2360c8b5ac4 languageName: node linkType: hard +"regexpp@npm:^3.2.0": + version: 3.2.0 + resolution: "regexpp@npm:3.2.0" + checksum: 91aaccadd046fc1b60477df4f44bb69d61aeca81082f2ebf879a32ff25cd7bcb7067fcd69eb9a0987ca0a3e8e2d837b2737e80961c14a504a912bed4c51c8e3e + languageName: node + linkType: hard + "regexpu-core@npm:^2.0.0": version: 2.0.0 resolution: "regexpu-core@npm:2.0.0" @@ -23142,6 +23934,19 @@ resolve@1.1.x: languageName: node linkType: hard +resolve@^1.22.1: + version: 1.22.1 + resolution: "resolve@npm:1.22.1" + dependencies: + is-core-module: ^2.9.0 + path-parse: ^1.0.7 + supports-preserve-symlinks-flag: ^1.0.0 + bin: + resolve: bin/resolve + checksum: ceb58a131752b5fecedbac0eca6df09d2bac0f54d6a221e525738cae49c24bf7905f9d3c06b163f32096d599aaa054bc3709f91fcc23695ccd3dd72a38513ed7 + languageName: node + linkType: hard + "resolve@patch:resolve@1.1.x#builtin": version: 1.1.7 resolution: "resolve@patch:resolve@npm%3A1.1.7#builtin::version=1.1.7&hash=3388aa" @@ -23158,6 +23963,19 @@ resolve@1.1.x: languageName: node linkType: hard +"resolve@patch:resolve@^1.22.1#builtin": + version: 1.22.1 + resolution: "resolve@patch:resolve@npm%3A1.22.1#builtin::version=1.22.1&hash=3388aa" + dependencies: + is-core-module: ^2.9.0 + path-parse: ^1.0.7 + supports-preserve-symlinks-flag: ^1.0.0 + bin: + resolve: bin/resolve + checksum: 2029682d258c40a095e3860f31c521e08a7c2f679425534550a0b3b760bf6cc231f9e1b63bb12d6dcdf3c1d19379332692fa0ba4434f0cd9e725321dad8a5173 + languageName: node + linkType: hard + "responselike@npm:1.0.2, responselike@npm:^1.0.2": version: 1.0.2 resolution: "responselike@npm:1.0.2" @@ -23409,6 +24227,17 @@ resolve@1.1.x: languageName: node linkType: hard +"safe-regex-test@npm:^1.0.0": + version: 1.0.0 + resolution: "safe-regex-test@npm:1.0.0" + dependencies: + call-bind: ^1.0.2 + get-intrinsic: ^1.1.3 + is-regex: ^1.1.4 + checksum: 73c9a2a79a40725371a3cdd14e0e1a8338057ef873488b23ff4b46d08a0e2c4bf0a0df3e2cde6f3fd3f67085552b74c191a52b099240efde11f59d10acd82cc5 + languageName: node + linkType: hard + "safe-regex@npm:^1.1.0": version: 1.1.0 resolution: "safe-regex@npm:1.1.0" @@ -23629,7 +24458,18 @@ resolve@1.1.x: languageName: node linkType: hard -"semver@npm:^7.2.1, semver@npm:^7.3.2": +"semver@npm:^7.0.0, semver@npm:^7.3.8": + version: 7.3.8 + resolution: "semver@npm:7.3.8" + dependencies: + lru-cache: ^6.0.0 + bin: + semver: bin/semver.js + checksum: cfb9c2101dae4ee93c415471f48797c750174d65def4e06ff691bf910194cc6ca92793e597be8302175ceb640100a3da36451e7656320da53b51167eeaf11eb5 + languageName: node + linkType: hard + +"semver@npm:^7.3.2": version: 7.3.2 resolution: "semver@npm:7.3.2" bin: @@ -23925,6 +24765,17 @@ resolve@1.1.x: languageName: node linkType: hard +"side-channel@npm:^1.0.4": + version: 1.0.4 + resolution: "side-channel@npm:1.0.4" + dependencies: + call-bind: ^1.0.0 + get-intrinsic: ^1.0.2 + object-inspect: ^1.9.0 + checksum: 84258ce3edb1ad35810ca17eccd52fd504b5d4da59447a6829cfd1ae8e3cff97b7df2a14f9a45b7aaa3b507ded95626cf20a500735d3b797e9ffb1eba3cfa9e7 + languageName: node + linkType: hard + "signal-exit@npm:^3.0.0, signal-exit@npm:^3.0.2": version: 3.0.3 resolution: "signal-exit@npm:3.0.3" @@ -24850,6 +25701,17 @@ resolve@1.1.x: languageName: node linkType: hard +"string.prototype.trimend@npm:^1.0.6": + version: 1.0.6 + resolution: "string.prototype.trimend@npm:1.0.6" + dependencies: + call-bind: ^1.0.2 + define-properties: ^1.1.4 + es-abstract: ^1.20.4 + checksum: 2001a6707fa89e33a454886fe7e2cb927864d288c423069fe97b0748bb8977713a1c7f46b652c4e3296fe2704b673a5087e2773e387b93935a67e44ab3e71c4f + languageName: node + linkType: hard + "string.prototype.trimstart@npm:^1.0.1": version: 1.0.1 resolution: "string.prototype.trimstart@npm:1.0.1" @@ -24860,6 +25722,17 @@ resolve@1.1.x: languageName: node linkType: hard +"string.prototype.trimstart@npm:^1.0.6": + version: 1.0.6 + resolution: "string.prototype.trimstart@npm:1.0.6" + dependencies: + call-bind: ^1.0.2 + define-properties: ^1.1.4 + es-abstract: ^1.20.4 + checksum: 0d87be52f12f075084d3eb00d76e37e36592299b2e3a9f46ccd86489a989b47e6f688c34584a3f9498989730c1840c364a83c3d1ba3aa653c96a52f5e299f2cf + languageName: node + linkType: hard + "string_decoder@npm:^1.0.0, string_decoder@npm:^1.1.1": version: 1.3.0 resolution: "string_decoder@npm:1.3.0" @@ -25191,6 +26064,13 @@ resolve@1.1.x: languageName: node linkType: hard +"supports-preserve-symlinks-flag@npm:^1.0.0": + version: 1.0.0 + resolution: "supports-preserve-symlinks-flag@npm:1.0.0" + checksum: a0f31404231c6450ae2d23acd7b066a31b9ca4649e02b6c70a4fbc955693cf65067507f450f43e4480df0f1fd87f72f78ed12c1a268a876c528be977c7096a69 + languageName: node + linkType: hard + "svgo@npm:^1.0.0, svgo@npm:^1.3.2": version: 1.3.2 resolution: "svgo@npm:1.3.2" @@ -25909,6 +26789,18 @@ resolve@1.1.x: languageName: node linkType: hard +"tsconfig-paths@npm:^3.14.1": + version: 3.14.1 + resolution: "tsconfig-paths@npm:3.14.1" + dependencies: + "@types/json5": ^0.0.29 + json5: ^1.0.1 + minimist: ^1.2.6 + strip-bom: ^3.0.0 + checksum: f9e00c9b784d882579bdb6a2bdef6ec53907dd6e6da6aff4e92305f149daca939b0e29c8332abc6b6a990b273ee2971baaf5394b73e8927f3c53d149d47dcb4c + languageName: node + linkType: hard + "tsconfig-paths@npm:^3.9.0": version: 3.9.0 resolution: "tsconfig-paths@npm:3.9.0" @@ -26011,6 +26903,13 @@ resolve@1.1.x: languageName: node linkType: hard +"type-fest@npm:^0.20.2": + version: 0.20.2 + resolution: "type-fest@npm:0.20.2" + checksum: 1f887bc6150e632fb772fd28e33c22a4ab036c6f484fa9ac2e2115f6cae9d62bba7ca0368e3332b539d85bd2c8391c7bff22ad410abcbc9ab3774d61e250b210 + languageName: node + linkType: hard + "type-fest@npm:^0.3.0": version: 0.3.1 resolution: "type-fest@npm:0.3.1" @@ -26063,6 +26962,17 @@ resolve@1.1.x: languageName: node linkType: hard +"typed-array-length@npm:^1.0.4": + version: 1.0.4 + resolution: "typed-array-length@npm:1.0.4" + dependencies: + call-bind: ^1.0.2 + for-each: ^0.3.3 + is-typed-array: ^1.1.9 + checksum: 9cc13aa4d0f8f9beb27a5dad5dbde011824ada72532e2b352229c600fd3df324f8ab1c56645597d68507798940b2aecf6e978f76535702bdb09a83aafd5e0361 + languageName: node + linkType: hard + "typedarray-to-buffer@npm:^3.1.5": version: 3.1.5 resolution: "typedarray-to-buffer@npm:3.1.5" @@ -26150,6 +27060,18 @@ resolve@1.1.x: languageName: node linkType: hard +"unbox-primitive@npm:^1.0.2": + version: 1.0.2 + resolution: "unbox-primitive@npm:1.0.2" + dependencies: + call-bind: ^1.0.2 + has-bigints: ^1.0.2 + has-symbols: ^1.0.3 + which-boxed-primitive: ^1.0.2 + checksum: 81713e98693758495541559c34f2a08a487353205ca6d3cb48b590bdf901c684f76c022e462515d9d6c0169d1cb62979e618d9744dbce54d0cd3cbe714be1863 + languageName: node + linkType: hard + "unbzip2-stream@npm:^1.0.9": version: 1.4.3 resolution: "unbzip2-stream@npm:1.4.3" @@ -26378,6 +27300,20 @@ resolve@1.1.x: languageName: node linkType: hard +"update-browserslist-db@npm:^1.0.10": + version: 1.0.10 + resolution: "update-browserslist-db@npm:1.0.10" + dependencies: + escalade: ^3.1.1 + picocolors: ^1.0.0 + peerDependencies: + browserslist: ">= 4.21.0" + bin: + browserslist-lint: cli.js + checksum: 3dca54e562e94fca889b5b9e05c671973d772f7eafbfd420c4483ec1d732a6c630510c14020df76b555d25c5c2a2e99a5225c49d23edc171d8c3b18167be9a4f + languageName: node + linkType: hard + "update-notifier@npm:^4.1.1": version: 4.1.3 resolution: "update-notifier@npm:4.1.3" @@ -26597,7 +27533,7 @@ resolve@1.1.x: languageName: node linkType: hard -"v8-compile-cache@npm:^2.0.0, v8-compile-cache@npm:^2.0.3": +"v8-compile-cache@npm:^2.0.0": version: 2.1.1 resolution: "v8-compile-cache@npm:2.1.1" checksum: 1290922fe1501a732155206f2d516f91bdfd7acf318542ffe2813ff06465cf49051fae7e1a40f3e0a56cf78b41f799473f6e389fec0534e4ecc62eb4105cf22f @@ -28086,6 +29022,19 @@ resolve@1.1.x: languageName: node linkType: hard +"which-boxed-primitive@npm:^1.0.2": + version: 1.0.2 + resolution: "which-boxed-primitive@npm:1.0.2" + dependencies: + is-bigint: ^1.0.1 + is-boolean-object: ^1.1.0 + is-number-object: ^1.0.4 + is-string: ^1.0.5 + is-symbol: ^1.0.3 + checksum: 771ef43357afbba9febf2da4867b2971ada0a5126227f9b7926751525e3721f7f5f3722f8c60af67881714d9a82a98ed686f1768490cfb2cd40518df5f2e056e + languageName: node + linkType: hard + "which-module@npm:^1.0.0": version: 1.0.0 resolution: "which-module@npm:1.0.0" @@ -28100,6 +29049,20 @@ resolve@1.1.x: languageName: node linkType: hard +"which-typed-array@npm:^1.1.9": + version: 1.1.9 + resolution: "which-typed-array@npm:1.1.9" + dependencies: + available-typed-arrays: ^1.0.5 + call-bind: ^1.0.2 + for-each: ^0.3.3 + gopd: ^1.0.1 + has-tostringtag: ^1.0.0 + is-typed-array: ^1.1.10 + checksum: bc1ee3e2273b4fb710ef41746e8c6442c7d10ad30e859b695eef0a64cf56fbe3ae92146c3f50fb69d7163d2779426041d1fa1f3096673f8072547c74d88586f6 + languageName: node + linkType: hard + "which@npm:1.3.1, which@npm:^1.1.1, which@npm:^1.2.9, which@npm:^1.3.1": version: 1.3.1 resolution: "which@npm:1.3.1" From 16ce326df496afb4bcf7e146dcf417ae5dd86323 Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Tue, 21 Feb 2023 19:34:35 +0200 Subject: [PATCH 04/14] =?UTF-8?q?=F0=9F=A4=96:=20enable=20pre-commit=20esl?= =?UTF-8?q?int=20--fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .husky/pre-commit | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.husky/pre-commit b/.husky/pre-commit index 189614670..265cc9c25 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -4,5 +4,4 @@ yarn compile yarn lint:sol -# TODO: uncomment. it's temporarily disabled on staking_router + withdrawals-poc merge -# yarn lint:js:fix +yarn lint:js:fix From cd462ab41b307426c8181927a1748763996e4642 Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Tue, 21 Feb 2023 19:39:18 +0200 Subject: [PATCH 05/14] =?UTF-8?q?=F0=9F=92=85:=20mass=20prettier=20reforma?= =?UTF-8?q?t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/lido/hardhat.config.js | 6 +- apps/lido/scripts/buidler-hooks.js | 2 +- .../node-operators-registry/hardhat.config.js | 6 +- .../scripts/buidler-hooks.js | 2 +- estimate_deposit_loop_gas.js | 30 +- hardhat.config.aragon-apps.js | 4 +- hardhat.config.js | 85 ++-- lib/src/dao.js | 6 +- lib/src/index.js | 8 +- lib/src/lido.js | 12 +- lib/src/node-operators-registry.js | 8 +- lib/src/oracle.js | 11 +- test/0.4.24/helpers/constants.js | 6 +- test/0.4.24/helpers/dao.js | 6 +- test/0.4.24/helpers/permissions.js | 2 +- test/0.4.24/helpers/permit_helpers.js | 12 +- test/0.4.24/helpers/sign_utils.js | 2 +- test/0.4.24/legacyoracle.test.js | 1 - test/0.4.24/lido-deposit-scenarios.test.js | 36 +- test/0.4.24/lido-handle-oracle-report.test.js | 174 ++++--- test/0.4.24/lido.test.js | 257 ++++++---- .../node-operators-registry-penalty.test.js | 135 +++--- test/0.4.24/node-operators-registry.test.js | 190 ++++---- test/0.4.24/staking-limit.test.js | 31 +- test/0.4.24/steth.test.js | 66 ++- test/0.4.24/stethpermit.test.js | 71 ++- test/0.6.12/helpers/ERC20.behavior.js | 43 +- test/0.6.12/helpers/constants.js | 34 +- test/0.6.12/helpers/index.js | 13 +- test/0.6.12/helpers/permit_helpers.js | 8 +- test/0.6.12/wsteth.permit.test.js | 34 +- test/0.6.12/wsteth.test.js | 43 +- test/0.8.9/burner.test.js | 141 +++--- test/0.8.9/deposit-security-module.test.js | 211 +++++--- test/0.8.9/lido-exec-layer-rewards-vault.js | 39 +- test/0.8.9/lido-locator.test.js | 8 +- test/0.8.9/oracle-daemon-config.test.js | 22 +- .../oracle-report-sanity-checker.test.js | 73 +-- .../accounting-oracle-access-control.test.js | 14 +- .../oracle/accounting-oracle-deploy.test.js | 36 +- .../accounting-oracle-happy-path.test.js | 153 +++--- ...counting-oracle-submit-report-data.test.js | 56 +-- ...ng-oracle-submit-report-extra-data.test.js | 74 +-- .../oracle/base-oracle-access-control.test.js | 2 +- test/0.8.9/oracle/base-oracle-deploy.test.js | 4 +- .../oracle/base-oracle-set-consensus.test.js | 2 +- .../oracle/base-oracle-submit-report.test.js | 8 +- .../oracle/hash-consensus-deploy.test.js | 10 +- .../hash-consensus-fast-lane-members.test.js | 248 +++++----- test/0.8.9/oracle/hash-consensus-frames.js | 2 +- .../oracle/hash-consensus-happy-path.test.js | 46 +- .../oracle/hash-consensus-members.test.js | 282 +++++------ .../hash-consensus-report-processor.test.js | 8 +- .../0.8.9/oracle/hash-consensus-set-quorum.js | 20 +- ...ors-exit-bus-oracle-access-control.test.js | 12 +- .../validators-exit-bus-oracle-deploy.test.js | 18 +- .../validators-exit-bus-oracle-gas.test.js | 103 ++-- ...idators-exit-bus-oracle-happy-path.test.js | 119 ++--- ...exit-bus-oracle-submit-report-data.test.js | 64 +-- test/0.8.9/pausable-until.test.js | 11 +- .../positive-token-rebase-limiter.test.js | 2 +- ...ing-router-allocation-combinations.test.js | 14 +- ...staking-router-deposits-allocation.test.js | 13 +- test/0.8.9/staking-router-deposits.test.js | 4 +- .../staking-router-keys-reporting.test.js | 459 ++++++++++-------- test/0.8.9/staking-router.test.js | 174 ++++--- test/0.8.9/withdrawal-queue.test.js | 249 ++++++---- test/0.8.9/withdrawal-request-nft.test.js | 62 +-- .../lib/min-first-allocation-strategy.test.js | 28 +- test/deposit.test.js | 106 ++-- test/helpers/assert.js | 70 +-- test/helpers/assertThrow.js | 41 +- test/helpers/blockchain.js | 2 +- test/helpers/config.js | 10 +- test/helpers/constants.js | 1 - test/helpers/dao.js | 6 +- test/helpers/factories.js | 51 +- test/helpers/locator-deploy.js | 16 +- test/helpers/locator.js | 4 +- test/helpers/node-operators.js | 2 +- test/helpers/oracle.js | 10 +- test/helpers/protocol.js | 8 +- test/helpers/signatures.js | 14 +- test/helpers/signing-keys.js | 2 +- test/helpers/staking-modules.js | 14 +- test/helpers/stubs/generic.stub.js | 10 +- test/helpers/stubs/staking-module.stub.js | 12 +- test/helpers/utils.js | 33 +- test/helpers/wei.js | 2 +- test/helpers/withdrawals.js | 6 +- .../scenario/changing_oracles_during_epoch.js | 33 +- test/scenario/deposit_distribution.js | 8 +- ...execution_layer_rewards_after_the_merge.js | 213 +++++--- test/scenario/helpers/deploy.js | 30 +- test/scenario/lido_deposit_iteration_limit.js | 20 +- test/scenario/lido_happy_path.js | 93 ++-- test/scenario/lido_penalties_slashing.js | 258 ++++++---- .../lido_rewards_distribution_math.js | 72 ++- 98 files changed, 2976 insertions(+), 2306 deletions(-) diff --git a/apps/lido/hardhat.config.js b/apps/lido/hardhat.config.js index 213cb0417..63482a402 100644 --- a/apps/lido/hardhat.config.js +++ b/apps/lido/hardhat.config.js @@ -7,7 +7,7 @@ module.exports = { ...baseConfig, paths: { ...baseConfig.paths, - root: '../..' + root: '../..', }, defaultNetwork: process.env.NETWORK_NAME || 'localhost', // Aragon plugin configuration @@ -18,6 +18,6 @@ module.exports = { appSrcPath: 'apps/lido/app/', appBuildOutputPath: 'apps/lido/dist/', appName: 'lido', - hooks // Path to script hooks - } + hooks, // Path to script hooks + }, } diff --git a/apps/lido/scripts/buidler-hooks.js b/apps/lido/scripts/buidler-hooks.js index 817ab2c8b..d0eb47a22 100644 --- a/apps/lido/scripts/buidler-hooks.js +++ b/apps/lido/scripts/buidler-hooks.js @@ -53,5 +53,5 @@ module.exports = { }, // Called after the app's proxy is updated with a new implementation. - postUpdate: async ({ proxy, log }, { web3, artifacts }) => {} + postUpdate: async ({ proxy, log }, { web3, artifacts }) => {}, } diff --git a/apps/node-operators-registry/hardhat.config.js b/apps/node-operators-registry/hardhat.config.js index 38e49c225..26b978562 100644 --- a/apps/node-operators-registry/hardhat.config.js +++ b/apps/node-operators-registry/hardhat.config.js @@ -7,7 +7,7 @@ module.exports = { ...baseConfig, paths: { ...baseConfig.paths, - root: '../..' + root: '../..', }, defaultNetwork: process.env.NETWORK_NAME || 'localhost', // Aragon plugin configuration @@ -18,6 +18,6 @@ module.exports = { appSrcPath: 'apps/node-operators-registry/app/', appBuildOutputPath: 'apps/node-operators-registry/dist/', appName: 'node-operators-registry', - hooks // Path to script hooks - } + hooks, // Path to script hooks + }, } diff --git a/apps/node-operators-registry/scripts/buidler-hooks.js b/apps/node-operators-registry/scripts/buidler-hooks.js index 20d8b2e1a..2f3f5caf2 100644 --- a/apps/node-operators-registry/scripts/buidler-hooks.js +++ b/apps/node-operators-registry/scripts/buidler-hooks.js @@ -31,5 +31,5 @@ module.exports = { }, // Called after the app's proxy is updated with a new implementation. - postUpdate: async ({ proxy, log }, { web3, artifacts }) => {} + postUpdate: async ({ proxy, log }, { web3, artifacts }) => {}, } diff --git a/estimate_deposit_loop_gas.js b/estimate_deposit_loop_gas.js index 9086fee4b..71fba2d0e 100644 --- a/estimate_deposit_loop_gas.js +++ b/estimate_deposit_loop_gas.js @@ -18,7 +18,7 @@ contract('Lido: deposit loop gas estimate', (addresses) => { user1, user2, // an unrelated address - nobody + nobody, ] = addresses let pool, nodeOperatorsRegistry, depositContractMock @@ -50,16 +50,23 @@ contract('Lido: deposit loop gas estimate', (addresses) => { const numKeys = 3 for (let iOperator = 0; iOperator < numOperators; ++iOperator) { - const txn = await nodeOperatorsRegistry.addNodeOperator(`operator-${iOperator}`, nodeOperator, operatorValidatorsLimit, { - from: voting + const txn = await nodeOperatorsRegistry.addNodeOperator( + `operator-${iOperator}`, + nodeOperator, + operatorValidatorsLimit, + { + from: voting, + } + ) + const nodeOperatorId = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { + decodeForAbi: NodeOperatorsRegistry._json.abi, }) - const nodeOperatorId = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi }) const data = Array.from({ length: numKeys }, (_, iKey) => { const n = arbitraryN.clone().addn(10 * iKey + 1000 * iOperator) return { key: pad(`0x${n.toString(16)}`, 48, 'd'), - sig: pad(`0x${n.toString(16)}`, 96, 'e') + sig: pad(`0x${n.toString(16)}`, 96, 'e'), } }) @@ -85,7 +92,10 @@ contract('Lido: deposit loop gas estimate', (addresses) => { it('calling DepositContractMock.deposit multiple times', async () => { const results = await Promise.all( validatorData.map(({ key, sig }, i) => - depositContractMock.deposit(key, withdrawalCredentials, sig, `0x${arbitraryN.toString(16)}`, { from: user1, value: ETH(32) }) + depositContractMock.deposit(key, withdrawalCredentials, sig, `0x${arbitraryN.toString(16)}`, { + from: user1, + value: ETH(32), + }) ) ) @@ -200,8 +210,12 @@ contract('Lido: deposit loop gas estimate', (addresses) => { const diff5 = Math.floor(Math.abs(predictedGasPer5 - gasPerNValidators['5']) / 5) const diff30 = Math.floor(Math.abs(predictedGasPer30 - gasPerNValidators['30']) / 30) - console.log(`predicted gas per 5 val, w/mock: ${predictedGasPer5}, actual: ${gasPerNValidators['5']}, diff/iter: ${diff5}`) - console.log(`predicted gas per 30 val, w/mock: ${predictedGasPer30}, actual: ${gasPerNValidators['30']}, diff/iter: ${diff30}\n`) + console.log( + `predicted gas per 5 val, w/mock: ${predictedGasPer5}, actual: ${gasPerNValidators['5']}, diff/iter: ${diff5}` + ) + console.log( + `predicted gas per 30 val, w/mock: ${predictedGasPer30}, actual: ${gasPerNValidators['30']}, diff/iter: ${diff30}\n` + ) const blockGasLimit = 12000000 const targetBlockFraction = 0.2 diff --git a/hardhat.config.aragon-apps.js b/hardhat.config.aragon-apps.js index 6a30e642d..9f3165907 100644 --- a/hardhat.config.aragon-apps.js +++ b/hardhat.config.aragon-apps.js @@ -13,6 +13,6 @@ module.exports = { ...baseConfig, aragon: { ...baseConfig.aragon, - ...aragonConfig - } + ...aragonConfig, + }, } diff --git a/hardhat.config.js b/hardhat.config.js index ee6a712ad..b4cf9943a 100644 --- a/hardhat.config.js +++ b/hardhat.config.js @@ -28,34 +28,37 @@ const accounts = readJson(`./accounts.json`) || { eth: { dev: 'remote' }, etherscan: { apiKey: undefined }, infura: { projectId: undefined }, - infura_ipfs: { projectId: undefined, projectSecret: undefined } + infura_ipfs: { projectId: undefined, projectSecret: undefined }, } const getNetConfig = (networkName, ethAccountName) => { const netState = readJson(`./deployed-${networkName}.json`) || {} const ethAccts = accounts.eth || {} const base = { - accounts: ethAccountName === 'remote' ? 'remote' : ethAccts[ethAccountName] || ethAccts[networkName] || ethAccts.dev || 'remote', + accounts: + ethAccountName === 'remote' + ? 'remote' + : ethAccts[ethAccountName] || ethAccts[networkName] || ethAccts.dev || 'remote', ensAddress: netState.ensAddress, - timeout: 60000 + timeout: 60000, } const localhost = { ...base, url: 'http://localhost:8545', chainId: 31337, - gas: 80000000 // the same as in Görli + gas: 80000000, // the same as in Görli } const mainnetfork = { ...base, url: 'http://localhost:8545', chainId: 1337, - gas: 80000000 // the same as in Görli + gas: 80000000, // the same as in Görli } const devnet3 = { ...base, url: 'http://35.228.211.212:8545', chainId: 1337807, - gas: 9194304 + gas: 9194304, } const byNetName = { localhost, @@ -65,10 +68,10 @@ const getNetConfig = (networkName, ethAccountName) => { local: { ...base, accounts: { - mnemonic: 'explain tackle mirror kit van hammer degree position ginger unfair soup bonus' + mnemonic: 'explain tackle mirror kit van hammer degree position ginger unfair soup bonus', }, url: 'http://localhost:8545', - chainId: 1337 + chainId: 1337, }, hardhat: { blockGasLimit: 30000000, @@ -80,47 +83,47 @@ const getNetConfig = (networkName, ethAccountName) => { mnemonic: 'test test test test test test test test test test test junk', count: 20, accountsBalance: '100000000000000000000000', - gasPrice: 0 - } + gasPrice: 0, + }, }, 'goerli-pyrmont': { ...base, url: 'http://206.81.31.11/rpc', - chainId: 5 + chainId: 5, }, rinkeby: { ...base, url: 'https://rinkeby.infura.io/v3/' + accounts.infura.projectId, chainId: 4, - timeout: 60000 * 10 + timeout: 60000 * 10, }, goerli: { ...base, url: 'https://goerli.infura.io/v3/' + accounts.infura.projectId, chainId: 5, - timeout: 60000 * 10 + timeout: 60000 * 10, }, 'mainnet-test': { ...base, url: 'https://mainnet.infura.io/v3/' + accounts.infura.projectId, chainId: 1, - timeout: 60000 * 10 + timeout: 60000 * 10, }, mainnet: { ...base, url: 'https://mainnet.infura.io/v3/' + accounts.infura.projectId, chainId: 1, - timeout: 60000 * 10 + timeout: 60000 * 10, }, fork: { ...base, chainId: 1, timeout: 60000 * 10, forking: { - url: 'https://mainnet.infura.io/v3/' + accounts.infura.projectId + url: 'https://mainnet.infura.io/v3/' + accounts.infura.projectId, // url: 'https://eth-mainnet.alchemyapi.io/v2/' + accounts.alchemy.apiKey - } - } + }, + }, } const netConfig = byNetName[networkName] return netConfig ? { [networkName]: netConfig } : {} @@ -129,23 +132,23 @@ const getNetConfig = (networkName, ethAccountName) => { const solcSettings4 = { optimizer: { enabled: true, - runs: 200 + runs: 200, }, - evmVersion: 'constantinople' + evmVersion: 'constantinople', } const solcSettings6 = { optimizer: { enabled: true, - runs: 200 + runs: 200, }, - evmVersion: 'istanbul' + evmVersion: 'istanbul', } const solcSettings8 = { optimizer: { enabled: true, - runs: 200 + runs: 200, }, - evmVersion: 'istanbul' + evmVersion: 'istanbul', } module.exports = { @@ -155,20 +158,20 @@ module.exports = { compilers: [ { version: '0.4.24', - settings: solcSettings4 + settings: solcSettings4, }, { version: '0.6.11', - settings: solcSettings6 + settings: solcSettings6, }, { version: '0.6.12', - settings: solcSettings6 + settings: solcSettings6, }, { version: '0.8.9', - settings: solcSettings8 - } + settings: solcSettings8, + }, ], overrides: { 'contracts/0.6.11/deposit_contract.sol': { @@ -176,15 +179,15 @@ module.exports = { settings: { optimizer: { enabled: true, - runs: 5000000 // https://etherscan.io/address/0x00000000219ab540356cbb839cbe05303d7705fa#code - } - } + runs: 5000000, // https://etherscan.io/address/0x00000000219ab540356cbb839cbe05303d7705fa#code + }, + }, }, 'contracts/0.4.24/test_helpers/MinFirstAllocationStrategyConsumerMockLegacyVersion.sol': { version: '0.4.24', - settings: {} - } - } + settings: {}, + }, + }, }, warnings: { '@aragon/**/*': { @@ -192,31 +195,31 @@ module.exports = { }, 'contracts/*/test_helpers/**/*': { default: 'off', - } + }, }, gasReporter: { enabled: !!process.env.REPORT_GAS, - currency: 'USD' + currency: 'USD', }, etherscan: accounts.etherscan, aragon: { ipfsApi: process.env.IPFS_API_URL || 'https://ipfs.infura.io:5001/api/v0', - ipfsGateway: process.env.IPFS_GATEWAY_URL || 'https://ipfs.io/' + ipfsGateway: process.env.IPFS_GATEWAY_URL || 'https://ipfs.io/', }, ipfs: { url: process.env.IPFS_API_URL || 'https://ipfs.infura.io:5001/api/v0', gateway: process.env.IPFS_GATEWAY_URL || 'https://ipfs.io/', pinata: { key: 'YOUR_PINATA_API_KEY', - secret: 'YOUR_PINATA_API_SECRET_KEY' - } + secret: 'YOUR_PINATA_API_SECRET_KEY', + }, }, contractSizer: { disambiguatePaths: false, runOnCompile: true, strict: true, except: ['test_helpers', 'template', 'mocks', '@aragon', 'openzeppelin'], - } + }, } function getNetworkName() { diff --git a/lib/src/dao.js b/lib/src/dao.js index 62b65ba8b..2277b4884 100644 --- a/lib/src/dao.js +++ b/lib/src/dao.js @@ -46,8 +46,8 @@ async function createVote(voting, tokenManager, voteDesc, evmScript, txOpts) { const newVoteEvmScript = encodeCallScript([ { to: voting.address, - calldata: await voting.contract.methods.newVote(evmScript, voteDesc, false, false).encodeABI() - } + calldata: await voting.contract.methods.newVote(evmScript, voteDesc, false, false).encodeABI(), + }, ]) const result = await tokenManager.forward(newVoteEvmScript, txOpts) const voteId = getEventArgument(result, 'StartVote', 'voteId', { decodeForAbi: getABI('Voting') }) @@ -61,5 +61,5 @@ module.exports = { getTokenManager, proposeChangingVotingQuorum, proposeChangingVotingSupport, - createVote + createVote, } diff --git a/lib/src/index.js b/lib/src/index.js index 66b8bf447..8f256f37b 100644 --- a/lib/src/index.js +++ b/lib/src/index.js @@ -24,17 +24,17 @@ module.exports = { list: nodeOperators.listOperators, addSigningKeys: nodeOperators.addSigningKeys, removeSigningKeys: nodeOperators.removeSigningKeys, - setStakingLimit: nodeOperators.setStakingLimit + setStakingLimit: nodeOperators.setStakingLimit, }, oracle: { LegacyOracle: oracle.LegacyOracle, getOracle: oracle.getOracle, getBeaconSpec: oracle.getBeaconSpec, - proposeBeaconSpecChange: oracle.proposeBeaconSpecChange + proposeBeaconSpecChange: oracle.proposeBeaconSpecChange, }, dao: { proposeChangingVotingQuorum: dao.proposeChangingVotingQuorum, proposeChangingVotingSupport: dao.proposeChangingVotingSupport, - createVote: dao.createVote - } + createVote: dao.createVote, + }, } diff --git a/lib/src/lido.js b/lib/src/lido.js index c7e8707db..55d553ba8 100644 --- a/lib/src/lido.js +++ b/lib/src/lido.js @@ -25,7 +25,7 @@ async function submitEther(lido, amount, txOpts = {}, referral = null, doDeposit } const depositResult = await lido.depositBufferedEther({ gasPrice: txOpts.gasPrice, - from: txOpts.from + from: txOpts.from, }) return { submitResult, depositResult } } @@ -34,8 +34,8 @@ async function setWithdrawalCredentials(lido, voting, tokenManager, credentials, const evmScript = encodeCallScript([ { to: lido.address, - calldata: await lido.contract.methods.setWithdrawalCredentials(credentials).encodeABI() - } + calldata: await lido.contract.methods.setWithdrawalCredentials(credentials).encodeABI(), + }, ]) const voteDesc = `Set withdrawal credentials to ${credentials}` return await createVote(voting, tokenManager, voteDesc, evmScript, txOpts) @@ -58,8 +58,8 @@ async function setFeeDistribution( to: lido.address, calldata: await lido.contract.methods .setFeeDistribution(treasuryFeeBasisPoints, insuranceFeeBasisPoints, operatorsFeeBasisPoints) - .encodeABI() - } + .encodeABI(), + }, ]) const voteDesc = `Set fee distribution to: (treasury ${treasuryFeeBasisPoints}, ` + @@ -74,5 +74,5 @@ module.exports = { getStETH, submitEther, setWithdrawalCredentials, - setFeeDistribution + setFeeDistribution, } diff --git a/lib/src/node-operators-registry.js b/lib/src/node-operators-registry.js index fdd648fa1..bb865179d 100644 --- a/lib/src/node-operators-registry.js +++ b/lib/src/node-operators-registry.js @@ -77,8 +77,8 @@ async function setStakingLimit(registry, voting, tokenManager, operatorId, newLi const evmScript = encodeCallScript([ { to: registry.address, - calldata: await registry.contract.methods.setNodeOperatorStakingLimit(operatorId, newLimit).encodeABI() - } + calldata: await registry.contract.methods.setNodeOperatorStakingLimit(operatorId, newLimit).encodeABI(), + }, ]) const op = normalizeNodeOperator(await registry.getNodeOperator(operatorId, true)) const voteDesc = @@ -95,7 +95,7 @@ function normalizeNodeOperator(op) { stakingLimit: +op.stakingLimit, stoppedValidators: +op.stoppedValidators, totalSigningKeys: +op.totalSigningKeys, - usedSigningKeys: +op.usedSigningKeys + usedSigningKeys: +op.usedSigningKeys, } } @@ -105,5 +105,5 @@ module.exports = { listOperators, addSigningKeys, removeSigningKeys, - setStakingLimit + setStakingLimit, } diff --git a/lib/src/oracle.js b/lib/src/oracle.js index 32082560f..b10d48038 100644 --- a/lib/src/oracle.js +++ b/lib/src/oracle.js @@ -19,7 +19,12 @@ async function proposeBeaconSpecChange(oracle, voting, tokenManager, newSpec, tx const currentSpec = await getBeaconSpec(oracle) const updatedSpec = { ...currentSpec, ...newSpec } const calldata = await oracle.contract.methods - .setBeaconSpec(updatedSpec.epochsPerFrame, updatedSpec.slotsPerEpoch, updatedSpec.secondsPerSlot, updatedSpec.genesisTime) + .setBeaconSpec( + updatedSpec.epochsPerFrame, + updatedSpec.slotsPerEpoch, + updatedSpec.secondsPerSlot, + updatedSpec.genesisTime + ) .encodeABI() const evmScript = encodeCallScript([{ to: oracle.address, calldata }]) const updatesDesc = Object.entries(newSpec) @@ -34,7 +39,7 @@ function normalizeBeaconSpec(spec) { epochsPerFrame: +spec.epochsPerFrame, slotsPerEpoch: +spec.slotsPerEpoch, secondsPerSlot: +spec.secondsPerSlot, - genesisTime: +spec.genesisTime + genesisTime: +spec.genesisTime, } } @@ -42,5 +47,5 @@ module.exports = { LegacyOracle, getOracle, getBeaconSpec, - proposeBeaconSpecChange + proposeBeaconSpecChange, } diff --git a/test/0.4.24/helpers/constants.js b/test/0.4.24/helpers/constants.js index 4d33269a4..2baff6413 100644 --- a/test/0.4.24/helpers/constants.js +++ b/test/0.4.24/helpers/constants.js @@ -5,12 +5,12 @@ const MAX_UINT256 = '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffff const ACCOUNTS_AND_KEYS = [ { address: '0xF4C028683CAd61ff284d265bC0F77EDd67B4e65A', - key: '0x5f7edf5892efb4a5cd75dedd496598f48e579b562a70eb1360474cc83a982987' + key: '0x5f7edf5892efb4a5cd75dedd496598f48e579b562a70eb1360474cc83a982987', }, { address: '0x7F94c1F9e4BfFccc8Cd79195554E0d83a0a5c5f2', - key: '0x3fe2f6bd9dbc7d507a6cb95ec36a36787706617e34385292b66c74cd39874605' - } + key: '0x3fe2f6bd9dbc7d507a6cb95ec36a36787706617e34385292b66c74cd39874605', + }, ] module.exports = { diff --git a/test/0.4.24/helpers/dao.js b/test/0.4.24/helpers/dao.js index 27e3f0c58..144743a74 100644 --- a/test/0.4.24/helpers/dao.js +++ b/test/0.4.24/helpers/dao.js @@ -62,7 +62,7 @@ class AragonDAO { const initPayload = config.initPayload || '0x' const receipt = await this.kernel.newAppInstance(hash(`${name}.aragonpm.test`), base.address, initPayload, false, { - from: this.appManager + from: this.appManager, }) const logs = receipt.logs const log = logs.find((l) => l.event === 'NewAppProxy') @@ -82,7 +82,7 @@ class AragonDAO { async createPermission(entityAddress, app, permissionName) { const permission = await app[permissionName]() return await this.acl.createPermission(entityAddress, app.address, permission, this.appManager, { - from: this.appManager + from: this.appManager, }) } @@ -136,5 +136,5 @@ const newApp = async (dao, appName, baseAppAddress, rootAccount) => { module.exports = { AragonDAO, newDao, - newApp + newApp, } diff --git a/test/0.4.24/helpers/permissions.js b/test/0.4.24/helpers/permissions.js index 7ba37fcb0..c0d012375 100644 --- a/test/0.4.24/helpers/permissions.js +++ b/test/0.4.24/helpers/permissions.js @@ -13,5 +13,5 @@ const setOpenPermission = async (acl, appAddress, role, rootAddress) => { } module.exports = { - setOpenPermission + setOpenPermission, } diff --git a/test/0.4.24/helpers/permit_helpers.js b/test/0.4.24/helpers/permit_helpers.js index 7378f157f..d8e18b660 100644 --- a/test/0.4.24/helpers/permit_helpers.js +++ b/test/0.4.24/helpers/permit_helpers.js @@ -4,7 +4,9 @@ const transferWithAuthorizationTypeHash = web3.utils.keccak256( 'TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)' ) -const permitTypeHash = web3.utils.keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)') +const permitTypeHash = web3.utils.keccak256( + 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' +) function signTransferAuthorization(from, to, value, validAfter, validBefore, nonce, domainSeparator, privateKey) { return signEIP712( @@ -29,8 +31,8 @@ function signPermit(owner, spender, value, nonce, deadline, domainSeparator, pri function signEIP712(domainSeparator, typeHash, types, parameters, privateKey) { const digest = web3.utils.keccak256( '0x1901' + - strip0x(domainSeparator) + - strip0x(web3.utils.keccak256(web3.eth.abi.encodeParameters(['bytes32', ...types], [typeHash, ...parameters]))) + strip0x(domainSeparator) + + strip0x(web3.utils.keccak256(web3.eth.abi.encodeParameters(['bytes32', ...types], [typeHash, ...parameters]))) ) return ecSign(digest, privateKey) @@ -45,7 +47,7 @@ function makeDomainSeparator(name, version, chainId, verifyingContract) { web3.utils.keccak256(name), web3.utils.keccak256(version), chainId, - verifyingContract + verifyingContract, ] ) ) @@ -55,5 +57,5 @@ module.exports = { signPermit, permitTypeHash, signTransferAuthorization, - makeDomainSeparator + makeDomainSeparator, } diff --git a/test/0.4.24/helpers/sign_utils.js b/test/0.4.24/helpers/sign_utils.js index 73e981e22..f05e4a503 100644 --- a/test/0.4.24/helpers/sign_utils.js +++ b/test/0.4.24/helpers/sign_utils.js @@ -22,5 +22,5 @@ module.exports = { hexStringFromBuffer, strip0x, ecSign, - bufferFromHexString + bufferFromHexString, } diff --git a/test/0.4.24/legacyoracle.test.js b/test/0.4.24/legacyoracle.test.js index 47e8c6bd6..bfd145e7d 100644 --- a/test/0.4.24/legacyoracle.test.js +++ b/test/0.4.24/legacyoracle.test.js @@ -6,7 +6,6 @@ const { assertRevert } = require('../helpers/assertThrow') const { toBN } = require('../helpers/utils') const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') - contract('LegacyOracle', ([admin, stranger]) => { it.skip('TODO: legacy compat tests', async () => {}) }) diff --git a/test/0.4.24/lido-deposit-scenarios.test.js b/test/0.4.24/lido-deposit-scenarios.test.js index 9950d6f0b..d60719631 100644 --- a/test/0.4.24/lido-deposit-scenarios.test.js +++ b/test/0.4.24/lido-deposit-scenarios.test.js @@ -28,8 +28,8 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { name: 'stubbed staking module', targetShares: 100_00, moduleFee: 5_00, - treasuryFee: 5_00 - } + treasuryFee: 5_00, + }, ] }, depositSecurityModuleFactory: async () => ({ address: depositor }), @@ -37,7 +37,7 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { postSetup: async ({ pool, lidoLocator, eip712StETH, voting }) => { await pool.initialize(lidoLocator.address, eip712StETH.address, { value: wei.str`1 ether` }) await pool.resumeProtocolAndStaking({ from: voting.address }) - } + }, }) lido = protocol.pool stakingRouter = protocol.stakingRouter @@ -63,12 +63,12 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { await StakingModuleStub.stubGetStakingModuleSummary(stakingModuleStub, { totalExitedValidators: 5, totalDepositedValidators: 16, - availableValidatorsCount + availableValidatorsCount, }) const depositDataLength = availableValidatorsCount await StakingModuleStub.stubObtainDepositData(stakingModuleStub, { - return: { depositDataLength } + return: { depositDataLength }, }) const submitAmount = wei`320 ether` @@ -97,12 +97,12 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { await StakingModuleStub.stubGetStakingModuleSummary(stakingModuleStub, { totalExitedValidators: 5, totalDepositedValidators: 16, - availableValidatorsCount + availableValidatorsCount, }) const depositDataLength = availableValidatorsCount + 2 await StakingModuleStub.stubObtainDepositData(stakingModuleStub, { - return: { depositDataLength } + return: { depositDataLength }, }) const initialLidETHBalance = await getBalance(lido) @@ -129,7 +129,7 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { await StakingModuleStub.stubGetStakingModuleSummary(stakingModuleStub, { totalExitedValidators: 5, totalDepositedValidators: 16, - availableValidatorsCount + availableValidatorsCount, }) const depositDataLength = availableValidatorsCount + 2 @@ -137,8 +137,8 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { await StakingModuleStub.stubObtainDepositData(stakingModuleStub, { return: { publicKeysBatch: depositData.slice()[0], // two extra signatures returned - signaturesBatch: depositData.slice(0, availableValidatorsCount)[1] - } + signaturesBatch: depositData.slice(0, availableValidatorsCount)[1], + }, }) const initialLidETHBalance = await getBalance(lido) @@ -165,7 +165,7 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { await StakingModuleStub.stubGetStakingModuleSummary(stakingModuleStub, { totalExitedValidators: 5, totalDepositedValidators: 16, - availableValidatorsCount + availableValidatorsCount, }) const depositDataLength = availableValidatorsCount + 2 @@ -173,8 +173,8 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { await StakingModuleStub.stubObtainDepositData(stakingModuleStub, { return: { publicKeysBatch: depositData.slice(0, availableValidatorsCount)[0], - signaturesBatch: depositData.slice()[1] // two extra signatures returned - } + signaturesBatch: depositData.slice()[1], // two extra signatures returned + }, }) const initialLidETHBalance = await getBalance(lido) @@ -195,7 +195,7 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { it('invalid ETH value was used for deposits in StakingRouter', async () => { // on each deposit call forward back 1 ether to the staking router await GenericStub.stub(depositContractStub, 'deposit', { - forwardETH: { value: wei.str`1 ether`, recipient: stakingRouter.address } + forwardETH: { value: wei.str`1 ether`, recipient: stakingRouter.address }, }) const submitAmount = wei`320 ether` @@ -208,12 +208,12 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { await StakingModuleStub.stubGetStakingModuleSummary(stakingModuleStub, { totalExitedValidators: 5, totalDepositedValidators: 16, - availableValidatorsCount + availableValidatorsCount, }) const depositDataLength = availableValidatorsCount await StakingModuleStub.stubObtainDepositData(stakingModuleStub, { - return: { depositDataLength } + return: { depositDataLength }, }) const maxDepositsCount = 10 await assert.reverts(lido.deposit(maxDepositsCount, CURATED_MODULE_ID, DEPOSIT_CALLDATA, { from: depositor })) @@ -230,11 +230,11 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { await StakingModuleStub.stubGetStakingModuleSummary(stakingModuleStub, { totalExitedValidators: 5, totalDepositedValidators: 16, - availableValidatorsCount + availableValidatorsCount, }) await StakingModuleStub.stub(stakingModuleStub, 'obtainDepositData', { - revert: { reason: 'INVALID_ALLOCATED_KEYS_COUNT' } + revert: { reason: 'INVALID_ALLOCATED_KEYS_COUNT' }, }) const maxDepositsCount = 10 diff --git a/test/0.4.24/lido-handle-oracle-report.test.js b/test/0.4.24/lido-handle-oracle-report.test.js index 602e4341a..eed66e512 100644 --- a/test/0.4.24/lido-handle-oracle-report.test.js +++ b/test/0.4.24/lido-handle-oracle-report.test.js @@ -36,7 +36,7 @@ const checkEvents = async ({ preTotalEther, postTotalShares, postTotalEther, - sharesMintedAsFees + sharesMintedAsFees, }) => { assert.emits( tx, @@ -44,10 +44,10 @@ const checkEvents = async ({ { reportTimestamp: 0, preCLValidators, - postCLValidators + postCLValidators, }, { - abi: Lido.abi + abi: Lido.abi, } ) assert.emits( @@ -59,10 +59,10 @@ const checkEvents = async ({ postCLBalance, withdrawalsWithdrawn, executionLayerRewardsWithdrawn, - postBufferedEther + postBufferedEther, }, { - abi: Lido.abi + abi: Lido.abi, } ) assert.emits( @@ -75,10 +75,10 @@ const checkEvents = async ({ preTotalEther, postTotalShares, postTotalEther, - sharesMintedAsFees + sharesMintedAsFees, }, { - abi: Lido.abi + abi: Lido.abi, } ) } @@ -104,13 +104,13 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another name: 'Curated', targetShares: 10000, moduleFee: 500, - treasuryFee: 500 - } + treasuryFee: 500, + }, ] }, depositSecurityModuleFactory: async (protocol) => { return { address: depositor } - } + }, }) await setBalance(deployed.oracle.address, ETH(1)) @@ -170,7 +170,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff, anotherStrangerBalanceDiff, curatedModuleBalanceDiff, - initialHolderBalanceDiff + initialHolderBalanceDiff, }) => { assert.equals( await lido.getTotalPooledEther(), @@ -234,7 +234,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another preTotalEther: ETH(100), postTotalShares: ETH(100), postTotalEther: ETH(100), - sharesMintedAsFees: 0 + sharesMintedAsFees: 0, }) await checkStat({ depositedValidators: 0, beaconValidators: 0, beaconBalance: 0 }) @@ -244,7 +244,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) }) @@ -258,7 +258,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) }) @@ -278,7 +278,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another preTotalEther: ETH(100), postTotalShares: ETH(100), postTotalEther: ETH(100), - sharesMintedAsFees: 0 + sharesMintedAsFees: 0, }) await checkStat({ depositedValidators: 3, beaconValidators: 1, beaconBalance: ETH(32) }) @@ -288,7 +288,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) }) @@ -309,7 +309,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another preTotalEther: ETH(100), postTotalShares: toBN(ETH(100)).add(sharesMintedAsFees).toString(), postTotalEther: ETH(101), - sharesMintedAsFees: sharesMintedAsFees + sharesMintedAsFees, }) await checkStat({ depositedValidators: 3, beaconValidators: 1, beaconBalance: ETH(33) }) @@ -320,7 +320,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3 * 0.9), anotherStrangerBalanceDiff: ETH(0.69 * 0.9), curatedModuleBalanceDiff: ETH(0.05), - initialHolderBalanceDiff: ETH(0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.01 * 0.9), }) }) }) @@ -373,7 +373,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another preTotalEther: ETH(100), postTotalShares: ETH(100), postTotalEther: ETH(100), - sharesMintedAsFees: 0 + sharesMintedAsFees: 0, }) await checkStat({ depositedValidators: 3, beaconValidators: 3, beaconBalance: ETH(96) }) await checkBalanceDeltas({ @@ -382,7 +382,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) tx = await lido.handleOracleReport(0, 0, 3, ETH(96), 0, 0, 0, 0, { from: oracle }) await checkEvents({ @@ -399,7 +399,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another preTotalEther: ETH(100), postTotalShares: ETH(100), postTotalEther: ETH(100), - sharesMintedAsFees: 0 + sharesMintedAsFees: 0, }) await checkStat({ depositedValidators: 3, beaconValidators: 3, beaconBalance: ETH(96) }) await checkBalanceDeltas({ @@ -408,16 +408,13 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) }) it('does not revert on new total balance decrease under the limit', async () => { // set oneOffCLBalanceDecreaseBPLimit = 1% - await oracleReportSanityChecker.setOracleReportLimits( - ORACLE_REPORT_LIMITS_BOILERPLATE, - { from: voting } - ) + await oracleReportSanityChecker.setOracleReportLimits(ORACLE_REPORT_LIMITS_BOILERPLATE, { from: voting }) let tx = await lido.handleOracleReport(0, 0, 3, ETH(96), 0, 0, 0, 0, { from: oracle }) await checkEvents({ @@ -434,7 +431,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another preTotalEther: ETH(100), postTotalShares: ETH(100), postTotalEther: ETH(100), - sharesMintedAsFees: 0 + sharesMintedAsFees: 0, }) await checkStat({ depositedValidators: 3, beaconValidators: 3, beaconBalance: ETH(96) }) await checkBalanceDeltas({ @@ -443,7 +440,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) tx = await lido.handleOracleReport(0, 0, 3, ETH(95.04), 0, 0, 0, 0, { from: oracle }) await checkEvents({ @@ -460,7 +457,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another preTotalEther: ETH(100), postTotalShares: ETH(100), postTotalEther: ETH(99.04), - sharesMintedAsFees: 0 + sharesMintedAsFees: 0, }) await checkStat({ depositedValidators: 3, beaconValidators: 3, beaconBalance: ETH(95.04) }) @@ -470,16 +467,13 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(-30 * 0.0096), anotherStrangerBalanceDiff: toBN(ETH(0.0096)).mul(toBN(-69)).toString(), curatedModuleBalanceDiff: ETH(0), - initialHolderBalanceDiff: ETH(-1 * 0.0096) + initialHolderBalanceDiff: ETH(-1 * 0.0096), }) }) it('reverts on new total balance decrease over the limit', async () => { // set oneOffCLBalanceDecreaseBPLimit = 1% - await oracleReportSanityChecker.setOracleReportLimits( - ORACLE_REPORT_LIMITS_BOILERPLATE, - { from: voting } - ) + await oracleReportSanityChecker.setOracleReportLimits(ORACLE_REPORT_LIMITS_BOILERPLATE, { from: voting }) await lido.handleOracleReport(0, 0, 3, ETH(96), 0, 0, 0, 0, { from: oracle }) await checkStat({ depositedValidators: 3, beaconValidators: 3, beaconBalance: ETH(96) }) @@ -489,7 +483,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) await assert.reverts( lido.handleOracleReport(0, 0, 3, ETH(95.03), 0, 0, 0, 0, { from: oracle }), @@ -499,7 +493,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('does not revert on new total balance increase under the limit', async () => { // set annualBalanceIncreaseBPLimit = 1% - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, annualBalanceIncreaseBPLimit: 100, }, @@ -514,7 +509,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) const tx = await lido.handleOracleReport(0, ONE_YEAR, 3, ETH(96.96), 0, 0, 0, 0, { from: oracle }) const sharesMintedAsFees = calcSharesMintedAsFees(ETH(0.96), 10, 100, ETH(100), ETH(100.96)) @@ -532,7 +527,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another preTotalEther: ETH(100), postTotalShares: toBN(ETH(100)).add(sharesMintedAsFees).toString(), postTotalEther: ETH(100.96), - sharesMintedAsFees: sharesMintedAsFees.toString() + sharesMintedAsFees: sharesMintedAsFees.toString(), }) await checkStat({ depositedValidators: 3, beaconValidators: 3, beaconBalance: ETH(96.96) }) @@ -542,13 +537,14 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(30 * 0.0096 * 0.9), anotherStrangerBalanceDiff: ETH(69 * 0.0096 * 0.9), curatedModuleBalanceDiff: ETH(0.96 * 0.05), - initialHolderBalanceDiff: ETH(0.96 * 0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.96 * 0.01 * 0.9), }) }) it('reverts on new total balance increase over the limit', async () => { // set annualBalanceIncreaseBPLimit = 1% - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, annualBalanceIncreaseBPLimit: 100, }, @@ -563,7 +559,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) await assert.reverts( lido.handleOracleReport(0, ONE_YEAR, 3, ETH(96.97), 0, 0, 0, 0, { from: oracle }), @@ -574,7 +570,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('does not revert on validators reported under limit', async () => { await lido.submit(ZERO_ADDRESS, { from: stranger, value: ETH(3100), gasPrice: 1 }) await lido.deposit(100, 1, '0x', { from: depositor }) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, annualBalanceIncreaseBPLimit: 100, @@ -589,7 +586,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('reverts on validators reported when over limit', async () => { await lido.submit(ZERO_ADDRESS, { from: stranger, value: ETH(3200), gasPrice: 1 }) await lido.deposit(101, 1, '0x', { from: depositor }) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, annualBalanceIncreaseBPLimit: 100, @@ -613,12 +611,13 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) }) it('does not smooth if report in limits', async () => { - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, }, @@ -629,7 +628,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another }) it('does not smooth if cl balance report over limit', async () => { - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, }, @@ -643,14 +643,15 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(4 * 0.3 * 0.9), anotherStrangerBalanceDiff: ETH(4 * 0.69 * 0.9), curatedModuleBalanceDiff: ETH(4 * 0.05), - initialHolderBalanceDiff: ETH(0.036) + initialHolderBalanceDiff: ETH(0.036), }) }) it('does not smooth withdrawals if report in limits', async () => { await setBalance(withdrawalVault, ETH(1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, annualBalanceIncreaseBPLimit: 100, @@ -665,7 +666,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3 * 0.9), anotherStrangerBalanceDiff: ETH(0.69 * 0.9), curatedModuleBalanceDiff: ETH(0.05), - initialHolderBalanceDiff: ETH(0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.01 * 0.9), }) assert.equals(await ethers.provider.getBalance(withdrawalVault), 0) }) @@ -673,7 +674,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('smooths withdrawals if report out of limit', async () => { await setBalance(withdrawalVault, ETH(1.1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, maxPositiveTokenRebase: 10000000, @@ -688,7 +690,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3 * 0.9), anotherStrangerBalanceDiff: ETH(0.69 * 0.9), curatedModuleBalanceDiff: ETH(0.05), - initialHolderBalanceDiff: ETH(0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.01 * 0.9), }) assert.equals(await ethers.provider.getBalance(withdrawalVault), ETH(0.1)) @@ -697,7 +699,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('does not smooth el rewards if report in limit without lido fee', async () => { await setBalance(elRewardsVault, ETH(1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, maxPositiveTokenRebase: 10000000, @@ -713,7 +716,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3), anotherStrangerBalanceDiff: ETH(0.69), curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: ETH(0.01) + initialHolderBalanceDiff: ETH(0.01), }) assert.equals(await ethers.provider.getBalance(elRewardsVault), ETH(0)) @@ -722,7 +725,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('does not smooth el rewards if report in limit without lido fee 2', async () => { await setBalance(elRewardsVault, ETH(1.5)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, maxPositiveTokenRebase: 10000000, @@ -737,7 +741,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3), anotherStrangerBalanceDiff: ETH(0.69), curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: ETH(0.01) + initialHolderBalanceDiff: ETH(0.01), }) assert.equals(await ethers.provider.getBalance(elRewardsVault), ETH(0)) @@ -746,7 +750,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('smooths el rewards if report out of limit without lido fee', async () => { await setBalance(elRewardsVault, ETH(1.1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, maxPositiveTokenRebase: 10000000, @@ -761,7 +766,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3), anotherStrangerBalanceDiff: ETH(0.69), curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: ETH(0.01) + initialHolderBalanceDiff: ETH(0.01), }) assert.equals(await ethers.provider.getBalance(elRewardsVault), ETH(0.1)) @@ -770,7 +775,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('does not smooth el rewards if report in limit', async () => { await setBalance(elRewardsVault, ETH(1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, }, @@ -785,7 +791,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3 * 0.9), anotherStrangerBalanceDiff: ETH(0.69 * 0.9), curatedModuleBalanceDiff: ETH(0.05), - initialHolderBalanceDiff: ETH(0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.01 * 0.9), }) assert.equals(await ethers.provider.getBalance(elRewardsVault), ETH(0.1)) @@ -794,7 +800,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('smooths el rewards if report out of limit', async () => { await setBalance(elRewardsVault, ETH(1.1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, maxPositiveTokenRebase: 10000000, @@ -809,7 +816,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3 * 0.9), anotherStrangerBalanceDiff: ETH(0.69 * 0.9), curatedModuleBalanceDiff: ETH(0.05), - initialHolderBalanceDiff: ETH(0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.01 * 0.9), }) assert.equals(await ethers.provider.getBalance(elRewardsVault), ETH(0.2)) @@ -825,13 +832,14 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: 0, anotherStrangerBalanceDiff: 0, curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: 0 + initialHolderBalanceDiff: 0, }) }) it('smooths el rewards if report out of limit', async () => { await setBalance(elRewardsVault, ETH(1.1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, maxPositiveTokenRebase: 10000000, @@ -846,13 +854,14 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3 * 0.9), anotherStrangerBalanceDiff: ETH(0.69 * 0.9), curatedModuleBalanceDiff: ETH(0.05), - initialHolderBalanceDiff: ETH(0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.01 * 0.9), }) assert.equals(await ethers.provider.getBalance(elRewardsVault), ETH(0.2)) }) it('does not smooth if report in limits', async () => { - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, }, @@ -864,7 +873,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('does not smooth if cl balance report over limit', async () => { const clIncrease = 0.0028 - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, }, @@ -882,14 +892,15 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.0028 * 0.9 * 0.3), anotherStrangerBalanceDiff: ETH(0.0028 * 0.9 * 0.69), curatedModuleBalanceDiff: ETH(0.00014), - initialHolderBalanceDiff: ETH(0.0028 * 0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.0028 * 0.01 * 0.9), }) }) it('does not smooth withdrawals if report in limits', async () => { await setBalance(withdrawalVault, ETH(1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, annualBalanceIncreaseBPLimit: 100, @@ -904,7 +915,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3 * 0.9), anotherStrangerBalanceDiff: ETH(0.69 * 0.9), curatedModuleBalanceDiff: ETH(0.05), - initialHolderBalanceDiff: ETH(0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.01 * 0.9), }) assert.equals(await ethers.provider.getBalance(withdrawalVault), 0) }) @@ -912,7 +923,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('smooths withdrawals if report out of limit', async () => { await setBalance(withdrawalVault, ETH(1.1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, maxPositiveTokenRebase: 10000000, @@ -927,7 +939,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3 * 0.9), anotherStrangerBalanceDiff: ETH(0.69 * 0.9), curatedModuleBalanceDiff: ETH(0.05), - initialHolderBalanceDiff: ETH(0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.01 * 0.9), }) assert.equals(await ethers.provider.getBalance(withdrawalVault), ETH(0.1)) @@ -936,7 +948,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('does not smooth el rewards if report in limit without lido fee', async () => { await setBalance(elRewardsVault, ETH(1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, maxPositiveTokenRebase: 10000000, @@ -952,7 +965,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3), anotherStrangerBalanceDiff: ETH(0.69), curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: ETH(0.01) + initialHolderBalanceDiff: ETH(0.01), }) assert.equals(await ethers.provider.getBalance(elRewardsVault), ETH(0)) @@ -961,7 +974,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('does not smooth el rewards if report in limit without lido fee 2', async () => { await setBalance(elRewardsVault, ETH(1.5)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, maxPositiveTokenRebase: 10000000, @@ -976,7 +990,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3), anotherStrangerBalanceDiff: ETH(0.69), curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: ETH(0.01) + initialHolderBalanceDiff: ETH(0.01), }) assert.equals(await ethers.provider.getBalance(elRewardsVault), ETH(0)) @@ -985,7 +999,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('smooths el rewards if report out of limit without lido fee', async () => { await setBalance(elRewardsVault, ETH(1.1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, maxPositiveTokenRebase: 10000000, @@ -1000,7 +1015,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3), anotherStrangerBalanceDiff: ETH(0.69), curatedModuleBalanceDiff: 0, - initialHolderBalanceDiff: ETH(0.01) + initialHolderBalanceDiff: ETH(0.01), }) assert.equals(await ethers.provider.getBalance(elRewardsVault), ETH(0.1)) @@ -1009,7 +1024,8 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another it('does not smooth el rewards if report in limit', async () => { await setBalance(elRewardsVault, ETH(1)) - await oracleReportSanityChecker.setOracleReportLimits({ + await oracleReportSanityChecker.setOracleReportLimits( + { ...ORACLE_REPORT_LIMITS_BOILERPLATE, churnValidatorsPerDayLimit: 100, }, @@ -1024,7 +1040,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another strangerBalanceDiff: ETH(0.3 * 0.9), anotherStrangerBalanceDiff: ETH(0.69 * 0.9), curatedModuleBalanceDiff: ETH(0.05), - initialHolderBalanceDiff: ETH(0.01 * 0.9) + initialHolderBalanceDiff: ETH(0.01 * 0.9), }) assert.equals(await ethers.provider.getBalance(elRewardsVault), ETH(0.1)) diff --git a/test/0.4.24/lido.test.js b/test/0.4.24/lido.test.js index be070bce2..e3689e52b 100644 --- a/test/0.4.24/lido.test.js +++ b/test/0.4.24/lido.test.js @@ -19,7 +19,7 @@ const { StETH, shares, setBalance, - prepIdsCountsPayload + prepIdsCountsPayload, } = require('../helpers/utils') const { assert } = require('../helpers/assert') const nodeOperators = require('../helpers/node-operators') @@ -50,7 +50,6 @@ const MAX_DEPOSITS = 150 const CURATED_MODULE_ID = 1 const CALLDATA = '0x0' - contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody, depositor, treasury]) => { let app, oracle, depositContract, operators let treasuryAddress @@ -91,13 +90,13 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody name: 'Curated', targetShares: 10000, moduleFee: 500, - treasuryFee: 500 - } + treasuryFee: 500, + }, ] }, depositSecurityModuleFactory: async () => { return { address: depositor } - } + }, }) dao = deployed.dao @@ -143,7 +142,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody app.balanceOf(ADDRESS_1), app.balanceOf(ADDRESS_2), app.balanceOf(ADDRESS_3), - app.balanceOf(ADDRESS_4) + app.balanceOf(ADDRESS_4), ]) assertBn(div15(treasury_b), treasury, 'treasury token balance check') @@ -193,7 +192,10 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody }) it('reverts with UNEXPECTED_CONTRACT_VERSION on implementation finalization', async () => { - await assert.reverts(appBase.finalizeUpgrade_v2(lidoLocator.address, eip712StETH.address), 'UNEXPECTED_CONTRACT_VERSION') + await assert.reverts( + appBase.finalizeUpgrade_v2(lidoLocator.address, eip712StETH.address), + 'UNEXPECTED_CONTRACT_VERSION' + ) }) it('reverts if already initialized', async () => { @@ -216,13 +218,12 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody }) context('EL Rewards', async () => { - beforeEach('set up limits', async () => { - //TODO(DZhon): revive - //const maxPositiveTokenRebase = bn(1).mul(bn(10).pow(bn(8))) // 10% - //await assertRevert(app.setMaxPositiveTokenRebase(maxPositiveTokenRebase), 'APP_AUTH_FAILED') - //const receipt = await app.setMaxPositiveTokenRebase(maxPositiveTokenRebase, { from: voting }) - //assertEvent(receipt, 'MaxPositiveTokenRebaseSet', { expectedArgs: { maxPositiveTokenRebase: maxPositiveTokenRebase } }) + // TODO(DZhon): revive + // const maxPositiveTokenRebase = bn(1).mul(bn(10).pow(bn(8))) // 10% + // await assertRevert(app.setMaxPositiveTokenRebase(maxPositiveTokenRebase), 'APP_AUTH_FAILED') + // const receipt = await app.setMaxPositiveTokenRebase(maxPositiveTokenRebase, { from: voting }) + // assertEvent(receipt, 'MaxPositiveTokenRebaseSet', { expectedArgs: { maxPositiveTokenRebase: maxPositiveTokenRebase } }) }) it('Execution layer rewards distribution works when zero cl rewards reported', async () => { @@ -260,7 +261,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await pushReport(1, ETH(totalDeposit + clRewards)) assertBn(await app.getTotalPooledEther(), ETH(initialDeposit + user2Deposit + totalElRewards + clRewards)) - assertBn(await app.balanceOf(user2), StETH(user2Deposit + user2Rewards + clRewards * 31 / 32)) + assertBn(await app.balanceOf(user2), StETH(user2Deposit + user2Rewards + (clRewards * 31) / 32)) assertBn(await app.getTotalELRewardsCollected(), ETH(totalElRewards)) }) @@ -282,16 +283,16 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const fee = await app.getFee() - const stakersReward = (totalElRewards + clRewards) * (TOTAL_BASIS_POINTS - fee) / TOTAL_BASIS_POINTS + const stakersReward = ((totalElRewards + clRewards) * (TOTAL_BASIS_POINTS - fee)) / TOTAL_BASIS_POINTS - assertBn(await app.balanceOf(user2), StETH(user2Deposit + stakersReward * 31 / 32)) + assertBn(await app.balanceOf(user2), StETH(user2Deposit + (stakersReward * 31) / 32)) }) it('Attempt to set invalid execution layer rewards withdrawal limit', async () => { - //TODO: revive - //const initialValue = await app.getMaxPositiveTokenRebase() + // TODO: revive + // const initialValue = await app.getMaxPositiveTokenRebase() - //assertEvent(await app.setMaxPositiveTokenRebase(1, { from: voting }), 'MaxPositiveTokenRebaseSet', { + // assertEvent(await app.setMaxPositiveTokenRebase(1, { from: voting }), 'MaxPositiveTokenRebaseSet', { // expectedArgs: { maxPositiveTokenRebase: 1 } const setupNodeOperatorsForELRewardsVaultTests = async (userAddress, initialDepositAmount) => { @@ -369,7 +370,10 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const shareOfRewardsForStakers = (TOTAL_BASIS_POINTS - totalFee) / TOTAL_BASIS_POINTS assertBn(await app.getTotalPooledEther(), ETH(depositAmount + elRewards + beaconRewards)) assertBn(await app.getBufferedEther(), ETH(elRewards)) - assertBn(await app.balanceOf(user2), StETH(depositAmount + shareOfRewardsForStakers * (elRewards + beaconRewards))) + assertBn( + await app.balanceOf(user2), + StETH(depositAmount + shareOfRewardsForStakers * (elRewards + beaconRewards)) + ) assertBn(await app.getTotalELRewardsCollected(), ETH(elRewards)) }) @@ -377,7 +381,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const initialValue = await app.getELRewardsWithdrawalLimit() assertEvent(await app.setELRewardsWithdrawalLimit(1, { from: voting }), 'ELRewardsWithdrawalLimitSet', { - expectedArgs: { limitPoints: 1 } + expectedArgs: { limitPoints: 1 }, }) await assertNoEvent(app.setELRewardsWithdrawalLimit(1, { from: voting }), 'ELRewardsWithdrawalLimitSet') @@ -405,7 +409,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const receipt = await app.receiveELRewards({ from: elRewardsVault.address, value: ETH(2) }) assertEvent(receipt, 'ELRewardsReceived', { - expectedArgs: { amount: ETH(2) } + expectedArgs: { amount: ETH(2) }, }) assertBn(await app.getTotalELRewardsCollected(), ETH(2)) @@ -431,9 +435,15 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await stakingRouter.setWithdrawalCredentials(pad('0x0202', 32), { from: voting }) await operators.addSigningKeys(0, 1, pad('0x010203', 48), pad('0x01', 96), { from: voting }) - await operators.addSigningKeys(1, 2, hexConcat(pad('0x050505', 48), pad('0x060606', 48)), hexConcat(pad('0x02', 96), pad('0x03', 96)), { - from: voting - }) + await operators.addSigningKeys( + 1, + 2, + hexConcat(pad('0x050505', 48), pad('0x060606', 48)), + hexConcat(pad('0x02', 96), pad('0x03', 96)), + { + from: voting, + } + ) await operators.setNodeOperatorStakingLimit(0, UNLIMITED, { from: voting }) await operators.setNodeOperatorStakingLimit(1, UNLIMITED, { from: voting }) @@ -603,12 +613,12 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const op0 = { keys: Array.from({ length: 3 }, (_, i) => `0x11${i}${i}` + 'abcd'.repeat(46 / 2)), - sigs: Array.from({ length: 3 }, (_, i) => `0x11${i}${i}` + 'cdef'.repeat(94 / 2)) + sigs: Array.from({ length: 3 }, (_, i) => `0x11${i}${i}` + 'cdef'.repeat(94 / 2)), } const op1 = { keys: Array.from({ length: 3 }, (_, i) => `0x22${i}${i}` + 'efab'.repeat(46 / 2)), - sigs: Array.from({ length: 3 }, (_, i) => `0x22${i}${i}` + 'fcde'.repeat(94 / 2)) + sigs: Array.from({ length: 3 }, (_, i) => `0x22${i}${i}` + 'fcde'.repeat(94 / 2)), } await stakingRouter.setWithdrawalCredentials(pad('0x0202', 32), { from: voting }) @@ -683,15 +693,15 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody isStakingPaused = await app.isStakingPaused() assert.equal(isStakingPaused, expectedIsStakingPaused) - ; ({ - isStakingPaused, - isStakingLimitSet, - currentStakeLimit, - maxStakeLimit, - maxStakeLimitGrowthBlocks, - prevStakeLimit, - prevStakeBlockNumber - } = await app.getStakeLimitFullInfo()) + ;({ + isStakingPaused, + isStakingLimitSet, + currentStakeLimit, + maxStakeLimit, + maxStakeLimitGrowthBlocks, + prevStakeLimit, + prevStakeBlockNumber, + } = await app.getStakeLimitFullInfo()) assertBn(currentStakeLimit, expectedCurrentStakeLimit) assertBn(maxStakeLimit, expectedMaxStakeLimit) @@ -745,8 +755,8 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody assertEvent(receipt, 'StakingLimitSet', { expectedArgs: { maxStakeLimit: expectedMaxStakeLimit, - stakeLimitIncreasePerBlock: limitIncreasePerBlock - } + stakeLimitIncreasePerBlock: limitIncreasePerBlock, + }, }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, expectedMaxStakeLimit, false, true) @@ -754,7 +764,13 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user2, amount: ETH(2), referral: ZERO_ADDRESS } }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, ETH(1), false, true) await assertRevert(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2.5) }), `STAKE_LIMIT`) - await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, bn(ETH(1)).add(limitIncreasePerBlock), false, true) + await verifyStakeLimitState( + expectedMaxStakeLimit, + limitIncreasePerBlock, + bn(ETH(1)).add(limitIncreasePerBlock), + false, + true + ) // expect to grow for another 1.5 ETH since last submit // every revert produces new block, so we need to account that block @@ -763,10 +779,22 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await assertRevert(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2.6) }), `STAKE_LIMIT`) receipt = await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2.5) }) assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user2, amount: ETH(2.5), referral: ZERO_ADDRESS } }) - await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, limitIncreasePerBlock.muln(2), false, true) + await verifyStakeLimitState( + expectedMaxStakeLimit, + limitIncreasePerBlock, + limitIncreasePerBlock.muln(2), + false, + true + ) await assertRevert(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(0.1) }), `STAKE_LIMIT`) - await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, limitIncreasePerBlock.muln(3), false, true) + await verifyStakeLimitState( + expectedMaxStakeLimit, + limitIncreasePerBlock, + limitIncreasePerBlock.muln(3), + false, + true + ) // once again, we are subtracting blocks number induced by revert checks await waitBlocks(blocksToReachMaxStakeLimit / 3 - 4) @@ -799,8 +827,8 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody assertEvent(receipt, 'StakingLimitSet', { expectedArgs: { maxStakeLimit: expectedMaxStakeLimit, - stakeLimitIncreasePerBlock: limitIncreasePerBlock - } + stakeLimitIncreasePerBlock: limitIncreasePerBlock, + }, }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, expectedMaxStakeLimit, false, true) @@ -828,8 +856,8 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody assertEvent(receipt, 'StakingLimitSet', { expectedArgs: { maxStakeLimit: expectedMaxStakeLimit, - stakeLimitIncreasePerBlock: limitIncreasePerBlock - } + stakeLimitIncreasePerBlock: limitIncreasePerBlock, + }, }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, expectedMaxStakeLimit, false, true) @@ -841,11 +869,17 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody assertEvent(receipt, 'StakingLimitSet', { expectedArgs: { maxStakeLimit: smallerExpectedMaxStakeLimit, - stakeLimitIncreasePerBlock: smallerLimitIncreasePerBlock - } + stakeLimitIncreasePerBlock: smallerLimitIncreasePerBlock, + }, }) - await verifyStakeLimitState(smallerExpectedMaxStakeLimit, smallerLimitIncreasePerBlock, smallerExpectedMaxStakeLimit, false, true) + await verifyStakeLimitState( + smallerExpectedMaxStakeLimit, + smallerLimitIncreasePerBlock, + smallerExpectedMaxStakeLimit, + false, + true + ) const largerExpectedMaxStakeLimit = ETH(10) const largerLimitIncreasePerBlock = bn(largerExpectedMaxStakeLimit).divn(1000) @@ -854,11 +888,17 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody assertEvent(receipt, 'StakingLimitSet', { expectedArgs: { maxStakeLimit: largerExpectedMaxStakeLimit, - stakeLimitIncreasePerBlock: largerLimitIncreasePerBlock - } + stakeLimitIncreasePerBlock: largerLimitIncreasePerBlock, + }, }) - await verifyStakeLimitState(largerExpectedMaxStakeLimit, largerLimitIncreasePerBlock, smallerExpectedMaxStakeLimit, false, true) + await verifyStakeLimitState( + largerExpectedMaxStakeLimit, + largerLimitIncreasePerBlock, + smallerExpectedMaxStakeLimit, + false, + true + ) await assertRevert(app.removeStakingLimit(), 'APP_AUTH_FAILED') receipt = await app.removeStakingLimit({ from: voting }) @@ -869,8 +909,14 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody it('reverts when trying to call unknown function', async () => { const wrongMethodABI = '0x00' - await assertRevert(web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(1), data: wrongMethodABI }), 'NON_EMPTY_DATA') - await assertRevert(web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(0), data: wrongMethodABI }), 'NON_EMPTY_DATA') + await assertRevert( + web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(1), data: wrongMethodABI }), + 'NON_EMPTY_DATA' + ) + await assertRevert( + web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(0), data: wrongMethodABI }), + 'NON_EMPTY_DATA' + ) }) it('key removal is taken into account during deposit', async () => { @@ -974,7 +1020,10 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await pushReport(1, ETH(30)) await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(30) }) - await assertRevert(app.handleOracleReport(await getCurrentBlockTimestamp(), 1, ETH(29), 0, 0, 0, 0, 0, { from: nobody }), 'APP_AUTH_FAILED') + await assertRevert( + app.handleOracleReport(await getCurrentBlockTimestamp(), 1, ETH(29), 0, 0, 0, 0, 0, { from: nobody }), + 'APP_AUTH_FAILED' + ) await pushReport(1, ETH(100)) // stale data await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(100) }) @@ -1068,7 +1117,10 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await assertRevert(web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(4) }), 'STAKING_PAUSED') await assertRevert(web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(4) }), 'STAKING_PAUSED') - await assertRevert(app.submit('0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', { from: user1, value: ETH(4) }), 'STAKING_PAUSED') + await assertRevert( + app.submit('0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', { from: user1, value: ETH(4) }), + 'STAKING_PAUSED' + ) await assertRevert(app.resume({ from: user2 }), 'APP_AUTH_FAILED') await app.resume({ from: voting }) @@ -1135,7 +1187,6 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody }) it('rewards distribution works in a simple case', async () => { - await operators.addNodeOperator('1', ADDRESS_1, { from: voting }) await operators.addNodeOperator('2', ADDRESS_2, { from: voting }) @@ -1248,12 +1299,22 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody // id: 2 await nodeOperators.addNodeOperator( operators, - { name: 'deactivated', rewardAddress: ADDRESS_3, totalSigningKeysCount: 2, vettedSigningKeysCount: 2, isActive: false }, + { + name: 'deactivated', + rewardAddress: ADDRESS_3, + totalSigningKeysCount: 2, + vettedSigningKeysCount: 2, + isActive: false, + }, { from: voting } ) // id: 3 - await nodeOperators.addNodeOperator(operators, { name: 'short on keys', rewardAddress: ADDRESS_4 }, { from: voting }) + await nodeOperators.addNodeOperator( + operators, + { name: 'short on keys', rewardAddress: ADDRESS_4 }, + { from: voting } + ) // Deposit huge chunk await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(32 * 3 + 49) }) @@ -1372,12 +1433,22 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody // id: 2 await nodeOperators.addNodeOperator( operators, - { name: 'deactivated', rewardAddress: ADDRESS_3, totalSigningKeysCount: 2, vettedSigningKeysCount: 2, isActive: false }, + { + name: 'deactivated', + rewardAddress: ADDRESS_3, + totalSigningKeysCount: 2, + vettedSigningKeysCount: 2, + isActive: false, + }, { from: voting } ) // id: 3 - await nodeOperators.addNodeOperator(operators, { name: 'short on keys', rewardAddress: ADDRESS_4 }, { from: voting }) + await nodeOperators.addNodeOperator( + operators, + { name: 'short on keys', rewardAddress: ADDRESS_4 }, + { from: voting } + ) // Small deposits for (let i = 0; i < 14; i++) await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(10) }) @@ -1483,21 +1554,39 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await stakingRouter.setWithdrawalCredentials(pad('0x0202', 32), { from: voting }) await operators.addNodeOperator('good', ADDRESS_1, { from: voting }) // 0 - await operators.addSigningKeys(0, 2, hexConcat(pad('0x0001', 48), pad('0x0002', 48)), hexConcat(pad('0x01', 96), pad('0x01', 96)), { - from: voting - }) + await operators.addSigningKeys( + 0, + 2, + hexConcat(pad('0x0001', 48), pad('0x0002', 48)), + hexConcat(pad('0x01', 96), pad('0x01', 96)), + { + from: voting, + } + ) await operators.setNodeOperatorStakingLimit(0, UNLIMITED, { from: voting }) await operators.addNodeOperator('2nd good', ADDRESS_2, { from: voting }) // 1 - await operators.addSigningKeys(1, 2, hexConcat(pad('0x0101', 48), pad('0x0102', 48)), hexConcat(pad('0x01', 96), pad('0x01', 96)), { - from: voting - }) + await operators.addSigningKeys( + 1, + 2, + hexConcat(pad('0x0101', 48), pad('0x0102', 48)), + hexConcat(pad('0x01', 96), pad('0x01', 96)), + { + from: voting, + } + ) await operators.setNodeOperatorStakingLimit(1, UNLIMITED, { from: voting }) await operators.addNodeOperator('deactivated', ADDRESS_3, { from: voting }) // 2 - await operators.addSigningKeys(2, 2, hexConcat(pad('0x0201', 48), pad('0x0202', 48)), hexConcat(pad('0x01', 96), pad('0x01', 96)), { - from: voting - }) + await operators.addSigningKeys( + 2, + 2, + hexConcat(pad('0x0201', 48), pad('0x0202', 48)), + hexConcat(pad('0x01', 96), pad('0x01', 96)), + { + from: voting, + } + ) await operators.setNodeOperatorStakingLimit(2, UNLIMITED, { from: voting }) await operators.deactivateNodeOperator(2, { from: voting }) @@ -1519,9 +1608,15 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody // Reactivation of #2 & setting staking limit - has the smallest stake await operators.activateNodeOperator(2, { from: voting }) - await operators.addSigningKeys(2, 2, hexConcat(pad('0x0201', 48), pad('0x0202', 48)), hexConcat(pad('0x01', 96), pad('0x01', 96)), { - from: voting - }) + await operators.addSigningKeys( + 2, + 2, + hexConcat(pad('0x0201', 48), pad('0x0202', 48)), + hexConcat(pad('0x01', 96), pad('0x01', 96)), + { + from: voting, + } + ) await operators.setNodeOperatorStakingLimit(2, UNLIMITED, { from: voting }) await web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(36) }) @@ -1549,8 +1644,8 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody account: user1, preRebaseTokenAmount: pre1SharePrice, postRebaseTokenAmount: post1SharePrice, - sharesAmount: shares(1) - } + sharesAmount: shares(1), + }, }) const pre2SharePrice = await app.getPooledEthByShares(shares(1)) @@ -1561,8 +1656,8 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody account: user1, preRebaseTokenAmount: pre2SharePrice, postRebaseTokenAmount: post2SharePrice, - sharesAmount: shares(1) - } + sharesAmount: shares(1), + }, }) assertBn(pre1SharePrice.muln(3), pre2SharePrice.muln(2)) @@ -1612,18 +1707,12 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody }) it('recovery with erc20 tokens reverts', async () => { - await assertRevert( - app.transferToVault(anyToken.address, { from: nobody }), - 'NOT_SUPPORTED' - ) + await assertRevert(app.transferToVault(anyToken.address, { from: nobody }), 'NOT_SUPPORTED') }) it('recovery with unaccounted ether reverts', async () => { await app.makeUnaccountedEther({ from: user1, value: ETH(10) }) - await assertRevert( - app.transferToVault(ZERO_ADDRESS, { from: nobody }), - 'NOT_SUPPORTED' - ) + await assertRevert(app.transferToVault(ZERO_ADDRESS, { from: nobody }), 'NOT_SUPPORTED') }) }) }) diff --git a/test/0.4.24/node-operators-registry-penalty.test.js b/test/0.4.24/node-operators-registry-penalty.test.js index c21fe47af..cc7e0c397 100644 --- a/test/0.4.24/node-operators-registry-penalty.test.js +++ b/test/0.4.24/node-operators-registry-penalty.test.js @@ -30,7 +30,7 @@ const NODE_OPERATORS = [ targetValidatorsKeysCount: 1, unavaliableKeysCount: 2, stuckSigningKeysCount: 3, - refundedSigningKeysCount: 4 + refundedSigningKeysCount: 4, }, { name: ' bar', @@ -43,7 +43,7 @@ const NODE_OPERATORS = [ targetValidatorsKeysCount: 1, unavaliableKeysCount: 2, stuckSigningKeysCount: 3, - refundedSigningKeysCount: 4 + refundedSigningKeysCount: 4, }, { name: 'deactivated', @@ -57,8 +57,8 @@ const NODE_OPERATORS = [ targetValidatorsKeysCount: 1, unavaliableKeysCount: 2, stuckSigningKeysCount: 3, - refundedSigningKeysCount: 4 - } + refundedSigningKeysCount: 4, + }, ] // bytes32 0x63757261746564 @@ -80,7 +80,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use const locatorConfig = getRandomLocatorConfig({ lido: steth.address, - burner: burner.address + burner: burner.address, }) locator = await LidoLocator.new(locatorConfig) @@ -92,11 +92,11 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use MANAGE_SIGNING_KEYS: voting, MANAGE_NODE_OPERATOR_ROLE: voting, SET_NODE_OPERATOR_LIMIT_ROLE: voting, - STAKING_ROUTER_ROLE: voting - } + STAKING_ROUTER_ROLE: voting, + }, }) - //grant REQUEST_BURN_SHARES_ROLE to NOR + // grant REQUEST_BURN_SHARES_ROLE to NOR await burner.grantRole(web3.utils.keccak256(`REQUEST_BURN_SHARES_ROLE`), app.address, { from: voting }) // grant role to app itself cause it uses solidity's call method to itself @@ -110,7 +110,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use // Initialize the app's proxy. const tx = await app.initialize(locator.address, CURATED_TYPE, PENALTY_DELAY) - //set stuck penalty voting + // set stuck penalty voting // await app.setStuckPenaltyDelay(PENALTY_DELAY, { from: voting }) // Implementation initializer reverts because initialization block was set to max(uint256) @@ -130,8 +130,8 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use }) describe('distributeRewards()', () => { - let firstNodeOperator = 0; - let secondNodeOperator = 1; + const firstNodeOperator = 0 + const secondNodeOperator = 1 beforeEach(async () => { await app.testing_addNodeOperator('0', user1, 3, 3, 3, 0) @@ -145,7 +145,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use const recipientsSharesBefore = await Promise.all([ steth.sharesOf(user1), steth.sharesOf(user2), - steth.sharesOf(user3) + steth.sharesOf(user3), ]) // calls distributeRewards() inside @@ -154,7 +154,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use const recipientsSharesAfter = await Promise.all([ steth.sharesOf(user1), steth.sharesOf(user2), - steth.sharesOf(user3) + steth.sharesOf(user3), ]) assert.equal(recipientsSharesBefore.length, recipientsSharesAfter.length) for (let i = 0; i < recipientsSharesBefore.length; ++i) { @@ -187,80 +187,80 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use }) it('distribute with stopped works', async () => { - let totalRewardShares = ETH(10) + const totalRewardShares = ETH(10) await steth.setTotalPooledEther(ETH(100)) await steth.mintShares(app.address, totalRewardShares) - //before + // before // operatorId | Total | Deposited | Exited | Active (deposited-exited) // 0 3 3 0 3 // 1 7 7 0 7 // 2 0 0 0 0 - //----------------------------------------------------------------------------- - //total 3 10 10 0 10 + // ----------------------------------------------------------------------------- + // total 3 10 10 0 10 // - //perValidatorShare 10*10^18 / 10 = 10^18 + // perValidatorShare 10*10^18 / 10 = 10^18 - //update [operator, exited, stuck] - await app.unsafeUpdateValidatorsCount(firstNodeOperator, 1, 0 , { from: voting }) - await app.unsafeUpdateValidatorsCount(secondNodeOperator, 1, 0 , { from: voting }) + // update [operator, exited, stuck] + await app.unsafeUpdateValidatorsCount(firstNodeOperator, 1, 0, { from: voting }) + await app.unsafeUpdateValidatorsCount(secondNodeOperator, 1, 0, { from: voting }) - //after + // after // operatorId | Total | Deposited | Exited | Stuck | Active (deposited-exited) // 0 3 3 1 0 2 // 1 7 7 1 0 6 // 2 0 0 0 0 0 - //----------------------------------------------------------------------------- - //total 3 10 10 2 0 8 + // ----------------------------------------------------------------------------- + // total 3 10 10 2 0 8 // - //perValidatorShare 10*10^18 / 8 = 1250000000000000000 == 1.25 * 10^18 + // perValidatorShare 10*10^18 / 8 = 1250000000000000000 == 1.25 * 10^18 // calls distributeRewards() inside receipt = await app.testing__distributeRewards({ from: voting }) - assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(2*1.25) }) - assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(6*1.25) }) + assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(2 * 1.25) }) + assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(6 * 1.25) }) assert.notEmits(receipt, 'RewardsDistributed', { rewardAddress: user3, sharesAmount: 0 }) // assert.emits(receipt, 'NodeOperatorPenalized', { recipientAddress: user1, sharesPenalizedAmount: ETH(3) }) }) it('penalized keys with stopped and stuck works', async () => { - let totalRewardShares = ETH(10) + const totalRewardShares = ETH(10) await steth.setTotalPooledEther(ETH(100)) await steth.mintShares(app.address, totalRewardShares) - //before + // before // operatorId | Total | Deposited | Exited | Active (deposited-exited) // 0 3 3 0 3 // 1 7 7 0 7 // 2 0 0 0 0 - //----------------------------------------------------------------------------- - //total 3 10 10 0 10 + // ----------------------------------------------------------------------------- + // total 3 10 10 0 10 // - //perValidatorShare 10*10^18 / 10 = 10^18 + // perValidatorShare 10*10^18 / 10 = 10^18 - //update [operator, exited, stuck] - await app.unsafeUpdateValidatorsCount(firstNodeOperator, 1, 1 , { from: voting }) - await app.unsafeUpdateValidatorsCount(secondNodeOperator, 1, 0 , { from: voting }) + // update [operator, exited, stuck] + await app.unsafeUpdateValidatorsCount(firstNodeOperator, 1, 1, { from: voting }) + await app.unsafeUpdateValidatorsCount(secondNodeOperator, 1, 0, { from: voting }) - //after + // after // operatorId | Total | Deposited | Exited | Stuck | Active (deposited-exited) // 0 3 3 1 1 2 // 1 7 7 1 0 6 // 2 0 0 0 0 0 - //----------------------------------------------------------------------------- - //total 3 10 10 2 1 8 + // ----------------------------------------------------------------------------- + // total 3 10 10 2 1 8 // - //perValidatorShare 10*10^18 / 8 = 1250000000000000000 == 1.25 * 10^18 + // perValidatorShare 10*10^18 / 8 = 1250000000000000000 == 1.25 * 10^18 // but half goes to burner // calls distributeRewards() inside receipt = await app.testing__distributeRewards({ from: voting }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(1.25) }) - assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(6*1.25) }) + assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(6 * 1.25) }) assert.notEmits(receipt, 'RewardsDistributed', { rewardAddress: user3, sharesAmount: 0 }) assert.emits(receipt, 'NodeOperatorPenalized', { recipientAddress: user1, sharesPenalizedAmount: ETH(1.25) }) }) @@ -269,9 +269,9 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use await steth.setTotalPooledEther(ETH(100)) await steth.mintShares(app.address, ETH(10)) - //update [operator, exited, stuck] - await app.unsafeUpdateValidatorsCount(firstNodeOperator, 1, 1 , { from: voting }) - await app.unsafeUpdateValidatorsCount(secondNodeOperator, 1, 0 , { from: voting }) + // update [operator, exited, stuck] + await app.unsafeUpdateValidatorsCount(firstNodeOperator, 1, 1, { from: voting }) + await app.unsafeUpdateValidatorsCount(secondNodeOperator, 1, 0, { from: voting }) await app.updateRefundedValidatorsCount(firstNodeOperator, 1, { from: voting }) @@ -279,7 +279,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use receipt = await app.testing__distributeRewards({ from: voting }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(1.25) }) - assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(6*1.25) }) + assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(6 * 1.25) }) assert.notEmits(receipt, 'RewardsDistributed', { rewardAddress: user3, sharesAmount: 0 }) assert.emits(receipt, 'NodeOperatorPenalized', { recipientAddress: user1, sharesPenalizedAmount: ETH(1.25) }) }) @@ -292,7 +292,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use await app.unsafeUpdateValidatorsCount(firstNodeOperator, 1, 1, { from: voting }) await app.unsafeUpdateValidatorsCount(secondNodeOperator, 1, 0, { from: voting }) - await assert.reverts(app.updateRefundedValidatorsCount(firstNodeOperator, 1000, { from: voting }), "OUT_OF_RANGE") + await assert.reverts(app.updateRefundedValidatorsCount(firstNodeOperator, 1000, { from: voting }), 'OUT_OF_RANGE') }) it('penalized firstOperator, add refund less than stuck validators', async () => { @@ -310,7 +310,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use // calls distributeRewards() inside receipt = await app.testing__distributeRewards({ from: voting }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(1) }) - assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(4*2) }) + assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(4 * 2) }) assert.notEmits(receipt, 'RewardsDistributed', { rewardAddress: user3, sharesAmount: 0 }) assert.emits(receipt, 'NodeOperatorPenalized', { recipientAddress: user1, sharesPenalizedAmount: ETH(1) }) }) @@ -319,13 +319,11 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use await steth.setTotalPooledEther(ETH(100)) await steth.mintShares(app.address, ETH(10)) - - assert.isFalse(await app.testing_isNodeOperatorPenalized(firstNodeOperator)) - //update [operator, exited, stuck] - await app.unsafeUpdateValidatorsCount(firstNodeOperator, 1, 1 , { from: voting }) - await app.unsafeUpdateValidatorsCount(secondNodeOperator, 1, 0 , { from: voting }) + // update [operator, exited, stuck] + await app.unsafeUpdateValidatorsCount(firstNodeOperator, 1, 1, { from: voting }) + await app.unsafeUpdateValidatorsCount(secondNodeOperator, 1, 0, { from: voting }) assert.isTrue(await app.testing_isNodeOperatorPenalized(firstNodeOperator)) await app.updateRefundedValidatorsCount(firstNodeOperator, 1, { from: voting }) @@ -347,7 +345,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use describe('getNodeOperatorSummary()', () => { beforeEach(async () => { - //total vetted deposited exited + // total vetted deposited exited await app.testing_addNodeOperator('0', user1, 20, 15, 10, 2) await app.testing_addNodeOperator('1', user2, 20, 10, 5, 0) await app.testing_addNodeOperator('2', user3, 15, 5, 0, 0) @@ -399,20 +397,18 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use assert.equal(+keyStats.depositableValidatorsCount, 5) }) - it('updateExitedValidatorsCount() - check if appeared a new deposited keys', async () => { await app.updateTargetValidatorsLimits(3, true, 5, { from: voting }) - let keyStats = await app.getNodeOperatorSummary(3) + const keyStats = await app.getNodeOperatorSummary(3) - //excess = deposited - stopped - targetLimit + // excess = deposited - stopped - targetLimit assert.equal(+keyStats.targetValidatorsCount, 5) - //increase _newActiveValidatorsCount by add new depositedKeys + // increase _newActiveValidatorsCount by add new depositedKeys await app.increaseNodeOperatorDepositedSigningKeysCount(3, 2) const { operatorIds, keysCounts } = prepIdsCountsPayload(3, 1) await app.updateExitedValidatorsCount(operatorIds, keysCounts, { from: voting }) - }) it('updateTargetValidatorsLimits() - try to update to the same active flag', async () => { @@ -427,7 +423,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use assert.equal(keyStats.isTargetLimitActive, false) assert.equal(+targetValidatorsCountBefore, +targetValidatorsCountAfter) - targetValidatorsCountBefore = keyStats.targetValidatorsCount + targetValidatorsCountBefore = keyStats.targetValidatorsCount await app.updateTargetValidatorsLimits(0, true, 20, { from: voting }) keyStats = await app.getNodeOperatorSummary(0) targetValidatorsCountAfter = keyStats.targetValidatorsCount @@ -455,7 +451,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use let keysStatOp = await app.getNodeOperatorSummary(0) assert.equal(+keysStatOp.totalExitedValidators, 2) - assert.equal(keysStatOp.totalDepositedValidators.toNumber()-keysStatOp.totalExitedValidators.toNumber(), 8) + assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 8) assert.equal(+keysStatOp.depositableValidatorsCount, 2) await app.updateTargetValidatorsLimits(0, false, 10, { from: voting }) @@ -471,7 +467,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use keysStatOp = await app.getNodeOperatorSummary(0) assert.equal(+keysStatOp.totalExitedValidators, 2) - assert.equal(keysStatOp.totalDepositedValidators.toNumber()-keysStatOp.totalExitedValidators.toNumber(), 8) + assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 8) assert.equal(+keysStatOp.depositableValidatorsCount, 5) }) @@ -492,7 +488,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use let keysStatOp = await app.getNodeOperatorSummary(0) assert.equal(keysStatOp.totalExitedValidators, 2) - assert.equal(keysStatOp.totalDepositedValidators.toNumber()-keysStatOp.totalExitedValidators.toNumber(), 8) + assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 8) assert.equal(keysStatOp.depositableValidatorsCount, 0) // op 1 @@ -502,7 +498,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use keysStatOp = await app.getNodeOperatorSummary(1) assert.equal(keysStatOp.totalExitedValidators, 0) - assert.equal(keysStatOp.totalDepositedValidators.toNumber()-keysStatOp.totalExitedValidators.toNumber(), 5) + assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 5) assert.equal(keysStatOp.depositableValidatorsCount, 0) // console.log(o2n(limitStatOp)) @@ -514,7 +510,10 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use keysStatTotal = await app.getStakingModuleSummary() // console.log(o2n(keysStatTotal)) assert.equal(+keysStatTotal.totalExitedValidators, 4) - assert.equal(keysStatTotal.totalDepositedValidators.toNumber()-keysStatTotal.totalExitedValidators.toNumber(), 25-(3+1)) + assert.equal( + keysStatTotal.totalDepositedValidators.toNumber() - keysStatTotal.totalExitedValidators.toNumber(), + 25 - (3 + 1) + ) assert.equal(+keysStatTotal.depositableValidatorsCount, 11) // op 0 @@ -524,7 +523,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use keysStatOp = await app.getNodeOperatorSummary(0) assert.equal(keysStatOp.totalExitedValidators, 3) - assert.equal(keysStatOp.totalDepositedValidators.toNumber()-keysStatOp.totalExitedValidators.toNumber(), 7) + assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 7) assert.equal(keysStatOp.depositableValidatorsCount, 0) // op 1 @@ -534,7 +533,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use keysStatOp = await app.getNodeOperatorSummary(1) assert.equal(keysStatOp.totalExitedValidators, 1) - assert.equal(keysStatOp.totalDepositedValidators.toNumber()-keysStatOp.totalExitedValidators.toNumber(), 4) + assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 4) assert.equal(keysStatOp.depositableValidatorsCount, 1) }) @@ -545,7 +544,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use await app.setNodeOperatorStakingLimit(0, 10, { from: voting }) await app.setNodeOperatorStakingLimit(1, 15, { from: voting }) - let keysStatTotal = await app.getStakingModuleSummary() + const keysStatTotal = await app.getStakingModuleSummary() // console.log(o2n(keysStatTotal)) assert.equal(+keysStatTotal.totalExitedValidators, 2) assert.equal(+keysStatTotal.totalDepositedValidators, 25) @@ -558,7 +557,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use let keysStatOp = await app.getNodeOperatorSummary(0) assert.equal(+keysStatOp.totalExitedValidators, 2) - assert.equal(keysStatOp.totalDepositedValidators.toNumber()-keysStatOp.totalExitedValidators.toNumber(), 8) + assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 8) assert.equal(+keysStatOp.depositableValidatorsCount, 0) // op 1 @@ -568,7 +567,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use keysStatOp = await app.getNodeOperatorSummary(1) assert.equal(keysStatOp.totalExitedValidators, 0) - assert.equal(keysStatOp.totalDepositedValidators.toNumber()-keysStatOp.totalExitedValidators.toNumber(), 5) + assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 5) assert.equal(keysStatOp.depositableValidatorsCount, 10) }) }) diff --git a/test/0.4.24/node-operators-registry.test.js b/test/0.4.24/node-operators-registry.test.js index 57db0b3a5..f8e78c344 100644 --- a/test/0.4.24/node-operators-registry.test.js +++ b/test/0.4.24/node-operators-registry.test.js @@ -32,7 +32,7 @@ const NODE_OPERATORS = [ vettedSigningKeysCount: 6, stuckValidatorsCount: 0, refundedValidatorsCount: 0, - stuckPenaltyEndAt: 0 + stuckPenaltyEndAt: 0, }, { name: ' bar', @@ -43,7 +43,7 @@ const NODE_OPERATORS = [ vettedSigningKeysCount: 10, stuckValidatorsCount: 0, refundedValidatorsCount: 0, - stuckPenaltyEndAt: 0 + stuckPenaltyEndAt: 0, }, { name: 'deactivated', @@ -55,8 +55,8 @@ const NODE_OPERATORS = [ vettedSigningKeysCount: 5, stuckValidatorsCount: 0, refundedValidatorsCount: 0, - stuckPenaltyEndAt: 0 - } + stuckPenaltyEndAt: 0, + }, ] // bytes32 0x63757261746564 @@ -89,7 +89,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob appBase = await NodeOperatorsRegistry.new() steth = await StETH.new({ value: ETH(1) }) const locatorConfig = getRandomLocatorConfig({ - lido: steth.address + lido: steth.address, }) locator = await LidoLocator.new(locatorConfig) @@ -101,8 +101,8 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob MANAGE_SIGNING_KEYS: voting, MANAGE_NODE_OPERATOR_ROLE: voting, SET_NODE_OPERATOR_LIMIT_ROLE: voting, - STAKING_ROUTER_ROLE: voting - } + STAKING_ROUTER_ROLE: voting, + }, }) // grant role to app itself cause it uses solidity's call method to itself @@ -264,7 +264,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob exitedSigningKeysCount: 5, stuckValidatorsCount: 0, refundedValidatorsCount: 0, - stuckPenaltyEndAt: 0 + stuckPenaltyEndAt: 0, } await app.testing_addNodeOperator( config.name, @@ -303,7 +303,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob exitedSigningKeysCount: 5, stuckValidatorsCount: 0, refundedValidatorsCount: 0, - stuckPenaltyEndAt: 0 + stuckPenaltyEndAt: 0, } await app.testing_addNodeOperator( @@ -528,7 +528,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const [nodeOperator, keysOpIndexBefore, nonceBefore] = await Promise.all([ app.getNodeOperator(nodeOperatorId, false), app.getKeysOpIndex(), - app.getNonce() + app.getNonce(), ]) assert.isFalse(nodeOperator.active) await app.activateNodeOperator(nodeOperatorId, { from: voting }) @@ -688,7 +688,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const [nodeOperator, operatorReportBefore, allValidatorsReportBefore] = await Promise.all([ app.getNodeOperator(activeNodeOperatorId, false), app.getNodeOperatorSummary(activeNodeOperatorId), - app.getStakingModuleSummary() + app.getStakingModuleSummary(), ]) assert.isTrue( @@ -704,7 +704,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const [operatorReportAfter, allValidatorsReportAfter] = await Promise.all([ app.getNodeOperatorSummary(activeNodeOperatorId), - app.getStakingModuleSummary() + app.getStakingModuleSummary(), ]) assert.equals(+operatorReportAfter.depositableValidatorsCount, 0) @@ -730,7 +730,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const receipt = await app.deactivateNodeOperator(activeNodeOperatorId, { from: voting }) assert.emits(receipt, 'VettedSigningKeysCountChanged', { nodeOperatorId: activeNodeOperatorId, - approvedValidatorsCount: usedSigningKeys + approvedValidatorsCount: usedSigningKeys, }) }) @@ -741,7 +741,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const [nodeOperator, operatorReportBefore, allValidatorsReportBefore] = await Promise.all([ app.getNodeOperator(activeNodeOperatorId, false), app.getNodeOperatorSummary(activeNodeOperatorId), - app.getStakingModuleSummary() + app.getStakingModuleSummary(), ]) assert.isTrue(nodeOperator.active, 'Invariant Failed: not active') @@ -749,7 +749,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const [operatorReportAfter, allValidatorsReportAfter] = await Promise.all([ app.getNodeOperatorSummary(activeNodeOperatorId), - app.getStakingModuleSummary() + app.getStakingModuleSummary(), ]) assert.equals(operatorReportBefore.totalDepositedValidators, operatorReportAfter.totalDepositedValidators) @@ -911,7 +911,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const receipt = await app.setNodeOperatorRewardAddress(firstNodeOperatorId, ADDRESS_4, { from: voting }) assert.emits(receipt, 'NodeOperatorRewardAddressSet', { nodeOperatorId: firstNodeOperatorId, - rewardAddress: ADDRESS_4 + rewardAddress: ADDRESS_4, }) }) @@ -998,14 +998,14 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const [{ stakingLimit: stakingLimitBefore }, nonceBefore, keysOpIndexBefore] = await Promise.all([ app.getNodeOperator(firstNodeOperatorId, false), app.getNonce(), - app.getKeysOpIndex() + app.getKeysOpIndex(), ]) const receipt = await app.setNodeOperatorStakingLimit(firstNodeOperatorId, stakingLimitBefore, { from: voting }) assert.notEmits(receipt, 'VettedSigningKeysCountChanged') const [{ stakingLimit: stakingLimitAfter }, nonceAfter, keysOpIndexAfter] = await Promise.all([ app.getNodeOperator(firstNodeOperatorId, false), app.getNonce(), - app.getKeysOpIndex() + app.getKeysOpIndex(), ]) assert.equals(stakingLimitBefore, stakingLimitAfter) assert.equals(keysOpIndexBefore, keysOpIndexAfter) @@ -1031,7 +1031,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const receipt = await app.setNodeOperatorStakingLimit(firstNodeOperatorId, newStakingLimit, { from: voting }) assert.emits(receipt, 'VettedSigningKeysCountChanged', { nodeOperatorId: firstNodeOperatorId, - approvedValidatorsCount: newStakingLimit + approvedValidatorsCount: newStakingLimit, }) }) @@ -1155,10 +1155,10 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const newExitedValidatorsCount = 4 const [ { stoppedValidators: exitedValidatorsKeysCountBefore }, - { exitedSigningKeysCount: exitedSigningKeysCountBefore } + { exitedSigningKeysCount: exitedSigningKeysCountBefore }, ] = await Promise.all([ await app.getNodeOperator(firstNodeOperatorId, false), - app.testing_getTotalSigningKeysStats() + app.testing_getTotalSigningKeysStats(), ]) const { operatorIds, keysCounts } = prepIdsCountsPayload(firstNodeOperatorId, newExitedValidatorsCount) await app.updateExitedValidatorsCount(operatorIds, keysCounts, { from: voting }) @@ -1176,7 +1176,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const receipt = await app.updateExitedValidatorsCount(operatorIds, keysCounts, { from: voting }) assert.emits(receipt, 'ExitedSigningKeysCountChanged', { nodeOperatorId: firstNodeOperatorId, - exitedValidatorsCount: newExitedValidatorsCount + exitedValidatorsCount: newExitedValidatorsCount, }) }) @@ -1208,13 +1208,13 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it('decreases the stuck validators count when new value is less then previous one', async () => { const newStuckValidatorsCount = 1 await app.unsafeUpdateValidatorsCount(firstNodeOperatorId, exitedSigningKeysCount, stuckValidatorsCount, { - from: voting + from: voting, }) const { stuckValidatorsCount: stuckValidatorsCountBefore } = await app.getNodeOperatorSummary(firstNodeOperatorId) assert(newStuckValidatorsCount < stuckValidatorsCountBefore) await app.unsafeUpdateValidatorsCount(firstNodeOperatorId, exitedSigningKeysCount, newStuckValidatorsCount, { - from: voting + from: voting, }) const { stuckValidatorsCount: stuckValidatorsCountAfter } = await app.getNodeOperatorSummary(firstNodeOperatorId) assert.equals(stuckValidatorsCountAfter, newStuckValidatorsCount) @@ -1227,7 +1227,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob ) assert(newStuckValidatorsCount > stuckValidatorsCountBefore) await app.unsafeUpdateValidatorsCount(secondNodeOperatorId, exitedSigningKeysCount, newStuckValidatorsCount, { - from: voting + from: voting, }) const { stuckValidatorsCount: stuckValidatorsCountAfter } = await app.getNodeOperatorSummary(secondNodeOperatorId) assert.equals(stuckValidatorsCountAfter, newStuckValidatorsCount) @@ -1243,14 +1243,14 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob ) assert.emits(receipt, 'StuckPenaltyStateChanged', { nodeOperatorId: firstNodeOperatorId, - stuckValidatorsCount: newStuckValidatorsCount + stuckValidatorsCount: newStuckValidatorsCount, }) }) it("doesn't change the state when new stuck validators value is equal to the previous one", async () => { const { stuckValidatorsCount: stuckValidatorsCountBefore } = await app.getNodeOperatorSummary(firstNodeOperatorId) await app.unsafeUpdateValidatorsCount(firstNodeOperatorId, exitedSigningKeysCount, stuckValidatorsCountBefore, { - from: voting + from: voting, }) const { stuckValidatorsCount: stuckValidatorsCountAfter } = await app.getNodeOperatorSummary(firstNodeOperatorId) @@ -1264,7 +1264,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob exitedSigningKeysCount, stuckValidatorsCountBefore, { - from: voting + from: voting, } ) assert.notEmits(receipt, 'StuckPenaltyStateChanged') @@ -1276,7 +1276,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob firstNodeOperatorId ) await app.unsafeUpdateValidatorsCount(secondNodeOperatorId, exitedSigningKeysCount, newStuckValidatorsCount, { - from: voting + from: voting, }) const { stuckValidatorsCount: secondNodeOperatorStuckValidatorsCountAfter } = await app.getNodeOperatorSummary( firstNodeOperatorId @@ -1290,7 +1290,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob assert(newStuckValidatorsCount > stuckValidatorsCount) await assert.reverts( app.unsafeUpdateValidatorsCount(firstNodeOperatorId, exitedSigningKeysCount, newStuckValidatorsCount, { - from: voting + from: voting, }), 'OUT_OF_RANGE' ) @@ -1342,7 +1342,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob exitedValidatorsKeysCountBefore, stuckValidatorsCount, { - from: voting + from: voting, } ) assert.notEmits(receipt, 'ExitedSigningKeysCountChanged') @@ -1354,7 +1354,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob assert(newExitedValidatorsCount > nodeOperator.usedSigningKeys.toNumber()) await assert.reverts( app.unsafeUpdateValidatorsCount(firstNodeOperatorId, newExitedValidatorsCount, stuckValidatorsCount, { - from: voting + from: voting, }), 'OUT_OF_RANGE' ) @@ -1369,7 +1369,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob ) assert(newExitedValidatorsCount < exitedValidatorsKeysCountBefore.toNumber()) await app.unsafeUpdateValidatorsCount(firstNodeOperatorId, newExitedValidatorsCount, newStuckValidatorsCount, { - from: voting + from: voting, }) const { stoppedValidators: exitedValidatorsKeysCountAfter } = await app.getNodeOperator( firstNodeOperatorId, @@ -1386,7 +1386,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob ) assert(newExitedValidatorsCount > exitedValidatorsKeysCountBefore.toNumber()) await app.unsafeUpdateValidatorsCount(secondNodeOperatorId, newExitedValidatorsCount, stuckValidatorsCount, { - from: voting + from: voting, }) const { stoppedValidators: exitedValidatorsKeysCountAfter } = await app.getNodeOperator( secondNodeOperatorId, @@ -1399,14 +1399,11 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const newExitedValidatorsCount = 1 const [ { stoppedValidators: exitedValidatorsKeysCountBefore }, - { exitedSigningKeysCount: exitedSigningKeysCountBefore } - ] = await Promise.all([ - app.getNodeOperator(firstNodeOperatorId, false), - app.testing_getTotalSigningKeysStats() - ]) + { exitedSigningKeysCount: exitedSigningKeysCountBefore }, + ] = await Promise.all([app.getNodeOperator(firstNodeOperatorId, false), app.testing_getTotalSigningKeysStats()]) assert(newExitedValidatorsCount < exitedValidatorsKeysCountBefore.toNumber()) await app.unsafeUpdateValidatorsCount(firstNodeOperatorId, newExitedValidatorsCount, stuckValidatorsCount, { - from: voting + from: voting, }) const exitedSigningKeysCountIncrement = exitedValidatorsKeysCountBefore.toNumber() - newExitedValidatorsCount const { exitedSigningKeysCount: exitedSigningKeysCountAfter } = await app.testing_getTotalSigningKeysStats() @@ -1421,14 +1418,11 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const newStuckValidatorsCount = 0 const [ { stoppedValidators: exitedValidatorsKeysCountBefore }, - { exitedSigningKeysCount: exitedSigningKeysCountBefore } - ] = await Promise.all([ - app.getNodeOperator(firstNodeOperatorId, false), - app.testing_getTotalSigningKeysStats() - ]) + { exitedSigningKeysCount: exitedSigningKeysCountBefore }, + ] = await Promise.all([app.getNodeOperator(firstNodeOperatorId, false), app.testing_getTotalSigningKeysStats()]) assert(newExitedValidatorsCount > exitedValidatorsKeysCountBefore.toNumber()) await app.unsafeUpdateValidatorsCount(firstNodeOperatorId, newExitedValidatorsCount, newStuckValidatorsCount, { - from: voting + from: voting, }) const exitedSigningKeysCountIncrement = newExitedValidatorsCount - exitedValidatorsKeysCountBefore.toNumber() const { exitedSigningKeysCount: exitedSigningKeysCountAfter } = await app.testing_getTotalSigningKeysStats() @@ -1448,7 +1442,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob ) assert.emits(receipt, 'ExitedSigningKeysCountChanged', { nodeOperatorId: secondNodeOperatorId, - exitedValidatorsCount: newExitedValidatorsCount + exitedValidatorsCount: newExitedValidatorsCount, }) }) @@ -1459,10 +1453,10 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob true ) await app.unsafeUpdateValidatorsCount(secondNodeOperatorId, newExitedValidatorsCount, stuckValidatorsCount, { - from: voting + from: voting, }) await app.unsafeUpdateValidatorsCount(secondNodeOperatorId, newExitedValidatorsCount, stuckValidatorsCount, { - from: voting + from: voting, }) const { stakingLimit: secondNodeOperatorStakingLimitAfter } = await app.getNodeOperator(firstNodeOperatorId, true) assert.equals(secondNodeOperatorStakingLimitAfter, secondNodeOperatorStakingLimitBefore) @@ -1479,7 +1473,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob { ...NODE_OPERATORS[2], vettedSigningKeysCount: NODE_OPERATORS[2].totalSigningKeysCount, - depositedSigningKeysCount: NODE_OPERATORS[2].totalSigningKeysCount + depositedSigningKeysCount: NODE_OPERATORS[2].totalSigningKeysCount, }, { from: voting } ) @@ -1513,11 +1507,11 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob if (nodeOperatorBefore.totalSigningKeys.toNumber() !== nodeOperatorAfter.usedSigningKeys.toNumber()) { assert.emits(receipt, 'TotalSigningKeysCountChanged', { nodeOperatorId: i, - totalValidatorsCount: nodeOperatorAfter.usedSigningKeys + totalValidatorsCount: nodeOperatorAfter.usedSigningKeys, }) assert.emits(receipt, 'VettedSigningKeysCountChanged', { nodeOperatorId: i, - approvedValidatorsCount: nodeOperatorAfter.usedSigningKeys + approvedValidatorsCount: nodeOperatorAfter.usedSigningKeys, }) } else { assert.notEmits(receipt, 'TotalSigningKeysCountChanged', { nodeOperatorId: i }) @@ -1537,7 +1531,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob assert.emits(receipt, 'NodeOperatorTotalKeysTrimmed', { nodeOperatorId: i, totalKeysTrimmed: - nodeOperatorBefore.totalSigningKeys.toNumber() - nodeOperatorAfter.usedSigningKeys.toNumber() + nodeOperatorBefore.totalSigningKeys.toNumber() - nodeOperatorAfter.usedSigningKeys.toNumber(), }) } else { assert.notEmits(receipt, 'NodeOperatorTotalKeysTrimmed', { nodeOperatorId: i }) @@ -1654,7 +1648,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it.skip('respects staking limit', async () => { const [firstNodeOperatorKeysStats, secondNodeOperatorKeysStats] = await Promise.all([ app.getNodeOperatorSummary(firstNodeOperatorId), - app.getValidatorsKeysStats(secondNodeOperatorId) + app.getValidatorsKeysStats(secondNodeOperatorId), ]) assert.isTrue(firstNodeOperatorKeysStats.readyToDepositValidatorsKeysCount.toNumber() > 0) @@ -1717,7 +1711,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob await app.deactivateNodeOperator(secondNodeOperatorId, { from: voting }) const [firstNodeOperator, secondNodeOperator] = await Promise.all([ app.getNodeOperator(firstNodeOperatorId, false), - app.getNodeOperator(secondNodeOperatorId, false) + app.getNodeOperator(secondNodeOperatorId, false), ]) assert.isFalse(firstNodeOperator.active) assert.isFalse(secondNodeOperator.active) @@ -1735,7 +1729,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob await app.onWithdrawalCredentialsChanged({ from: voting }) const [firstNodeOperator, secondNodeOperator] = await Promise.all([ app.getNodeOperator(firstNodeOperatorId, false), - app.getNodeOperator(secondNodeOperatorId, false) + app.getNodeOperator(secondNodeOperatorId, false), ]) assert.equals(firstNodeOperator.totalSigningKeys, firstNodeOperator.usedSigningKeys) assert.equals(secondNodeOperator.totalSigningKeys, secondNodeOperator.usedSigningKeys) @@ -1751,7 +1745,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob await app.testing_markAllKeysDeposited() const [firstNodeOperator, secondNodeOperator] = await Promise.all([ app.getNodeOperator(firstNodeOperatorId, false), - app.getNodeOperator(secondNodeOperatorId, false) + app.getNodeOperator(secondNodeOperatorId, false), ]) assert.equals(firstNodeOperator.usedSigningKeys, firstNodeOperator.stakingLimit) assert.equals(secondNodeOperator.usedSigningKeys, secondNodeOperator.stakingLimit) @@ -1766,7 +1760,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob await app.testing_markAllKeysDeposited(firstNodeOperatorId) const [firstNodeOperator, secondNodeOperator] = await Promise.all([ app.getNodeOperator(firstNodeOperatorId, false), - app.getNodeOperator(secondNodeOperatorId, false) + app.getNodeOperator(secondNodeOperatorId, false), ]) assert.equals(firstNodeOperator.stakingLimit, firstNodeOperator.usedSigningKeys) @@ -1797,7 +1791,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it('allocates deposits firstly to node operators with min active keys count & with available keys', async () => { const [firstNodeOperatorReport, secondNodeOperatorReport] = await Promise.all([ app.getNodeOperatorSummary(firstNodeOperatorId), - app.getNodeOperatorSummary(secondNodeOperatorId) + app.getNodeOperatorSummary(secondNodeOperatorId), ]) const firstNodeOperatorAvailableValidators = +firstNodeOperatorReport.depositableValidatorsCount @@ -1839,7 +1833,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const [firstNodeOperatorReport, secondNodeOperatorReport] = await Promise.all([ app.getNodeOperatorSummary(firstNodeOperatorId), - app.getNodeOperatorSummary(secondNodeOperatorId) + app.getNodeOperatorSummary(secondNodeOperatorId), ]) const firstNodeOperatorAvailableValidators = +firstNodeOperatorReport.depositableValidatorsCount @@ -1874,7 +1868,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it('respects staking limit', async () => { const [firstNodeOperatorReport, secondNodeOperatorReport] = await Promise.all([ app.getNodeOperatorSummary(firstNodeOperatorId), - app.getNodeOperatorSummary(secondNodeOperatorId) + app.getNodeOperatorSummary(secondNodeOperatorId), ]) const firstNodeOperatorAvailableValidators = firstNodeOperatorReport.depositableValidatorsCount @@ -2064,11 +2058,11 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob let receipt = await app.testing_obtainDepositData(keysToAllocate) assert.emits(receipt, 'DepositedSigningKeysCountChanged', { nodeOperatorId: firstNodeOperatorId, - depositedValidatorsCount: 6 + depositedValidatorsCount: 6, }) assert.emits(receipt, 'DepositedSigningKeysCountChanged', { nodeOperatorId: secondNodeOperatorId, - depositedValidatorsCount: 8 + depositedValidatorsCount: 8, }) const stakingModuleSummary = await app.getStakingModuleSummary() @@ -2076,11 +2070,11 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob receipt = await app.testing_obtainDepositData(keysToAllocate) assert.notEmits(receipt, 'DepositedSigningKeysCountChanged', { nodeOperatorId: firstNodeOperatorId, - depositedSigningKeysCount: 6 + depositedSigningKeysCount: 6, }) assert.emits(receipt, 'DepositedSigningKeysCountChanged', { nodeOperatorId: secondNodeOperatorId, - depositedValidatorsCount: 10 + depositedValidatorsCount: 10, }) }) }) @@ -2153,7 +2147,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob [firstNodeOperatorId, secondNodeOperatorId], [ NODE_OPERATORS[firstNodeOperatorId].depositedSigningKeysCount, - NODE_OPERATORS[secondNodeOperatorId].depositedSigningKeysCount + NODE_OPERATORS[secondNodeOperatorId].depositedSigningKeysCount, ] ) await app.updateExitedValidatorsCount(operatorIds, keysCounts, { from: voting }) @@ -2278,7 +2272,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it('increases node operator total signing keys counter correctly', async () => { const { totalSigningKeys: totalSigningKeysCountBefore } = await app.getNodeOperator(firstNodeOperatorId, false) await app.addSigningKeys(firstNodeOperatorId, firstNodeOperatorKeys.count, ...firstNodeOperatorKeys.slice(), { - from: voting + from: voting, }) const { totalSigningKeys: totalSigningKeysCountAfter } = await app.getNodeOperator(firstNodeOperatorId, false) assert.equals( @@ -2290,7 +2284,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it("doesn't modify total signing keys counter of other node operators", async () => { const { totalSigningKeys: totalSigningKeysCountBefore } = await app.getNodeOperator(secondNodeOperatorId, false) await app.addSigningKeys(firstNodeOperatorId, firstNodeOperatorKeys.count, ...firstNodeOperatorKeys.slice(), { - from: voting + from: voting, }) const { totalSigningKeys: totalSigningKeysCountAfter } = await app.getNodeOperator(secondNodeOperatorId, false) assert.equals(totalSigningKeysCountBefore, totalSigningKeysCountAfter) @@ -2298,7 +2292,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it('stores keys correctly for node operator without keys', async () => { await app.addSigningKeys(secondNodeOperatorId, secondNodeOperatorKeys.count, ...secondNodeOperatorKeys.slice(), { - from: voting + from: voting, }) for (let i = 0; i < secondNodeOperatorKeys.count; ++i) { const { key, depositSignature } = await app.getSigningKey(secondNodeOperatorId, i) @@ -2321,7 +2315,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob firstNodeOperatorKeys.count - initialKeysCount, ...firstNodeOperatorKeys.slice(2), { - from: voting + from: voting, } ) for (let i = initialKeysCount; i < firstNodeOperatorKeys.count; ++i) { @@ -2334,10 +2328,10 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it("doesn't modify the keys of other node operators", async () => { await app.addSigningKeys(firstNodeOperatorId, firstNodeOperatorKeys.count, ...firstNodeOperatorKeys.slice(), { - from: voting + from: voting, }) await app.addSigningKeys(secondNodeOperatorId, secondNodeOperatorKeys.count, ...secondNodeOperatorKeys.slice(), { - from: voting + from: voting, }) for (let i = 0; i < firstNodeOperatorKeys.count; ++i) { const { key, depositSignature } = await app.getSigningKey(firstNodeOperatorId, i) @@ -2349,11 +2343,11 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it('increases global total signing keys counter correctly', async () => { await app.addSigningKeys(secondNodeOperatorId, secondNodeOperatorKeys.count, ...secondNodeOperatorKeys.slice(), { - from: voting + from: voting, }) const { totalSigningKeysCount: totalSigningKeysCountBefore } = await app.testing_getTotalSigningKeysStats() await app.addSigningKeys(firstNodeOperatorId, firstNodeOperatorKeys.count, ...firstNodeOperatorKeys.slice(), { - from: voting + from: voting, }) const { totalSigningKeysCount: totalSigningKeysCountAfter } = await app.testing_getTotalSigningKeysStats() assert.equals(totalSigningKeysCountAfter, totalSigningKeysCountBefore.toNumber() + firstNodeOperatorKeys.count) @@ -2362,7 +2356,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it('increases keysOpIndex & changes nonce', async () => { const [keysOpIndexBefore, nonceBefore] = await Promise.all([app.getKeysOpIndex(), app.getNonce()]) await app.addSigningKeys(firstNodeOperatorId, firstNodeOperatorKeys.count, ...firstNodeOperatorKeys.slice(), { - from: voting + from: voting, }) const [keysOpIndexAfter, nonceAfter] = await Promise.all([app.getKeysOpIndex(), app.getNonce()]) assert.equals(keysOpIndexAfter, keysOpIndexBefore.toNumber() + 1) @@ -2376,7 +2370,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob firstNodeOperatorKeys.count, ...firstNodeOperatorKeys.slice(), { - from: voting + from: voting, } ) const nonceAfter = await app.getNonce() @@ -2390,7 +2384,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob firstNodeOperatorKeys.count, ...firstNodeOperatorKeys.slice(), { - from: voting + from: voting, } ) for (let i = 0; i < firstNodeOperatorKeys.count; ++i) { @@ -2409,12 +2403,12 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob secondNodeOperatorKeys.count, ...secondNodeOperatorKeys.slice(), { - from: voting + from: voting, } ) assert.emits(receipt, 'TotalSigningKeysCountChanged', { nodeOperatorId: secondNodeOperatorId, - totalValidatorsCount: secondNodeOperatorKeys.count + totalValidatorsCount: secondNodeOperatorKeys.count, }) }) }) @@ -2434,7 +2428,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob firstNodeOperatorKeys.count, ...firstNodeOperatorKeys.slice(), { - from: user2 + from: user2, } ), 'APP_AUTH_FAILED' @@ -2455,7 +2449,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob firstNodeOperatorKeys.count, ...firstNodeOperatorKeys.slice(), { - from: user1 + from: user1, } ) for (let i = 0; i < firstNodeOperatorKeys.count; ++i) { @@ -2574,7 +2568,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const { isTargetLimitActive: isTargetLimitActiveBefore, targetValidatorsCount: targetValidatorsCountBefore, - excessValidatorsCount: excessValidatorsCountBefore + excessValidatorsCount: excessValidatorsCountBefore, } = await app.testing_getTotalTargetStats() await app.removeSigningKey(secondNodeOperatorId, keyIndex, { from: voting }) @@ -2589,14 +2583,14 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const { isTargetLimitActive: isTargetLimitActiveAfter, targetValidatorsCount: targetValidatorsCountAfter, - excessValidatorsCount: excessValidatorsCountAfter + excessValidatorsCount: excessValidatorsCountAfter, } = await app.testing_getTotalTargetStats() console.log({ targetValidatorsCountBefore: targetValidatorsCountBefore.toNumber(), targetValidatorsCountAfter: targetValidatorsCountAfter.toNumber(), vettedSigningKeysCountBefore: vettedSigningKeysCountBefore.toNumber(), - vettedSigningKeysDecrement + vettedSigningKeysDecrement, }) assertBn(isTargetLimitActiveAfter, isTargetLimitActiveBefore) @@ -2686,7 +2680,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob for (let i = 0; i < unusedKeysCount; ++i) { // always remove the first signing key await app.removeSigningKey(firstNodeOperatorId, NODE_OPERATORS[firstNodeOperatorId].depositedSigningKeysCount, { - from: voting + from: voting, }) } const { totalSigningKeys, stakingLimit, usedSigningKeys } = await app.getNodeOperator(firstNodeOperatorId, false) @@ -2708,7 +2702,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob // remove all unused signing keys of first node operator for (let i = 0; i < unusedKeysCount; ++i) { await app.removeSigningKey(firstNodeOperatorId, NODE_OPERATORS[firstNodeOperatorId].depositedSigningKeysCount, { - from: voting + from: voting, }) } @@ -2738,7 +2732,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const receipt = await app.removeSigningKey(secondNodeOperatorId, keyIndex, { from: voting }) assert.emits(receipt, 'VettedSigningKeysCountChanged', { nodeOperatorId: secondNodeOperatorId, - approvedValidatorsCount: keyIndex + approvedValidatorsCount: keyIndex, }) }) @@ -2765,7 +2759,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob 'TotalSigningKeysCountChanged', { nodeOperatorId: firstNodeOperatorId, - totalValidatorsCount: NODE_OPERATORS[firstNodeOperatorId].totalSigningKeysCount - 1 + totalValidatorsCount: NODE_OPERATORS[firstNodeOperatorId].totalSigningKeysCount - 1, }, { abi: NodeOperatorsRegistry._json.abi } ) @@ -2780,7 +2774,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob 'SigningKeyRemoved', { nodeOperatorId: firstNodeOperatorId, - pubkey: firstNodeOperatorKeys.get(keyIndex)[0] + pubkey: firstNodeOperatorKeys.get(keyIndex)[0], }, { abi: SigningKeys._json.abi } ) @@ -3000,8 +2994,8 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob assert.equals( totalSigningKeys, NODE_OPERATORS[secondNodeOperatorId].totalSigningKeysCount - - (NODE_OPERATORS[secondNodeOperatorId].vettedSigningKeysCount - - NODE_OPERATORS[secondNodeOperatorId].depositedSigningKeysCount) + (NODE_OPERATORS[secondNodeOperatorId].vettedSigningKeysCount - + NODE_OPERATORS[secondNodeOperatorId].depositedSigningKeysCount) ) assert.equals(stakingLimit, NODE_OPERATORS[secondNodeOperatorId].depositedSigningKeysCount) @@ -3115,7 +3109,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const receipt = await app.removeSigningKeys(secondNodeOperatorId, keyIndex, keysCount, { from: voting }) assert.emits(receipt, 'VettedSigningKeysCountChanged', { nodeOperatorId: secondNodeOperatorId, - approvedValidatorsCount: keyIndex + approvedValidatorsCount: keyIndex, }) }) @@ -3142,7 +3136,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const receipt = await app.removeSigningKeys(firstNodeOperatorId, keyIndex, keysCount, { from: voting }) assert.emits(receipt, 'TotalSigningKeysCountChanged', { nodeOperatorId: firstNodeOperatorId, - totalValidatorsCount: NODE_OPERATORS[firstNodeOperatorId].depositedSigningKeysCount + totalValidatorsCount: NODE_OPERATORS[firstNodeOperatorId].depositedSigningKeysCount, }) }) @@ -3157,7 +3151,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob 'SigningKeyRemoved', { nodeOperatorId: firstNodeOperatorId, - pubkey: firstNodeOperatorKeys.get(i)[0] + pubkey: firstNodeOperatorKeys.get(i)[0], }, { abi: SigningKeys._json.abi } ) @@ -3269,14 +3263,14 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob const recipientsSharesBefore = await Promise.all([ steth.sharesOf(user1), steth.sharesOf(user2), - steth.sharesOf(user3) + steth.sharesOf(user3), ]) // calls distributeRewards() inside await app.onExitedAndStuckValidatorsCountsUpdated({ from: voting }) const recipientsSharesAfter = await Promise.all([ steth.sharesOf(user1), steth.sharesOf(user2), - steth.sharesOf(user3) + steth.sharesOf(user3), ]) assert.equals(recipientsSharesBefore.length, recipientsSharesAfter.length) for (let i = 0; i < recipientsSharesBefore.length; ++i) { @@ -3331,7 +3325,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob console.log(`gas used to distribute rewards for ${maxNodeOperatorsCount} NOs:`, +tx.receipt.gasUsed) // check that gas is lower than 10M - assert.isTrue(+tx.receipt.gasUsed < 10 * 10**6) + assert.isTrue(+tx.receipt.gasUsed < 10 * 10 ** 6) }) }) @@ -3415,7 +3409,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob it('returns correct key and signature', async () => { const nodeOperatorsData = [ [firstNodeOperatorId, firstNodeOperatorKeys], - [secondNodeOperatorId, secondNodeOperatorKeys] + [secondNodeOperatorId, secondNodeOperatorKeys], ] for (const [nodeOperatorId, nodeOperatorKeys] of nodeOperatorsData) { for (let i = 0; i < nodeOperatorKeys.count; ++i) { diff --git a/test/0.4.24/staking-limit.test.js b/test/0.4.24/staking-limit.test.js index 45a697cd9..eff792efa 100644 --- a/test/0.4.24/staking-limit.test.js +++ b/test/0.4.24/staking-limit.test.js @@ -108,18 +108,27 @@ contract('StakingLimits', ([account1]) => { maxStakeLimit = 5 maxStakeLimitGrowthBlocks = 6 - await assertRevert(limits.setStakingLimit(slot, maxStakeLimit, maxStakeLimitGrowthBlocks), 'TOO_LARGE_LIMIT_INCREASE') + await assertRevert( + limits.setStakingLimit(slot, maxStakeLimit, maxStakeLimitGrowthBlocks), + 'TOO_LARGE_LIMIT_INCREASE' + ) }) it('stake limit reverts on large values', async () => { let maxStakeLimit = toBN(2).pow(toBN(96)) let maxStakeLimitIncreasePerBlock = 1 const slot = await limits.setStorageStakeLimitStruct(0, 0, 0, 0) - await assertRevert(limits.setStakingLimit(slot, maxStakeLimit, maxStakeLimitIncreasePerBlock), 'TOO_LARGE_MAX_STAKE_LIMIT') + await assertRevert( + limits.setStakingLimit(slot, maxStakeLimit, maxStakeLimitIncreasePerBlock), + 'TOO_LARGE_MAX_STAKE_LIMIT' + ) maxStakeLimit = toBN(2).mul(toBN(10).pow(toBN(18))) maxStakeLimitIncreasePerBlock = toBN(10) - await assertRevert(limits.setStakingLimit(slot, maxStakeLimit, maxStakeLimitIncreasePerBlock), `TOO_SMALL_LIMIT_INCREASE`) + await assertRevert( + limits.setStakingLimit(slot, maxStakeLimit, maxStakeLimitIncreasePerBlock), + `TOO_SMALL_LIMIT_INCREASE` + ) }) it('check update calculate stake limit with different blocks', async () => { @@ -192,7 +201,12 @@ contract('StakingLimits', ([account1]) => { // check that we CAN set max value - const maxSlot = await limits.setStorageStakeLimitStruct(maxBlock, maxPrevStakeLimit, maxStakeLimitGrowthBlocks, maxStakeLimit) + const maxSlot = await limits.setStorageStakeLimitStruct( + maxBlock, + maxPrevStakeLimit, + maxStakeLimitGrowthBlocks, + maxStakeLimit + ) const maxUint256 = toBN(2).pow(toBN(256)).sub(toBN(1)) assertBn(maxSlot, maxUint256) @@ -215,12 +229,7 @@ contract('StakingLimits', ([account1]) => { const maxStakeLimit = ETH(150000) const maxStakeLimitGrowthBlocks = 12 - const slot = await limits.setStorageStakeLimitStruct( - block.number, - ETH(0), - maxStakeLimitGrowthBlocks, - maxStakeLimit - ) + const slot = await limits.setStorageStakeLimitStruct(block.number, ETH(0), maxStakeLimitGrowthBlocks, maxStakeLimit) // dry run to init the storage await limits.emitCurrentStakeLimit(slot) @@ -229,7 +238,7 @@ contract('StakingLimits', ([account1]) => { const referenceBlock = (await web3.eth.getBlock('latest')).number // spin up the loop to hit the max and impose saturation - for(i=0; i { assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: user2, value: amount } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: user1, to: user2, sharesValue: sharesAmount } }) + assertEvent(receipt, 'TransferShares', { + expectedArgs: { from: user1, to: user2, sharesValue: sharesAmount }, + }) assertBn(await stEth.balanceOf(user1), tokens(0)) assertBn(await stEth.balanceOf(user2), tokens(99)) }) @@ -115,7 +117,9 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: user2, value: amount } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: user1, to: user2, sharesValue: sharesAmount } }) + assertEvent(receipt, 'TransferShares', { + expectedArgs: { from: user1, to: user2, sharesValue: sharesAmount }, + }) assertBn(await stEth.balanceOf(user1), tokens(99)) assertBn(await stEth.balanceOf(user2), tokens(0)) }) @@ -159,11 +163,17 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { }) it('reverts when recipient is zero address', async () => { - await assertRevert(stEth.transferFrom(user1, ZERO_ADDRESS, tokens(1), { from: user2 }), 'TRANSFER_TO_THE_ZERO_ADDRESS') + await assertRevert( + stEth.transferFrom(user1, ZERO_ADDRESS, tokens(1), { from: user2 }), + 'TRANSFER_TO_THE_ZERO_ADDRESS' + ) }) it('reverts when sender is zero address', async () => { - await assertRevert(stEth.transferFrom(ZERO_ADDRESS, user3, tokens(0), { from: user2 }), 'TRANSFER_FROM_THE_ZERO_ADDRESS') + await assertRevert( + stEth.transferFrom(ZERO_ADDRESS, user3, tokens(0), { from: user2 }), + 'TRANSFER_FROM_THE_ZERO_ADDRESS' + ) }) it('reverts when amount exceeds allowance', async () => { @@ -183,7 +193,9 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { assertAmountOfEvents(receipt, 'Approval', { expectedAmount: 1 }) assertEvent(receipt, 'Approval', { expectedArgs: { owner: user1, spender: user2, value: bn(0) } }) assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: user3, value: amount } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: user1, to: user3, sharesValue: sharesAmount } }) + assertEvent(receipt, 'TransferShares', { + expectedArgs: { from: user1, to: user3, sharesValue: sharesAmount }, + }) assertBn(await stEth.allowance(user2, user1), bn(0)) assertBn(await stEth.balanceOf(user1), tokens(49)) assertBn(await stEth.balanceOf(user3), tokens(50)) @@ -220,7 +232,9 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { const increase_amount = tokens(50) const increased_amount = tokens(100) const receipt = await stEth.increaseAllowance(user2, increase_amount, { from: user1 }) - assertEvent(receipt, 'Approval', { expectedArgs: { owner: user1, spender: user2, value: increased_amount } }) + assertEvent(receipt, 'Approval', { + expectedArgs: { owner: user1, spender: user2, value: increased_amount }, + }) assertBn(await stEth.allowance(user1, user2), increased_amount) }) }) @@ -285,10 +299,10 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { assert(await stEth.isStopped()) await assertRevert(stEth.transfer(user2, tokens(2), { from: user1 }), 'CONTRACT_IS_STOPPED') - //NB: can approve if stopped + // NB: can approve if stopped await stEth.approve(user2, tokens(2), { from: user1 }) await assertRevert(stEth.transferFrom(user2, user3, tokens(2), { from: user1 }), 'CONTRACT_IS_STOPPED') - //NB: can change allowance if stopped + // NB: can change allowance if stopped await stEth.increaseAllowance(user2, tokens(2), { from: user1 }) await stEth.decreaseAllowance(user2, tokens(2), { from: user1 }) @@ -377,8 +391,8 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { account: user1, preRebaseTokenAmount: tokens(0), postRebaseTokenAmount: tokens(0), - sharesAmount: tokens(0) - } + sharesAmount: tokens(0), + }, }) assertBn(await stEth.totalSupply(), tokens(300)) @@ -398,9 +412,7 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { const user2Shares = await stEth.sharesOf(user2) const sharesToBurn = totalShares.sub( - totalSupply - .mul(totalShares.sub(user2Shares)) - .div(totalSupply.sub(user2Balance).add(bn(tokens(10)))) + totalSupply.mul(totalShares.sub(user2Shares)).div(totalSupply.sub(user2Balance).add(bn(tokens(10)))) ) const expectedPreTokenAmount = await stEth.getPooledEthByShares(sharesToBurn) @@ -411,8 +423,8 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { account: user2, preRebaseTokenAmount: expectedPreTokenAmount, postRebaseTokenAmount: expectedPostTokenAmount, - sharesAmount: sharesToBurn - } + sharesAmount: sharesToBurn, + }, }) assertBn(await stEth.totalSupply(), tokens(300)) @@ -435,8 +447,7 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { const user2Shares = await stEth.sharesOf(user2) const sharesToBurn = totalShares.sub( - totalSupply.mul(totalShares.sub(user2Shares)) - .div(totalSupply.sub(user2Balance).add(bn(tokens(50)))) + totalSupply.mul(totalShares.sub(user2Shares)).div(totalSupply.sub(user2Balance).add(bn(tokens(50)))) ) const expectedPreTokenAmount = await stEth.getPooledEthByShares(sharesToBurn) @@ -447,8 +458,8 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { account: user2, preRebaseTokenAmount: expectedPreTokenAmount, postRebaseTokenAmount: expectedPostTokenAmount, - sharesAmount: sharesToBurn - } + sharesAmount: sharesToBurn, + }, }) assertBn(await stEth.balanceOf(user2), tokens(50)) @@ -582,7 +593,7 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { await stEth.setTotalPooledEther(tokens(120)) - const tokensToTransfer = tokens(120 * 69 / 100) + const tokensToTransfer = tokens((120 * 69) / 100) receipt = await stEth.transferShares(nobody, tokens(69), { from: user1 }) assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) @@ -621,13 +632,22 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { assertBn(await stEth.balanceOf(user1), tokens(69)) assertBn(await stEth.balanceOf(nobody), tokens(30)) - await assertRevert(stEth.transferSharesFrom(user1, nobody, tokens(75), { from: user2 }), 'TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE') + await assertRevert( + stEth.transferSharesFrom(user1, nobody, tokens(75), { from: user2 }), + 'TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE' + ) await stEth.approve(user2, tokens(75), { from: user1 }) - await assertRevert(stEth.transferSharesFrom(user1, nobody, tokens(75), { from: user2 }), 'TRANSFER_AMOUNT_EXCEEDS_BALANCE') + await assertRevert( + stEth.transferSharesFrom(user1, nobody, tokens(75), { from: user2 }), + 'TRANSFER_AMOUNT_EXCEEDS_BALANCE' + ) await stEth.setTotalPooledEther(tokens(120)) - await assertRevert(stEth.transferSharesFrom(user1, nobody, tokens(70), { from: user2 }), 'TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE') + await assertRevert( + stEth.transferSharesFrom(user1, nobody, tokens(70), { from: user2 }), + 'TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE' + ) await stEth.approve(user2, tokens(84), { from: user1 }) receipt = await stEth.transferSharesFrom(user1, nobody, tokens(69), { from: user2 }) diff --git a/test/0.4.24/stethpermit.test.js b/test/0.4.24/stethpermit.test.js index b9290fde8..8ac99a0c9 100644 --- a/test/0.4.24/stethpermit.test.js +++ b/test/0.4.24/stethpermit.test.js @@ -19,7 +19,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { eip712StETH = await EIP712StETH.new(stEthPermit.address, { from: deployer }) await stEthPermit.initializeEIP712StETH(eip712StETH.address) - chainId = await web3.eth.net.getId(); + chainId = await web3.eth.net.getId() domainSeparator = makeDomainSeparator('Liquid staked Ether 2.0', '2', chainId, stEthPermit.address) await snapshot.make() @@ -41,7 +41,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { spender: bob.address, value: 6e6, nonce: 0, - deadline: MAX_UINT256 + deadline: MAX_UINT256, } beforeEach(async () => { @@ -50,10 +50,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { }) it('EIP-712 signature helper reverts when zero stETH address passed', async () => { - await assert.revertsWithCustomError( - EIP712StETH.new(ZERO_ADDRESS, { from: deployer }), - `ZeroStETHAddress()` - ) + await assert.revertsWithCustomError(EIP712StETH.new(ZERO_ADDRESS, { from: deployer }), `ZeroStETHAddress()`) }) it('EIP-712 signature helper contract matches the stored one', async () => { @@ -68,10 +65,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { assert.equals(chainId, await web3.eth.net.getId()) assert.equals(verifyingContract, stEthPermit.address) - assert.equals( - makeDomainSeparator(name, version, chainId, verifyingContract), - domainSeparator - ) + assert.equals(makeDomainSeparator(name, version, chainId, verifyingContract), domainSeparator) }) it('grants allowance when a valid permit is given', async () => { @@ -88,32 +82,22 @@ contract('StETHPermit', ([deployer, ...accounts]) => { // check that the next nonce expected is zero assert.equals(await stEthPermit.nonces(owner), bn(0)) // check domain separator - assert.equals( - await stEthPermit.DOMAIN_SEPARATOR(), - domainSeparator - ) + assert.equals(await stEthPermit.DOMAIN_SEPARATOR(), domainSeparator) // a third-party, Charlie (not Alice) submits the permit - const receipt = await stEthPermit.permit( - owner, spender, value, deadline, v, r, s, { from: charlie } - ) + const receipt = await stEthPermit.permit(owner, spender, value, deadline, v, r, s, { from: charlie }) // check that allowance is updated assert.equals(await stEthPermit.allowance(owner, spender), bn(value)) - assert.emits( - receipt, - 'Approval', - { owner: owner, spender: spender, value: bn(value) } - ) + assert.emits(receipt, 'Approval', { owner, spender, value: bn(value) }) assert.equals(await stEthPermit.nonces(owner), bn(1)) // increment nonce nonce = 1 value = 4e5 - - ; ({ v, r, s } = signPermit(owner, spender, value, nonce, deadline, domainSeparator, alice.key)) + ;({ v, r, s } = signPermit(owner, spender, value, nonce, deadline, domainSeparator, alice.key)) // submit the permit const receipt2 = await stEthPermit.permit(owner, spender, value, deadline, v, r, s, { from: charlie }) @@ -121,11 +105,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { // check that allowance is updated assert.equals(await stEthPermit.allowance(owner, spender), bn(value)) - assert.emits( - receipt2, - 'Approval', - { owner: owner, spender: spender, value: bn(value) } - ) + assert.emits(receipt2, 'Approval', { owner, spender, value: bn(value) }) assert.equals(await stEthPermit.nonces(owner), bn(2)) }) @@ -176,7 +156,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { // wrong person await assert.reverts( stEthPermit.permit(owner, spender, value, deadline, v, r, s, { - from: charlie + from: charlie, }), 'ERC20Permit: invalid signature' ) @@ -188,7 +168,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { // even Bob himself can't call permit with the invalid sig await assert.reverts( stEthPermit.permit(owner, spender, value, deadline, v, r, s, { - from: bob.address + from: bob.address, }), 'ERC20Permit: invalid signature' ) @@ -203,7 +183,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { // try to submit the permit that is expired await assert.reverts( stEthPermit.permit(owner, spender, value, deadline, v, r, s, { - from: charlie + from: charlie, }), 'ERC20Permit: expired deadline' ) @@ -215,11 +195,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { const receipt = await stEthPermit.permit(owner, spender, value, deadline1min, v, r, s, { from: charlie }) assert.equals(await stEthPermit.nonces(owner), bn(1)) - assert.emits( - receipt, - 'Approval', - { owner: owner, spender: spender, value: bn(value) } - ) + assert.emits(receipt, 'Approval', { owner, spender, value: bn(value) }) } }) @@ -234,7 +210,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { // try to submit the permit await assert.reverts( stEthPermit.permit(owner, spender, value, deadline, v, r, s, { - from: charlie + from: charlie, }), 'ERC20Permit: invalid signature' ) @@ -251,7 +227,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { // try to submit the permit again await assert.reverts( stEthPermit.permit(owner, spender, value, deadline, v, r, s, { - from: charlie + from: charlie, }), 'ERC20Permit: invalid signature' ) @@ -263,7 +239,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { // try to submit the permit again from Alice herself await assert.reverts( stEthPermit.permit(owner, spender, value, deadline, v, r, s, { - from: alice.address + from: alice.address, }), 'ERC20Permit: invalid signature' ) @@ -298,7 +274,7 @@ contract('StETHPermit', ([deployer, ...accounts]) => { // try to submit the permit with invalid approval parameters await assert.reverts( stEthPermit.permit(owner, spender, value, deadline, v, r, s, { - from: charlie + from: charlie, }), 'APPROVE_TO_ZERO_ADDRESS' ) @@ -309,12 +285,21 @@ contract('StETHPermit', ([deployer, ...accounts]) => { // create a signed permit for a transfer const validAfter = 0 const nonce = hexStringFromBuffer(crypto.randomBytes(32)) - const { v, r, s } = signTransferAuthorization(from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key) + const { v, r, s } = signTransferAuthorization( + from, + to, + value, + validAfter, + validBefore, + nonce, + domainSeparator, + alice.key + ) // try to submit the transfer permit await assert.reverts( stEthPermit.permit(from, to, value, validBefore, v, r, s, { - from: charlie + from: charlie, }), 'ERC20Permit: invalid signature' ) diff --git a/test/0.6.12/helpers/ERC20.behavior.js b/test/0.6.12/helpers/ERC20.behavior.js index 67a43aaaf..d8fa8ca05 100644 --- a/test/0.6.12/helpers/ERC20.behavior.js +++ b/test/0.6.12/helpers/ERC20.behavior.js @@ -65,8 +65,8 @@ function shouldBehaveLikeERC20(errorPrefix, initialSupply, initialHolder, recipi expectEvent.inLogs(logs, 'Transfer', { from: tokenOwner, - to: to, - value: amount + to, + value: amount, }) }) @@ -75,8 +75,8 @@ function shouldBehaveLikeERC20(errorPrefix, initialSupply, initialHolder, recipi expectEvent.inLogs(logs, 'Approval', { owner: tokenOwner, - spender: spender, - value: await this.token.allowance(tokenOwner, spender) + spender, + value: await this.token.allowance(tokenOwner, spender), }) }) }) @@ -154,9 +154,15 @@ function shouldBehaveLikeERC20(errorPrefix, initialSupply, initialHolder, recipi }) describe('approve', function () { - shouldBehaveLikeERC20Approve(errorPrefix, initialHolder, recipient, initialSupply, function (owner, spender, amount) { - return this.token.approve(spender, amount, { from: owner }) - }) + shouldBehaveLikeERC20Approve( + errorPrefix, + initialHolder, + recipient, + initialSupply, + function (owner, spender, amount) { + return this.token.approve(spender, amount, { from: owner }) + } + ) }) } @@ -187,7 +193,7 @@ function shouldBehaveLikeERC20Transfer(errorPrefix, from, to, balance, transfer) expectEvent.inLogs(logs, 'Transfer', { from, to, - value: amount + value: amount, }) }) }) @@ -209,7 +215,7 @@ function shouldBehaveLikeERC20Transfer(errorPrefix, from, to, balance, transfer) expectEvent.inLogs(logs, 'Transfer', { from, to, - value: amount + value: amount, }) }) }) @@ -217,7 +223,10 @@ function shouldBehaveLikeERC20Transfer(errorPrefix, from, to, balance, transfer) describe('when the recipient is the zero address', function () { it('reverts', async function () { - await expectRevert(transfer.call(this, from, ZERO_ADDRESS, balance), `${errorPrefix}: transfer to the zero address`) + await expectRevert( + transfer.call(this, from, ZERO_ADDRESS, balance), + `${errorPrefix}: transfer to the zero address` + ) }) }) } @@ -231,9 +240,9 @@ function shouldBehaveLikeERC20Approve(errorPrefix, owner, spender, supply, appro const { logs } = await approve.call(this, owner, spender, amount) expectEvent.inLogs(logs, 'Approval', { - owner: owner, - spender: spender, - value: amount + owner, + spender, + value: amount, }) }) @@ -265,9 +274,9 @@ function shouldBehaveLikeERC20Approve(errorPrefix, owner, spender, supply, appro const { logs } = await approve.call(this, owner, spender, amount) expectEvent.inLogs(logs, 'Approval', { - owner: owner, - spender: spender, - value: amount + owner, + spender, + value: amount, }) }) @@ -303,5 +312,5 @@ function shouldBehaveLikeERC20Approve(errorPrefix, owner, spender, supply, appro module.exports = { shouldBehaveLikeERC20, shouldBehaveLikeERC20Transfer, - shouldBehaveLikeERC20Approve + shouldBehaveLikeERC20Approve, } diff --git a/test/0.6.12/helpers/constants.js b/test/0.6.12/helpers/constants.js index e1baae660..2ab497f21 100644 --- a/test/0.6.12/helpers/constants.js +++ b/test/0.6.12/helpers/constants.js @@ -7,69 +7,69 @@ const MAX_UINT256 = '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffff const ACCOUNTS_AND_KEYS = [ { address: '0x8e81C8f0CFf3d6eA2Fe72c1A5ee49Fc377401c2D', - key: '84132dd41f32804774a98647c308c0c94a54c0f3931128c0210b6f3689d2b7e7' + key: '84132dd41f32804774a98647c308c0c94a54c0f3931128c0210b6f3689d2b7e7', }, { address: '0x244A0A1d21f21167c17e04EBc5FA33c885990674', - key: '31a372c197c7c5d6856bfac311a66f179bdc3bda20e78030b0fef90e40cbc83f' + key: '31a372c197c7c5d6856bfac311a66f179bdc3bda20e78030b0fef90e40cbc83f', }, { address: '0x6966f881B3Ee9074b0783CC614e3864e380B8b27', - key: '58bdc54eb2aa3a92e5a36fae01d23b7626fa89116a41e01ca3c6cb18799aee3d' + key: '58bdc54eb2aa3a92e5a36fae01d23b7626fa89116a41e01ca3c6cb18799aee3d', }, { address: '0xaC5faE80468DcC49D404d0625609C031B9AF2cb7', - key: 'd14ca7a30bc2921ddb89ea2f6c52393f91e794cd9c3c994f547eb7edeb092fd1' + key: 'd14ca7a30bc2921ddb89ea2f6c52393f91e794cd9c3c994f547eb7edeb092fd1', }, { address: '0x18C246058e9e4Ae1737387fA90cD69E39f78F73A', - key: '1c09baae4343b0a66567d56769b62537623389542480f30e9acdae0624612872' + key: '1c09baae4343b0a66567d56769b62537623389542480f30e9acdae0624612872', }, { address: '0xc4dc5dAD36fF9b8cB694E79238ECbe76ab13BcEc', - key: '2048571627de761088f2f369306f9c231e6c7ab94be1f0a0c979776a2f424328' + key: '2048571627de761088f2f369306f9c231e6c7ab94be1f0a0c979776a2f424328', }, { address: '0x75Bf6E76D3dB629f46da549D49C9ea821CE8e9A9', - key: '9a9afb6a8e2384e4cce14824d15162bba2eed7e31df846ff77d697fed8cba0c1' + key: '9a9afb6a8e2384e4cce14824d15162bba2eed7e31df846ff77d697fed8cba0c1', }, { address: '0x55937b3ae7a34F551e5aFa5BA51Fba4eD9f8FeD7', - key: '9747a0294186b8fef20ec1e4341a10c87840b18a8930b84c4c5dcd97799ba0bc' + key: '9747a0294186b8fef20ec1e4341a10c87840b18a8930b84c4c5dcd97799ba0bc', }, { address: '0x1eEEBc3900803a28ca6E68Eb98FDeCf98350D97B', - key: 'cdbaf218f6332bfa630ec2abc7a8bc450b2e8746133d84450dfc2234fdfb83ef' + key: 'cdbaf218f6332bfa630ec2abc7a8bc450b2e8746133d84450dfc2234fdfb83ef', }, { address: '0x8719beDE472E67642b88DbA9aD1b1b9dc05CC60e', - key: 'c08dbf2c9aaf5dc3cd5ce5349e754de086202a5f352a512851a4f174ac246198' + key: 'c08dbf2c9aaf5dc3cd5ce5349e754de086202a5f352a512851a4f174ac246198', }, { address: '0xE03701ea2248C7ca2Fed1e655ff3C803C7267302', - key: '40566af8625c93f95c5e1ea9aa42642bcbdd64fe4fe7926283d04173cb842189' + key: '40566af8625c93f95c5e1ea9aa42642bcbdd64fe4fe7926283d04173cb842189', }, { address: '0x10506aB975D36aa781B77C1Ce204F46e8f87dA57', - key: '55ef7a25bba3449344d8a1e525ba3ca4999bdc763be4efaf9e94a4de396f8370' + key: '55ef7a25bba3449344d8a1e525ba3ca4999bdc763be4efaf9e94a4de396f8370', }, { address: '0xee11cdb1f9eEe2eB40D2CF99b4fa7D782aE582A6', - key: '985117805090656613ae19743879efe4cff76049de03516debf41926313e3629' + key: '985117805090656613ae19743879efe4cff76049de03516debf41926313e3629', }, { address: '0xB9203C29E242d7a19AE6970cDf0d873048B99419', - key: '3a37d1ad3751e697c26dd05a71cd9263c023f3e8a1d1067215044032c62ee916' + key: '3a37d1ad3751e697c26dd05a71cd9263c023f3e8a1d1067215044032c62ee916', }, { address: '0xcC03603436Bc0Edd1e0661379f3Aa289ae967597', - key: 'db81ac68891890ec33021264ce81f9b5f9296a9fd95cdc785655db3066db2c08' - } + key: 'db81ac68891890ec33021264ce81f9b5f9296a9fd95cdc785655db3066db2c08', + }, ] module.exports = { ZERO_ADDRESS, ZERO_BYTES32, MAX_UINT256, - ACCOUNTS_AND_KEYS + ACCOUNTS_AND_KEYS, } diff --git a/test/0.6.12/helpers/index.js b/test/0.6.12/helpers/index.js index 2e9634c26..39f2c5dba 100644 --- a/test/0.6.12/helpers/index.js +++ b/test/0.6.12/helpers/index.js @@ -16,11 +16,12 @@ async function expectRevert(promise, reason) { const errMsg = err.hijackedMessage || err.message assert.match(errMsg, /revert/i) - if (!reason) { - } else if (reason instanceof RegExp) { - assert.match(errMsg, reason) - } else { - assert.include(errMsg, reason) + if (reason) { + if (reason instanceof RegExp) { + assert.match(errMsg, reason) + } else { + assert.include(errMsg, reason) + } } } @@ -47,5 +48,5 @@ module.exports = { hexStringFromBuffer, strip0x, ecSign, - bufferFromHexString + bufferFromHexString, } diff --git a/test/0.6.12/helpers/permit_helpers.js b/test/0.6.12/helpers/permit_helpers.js index b9d03a718..098c6cff2 100644 --- a/test/0.6.12/helpers/permit_helpers.js +++ b/test/0.6.12/helpers/permit_helpers.js @@ -4,7 +4,9 @@ const transferWithAuthorizationTypeHash = web3.utils.keccak256( 'TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)' ) -const permitTypeHash = web3.utils.keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)') +const permitTypeHash = web3.utils.keccak256( + 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' +) function signTransferAuthorization(from, to, value, validAfter, validBefore, nonce, domainSeparator, privateKey) { return signEIP712( @@ -45,7 +47,7 @@ function makeDomainSeparator(name, version, chainId, verifyingContract) { web3.utils.keccak256(name), web3.utils.keccak256(version), chainId, - verifyingContract + verifyingContract, ] ) ) @@ -55,5 +57,5 @@ module.exports = { signPermit, permitTypeHash, signTransferAuthorization, - makeDomainSeparator + makeDomainSeparator, } diff --git a/test/0.6.12/wsteth.permit.test.js b/test/0.6.12/wsteth.permit.test.js index e81075108..4ae960131 100644 --- a/test/0.6.12/wsteth.permit.test.js +++ b/test/0.6.12/wsteth.permit.test.js @@ -1,7 +1,12 @@ const crypto = require('crypto') const { ACCOUNTS_AND_KEYS, MAX_UINT256, ZERO_ADDRESS } = require('./helpers/constants') const { expectRevert, hexStringFromBuffer } = require('./helpers') -const { signPermit, signTransferAuthorization, permitTypeHash, makeDomainSeparator } = require('./helpers/permit_helpers') +const { + signPermit, + signTransferAuthorization, + permitTypeHash, + makeDomainSeparator, +} = require('./helpers/permit_helpers') const WstETH = artifacts.require('WstETHMock') const StETH = artifacts.require('StETHMockERC20') @@ -29,12 +34,12 @@ contract('WstETH.permit', function ([deployer, ...accounts]) { spender: bob.address, value: 7e6, nonce: 0, - deadline: MAX_UINT256 + deadline: MAX_UINT256, } beforeEach(async () => { await wsteth.mint(permitParams.owner, initialBalance, { - from: deployer + from: deployer, }) }) @@ -118,7 +123,7 @@ contract('WstETH.permit', function ([deployer, ...accounts]) { // wrong person await expectRevert( wsteth.permit(owner, spender, value, deadline, v, r, s, { - from: charlie + from: charlie, }), 'ERC20Permit: invalid signature' ) @@ -134,7 +139,7 @@ contract('WstETH.permit', function ([deployer, ...accounts]) { // try to submit the permit that is expired await expectRevert( wsteth.permit(owner, spender, value, deadline, v, r, s, { - from: charlie + from: charlie, }), 'ERC20Permit: expired deadline' ) @@ -151,7 +156,7 @@ contract('WstETH.permit', function ([deployer, ...accounts]) { // try to submit the permit await expectRevert( wsteth.permit(owner, spender, value, deadline, v, r, s, { - from: charlie + from: charlie, }), 'ERC20Permit: invalid signature' ) @@ -168,7 +173,7 @@ contract('WstETH.permit', function ([deployer, ...accounts]) { // try to submit the permit again await expectRevert( wsteth.permit(owner, spender, value, deadline, v, r, s, { - from: charlie + from: charlie, }), 'ERC20Permit: invalid signature' ) @@ -203,7 +208,7 @@ contract('WstETH.permit', function ([deployer, ...accounts]) { // try to submit the permit with invalid approval parameters await expectRevert( wsteth.permit(owner, spender, value, deadline, v, r, s, { - from: charlie + from: charlie, }), 'approve to the zero address' ) @@ -214,12 +219,21 @@ contract('WstETH.permit', function ([deployer, ...accounts]) { // create a signed permit for a transfer const validAfter = 0 const nonce = hexStringFromBuffer(crypto.randomBytes(32)) - const { v, r, s } = signTransferAuthorization(from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key) + const { v, r, s } = signTransferAuthorization( + from, + to, + value, + validAfter, + validBefore, + nonce, + domainSeparator, + alice.key + ) // try to submit the transfer permit await expectRevert( wsteth.permit(from, to, value, validBefore, v, r, s, { - from: charlie + from: charlie, }), 'ERC20Permit: invalid signature' ) diff --git a/test/0.6.12/wsteth.test.js b/test/0.6.12/wsteth.test.js index 94afc5764..06f75eaf0 100644 --- a/test/0.6.12/wsteth.test.js +++ b/test/0.6.12/wsteth.test.js @@ -65,7 +65,10 @@ contract('WstETH', function ([deployer, initialHolder, recipient, anotherAccount await this.wsteth.wrap(50, { from: user1 }) - expect(await this.wsteth.balanceOf(user1)).to.be.bignumber.equal(shouldMintWstETHAmount, 'returns correct amount of wstETH') + expect(await this.wsteth.balanceOf(user1)).to.be.bignumber.equal( + shouldMintWstETHAmount, + 'returns correct amount of wstETH' + ) await this.wsteth.approve(any_contract, 25, { from: user1 }) expect(await this.wsteth.allowance(user1, any_contract)).to.be.bignumber.equal('25') @@ -105,7 +108,9 @@ contract('WstETH', function ([deployer, initialHolder, recipient, anotherAccount const shouldGetStETHAmount = await this.wsteth.unwrap.call(50, { from: user1 }) await this.wsteth.unwrap(50, { from: user1 }) - expect(await this.steth.balanceOf(user1)).to.be.bignumber.equal(user1StETHBalanceBefore.add(shouldGetStETHAmount)) + expect(await this.steth.balanceOf(user1)).to.be.bignumber.equal( + user1StETHBalanceBefore.add(shouldGetStETHAmount) + ) expect(await this.steth.balanceOf(this.wsteth.address)).to.be.bignumber.equal('0') expect(await this.wsteth.balanceOf(user1)).to.be.bignumber.equal('0') }) @@ -283,8 +288,14 @@ contract('WstETH', function ([deployer, initialHolder, recipient, anotherAccount const recipientBalanceAfter = await this.wsteth.balanceOf(recipient) const wstETHBalanceAfter = await this.steth.balanceOf(this.wsteth.address) - expect(wstETHBalanceAfter.sub(wstETHBalanceBefore)).to.be.bignumber.equal(value, 'wstETH has got some stETH on balance') - expect(recipientBalanceAfter.sub(recipientBalanceBefore)).to.be.bignumber.equal(value, 'recepient has got wrapped stETH') + expect(wstETHBalanceAfter.sub(wstETHBalanceBefore)).to.be.bignumber.equal( + value, + 'wstETH has got some stETH on balance' + ) + expect(recipientBalanceAfter.sub(recipientBalanceBefore)).to.be.bignumber.equal( + value, + 'recepient has got wrapped stETH' + ) }) it(`can unwrap stETH received with direct transfer`, async function () { @@ -300,7 +311,10 @@ contract('WstETH', function ([deployer, initialHolder, recipient, anotherAccount await this.wsteth.unwrap(recepientWstETHBalance, { from: recipient }) expect(await this.wsteth.balanceOf(recipient)).to.be.bignumber.equal('0', 'funds unwrapped') - expect(await this.steth.balanceOf(recipient)).to.be.bignumber.equal(recepientStETHToUnwrap, 'received corrrect amount') + expect(await this.steth.balanceOf(recipient)).to.be.bignumber.equal( + recepientStETHToUnwrap, + 'received corrrect amount' + ) }) }) @@ -371,8 +385,8 @@ contract('WstETH', function ([deployer, initialHolder, recipient, anotherAccount expectEvent.inLogs(logs, 'Approval', { owner: initialHolder, - spender: spender, - value: new BN(0) + spender, + value: new BN(0), }) }) @@ -434,8 +448,8 @@ contract('WstETH', function ([deployer, initialHolder, recipient, anotherAccount expectEvent.inLogs(logs, 'Approval', { owner: initialHolder, - spender: spender, - value: amount + spender, + value: amount, }) }) @@ -468,8 +482,8 @@ contract('WstETH', function ([deployer, initialHolder, recipient, anotherAccount expectEvent.inLogs(logs, 'Approval', { owner: initialHolder, - spender: spender, - value: amount + spender, + value: amount, }) }) @@ -499,7 +513,10 @@ contract('WstETH', function ([deployer, initialHolder, recipient, anotherAccount const spender = ZERO_ADDRESS it(`reverts`, async function () { - await expectRevert(this.token.increaseAllowance(spender, amount, { from: initialHolder }), 'ERC20: approve to the zero address') + await expectRevert( + this.token.increaseAllowance(spender, amount, { from: initialHolder }), + 'ERC20: approve to the zero address' + ) }) }) }) @@ -528,7 +545,7 @@ contract('WstETH', function ([deployer, initialHolder, recipient, anotherAccount it(`emits Transfer event`, async function () { const event = expectEvent.inLogs(this.logs, 'Transfer', { from: ZERO_ADDRESS, - to: recipient + to: recipient, }) expect(event.args.value).to.be.bignumber.equal(amount) diff --git a/test/0.8.9/burner.test.js b/test/0.8.9/burner.test.js index 14da006d8..e6038825c 100644 --- a/test/0.8.9/burner.test.js +++ b/test/0.8.9/burner.test.js @@ -61,16 +61,12 @@ contract('Burner', ([deployer, _, anotherAccount]) => { }) it(`init with already burnt counters works`, async () => { - let newBurner = await Burner.new( - voting, treasury, lido.address, bn(0), bn(0), { from: deployer } - ) + let newBurner = await Burner.new(voting, treasury, lido.address, bn(0), bn(0), { from: deployer }) assert.equals(await newBurner.getCoverSharesBurnt(), bn(0)) assert.equals(await newBurner.getNonCoverSharesBurnt(), bn(0)) - newBurner = await Burner.new( - voting, treasury, lido.address, bn(123), bn(456), { from: deployer } - ) + newBurner = await Burner.new(voting, treasury, lido.address, bn(123), bn(456), { from: deployer }) assert.equals(await newBurner.getCoverSharesBurnt(), bn(123)) assert.equals(await newBurner.getNonCoverSharesBurnt(), bn(456)) @@ -104,10 +100,7 @@ contract('Burner', ([deployer, _, anotherAccount]) => { ) // and zero request on non-cover - await assert.revertsWithCustomError( - burner.requestBurnMyStETH(StETH(0), { from: voting }), - `ZeroBurnAmount()` - ) + await assert.revertsWithCustomError(burner.requestBurnMyStETH(StETH(0), { from: voting }), `ZeroBurnAmount()`) }) it(`reverts on burn request without assigned role`, async () => { @@ -159,7 +152,7 @@ contract('Burner', ([deployer, _, anotherAccount]) => { isCover: true, requestedBy: voting, amountOfStETH: StETH(8), - amountOfShares: sharesAmount8StETH + amountOfShares: sharesAmount8StETH, }) // check stETH balances @@ -174,7 +167,7 @@ contract('Burner', ([deployer, _, anotherAccount]) => { isCover: false, requestedBy: voting, amountOfStETH: StETH(12), - amountOfShares: sharesAmount12 + amountOfShares: sharesAmount12, }) // check stETH balances again, we didn't execute the actual burn @@ -189,10 +182,7 @@ contract('Burner', ([deployer, _, anotherAccount]) => { assert.equals(await lido.balanceOf(burner.address), StETH(9.7)) - await assert.revertsWithCustomError( - burner.commitSharesToBurn(ETH(10)), - `AppAuthLidoFailed()` - ) + await assert.revertsWithCustomError(burner.commitSharesToBurn(ETH(10)), `AppAuthLidoFailed()`) // mimic the Lido for the callback invocation const receipt = await burner.commitSharesToBurn(ETH(10), { from: lido.address }) @@ -256,7 +246,7 @@ contract('Burner', ([deployer, _, anotherAccount]) => { isCover: true, requestedBy: voting, amountOfStETH: StETH(1.5), - amountOfShares: sharesAmount1_5StETH + amountOfShares: sharesAmount1_5StETH, }) const receiptNonCover = await burner.requestBurnMyStETH(StETH(0.5), { from: voting }) @@ -265,7 +255,7 @@ contract('Burner', ([deployer, _, anotherAccount]) => { isCover: false, requestedBy: voting, amountOfStETH: StETH(0.5), - amountOfShares: sharesAmount0_5StETH + amountOfShares: sharesAmount0_5StETH, }) const burnerShares = await lido.sharesOf(burner.address) @@ -273,10 +263,7 @@ contract('Burner', ([deployer, _, anotherAccount]) => { assert.equals(await lido.balanceOf(burner.address), StETH(7.2)) - await assert.revertsWithCustomError( - burner.commitSharesToBurn(bn(500), { from: deployer }), - `AppAuthLidoFailed()` - ) + await assert.revertsWithCustomError(burner.commitSharesToBurn(bn(500), { from: deployer }), `AppAuthLidoFailed()`) await assert.revertsWithCustomError( // even @@ -287,11 +274,15 @@ contract('Burner', ([deployer, _, anotherAccount]) => { const receipt = await burner.commitSharesToBurn(ETH(3), { from: lido.address }) assert.emits(receipt, `StETHBurnt`, { - isCover: true, amountOfStETH: StETH(1.5), amountOfShares: sharesAmount1_5StETH + isCover: true, + amountOfStETH: StETH(1.5), + amountOfShares: sharesAmount1_5StETH, }) assert.emits(receipt, `StETHBurnt`, 1, { - isCover: false, amountOfStETH: StETH(0.5), amountOfShares: sharesAmount0_5StETH + isCover: false, + amountOfStETH: StETH(0.5), + amountOfShares: sharesAmount0_5StETH, }) // cover + non-cover events @@ -379,16 +370,16 @@ contract('Burner', ([deployer, _, anotherAccount]) => { assert.equals(await lido.sharesOf(burner.address), stETHShares(0.9)) const receipt = await burner.commitSharesToBurn(StETH(100), { from: lido.address }) - assert.emits( - receipt, `StETHBurnt`, { - isCover: true, amountOfStETH: StETH(0.9), amountOfShares: stETHShares(0.9) + assert.emits(receipt, `StETHBurnt`, { + isCover: true, + amountOfStETH: StETH(0.9), + amountOfShares: stETHShares(0.9), }) assert.emitsNumberOfEvents(receipt, `StETHBurnt`, 1) await lido.burnShares(burner.address, stETHShares(0.9)) assert.equals(await lido.sharesOf(burner.address), stETHShares(0)) - await burner.requestBurnMyStETHForCover(await lido.getPooledEthByShares(stETHShares(0.1)), { from: voting }) assert.equals(bnRound10(await lido.sharesOf(burner.address)), bnRound10(stETHShares(0.1))) await burner.commitSharesToBurn(ETH(1), { from: lido.address }) @@ -409,9 +400,10 @@ contract('Burner', ([deployer, _, anotherAccount]) => { const afterCoverSharesBurnt = await burner.getCoverSharesBurnt() const burnt = bn(afterCoverSharesBurnt).sub(beforeCoverSharesBurnt) - assert.emits( - receiptN, `StETHBurnt`, { - isCover: true, amountOfStETH: await lido.getPooledEthByShares(burnt), amountOfShares: burnt + assert.emits(receiptN, `StETHBurnt`, { + isCover: true, + amountOfStETH: await lido.getPooledEthByShares(burnt), + amountOfShares: burnt, }) await lido.burnShares(burner.address, burnt) @@ -425,7 +417,6 @@ contract('Burner', ([deployer, _, anotherAccount]) => { }) it(`limit burn shares per run works (noncover)`, async () => { - assert.equals(await lido.getTotalShares(), stETHShares(75)) // so the max amount to burn per single run is 75*10^18 * 0.012 = 0.9*10^18 @@ -435,15 +426,15 @@ contract('Burner', ([deployer, _, anotherAccount]) => { assert.equals(await lido.sharesOf(burner.address), stETHShares(0.9)) const receipt = await burner.commitSharesToBurn(ETH(0.9), { from: lido.address }) - assert.emits( - receipt, `StETHBurnt`, { - isCover: false, amountOfStETH: StETH(0.9), amountOfShares: stETHShares(0.9) + assert.emits(receipt, `StETHBurnt`, { + isCover: false, + amountOfStETH: StETH(0.9), + amountOfShares: stETHShares(0.9), }) assert.emitsNumberOfEvents(receipt, `StETHBurnt`, 1) await lido.burnShares(burner.address, stETHShares(0.9)) assert.equals(await lido.sharesOf(burner.address), stETHShares(0)) - await burner.requestBurnMyStETH(await lido.getPooledEthByShares(stETHShares(0.1)), { from: voting }) assert.equals(bnRound10(await lido.sharesOf(burner.address)), bnRound10(stETHShares(0.1))) @@ -466,8 +457,16 @@ contract('Burner', ([deployer, _, anotherAccount]) => { assert.equals(await lido.sharesOf(burner.address), stETHShares(0.9)) const receipt = await burner.commitSharesToBurn(ETH(0.5), { from: lido.address }) - assert.emits(receipt, `StETHBurnt`, { isCover: true, amountOfStETH: StETH(0.1), amountOfShares: stETHShares(0.1) }) - assert.emits(receipt, `StETHBurnt`, { isCover: false, amountOfStETH: StETH(0.4), amountOfShares: stETHShares(0.4) }) + assert.emits(receipt, `StETHBurnt`, { + isCover: true, + amountOfStETH: StETH(0.1), + amountOfShares: stETHShares(0.1), + }) + assert.emits(receipt, `StETHBurnt`, { + isCover: false, + amountOfStETH: StETH(0.4), + amountOfShares: stETHShares(0.4), + }) assert.emitsNumberOfEvents(receipt, `StETHBurnt`, 2) assert.equals(await burner.getCoverSharesBurnt(), stETHShares(0.1)) @@ -475,7 +474,11 @@ contract('Burner', ([deployer, _, anotherAccount]) => { const receipt2 = await burner.commitSharesToBurn(ETH(0.5), { from: lido.address }) - assert.emits(receipt2, `StETHBurnt`, { isCover: false, amountOfStETH: StETH(0.4), amountOfShares: stETHShares(0.4) }) + assert.emits(receipt2, `StETHBurnt`, { + isCover: false, + amountOfStETH: StETH(0.4), + amountOfShares: stETHShares(0.4), + }) assert.emitsNumberOfEvents(receipt2, `StETHBurnt`, 1) assert.equals(await burner.getCoverSharesBurnt(), stETHShares(0.1)) @@ -494,8 +497,16 @@ contract('Burner', ([deployer, _, anotherAccount]) => { assert.equals(await lido.sharesOf(burner.address), stETHShares(0.9)) const receipt = await burner.commitSharesToBurn(ETH(0.5), { from: lido.address }) - assert.emits(receipt, `StETHBurnt`, { isCover: true, amountOfStETH: StETH(0.1), amountOfShares: stETHShares(0.1) }) - assert.emits(receipt, `StETHBurnt`, { isCover: false, amountOfStETH: StETH(0.4), amountOfShares: stETHShares(0.4) }) + assert.emits(receipt, `StETHBurnt`, { + isCover: true, + amountOfStETH: StETH(0.1), + amountOfShares: stETHShares(0.1), + }) + assert.emits(receipt, `StETHBurnt`, { + isCover: false, + amountOfStETH: StETH(0.4), + amountOfShares: stETHShares(0.4), + }) assert.emitsNumberOfEvents(receipt, `StETHBurnt`, 2) assert.equals(await burner.getCoverSharesBurnt(), stETHShares(0.1)) @@ -503,7 +514,11 @@ contract('Burner', ([deployer, _, anotherAccount]) => { const receipt2 = await burner.commitSharesToBurn(ETH(0.5), { from: lido.address }) - assert.emits(receipt2, `StETHBurnt`, { isCover: false, amountOfStETH: StETH(0.4), amountOfShares: stETHShares(0.4) }) + assert.emits(receipt2, `StETHBurnt`, { + isCover: false, + amountOfStETH: StETH(0.4), + amountOfShares: stETHShares(0.4), + }) assert.emitsNumberOfEvents(receipt2, `StETHBurnt`, 1) assert.equals(await burner.getCoverSharesBurnt(), stETHShares(0.1)) @@ -553,11 +568,11 @@ contract('Burner', ([deployer, _, anotherAccount]) => { const sharesAmount2_3StETH = await lido.sharesOf(burner.address) const receipt = await burner.recoverExcessStETH({ from: voting }) - assert.emits( - receipt, - `ExcessStETHRecovered`, - { requestedBy: voting, amountOfStETH: StETH(2.3), amountOfShares: sharesAmount2_3StETH } - ) + assert.emits(receipt, `ExcessStETHRecovered`, { + requestedBy: voting, + amountOfStETH: StETH(2.3), + amountOfShares: sharesAmount2_3StETH, + }) // check burner and treasury balances after recovery assert.equals(await lido.balanceOf(burner.address), StETH(0)) @@ -600,11 +615,11 @@ contract('Burner', ([deployer, _, anotherAccount]) => { // should be transferred to the treasury const sharesAmount5stETH = await lido.getSharesByPooledEth(StETH(5)) const receipt = await burner.recoverExcessStETH({ from: voting }) - assert.emits( - receipt, - `ExcessStETHRecovered`, - { requestedBy: voting, amountOfStETH: StETH(5), amountOfShares: sharesAmount5stETH } - ) + assert.emits(receipt, `ExcessStETHRecovered`, { + requestedBy: voting, + amountOfStETH: StETH(5), + amountOfShares: sharesAmount5stETH, + }) assert.equals(await burner.getExcessStETH(), StETH(0)) @@ -646,14 +661,13 @@ contract('Burner', ([deployer, _, anotherAccount]) => { it(`can't recover zero ERC20 amount`, async () => { await assert.revertsWithCustomError( - burner.recoverERC20(mockERC20Token.address, bn(0), { from: voting }), `ZeroRecoveryAmount()` + burner.recoverERC20(mockERC20Token.address, bn(0), { from: voting }), + `ZeroRecoveryAmount()` ) }) it(`can't recover zero-address ERC20`, async () => { - await assert.reverts( - burner.recoverERC20(ZERO_ADDRESS, bn(10), { from: voting }) - ) + await assert.reverts(burner.recoverERC20(ZERO_ADDRESS, bn(10), { from: voting })) }) it(`can't recover stETH by recoverERC20`, async () => { @@ -696,7 +710,11 @@ contract('Burner', ([deployer, _, anotherAccount]) => { // recover ERC20 const firstReceipt = await burner.recoverERC20(mockERC20Token.address, bn(100000), { from: voting }) - assert.emits(firstReceipt, `ERC20Recovered`, { requestedBy: voting, token: mockERC20Token.address, amount: bn(100000) }) + assert.emits(firstReceipt, `ERC20Recovered`, { + requestedBy: voting, + token: mockERC20Token.address, + amount: bn(100000), + }) // check balances again assert.equals(await mockERC20Token.balanceOf(burner.address), bn(500000)) @@ -712,7 +730,11 @@ contract('Burner', ([deployer, _, anotherAccount]) => { // recover last portion const lastReceipt = await burner.recoverERC20(mockERC20Token.address, bn(500000), { from: voting }) - assert.emits(lastReceipt, `ERC20Recovered`, { requestedBy: voting, token: mockERC20Token.address, amount: bn(500000) }) + assert.emits(lastReceipt, `ERC20Recovered`, { + requestedBy: voting, + token: mockERC20Token.address, + amount: bn(500000), + }) // balance is zero already, have to be reverted await assert.reverts( @@ -817,7 +839,8 @@ contract('Burner', ([deployer, _, anotherAccount]) => { // try to send 1 ETH, should be reverted with fallback defined reason await assert.revertsWithCustomError( - web3.eth.sendTransaction({ from: anotherAccount, to: burner_addr, value: ETH(1) }), `DirectETHTransfer()` + web3.eth.sendTransaction({ from: anotherAccount, to: burner_addr, value: ETH(1) }), + `DirectETHTransfer()` ) }) }) diff --git a/test/0.8.9/deposit-security-module.test.js b/test/0.8.9/deposit-security-module.test.js index 663227ca2..352d7cdd3 100644 --- a/test/0.8.9/deposit-security-module.test.js +++ b/test/0.8.9/deposit-security-module.test.js @@ -28,14 +28,14 @@ const GUARDIAN3 = '0xdaEAd0E0194abd565d28c1013399801d79627c14' const GUARDIAN_PRIVATE_KEYS = { [GUARDIAN1]: '0x3578665169e03e05a26bd5c565ffd12c81a1e0df7d0679f8aee4153110a83c8c', [GUARDIAN2]: '0x88868f0fb667cfe50261bb385be8987e0ce62faee934af33c3026cf65f25f09e', - [GUARDIAN3]: '0x75e6f508b637327debc90962cd38943ddb9cfc1fc4a8572fc5e3d0984e1261de' + [GUARDIAN3]: '0x75e6f508b637327debc90962cd38943ddb9cfc1fc4a8572fc5e3d0984e1261de', } const UNRELATED_SIGNER1 = '0xb1e2Dd268D97a41d95f96293b08CD9b08857DA37' const UNRELATED_SIGNER2 = '0xe53486BBaC0628C9A5B84eFEf28e08FE73679e4d' const UNRELATED_SIGNER_PRIVATE_KEYS = { [UNRELATED_SIGNER1]: '0x543488a7f9249f22c1045352a627382cd60692a1b2054e0a9889277f728d8514', - [UNRELATED_SIGNER2]: '0xbabec7d3867c72f6c275135b1e1423ca8f565d6e21a1947d056a195b1c3cae27' + [UNRELATED_SIGNER2]: '0xbabec7d3867c72f6c275135b1e1423ca8f565d6e21a1947d056a195b1c3cae27', } const assertNoEvent = (receipt, eventName, msg) => { @@ -47,7 +47,7 @@ const assertNoEvent = (receipt, eventName, msg) => { const StakingModuleStatus = { Active: 0, // deposits and rewards allowed DepositsPaused: 1, // deposits NOT allowed, rewards allowed - Stopped: 2 // deposits and rewards NOT allowed + Stopped: 2, // deposits and rewards NOT allowed } contract('DepositSecurityModule', ([owner, stranger, guardian]) => { @@ -127,7 +127,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { DEPOSIT_CALLDATA, [], { - from: stranger + from: stranger, } ), 'DepositNoQuorum()' @@ -158,8 +158,12 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { { from: stranger } ) assertEvent(tx.receipt, 'StakingModuleDeposited', { - expectedArgs: { maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, stakingModuleId: STAKING_MODULE, depositCalldata: DEPOSIT_CALLDATA }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi + expectedArgs: { + maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, + stakingModuleId: STAKING_MODULE, + depositCalldata: DEPOSIT_CALLDATA, + }, + decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, }) }) @@ -237,7 +241,10 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const latestBlock = await web3.eth.getBlock('latest') const lastDepositBlock = await stakingRouterMock.getStakingModuleLastDepositBlock(STAKING_MODULE) - assert(latestBlock.number - lastDepositBlock < MIN_DEPOSIT_BLOCK_DISTANCE, 'invariant failed: last deposit block') + assert( + latestBlock.number - lastDepositBlock < MIN_DEPOSIT_BLOCK_DISTANCE, + 'invariant failed: last deposit block' + ) await assertRevert( depositSecurityModule.depositBufferedEther( @@ -295,9 +302,15 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { it('cannot deposit with zero block hash', async () => { await waitBlocks(255) await assertRevert( - depositSecurityModule.depositBufferedEther(block.number, '0x', DEPOSIT_ROOT, STAKING_MODULE, DEPOSIT_NONCE, DEPOSIT_CALLDATA, [ - validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]) - ]), + depositSecurityModule.depositBufferedEther( + block.number, + '0x', + DEPOSIT_ROOT, + STAKING_MODULE, + DEPOSIT_NONCE, + DEPOSIT_CALLDATA, + [validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1])] + ), 'DepositUnexpectedBlockHash()' ) }) @@ -318,7 +331,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const signatures = [ validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]), validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN2]), - validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN3]) + validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN3]), ] const tx = await depositSecurityModule.depositBufferedEther( @@ -333,15 +346,19 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { ) assertEvent(tx.receipt, 'StakingModuleDeposited', { - expectedArgs: { maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, stakingModuleId: STAKING_MODULE, depositCalldata: DEPOSIT_CALLDATA }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi + expectedArgs: { + maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, + stakingModuleId: STAKING_MODULE, + depositCalldata: DEPOSIT_CALLDATA, + }, + decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, }) }) it("can deposit with guardian's sigs (0,1)", async () => { const signatures = [ validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]), - validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN2]) + validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN2]), ] const tx = await depositSecurityModule.depositBufferedEther( @@ -356,15 +373,19 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { ) assertEvent(tx.receipt, 'StakingModuleDeposited', { - expectedArgs: { maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, stakingModuleId: STAKING_MODULE, depositCalldata: DEPOSIT_CALLDATA }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi + expectedArgs: { + maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, + stakingModuleId: STAKING_MODULE, + depositCalldata: DEPOSIT_CALLDATA, + }, + decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, }) }) it("can deposit with guardian's sigs (0,2)", async () => { const signatures = [ validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]), - validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN3]) + validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN3]), ] const tx = await depositSecurityModule.depositBufferedEther( @@ -379,15 +400,19 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { ) assertEvent(tx.receipt, 'StakingModuleDeposited', { - expectedArgs: { maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, stakingModuleId: STAKING_MODULE, depositCalldata: DEPOSIT_CALLDATA }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi + expectedArgs: { + maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, + stakingModuleId: STAKING_MODULE, + depositCalldata: DEPOSIT_CALLDATA, + }, + decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, }) }) it("can deposit with guardian's sigs (1,2)", async () => { const signatures = [ validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN2]), - validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN3]) + validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN3]), ] const tx = await depositSecurityModule.depositBufferedEther( @@ -402,8 +427,12 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { ) assertEvent(tx.receipt, 'StakingModuleDeposited', { - expectedArgs: { maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, stakingModuleId: STAKING_MODULE, depositCalldata: DEPOSIT_CALLDATA }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi + expectedArgs: { + maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, + stakingModuleId: STAKING_MODULE, + depositCalldata: DEPOSIT_CALLDATA, + }, + decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, }) }) @@ -425,7 +454,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { it("cannot deposit with guardian's sigs (1,0)", async () => { const signatures = [ validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN2]), - validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]) + validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]), ] await assertRevert( @@ -447,7 +476,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const signatures = [ validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]), validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]), - validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN2]) + validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN2]), ] await assertRevert( depositSecurityModule.depositBufferedEther( @@ -468,7 +497,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const signatures = [ validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]), validAttestMessage.sign(UNRELATED_SIGNER_PRIVATE_KEYS[UNRELATED_SIGNER1]), - validAttestMessage.sign(UNRELATED_SIGNER_PRIVATE_KEYS[UNRELATED_SIGNER2]) + validAttestMessage.sign(UNRELATED_SIGNER_PRIVATE_KEYS[UNRELATED_SIGNER2]), ] await assertRevert( depositSecurityModule.depositBufferedEther( @@ -495,30 +524,38 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { await depositSecurityModule.addGuardian(GUARDIAN2, 1, { from: owner }) const guardians = await depositSecurityModule.getGuardians() assert.equal(guardians.length, 2, 'invariant failed: guardians != 2') - assert.equal(await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), false, 'invariant failed: isPaused') + assert.equal( + await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), + false, + 'invariant failed: isPaused' + ) }) it('if called by a guardian 1 or 2', async () => { - const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { from: guardian }) + const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { + from: guardian, + }) assertEvent(tx, 'StakingModuleStatusSet', { expectedArgs: { stakingModuleId: STAKING_MODULE, status: StakingModuleStatus.DepositsPaused, - setBy: depositSecurityModule + setBy: depositSecurityModule, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi + decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, }) }) it('pauses if called by an anon submitting sig of guardian 1 or 2', async () => { - const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { from: guardian }) + const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { + from: guardian, + }) assertEvent(tx, 'StakingModuleStatusSet', { expectedArgs: { stakingModuleId: STAKING_MODULE, status: StakingModuleStatus.DepositsPaused, - setBy: depositSecurityModule + setBy: depositSecurityModule, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi + decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, }) }) @@ -533,9 +570,9 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { expectedArgs: { stakingModuleId: STAKING_MODULE, status: StakingModuleStatus.DepositsPaused, - setBy: depositSecurityModule + setBy: depositSecurityModule, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi + decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, }) }) @@ -578,32 +615,43 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { it('reverts if called by a guardian with a future blockNumber', async () => { const futureBlockNumber = block.number + 100 - await assertRevert(depositSecurityModule.pauseDeposits(futureBlockNumber, STAKING_MODULE, ['0x', '0x'], { from: guardian })) + await assertRevert( + depositSecurityModule.pauseDeposits(futureBlockNumber, STAKING_MODULE, ['0x', '0x'], { from: guardian }) + ) }) it("reverts if called by an anon submitting a guardian's sig with a future blockNumber", async () => { const futureBlockNumber = block.number + 100 const sig = new DSMPauseMessage(futureBlockNumber, STAKING_MODULE).sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN2]) - await assertRevert(depositSecurityModule.pauseDeposits(futureBlockNumber, STAKING_MODULE, sig, { from: guardian })) + await assertRevert( + depositSecurityModule.pauseDeposits(futureBlockNumber, STAKING_MODULE, sig, { from: guardian }) + ) }) it("pauseDeposits emits DepositsPaused(guardianAddr) event if wasn't paused before", async () => { - const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { from: guardian }) + const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { + from: guardian, + }) assertEvent(tx, 'DepositsPaused', { expectedArgs: { guardian, stakingModuleId: STAKING_MODULE } }) assertEvent(tx, 'StakingModuleStatusSet', { expectedArgs: { stakingModuleId: STAKING_MODULE, status: StakingModuleStatus.DepositsPaused, - setBy: depositSecurityModule + setBy: depositSecurityModule, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi + decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, }) }) it("pauseDeposits doesn't emit DepositsPaused(guardianAddr) event if was paused before", async () => { await stakingRouterMock.setStakingModuleStatus(STAKING_MODULE, StakingModuleStatus.DepositsPaused) - assert.isTrue(await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), 'invariant failed: isPaused != true') - const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { from: guardian }) + assert.isTrue( + await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), + 'invariant failed: isPaused != true' + ) + const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { + from: guardian, + }) assert.equal(tx.logs.length, 0, 'invalid result: logs not empty') }) }) @@ -613,7 +661,11 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const guardians = await depositSecurityModule.getGuardians() assert.equal(guardians.length, 1, 'invariant failed: guardians != 1') await stakingRouterMock.setStakingModuleStatus(STAKING_MODULE, StakingModuleStatus.DepositsPaused) - assert.equal(await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), true, 'invariant failed: isPaused') + assert.equal( + await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), + true, + 'invariant failed: isPaused' + ) }) it('unpauses paused deposits', async () => { const tx = await depositSecurityModule.unpauseDeposits(STAKING_MODULE, { from: owner }) @@ -622,9 +674,9 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { expectedArgs: { stakingModuleId: STAKING_MODULE, status: StakingModuleStatus.Active, - setBy: depositSecurityModule + setBy: depositSecurityModule, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi + decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, }) }) @@ -819,10 +871,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.isTrue((await depositSecurityModule.getGuardians()).includes(GUARDIAN1)) }) it(`setGuardianQuorum can't be called by non-admin`, async () => { - await assertRevert( - depositSecurityModule.setGuardianQuorum(1, { from: stranger }), - `NotAnOwner("${stranger}")` - ) + await assertRevert(depositSecurityModule.setGuardianQuorum(1, { from: stranger }), `NotAnOwner("${stranger}")`) }) it(`setGuardianQuorum sets the quorum`, async () => { await depositSecurityModule.setGuardianQuorum(1, { from: owner }) @@ -840,7 +889,6 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.isTrue(quorum > guardians.length) }) it(`setGuardianQuorum allows to set the same value, but there no event emitted`, async () => { - const tx1 = await depositSecurityModule.setGuardianQuorum(2, { from: owner }) const quorum1 = await depositSecurityModule.getGuardianQuorum() assert.equal(quorum1, 2) @@ -849,13 +897,11 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const quorum2 = await depositSecurityModule.getGuardianQuorum() assert.equal(quorum2, 2) - assertEvent(tx1, 'GuardianQuorumChanged', { - expectedArgs: { newValue: quorum1 } + expectedArgs: { newValue: quorum1 }, }) await assertNoEvent(tx2, 'GuardianQuorumChanged') - }) }) }) @@ -864,20 +910,14 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.equal(await depositSecurityModule.getOwner(), owner, 'wrong initial owner') }) it('not owner cannot change', async () => { - await assertRevert( - depositSecurityModule.setOwner(stranger, { from: stranger }), - `NotAnOwner("${stranger}")` - ) + await assertRevert(depositSecurityModule.setOwner(stranger, { from: stranger }), `NotAnOwner("${stranger}")`) }) it('set new owner to zero address should reverts', async () => { - await assertRevert( - depositSecurityModule.setOwner(ZERO_ADDRESS, { from: owner }), - 'ZeroAddress("_newOwner")' - ) + await assertRevert(depositSecurityModule.setOwner(ZERO_ADDRESS, { from: owner }), 'ZeroAddress("_newOwner")') }) it('set new owner by owner', async () => { assertEvent(await depositSecurityModule.setOwner(stranger, { from: owner }), 'OwnerChanged', { - expectedArgs: { newValue: stranger } + expectedArgs: { newValue: stranger }, }) assert.equal(await depositSecurityModule.getOwner(), stranger, 'owner not changed') }) @@ -896,19 +936,23 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { newPauseIntentValidityPeriodBlocks.address, 'invariant failed: pauseIntentValidityPeriodBlocks' ) - const tx = await depositSecurityModule.setPauseIntentValidityPeriodBlocks(newPauseIntentValidityPeriodBlocks, { from: owner }) + const tx = await depositSecurityModule.setPauseIntentValidityPeriodBlocks(newPauseIntentValidityPeriodBlocks, { + from: owner, + }) assert.equal( await depositSecurityModule.getPauseIntentValidityPeriodBlocks(), newPauseIntentValidityPeriodBlocks, 'invalid result: pauseIntentValidityPeriodBlocks' ) assertEvent(tx, 'PauseIntentValidityPeriodBlocksChanged', { - expectedArgs: { newValue: newPauseIntentValidityPeriodBlocks } + expectedArgs: { newValue: newPauseIntentValidityPeriodBlocks }, }) }) it('setPauseIntentValidityPeriodBlocks reverts if called not by owner', async () => { const newPauseIntentValidityPeriodBlocks = PAUSE_INTENT_VALIDITY_PERIOD_BLOCKS + 1 - await assertRevert(depositSecurityModule.setPauseIntentValidityPeriodBlocks(newPauseIntentValidityPeriodBlocks, { from: stranger })) + await assertRevert( + depositSecurityModule.setPauseIntentValidityPeriodBlocks(newPauseIntentValidityPeriodBlocks, { from: stranger }) + ) }) it('setMaxDeposits sets new value maxDepositsPerBlock if called by owner', async () => { const newMaxDeposits = MAX_DEPOSITS_PER_BLOCK + 1 @@ -916,7 +960,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const tx = await depositSecurityModule.setMaxDeposits(newMaxDeposits, { from: owner }) assert.equal(await depositSecurityModule.getMaxDeposits(), newMaxDeposits, 'invalid result: setMaxDeposits') assertEvent(tx, 'MaxDepositsChanged', { - expectedArgs: { newValue: newMaxDeposits } + expectedArgs: { newValue: newMaxDeposits }, }) }) it('setMaxDeposits reverts if called not by owner', async () => { @@ -943,12 +987,14 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { 'invalid result: setMinDepositBlockDistance' ) assertEvent(tx, 'MinDepositBlockDistanceChanged', { - expectedArgs: { newValue: newMinDepositBlockDistance } + expectedArgs: { newValue: newMinDepositBlockDistance }, }) }) it('setMinDepositBlockDistance reverts if called not by owner', async () => { const newMinDepositBlockDistance = MIN_DEPOSIT_BLOCK_DISTANCE + 1 - await assertRevert(depositSecurityModule.setMinDepositBlockDistance(newMinDepositBlockDistance, { from: stranger })) + await assertRevert( + depositSecurityModule.setMinDepositBlockDistance(newMinDepositBlockDistance, { from: stranger }) + ) }) }) describe('canDeposit', () => { @@ -966,7 +1012,11 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { it('true if not paused and quorum > 0 and currentBlock - lastDepositBlock >= minDepositBlockDistance', async () => { await depositSecurityModule.addGuardian(GUARDIAN1, 1, { from: owner }) - assert.equal(await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), false, 'invariant failed: isPaused') + assert.equal( + await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), + false, + 'invariant failed: isPaused' + ) assert.isTrue((await depositSecurityModule.getGuardianQuorum()) > 0, 'invariant failed: quorum > 0') const lastDepositBlockNumber = await web3.eth.getBlockNumber() @@ -992,7 +1042,10 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.isTrue(latestBlock.number - lastDepositBlockNumber >= minDepositBlockDistance) await stakingRouterMock.setStakingModuleStatus(STAKING_MODULE, StakingModuleStatus.DepositsPaused) - assert.isTrue(await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), 'invariant failed: isPaused') + assert.isTrue( + await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), + 'invariant failed: isPaused' + ) assert.isFalse(await depositSecurityModule.canDeposit(STAKING_MODULE)) }) @@ -1000,7 +1053,11 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { await depositSecurityModule.addGuardians([GUARDIAN1, guardian], 1, { from: owner }) assert.isTrue((await depositSecurityModule.getGuardianQuorum()) > 0, 'invariant failed: quorum > 0') - assert.equal(await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), false, 'invariant failed: isPaused') + assert.equal( + await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), + false, + 'invariant failed: isPaused' + ) const lastDepositBlockNumber = await web3.eth.getBlockNumber() await stakingRouterMock.setStakingModuleLastDepositBlock(lastDepositBlockNumber) @@ -1018,7 +1075,11 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { await depositSecurityModule.addGuardian(GUARDIAN1, 1, { from: owner }) assert.isTrue((await depositSecurityModule.getGuardianQuorum()) > 0, 'invariant failed: quorum > 0') - assert.equal(await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), false, 'invariant failed: isPaused') + assert.equal( + await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), + false, + 'invariant failed: isPaused' + ) const lastDepositBlockNumber = await web3.eth.getBlockNumber() await stakingRouterMock.setStakingModuleLastDepositBlock(lastDepositBlockNumber) @@ -1032,7 +1093,11 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { it('false if Lido cant deposit', async () => { await depositSecurityModule.addGuardian(GUARDIAN1, 1, { from: owner }) - assert.equal(await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), false, 'invariant failed: isPaused') + assert.equal( + await stakingRouterMock.getStakingModuleIsDepositsPaused(STAKING_MODULE), + false, + 'invariant failed: isPaused' + ) assert.isTrue((await depositSecurityModule.getGuardianQuorum()) > 0, 'invariant failed: quorum > 0') const lastDepositBlockNumber = await web3.eth.getBlockNumber() @@ -1046,7 +1111,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.isTrue(await depositSecurityModule.canDeposit(STAKING_MODULE)) assert.isTrue(await lidoMock.canDeposit()) - await lidoMock.setCanDeposit(false); + await lidoMock.setCanDeposit(false) assert.isFalse(await lidoMock.canDeposit()) assert.isTrue(currentBlockNumber - lastDepositBlockNumber >= minDepositBlockDistance) diff --git a/test/0.8.9/lido-exec-layer-rewards-vault.js b/test/0.8.9/lido-exec-layer-rewards-vault.js index 033560c5a..3d258f5d8 100644 --- a/test/0.8.9/lido-exec-layer-rewards-vault.js +++ b/test/0.8.9/lido-exec-layer-rewards-vault.js @@ -47,7 +47,12 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { it('Execution layer rewards vault refuses to receive Ether by transfers with call data', async () => { const amount = 0.02 await assertRevert( - web3.eth.sendTransaction({ to: elRewardsVault.address, from: anotherAccount, value: ETH(amount), data: '0x12345678' }) + web3.eth.sendTransaction({ + to: elRewardsVault.address, + from: anotherAccount, + value: ETH(amount), + data: '0x12345678', + }) ) }) @@ -117,12 +122,14 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { // recover ERC20 const firstReceipt = await elRewardsVault.recoverERC20(mockERC20Token.address, bn(100000), { from: deployer }) assertEvent(firstReceipt, `ERC20Recovered`, { - expectedArgs: { requestedBy: deployer, token: mockERC20Token.address, amount: bn(100000) } + expectedArgs: { requestedBy: deployer, token: mockERC20Token.address, amount: bn(100000) }, }) - const secondReceipt = await elRewardsVault.recoverERC20(mockERC20Token.address, bn(400000), { from: anotherAccount }) + const secondReceipt = await elRewardsVault.recoverERC20(mockERC20Token.address, bn(400000), { + from: anotherAccount, + }) assertEvent(secondReceipt, `ERC20Recovered`, { - expectedArgs: { requestedBy: anotherAccount, token: mockERC20Token.address, amount: bn(400000) } + expectedArgs: { requestedBy: anotherAccount, token: mockERC20Token.address, amount: bn(400000) }, }) // check balances again @@ -132,13 +139,18 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { assertBn(await mockERC20Token.balanceOf(anotherAccount), bn(400000)) // recover last portion - const lastReceipt = await elRewardsVault.recoverERC20(mockERC20Token.address, bn(100000), { from: anotherAccount }) + const lastReceipt = await elRewardsVault.recoverERC20(mockERC20Token.address, bn(100000), { + from: anotherAccount, + }) assertEvent(lastReceipt, `ERC20Recovered`, { - expectedArgs: { requestedBy: anotherAccount, token: mockERC20Token.address, amount: bn(100000) } + expectedArgs: { requestedBy: anotherAccount, token: mockERC20Token.address, amount: bn(100000) }, }) // balance is zero already, have to be reverted - await assertRevert(elRewardsVault.recoverERC20(mockERC20Token.address, bn(1), { from: deployer }), `ERC20: transfer amount exceeds balance`) + await assertRevert( + elRewardsVault.recoverERC20(mockERC20Token.address, bn(1), { from: deployer }), + `ERC20: transfer amount exceeds balance` + ) }) it(`can't recover zero-address ERC721(NFT)`, async () => { @@ -157,16 +169,23 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { // recover nft2 should work const receiptNfc2 = await elRewardsVault.recoverERC721(mockNFT.address, nft2, { from: anotherAccount }) - assertEvent(receiptNfc2, `ERC721Recovered`, { expectedArgs: { requestedBy: anotherAccount, token: mockNFT.address, tokenId: nft2 } }) + assertEvent(receiptNfc2, `ERC721Recovered`, { + expectedArgs: { requestedBy: anotherAccount, token: mockNFT.address, tokenId: nft2 }, + }) // but nft1 recovery should revert - await assertRevert(elRewardsVault.recoverERC721(mockNFT.address, nft1), `ERC721: transfer caller is not owner nor approved`) + await assertRevert( + elRewardsVault.recoverERC721(mockNFT.address, nft1), + `ERC721: transfer caller is not owner nor approved` + ) // send nft1 to elRewardsVault and recover it await mockNFT.transferFrom(anotherAccount, elRewardsVault.address, nft1, { from: anotherAccount }) const receiptNft1 = await elRewardsVault.recoverERC721(mockNFT.address, nft1, { from: deployer }) - assertEvent(receiptNft1, `ERC721Recovered`, { expectedArgs: { requestedBy: deployer, token: mockNFT.address, tokenId: nft1 } }) + assertEvent(receiptNft1, `ERC721Recovered`, { + expectedArgs: { requestedBy: deployer, token: mockNFT.address, tokenId: nft1 }, + }) // check final NFT ownership state assertBn(await mockNFT.balanceOf(treasury), bn(2)) diff --git a/test/0.8.9/lido-locator.test.js b/test/0.8.9/lido-locator.test.js index aea91152c..bfc16fd53 100644 --- a/test/0.8.9/lido-locator.test.js +++ b/test/0.8.9/lido-locator.test.js @@ -43,7 +43,7 @@ contract('LidoLocator', ([deployer, agent]) => { initialConfig.stakingRouter, initialConfig.treasury, initialConfig.withdrawalQueue, - initialConfig.withdrawalVault + initialConfig.withdrawalVault, ] for (let i = 0; i < actualCoreComponents.length; i++) { @@ -64,7 +64,7 @@ contract('LidoLocator', ([deployer, agent]) => { initialConfig.burner, initialConfig.withdrawalQueue, initialConfig.withdrawalVault, - initialConfig.postTokenRebaseReceiver + initialConfig.postTokenRebaseReceiver, ] for (let i = 0; i < actualReportComponents.length; i++) { @@ -118,7 +118,7 @@ contract('LidoLocator', ([deployer, agent]) => { updatedConfig.stakingRouter, updatedConfig.treasury, updatedConfig.withdrawalQueue, - updatedConfig.withdrawalVault + updatedConfig.withdrawalVault, ] for (let i = 0; i < actualCoreComponents.length; i++) { @@ -139,7 +139,7 @@ contract('LidoLocator', ([deployer, agent]) => { initialConfig.burner, initialConfig.withdrawalQueue, initialConfig.withdrawalVault, - initialConfig.postTokenRebaseReceiver + initialConfig.postTokenRebaseReceiver, ] for (let i = 0; i < actualReportComponents.length; i++) { diff --git a/test/0.8.9/oracle-daemon-config.test.js b/test/0.8.9/oracle-daemon-config.test.js index bf6e4cc23..81f186b65 100644 --- a/test/0.8.9/oracle-daemon-config.test.js +++ b/test/0.8.9/oracle-daemon-config.test.js @@ -47,10 +47,7 @@ contract('OracleDaemonConfig', async ([deployer, manager, stranger]) => { const values = await config.getList([defaultKey]) assert.equal(values.length, 1) - assert.deepEqual( - values, - [updatedDefaultValue] - ) + assert.deepEqual(values, [updatedDefaultValue]) }) it('removes a value', async () => { @@ -99,7 +96,10 @@ contract('OracleDaemonConfig', async ([deployer, manager, stranger]) => { }) it('reverts when one of managers is zero address', async () => { - await assert.revertsWithCustomError(OracleDaemonConfig.new(deployer, [manager, ZERO_ADDRESS], { from: deployer }), 'ZeroAddress()') + await assert.revertsWithCustomError( + OracleDaemonConfig.new(deployer, [manager, ZERO_ADDRESS], { from: deployer }), + 'ZeroAddress()' + ) }) it('revers when empty value passed to set', async () => { @@ -159,20 +159,12 @@ contract('OracleDaemonConfig', async ([deployer, manager, stranger]) => { it('deployer cannot unset a defaultValue', async () => { await config.set(defaultKey, defaultValue, { from: manager }) - await assert.revertsOZAccessControl( - config.unset(defaultKey, { from: deployer }), - deployer, - `CONFIG_MANAGER_ROLE` - ) + await assert.revertsOZAccessControl(config.unset(defaultKey, { from: deployer }), deployer, `CONFIG_MANAGER_ROLE`) }) it('deployer cannot unset a defaultValue', async () => { await config.set(defaultKey, defaultValue, { from: manager }) - await assert.revertsOZAccessControl( - config.unset(defaultKey, { from: deployer }), - deployer, - `CONFIG_MANAGER_ROLE` - ) + await assert.revertsOZAccessControl(config.unset(defaultKey, { from: deployer }), deployer, `CONFIG_MANAGER_ROLE`) }) }) }) diff --git a/test/0.8.9/oracle-report-sanity-checker.test.js b/test/0.8.9/oracle-report-sanity-checker.test.js index c464de2f9..6f3ed1ab4 100644 --- a/test/0.8.9/oracle-report-sanity-checker.test.js +++ b/test/0.8.9/oracle-report-sanity-checker.test.js @@ -61,7 +61,10 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa lidoMock = await LidoStub.new({ from: deployer }) withdrawalQueueMock = await WithdrawalQueueStub.new({ from: deployer }) lidoLocatorMock = await LidoLocatorStub.new( - lidoMock.address, withdrawalVault, withdrawalQueueMock.address, elRewardsVault, + lidoMock.address, + withdrawalVault, + withdrawalQueueMock.address, + elRewardsVault, { from: deployer } ) @@ -71,7 +74,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa Object.values(defaultLimitsList), Object.values(managersRoster), { - from: deployer + from: deployer, } ) }) @@ -93,15 +96,24 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa assert.notEquals(limitsBefore.churnValidatorsPerDayLimit, newLimitsList.churnValidatorsPerDayLimit) assert.notEquals(limitsBefore.oneOffCLBalanceDecreaseBPLimit, newLimitsList.oneOffCLBalanceDecreaseBPLimit) assert.notEquals(limitsBefore.annualBalanceIncreaseBPLimit, newLimitsList.annualBalanceIncreaseBPLimit) - assert.notEquals(limitsBefore.simulatedShareRateDeviationBPLimit, newLimitsList.simulatedShareRateDeviationBPLimit) + assert.notEquals( + limitsBefore.simulatedShareRateDeviationBPLimit, + newLimitsList.simulatedShareRateDeviationBPLimit + ) assert.notEquals(limitsBefore.maxValidatorExitRequestsPerReport, newLimitsList.maxValidatorExitRequestsPerReport) - assert.notEquals(limitsBefore.maxAccountingExtraDataListItemsCount, newLimitsList.maxAccountingExtraDataListItemsCount) - assert.notEquals(limitsBefore.maxNodeOperatorsPerExtraDataItemCount, newLimitsList.maxNodeOperatorsPerExtraDataItemCount) + assert.notEquals( + limitsBefore.maxAccountingExtraDataListItemsCount, + newLimitsList.maxAccountingExtraDataListItemsCount + ) + assert.notEquals( + limitsBefore.maxNodeOperatorsPerExtraDataItemCount, + newLimitsList.maxNodeOperatorsPerExtraDataItemCount + ) assert.notEquals(limitsBefore.requestTimestampMargin, newLimitsList.requestTimestampMargin) assert.notEquals(limitsBefore.maxPositiveTokenRebase, newLimitsList.maxPositiveTokenRebase) await oracleReportSanityChecker.setOracleReportLimits(Object.values(newLimitsList), { - from: managersRoster.allLimitsManagers[0] + from: managersRoster.allLimitsManagers[0], }) const limitsAfter = await oracleReportSanityChecker.getOracleReportLimits() @@ -110,8 +122,14 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa assert.equals(limitsAfter.annualBalanceIncreaseBPLimit, newLimitsList.annualBalanceIncreaseBPLimit) assert.equals(limitsAfter.simulatedShareRateDeviationBPLimit, newLimitsList.simulatedShareRateDeviationBPLimit) assert.equals(limitsAfter.maxValidatorExitRequestsPerReport, newLimitsList.maxValidatorExitRequestsPerReport) - assert.equals(limitsAfter.maxAccountingExtraDataListItemsCount, newLimitsList.maxAccountingExtraDataListItemsCount) - assert.equals(limitsAfter.maxNodeOperatorsPerExtraDataItemCount, newLimitsList.maxNodeOperatorsPerExtraDataItemCount) + assert.equals( + limitsAfter.maxAccountingExtraDataListItemsCount, + newLimitsList.maxAccountingExtraDataListItemsCount + ) + assert.equals( + limitsAfter.maxNodeOperatorsPerExtraDataItemCount, + newLimitsList.maxNodeOperatorsPerExtraDataItemCount + ) assert.equals(limitsAfter.requestTimestampMargin, newLimitsList.requestTimestampMargin) assert.equals(limitsAfter.maxPositiveTokenRebase, newLimitsList.maxPositiveTokenRebase) }) @@ -120,7 +138,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa describe('checkAccountingOracleReport()', () => { beforeEach(async () => { await oracleReportSanityChecker.setOracleReportLimits(Object.values(defaultLimitsList), { - from: managersRoster.allLimitsManagers[0] + from: managersRoster.allLimitsManagers[0], }) }) @@ -157,7 +175,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa ...correctLidoOracleReport, preCLBalance: preCLBalance.toString(), postCLBalance: postCLBalance.toString(), - withdrawalVaultBalance: withdrawalVaultBalance.toString() + withdrawalVaultBalance: withdrawalVaultBalance.toString(), }) ), `IncorrectCLBalanceDecrease(${oneOffCLBalanceDecreaseBP.toString()})` @@ -176,7 +194,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa oracleReportSanityChecker.checkAccountingOracleReport( ...Object.values({ ...correctLidoOracleReport, - postCLBalance: postCLBalance.toString() + postCLBalance: postCLBalance.toString(), }) ), `IncorrectCLBalanceIncrease(${annualBalanceIncrease.toString()})` @@ -188,11 +206,13 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa }) it('set maxAccountingExtraDataListItemsCount', async () => { - const previousValue = (await oracleReportSanityChecker.getOracleReportLimits()).maxAccountingExtraDataListItemsCount + const previousValue = (await oracleReportSanityChecker.getOracleReportLimits()) + .maxAccountingExtraDataListItemsCount const newValue = 31 assert.notEquals(newValue, previousValue) - await oracleReportSanityChecker.setMaxAccountingExtraDataListItemsCount(newValue, - { from: managersRoster.maxAccountingExtraDataListItemsCountManagers[0] }) + await oracleReportSanityChecker.setMaxAccountingExtraDataListItemsCount(newValue, { + from: managersRoster.maxAccountingExtraDataListItemsCountManagers[0], + }) assert.equals( (await oracleReportSanityChecker.getOracleReportLimits()).maxAccountingExtraDataListItemsCount, newValue @@ -200,17 +220,18 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa }) it('set maxNodeOperatorsPerExtraDataItemCount', async () => { - const previousValue = (await oracleReportSanityChecker.getOracleReportLimits()).maxNodeOperatorsPerExtraDataItemCount + const previousValue = (await oracleReportSanityChecker.getOracleReportLimits()) + .maxNodeOperatorsPerExtraDataItemCount const newValue = 33 assert.notEquals(newValue, previousValue) - await oracleReportSanityChecker.setMaxNodeOperatorsPerExtraDataItemCount(newValue, - { from: managersRoster.maxNodeOperatorsPerExtraDataItemCountManagers[0] }) + await oracleReportSanityChecker.setMaxNodeOperatorsPerExtraDataItemCount(newValue, { + from: managersRoster.maxNodeOperatorsPerExtraDataItemCountManagers[0], + }) assert.equals( (await oracleReportSanityChecker.getOracleReportLimits()).maxNodeOperatorsPerExtraDataItemCount, newValue ) }) - }) describe('checkWithdrawalQueueOracleReport()', async () => { @@ -219,7 +240,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa let oldRequestCreationTimestamp, newRequestCreationTimestamp const correctWithdrawalQueueOracleReport = { requestIdToFinalizeUpTo: oldRequestId, - refReportTimestamp: -1 + refReportTimestamp: -1, } before(async () => { @@ -237,7 +258,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa oracleReportSanityChecker.checkWithdrawalQueueOracleReport( ...Object.values({ ...correctWithdrawalQueueOracleReport, - requestIdToFinalizeUpTo: newRequestId + requestIdToFinalizeUpTo: newRequestId, }) ), `IncorrectRequestFinalization(${newRequestCreationTimestamp})` @@ -257,18 +278,18 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa postTotalShares: ETH(4), etherLockedOnWithdrawalQueue: ETH(1), sharesBurntFromWithdrawalQueue: ETH(1), - simulatedShareRate: (BigInt(2) * 10n ** 27n).toString() + simulatedShareRate: (BigInt(2) * 10n ** 27n).toString(), } it('reverts with error IncorrectSimulatedShareRate() when reported and onchain share rate differs', async () => { - const simulatedShareRate = BigInt(ETH(2.10)) * 10n ** 9n + const simulatedShareRate = BigInt(ETH(2.1)) * 10n ** 9n const actualShareRate = BigInt(2) * 10n ** 27n const deviation = (100_00n * (simulatedShareRate - actualShareRate)) / actualShareRate await assert.revertsWithCustomError( oracleReportSanityChecker.checkSimulatedShareRate( ...Object.values({ ...correctSimulatedShareRate, - simulatedShareRate: simulatedShareRate.toString() + simulatedShareRate: simulatedShareRate.toString(), }) ), `IncorrectSimulatedShareRate(${deviation.toString()})` @@ -282,7 +303,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa ...Object.values({ ...correctSimulatedShareRate, etherLockedOnWithdrawalQueue: ETH(0), - postTotalPooledEther: ETH(0) + postTotalPooledEther: ETH(0), }) ), `IncorrectSimulatedShareRate(${deviation.toString()})` @@ -290,9 +311,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa }) it('passes all checks with correct share rate', async () => { - await oracleReportSanityChecker.checkSimulatedShareRate( - ...Object.values(correctSimulatedShareRate) - ) + await oracleReportSanityChecker.checkSimulatedShareRate(...Object.values(correctSimulatedShareRate)) }) }) }) diff --git a/test/0.8.9/oracle/accounting-oracle-access-control.test.js b/test/0.8.9/oracle/accounting-oracle-access-control.test.js index adb8f9ae5..e126a3ccc 100644 --- a/test/0.8.9/oracle/accounting-oracle-access-control.test.js +++ b/test/0.8.9/oracle/accounting-oracle-access-control.test.js @@ -11,7 +11,7 @@ const { calcReportDataHash, EXTRA_DATA_FORMAT_EMPTY, EXTRA_DATA_FORMAT_LIST, - ZERO_HASH + ZERO_HASH, } = require('./accounting-oracle-deploy.test') contract('AccountingOracle', ([admin, account1, account2, member1, member2, stranger]) => { @@ -24,7 +24,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const submitDataRoleKeccak156 = web3.utils.keccak256('SUBMIT_DATA_ROLE') - const deploy = async ({emptyExtraData = false} = {}) => { + const deploy = async ({ emptyExtraData = false } = {}) => { const deployed = await deployAndConfigureAccountingOracle(admin) const { refSlot } = await deployed.consensus.getCurrentFrame() @@ -32,12 +32,12 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra stuckKeys: [ { moduleId: 1, nodeOpIds: [0], keysCounts: [1] }, { moduleId: 2, nodeOpIds: [0], keysCounts: [2] }, - { moduleId: 3, nodeOpIds: [2], keysCounts: [3] } + { moduleId: 3, nodeOpIds: [2], keysCounts: [3] }, ], exitedKeys: [ { moduleId: 2, nodeOpIds: [1, 2], keysCounts: [1, 3] }, - { moduleId: 3, nodeOpIds: [1], keysCounts: [2] } - ] + { moduleId: 3, nodeOpIds: [1], keysCounts: [2] }, + ], } const extraDataItems = encodeExtraDataItems(extraData) @@ -58,7 +58,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra isBunkerMode: true, extraDataFormat: emptyExtraData ? EXTRA_DATA_FORMAT_EMPTY : EXTRA_DATA_FORMAT_LIST, extraDataHash: emptyExtraData ? ZERO_HASH : extraDataHash, - extraDataItemsCount: emptyExtraData ? 0 : extraDataItems.length + extraDataItemsCount: emptyExtraData ? 0 : extraDataItems.length, } reportItems = getReportDataItems(reportFields) const reportHash = calcReportDataHash(reportItems) @@ -141,7 +141,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra }) context('submitReportExtraDataEmpty', () => { - beforeEach(() => deploy({emptyExtraData: true})) + beforeEach(() => deploy({ emptyExtraData: true })) it('should revert from not consensus member without SUBMIT_DATA_ROLE role ', async () => { await assert.reverts(oracle.submitReportExtraDataEmpty({ from: account1 }), 'SenderNotAllowed()') diff --git a/test/0.8.9/oracle/accounting-oracle-deploy.test.js b/test/0.8.9/oracle/accounting-oracle-deploy.test.js index 6bd5abb21..3fbff1b2c 100644 --- a/test/0.8.9/oracle/accounting-oracle-deploy.test.js +++ b/test/0.8.9/oracle/accounting-oracle-deploy.test.js @@ -3,7 +3,7 @@ const { assert } = require('../../helpers/assert') const { hex } = require('../../helpers/utils') const { updateLocatorImplementation, - deployLocatorWithDummyAddressesImplementation + deployLocatorWithDummyAddressesImplementation, } = require('../../helpers/locator-deploy') const { @@ -27,7 +27,7 @@ const { HASH_4, HASH_5, CONSENSUS_VERSION, - deployHashConsensus + deployHashConsensus, } = require('./hash-consensus-deploy.test') const AccountingOracle = artifacts.require('AccountingOracleTimeTravellable') @@ -61,14 +61,14 @@ function getReportDataItems(r) { r.isBunkerMode, r.extraDataFormat, r.extraDataHash, - r.extraDataItemsCount + r.extraDataItemsCount, ] } function calcReportDataHash(reportItems) { const data = web3.eth.abi.encodeParameters( [ - '(uint256,uint256,uint256,uint256,uint256[],uint256[],uint256,uint256,uint256,uint256,bool,uint256,bytes32,uint256)' + '(uint256,uint256,uint256,uint256,uint256[],uint256[],uint256,uint256,uint256,uint256,bool,uint256,bytes32,uint256)', ], [reportItems] ) @@ -112,7 +112,7 @@ async function deployOracleReportSanityCheckerForAccounting(lidoLocator, admin) limitsList, managersRoster, { - from: admin + from: admin, } ) return oracleReportSanityChecker @@ -155,14 +155,14 @@ module.exports = { encodeExtraDataItem, encodeExtraDataItems, packExtraDataList, - calcExtraDataListHash + calcExtraDataListHash, } async function deployMockLegacyOracle({ epochsPerFrame = EPOCHS_PER_FRAME, slotsPerEpoch = SLOTS_PER_EPOCH, secondsPerSlot = SECONDS_PER_SLOT, genesisTime = GENESIS_TIME, - lastCompletedEpochId = V1_ORACLE_LAST_COMPLETED_EPOCH + lastCompletedEpochId = V1_ORACLE_LAST_COMPLETED_EPOCH, } = {}) { const legacyOracle = await MockLegacyOracle.new() await legacyOracle.setParams(epochsPerFrame, slotsPerEpoch, secondsPerSlot, genesisTime, lastCompletedEpochId) @@ -187,7 +187,7 @@ async function deployAccountingOracleSetup( getLidoAndStakingRouter = deployMockLidoAndStakingRouter, getLegacyOracle = deployMockLegacyOracle, lidoLocatorAddr: lidoLocatorAddrArg, - legacyOracleAddr: legacyOracleAddrArg + legacyOracleAddr: legacyOracleAddrArg, } = {} ) { const locatorAddr = (await deployLocatorWithDummyAddressesImplementation(admin)).address @@ -198,7 +198,7 @@ async function deployAccountingOracleSetup( lido: lido.address, stakingRouter: stakingRouter.address, withdrawalQueue: withdrawalQueue.address, - oracleReportSanityChecker: oracleReportSanityChecker.address + oracleReportSanityChecker: oracleReportSanityChecker.address, }) const legacyOracle = await getLegacyOracle() @@ -222,7 +222,7 @@ async function deployAccountingOracleSetup( slotsPerEpoch, secondsPerSlot, genesisTime, - initialEpoch + initialEpoch, }) // pretend we're at the first slot of the initial frame's epoch @@ -236,7 +236,7 @@ async function deployAccountingOracleSetup( legacyOracle, oracle, consensus, - oracleReportSanityChecker + oracleReportSanityChecker, } } @@ -245,7 +245,7 @@ async function initAccountingOracle({ oracle, consensus, dataSubmitter = null, - consensusVersion = CONSENSUS_VERSION + consensusVersion = CONSENSUS_VERSION, }) { const initTx = await oracle.initialize(admin, consensus.address, consensusVersion, { from: admin }) @@ -281,24 +281,24 @@ contract('AccountingOracle', ([admin, member1]) => { context('Deployment and initial configuration', () => { it('init fails if the chain config is different from the one of the legacy oracle', async () => { let deployed = await deployAccountingOracleSetup(admin, { - getLegacyOracle: () => deployMockLegacyOracle({ slotsPerEpoch: SLOTS_PER_EPOCH + 1 }) + getLegacyOracle: () => deployMockLegacyOracle({ slotsPerEpoch: SLOTS_PER_EPOCH + 1 }), }) await assert.reverts(initAccountingOracle({ admin, ...deployed }), 'IncorrectOracleMigration(0)') deployed = await deployAccountingOracleSetup(admin, { - getLegacyOracle: () => deployMockLegacyOracle({ secondsPerSlot: SECONDS_PER_SLOT + 1 }) + getLegacyOracle: () => deployMockLegacyOracle({ secondsPerSlot: SECONDS_PER_SLOT + 1 }), }) await assert.reverts(initAccountingOracle({ admin, ...deployed }), 'IncorrectOracleMigration(0)') deployed = await deployAccountingOracleSetup(admin, { - getLegacyOracle: () => deployMockLegacyOracle({ genesisTime: GENESIS_TIME + 1 }) + getLegacyOracle: () => deployMockLegacyOracle({ genesisTime: GENESIS_TIME + 1 }), }) await assert.reverts(initAccountingOracle({ admin, ...deployed }), 'IncorrectOracleMigration(0)') }) it('init fails if the frame size is different from the one of the legacy oracle', async () => { const deployed = await deployAccountingOracleSetup(admin, { - getLegacyOracle: () => deployMockLegacyOracle({ epochsPerFrame: EPOCHS_PER_FRAME - 1 }) + getLegacyOracle: () => deployMockLegacyOracle({ epochsPerFrame: EPOCHS_PER_FRAME - 1 }), }) await assert.reverts(initAccountingOracle({ admin, ...deployed }), 'IncorrectOracleMigration(1)') }) @@ -405,7 +405,9 @@ contract('AccountingOracle', ([admin, member1]) => { it('initializeWithoutMigration succeeds', async () => { const deployed = await deployAccountingOracleSetup(admin) const { refSlot } = await deployed.consensus.getCurrentFrame() - await deployed.oracle.initializeWithoutMigration(admin, deployed.consensus.address, CONSENSUS_VERSION, refSlot, { from: admin }) + await deployed.oracle.initializeWithoutMigration(admin, deployed.consensus.address, CONSENSUS_VERSION, refSlot, { + from: admin, + }) }) }) }) diff --git a/test/0.8.9/oracle/accounting-oracle-happy-path.test.js b/test/0.8.9/oracle/accounting-oracle-happy-path.test.js index d76ed1733..b2a5dae85 100644 --- a/test/0.8.9/oracle/accounting-oracle-happy-path.test.js +++ b/test/0.8.9/oracle/accounting-oracle-happy-path.test.js @@ -19,12 +19,10 @@ const { calcReportDataHash, encodeExtraDataItems, packExtraDataList, - calcExtraDataListHash + calcExtraDataListHash, } = require('./accounting-oracle-deploy.test') - contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { - context('Happy path', () => { let consensus let oracle @@ -51,17 +49,17 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { mockStakingRouter = deployed.stakingRouter mockLegacyOracle = deployed.legacyOracle - oracleVersion = +await oracle.getContractVersion() + oracleVersion = +(await oracle.getContractVersion()) - await consensus.addMember(member1, 1, {from: admin}) - await consensus.addMember(member2, 2, {from: admin}) - await consensus.addMember(member3, 2, {from: admin}) + await consensus.addMember(member1, 1, { from: admin }) + await consensus.addMember(member2, 2, { from: admin }) + await consensus.addMember(member3, 2, { from: admin }) await consensus.advanceTimeBySlots(SECONDS_PER_EPOCH + 1) }) async function triggerConsensusOnHash(hash) { - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() await consensus.submitReport(refSlot, hash, CONSENSUS_VERSION, { from: member1 }) await consensus.submitReport(refSlot, hash, CONSENSUS_VERSION, { from: member3 }) assert.equal((await consensus.getConsensusState()).consensusReport, hash) @@ -88,25 +86,27 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { assert.equal(+procState.extraDataItemsSubmitted, 0) }) - it(`reference slot of the empty initial consensus report is set to the last processed slot ` + - `of the legacy oracle`, async () => - { - const report = await oracle.getConsensusReport() - assert.equal(+report.refSlot, V1_ORACLE_LAST_REPORT_SLOT) - }) + it( + `reference slot of the empty initial consensus report is set to the last processed slot ` + + `of the legacy oracle`, + async () => { + const report = await oracle.getConsensusReport() + assert.equal(+report.refSlot, V1_ORACLE_LAST_REPORT_SLOT) + } + ) it('committee reaches consensus on a report hash', async () => { - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() extraData = { stuckKeys: [ - {moduleId: 1, nodeOpIds: [0], keysCounts: [1]}, - {moduleId: 2, nodeOpIds: [0], keysCounts: [2]}, - {moduleId: 3, nodeOpIds: [2], keysCounts: [3]}, + { moduleId: 1, nodeOpIds: [0], keysCounts: [1] }, + { moduleId: 2, nodeOpIds: [0], keysCounts: [2] }, + { moduleId: 3, nodeOpIds: [2], keysCounts: [3] }, ], exitedKeys: [ - {moduleId: 2, nodeOpIds: [1, 2], keysCounts: [1, 3]}, - {moduleId: 3, nodeOpIds: [1], keysCounts: [2]}, + { moduleId: 2, nodeOpIds: [1, 2], keysCounts: [1, 3] }, + { moduleId: 3, nodeOpIds: [1], keysCounts: [2] }, ], } @@ -127,7 +127,7 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { finalizationShareRate: e27(1), isBunkerMode: true, extraDataFormat: EXTRA_DATA_FORMAT_LIST, - extraDataHash: extraDataHash, + extraDataHash, extraDataItemsCount: extraDataItems.length, } @@ -141,20 +141,14 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const report = await oracle.getConsensusReport() assert.equal(report.hash, reportHash) assert.equal(+report.refSlot, +reportFields.refSlot) - assert.equal( - +report.processingDeadlineTime, - computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME) - ) + assert.equal(+report.processingDeadlineTime, computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME)) assert.isFalse(report.processingStarted) const frame = await consensus.getCurrentFrame() const procState = await oracle.getProcessingState() assert.equal(+procState.currentFrameRefSlot, +frame.refSlot) - assert.equal( - +procState.processingDeadlineTime, - computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot) - ) + assert.equal(+procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.equal(procState.mainDataHash, reportHash) assert.isFalse(procState.mainDataSubmitted) assert.equal(procState.extraDataHash, ZERO_HASH) @@ -170,14 +164,14 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { it('non-member cannot submit the data', async () => { await assert.reverts( - oracle.submitReportData(reportItems, oracleVersion, {from: stranger}), + oracle.submitReportData(reportItems, oracleVersion, { from: stranger }), 'SenderNotAllowed()' ) }) it('the data cannot be submitted passing a different contract version', async () => { await assert.reverts( - oracle.submitReportData(reportItems, oracleVersion - 1, {from: member1}), + oracle.submitReportData(reportItems, oracleVersion - 1, { from: member1 }), `UnexpectedContractVersion(${oracleVersion}, ${oracleVersion - 1})` ) }) @@ -187,7 +181,7 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const invalidReportItems = getReportDataItems(invalidReport) const invalidReportHash = calcReportDataHash(invalidReportItems) await assert.reverts( - oracle.submitReportData(invalidReportItems, oracleVersion, {from: member1}), + oracle.submitReportData(invalidReportItems, oracleVersion, { from: member1 }), `UnexpectedDataHash("${reportHash}", "${invalidReportHash}")` ) }) @@ -195,11 +189,11 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { let prevProcessingRefSlot it(`a committee member submits the rebase data`, async () => { - prevProcessingRefSlot = +await oracle.getLastProcessingRefSlot() - const tx = await oracle.submitReportData(reportItems, oracleVersion, {from: member1}) - assert.emits(tx, 'ProcessingStarted', {refSlot: reportFields.refSlot}) + prevProcessingRefSlot = +(await oracle.getLastProcessingRefSlot()) + const tx = await oracle.submitReportData(reportItems, oracleVersion, { from: member1 }) + assert.emits(tx, 'ProcessingStarted', { refSlot: reportFields.refSlot }) assert.isTrue((await oracle.getConsensusReport()).processingStarted) - assert.isAbove(+await oracle.getLastProcessingRefSlot(), prevProcessingRefSlot) + assert.isAbove(+(await oracle.getLastProcessingRefSlot()), prevProcessingRefSlot) }) it(`extra data processing is started`, async () => { @@ -207,10 +201,7 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const procState = await oracle.getProcessingState() assert.equal(+procState.currentFrameRefSlot, +frame.refSlot) - assert.equal( - +procState.processingDeadlineTime, - computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot) - ) + assert.equal(+procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.equal(procState.mainDataHash, reportHash) assert.isTrue(procState.mainDataSubmitted) assert.equal(procState.extraDataHash, reportFields.extraDataHash) @@ -249,11 +240,11 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const lastExitedKeysByModuleCall = await mockStakingRouter.lastCall_updateExitedKeysByModule() assert.equal(lastExitedKeysByModuleCall.callCount, 1) assert.sameOrderedMembers( - lastExitedKeysByModuleCall.moduleIds.map(x => +x), + lastExitedKeysByModuleCall.moduleIds.map((x) => +x), reportFields.stakingModuleIdsWithNewlyExitedValidators ) assert.sameOrderedMembers( - lastExitedKeysByModuleCall.exitedKeysCounts.map(x => +x), + lastExitedKeysByModuleCall.exitedKeysCounts.map((x) => +x), reportFields.numExitedValidatorsByStakingModule ) }) @@ -268,7 +259,7 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { it(`no data can be submitted for the same reference slot again`, async () => { await assert.reverts( - oracle.submitReportData(reportItems, oracleVersion, {from: member2}), + oracle.submitReportData(reportItems, oracleVersion, { from: member2 }), 'RefSlotAlreadyProcessing()' ) }) @@ -279,16 +270,13 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { }) it('a non-member cannot submit extra data', async () => { - await assert.reverts( - oracle.submitReportExtraDataList(extraDataList, {from: stranger}), - 'SenderNotAllowed()' - ) + await assert.reverts(oracle.submitReportExtraDataList(extraDataList, { from: stranger }), 'SenderNotAllowed()') }) it(`an extra data not matching the consensus hash cannot be submitted`, async () => { const invalidExtraData = { - stuckKeys: [ ...extraData.stuckKeys ], - exitedKeys: [ ...extraData.exitedKeys ], + stuckKeys: [...extraData.stuckKeys], + exitedKeys: [...extraData.exitedKeys], } invalidExtraData.exitedKeys[0].keysCounts = [...invalidExtraData.exitedKeys[0].keysCounts] ++invalidExtraData.exitedKeys[0].keysCounts[0] @@ -296,20 +284,20 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const invalidExtraDataList = packExtraDataList(invalidExtraDataItems) const invalidExtraDataHash = calcExtraDataListHash(invalidExtraDataList) await assert.reverts( - oracle.submitReportExtraDataList(invalidExtraDataList, {from: member2}), + oracle.submitReportExtraDataList(invalidExtraDataList, { from: member2 }), `UnexpectedExtraDataHash("${extraDataHash}", "${invalidExtraDataHash}")` ) }) it(`an empty extra data cannot be submitted`, async () => { await assert.reverts( - oracle.submitReportExtraDataEmpty({from: member2}), + oracle.submitReportExtraDataEmpty({ from: member2 }), `UnexpectedExtraDataFormat(${EXTRA_DATA_FORMAT_LIST}, ${EXTRA_DATA_FORMAT_EMPTY})` ) }) it('a committee member submits extra data', async () => { - const tx = await oracle.submitReportExtraDataList(extraDataList, {from: member2}) + const tx = await oracle.submitReportExtraDataList(extraDataList, { from: member2 }) assert.emits(tx, 'ExtraDataSubmitted', { refSlot: reportFields.refSlot, @@ -321,10 +309,7 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const procState = await oracle.getProcessingState() assert.equal(+procState.currentFrameRefSlot, +frame.refSlot) - assert.equal( - +procState.processingDeadlineTime, - computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot) - ) + assert.equal(+procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.equal(procState.mainDataHash, reportHash) assert.isTrue(procState.mainDataSubmitted) assert.equal(procState.extraDataHash, reportFields.extraDataHash) @@ -335,48 +320,49 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { }) it('Staking router got the exited keys by node op report', async () => { - const totalReportCalls = +await mockStakingRouter.totalCalls_reportExitedKeysByNodeOperator() + const totalReportCalls = +(await mockStakingRouter.totalCalls_reportExitedKeysByNodeOperator()) assert.equal(totalReportCalls, 2) const call1 = await mockStakingRouter.calls_reportExitedKeysByNodeOperator(0) assert.equal(+call1.stakingModuleId, 2) - assert.equal(call1.nodeOperatorIds, '0x' + [1, 2].map(i => hex(i, 8)).join('')) - assert.equal(call1.keysCounts, '0x' + [1, 3].map(i => hex(i, 16)).join('')) + assert.equal(call1.nodeOperatorIds, '0x' + [1, 2].map((i) => hex(i, 8)).join('')) + assert.equal(call1.keysCounts, '0x' + [1, 3].map((i) => hex(i, 16)).join('')) const call2 = await mockStakingRouter.calls_reportExitedKeysByNodeOperator(1) assert.equal(+call2.stakingModuleId, 3) - assert.equal(call2.nodeOperatorIds, '0x' + [1].map(i => hex(i, 8)).join('')) - assert.equal(call2.keysCounts, '0x' + [2].map(i => hex(i, 16)).join('')) + assert.equal(call2.nodeOperatorIds, '0x' + [1].map((i) => hex(i, 8)).join('')) + assert.equal(call2.keysCounts, '0x' + [2].map((i) => hex(i, 16)).join('')) }) it('Staking router got the stuck keys by node op report', async () => { - const totalReportCalls = +await mockStakingRouter.totalCalls_reportStuckKeysByNodeOperator() + const totalReportCalls = +(await mockStakingRouter.totalCalls_reportStuckKeysByNodeOperator()) assert.equal(totalReportCalls, 3) const call1 = await mockStakingRouter.calls_reportStuckKeysByNodeOperator(0) assert.equal(+call1.stakingModuleId, 1) - assert.equal(call1.nodeOperatorIds, '0x' + [0].map(i => hex(i, 8)).join('')) - assert.equal(call1.keysCounts, '0x' + [1].map(i => hex(i, 16)).join('')) + assert.equal(call1.nodeOperatorIds, '0x' + [0].map((i) => hex(i, 8)).join('')) + assert.equal(call1.keysCounts, '0x' + [1].map((i) => hex(i, 16)).join('')) const call2 = await mockStakingRouter.calls_reportStuckKeysByNodeOperator(1) assert.equal(+call2.stakingModuleId, 2) - assert.equal(call2.nodeOperatorIds, '0x' + [0].map(i => hex(i, 8)).join('')) - assert.equal(call2.keysCounts, '0x' + [2].map(i => hex(i, 16)).join('')) + assert.equal(call2.nodeOperatorIds, '0x' + [0].map((i) => hex(i, 8)).join('')) + assert.equal(call2.keysCounts, '0x' + [2].map((i) => hex(i, 16)).join('')) const call3 = await mockStakingRouter.calls_reportStuckKeysByNodeOperator(2) assert.equal(+call3.stakingModuleId, 3) - assert.equal(call3.nodeOperatorIds, '0x' + [2].map(i => hex(i, 8)).join('')) - assert.equal(call3.keysCounts, '0x' + [3].map(i => hex(i, 16)).join('')) + assert.equal(call3.nodeOperatorIds, '0x' + [2].map((i) => hex(i, 8)).join('')) + assert.equal(call3.keysCounts, '0x' + [3].map((i) => hex(i, 16)).join('')) }) it('Staking router was told that stuck and exited keys updating is finished', async () => { - const totalFinishedCalls = +await mockStakingRouter.totalCalls_onValidatorsCountsByNodeOperatorReportingFinished() + const totalFinishedCalls = + +(await mockStakingRouter.totalCalls_onValidatorsCountsByNodeOperatorReportingFinished()) assert.equal(totalFinishedCalls, 1) }) it(`extra data for the same reference slot cannot be re-submitted`, async () => { await assert.reverts( - oracle.submitReportExtraDataList(extraDataList, {from: member1}), + oracle.submitReportExtraDataList(extraDataList, { from: member1 }), 'ExtraDataAlreadyProcessed()' ) }) @@ -399,7 +385,7 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { }) it('new data report with empty extra data is agreed upon and submitted', async () => { - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() reportFields = { ...reportFields, @@ -413,8 +399,8 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { await triggerConsensusOnHash(reportHash) - const tx = await oracle.submitReportData(reportItems, oracleVersion, {from: member2}) - assert.emits(tx, 'ProcessingStarted', {refSlot: reportFields.refSlot}) + const tx = await oracle.submitReportData(reportItems, oracleVersion, { from: member2 }) + assert.emits(tx, 'ProcessingStarted', { refSlot: reportFields.refSlot }) }) it(`Lido got the oracle report`, async () => { @@ -434,13 +420,13 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { it(`a non-empty extra data cannot be submitted`, async () => { await assert.reverts( - oracle.submitReportExtraDataList(extraDataList, {from: member2}), + oracle.submitReportExtraDataList(extraDataList, { from: member2 }), `UnexpectedExtraDataFormat(${EXTRA_DATA_FORMAT_EMPTY}, ${EXTRA_DATA_FORMAT_LIST})` ) }) it('a committee member submits empty extra data', async () => { - const tx = await oracle.submitReportExtraDataEmpty({from: member3}) + const tx = await oracle.submitReportExtraDataEmpty({ from: member3 }) assert.emits(tx, 'ExtraDataSubmitted', { refSlot: reportFields.refSlot, @@ -452,10 +438,7 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const procState = await oracle.getProcessingState() assert.equal(+procState.currentFrameRefSlot, +frame.refSlot) - assert.equal( - +procState.processingDeadlineTime, - computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot) - ) + assert.equal(+procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.equal(procState.mainDataHash, reportHash) assert.isTrue(procState.mainDataSubmitted) assert.equal(procState.extraDataHash, ZERO_HASH) @@ -466,25 +449,23 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { }) it(`Staking router didn't get the exited keys by node op report`, async () => { - const totalReportCalls = +await mockStakingRouter.totalCalls_reportExitedKeysByNodeOperator() + const totalReportCalls = +(await mockStakingRouter.totalCalls_reportExitedKeysByNodeOperator()) assert.equal(totalReportCalls, 2) }) it(`Staking router didn't get the stuck keys by node op report`, async () => { - const totalReportCalls = +await mockStakingRouter.totalCalls_reportStuckKeysByNodeOperator() + const totalReportCalls = +(await mockStakingRouter.totalCalls_reportStuckKeysByNodeOperator()) assert.equal(totalReportCalls, 3) }) it('Staking router was told that stuck and exited keys updating is finished', async () => { - const totalFinishedCalls = +await mockStakingRouter.totalCalls_onValidatorsCountsByNodeOperatorReportingFinished() + const totalFinishedCalls = + +(await mockStakingRouter.totalCalls_onValidatorsCountsByNodeOperatorReportingFinished()) assert.equal(totalFinishedCalls, 2) }) it(`extra data for the same reference slot cannot be re-submitted`, async () => { - await assert.reverts( - oracle.submitReportExtraDataEmpty({from: member1}), - 'ExtraDataAlreadyProcessed()' - ) + await assert.reverts(oracle.submitReportExtraDataEmpty({ from: member1 }), 'ExtraDataAlreadyProcessed()') }) }) }) diff --git a/test/0.8.9/oracle/accounting-oracle-submit-report-data.test.js b/test/0.8.9/oracle/accounting-oracle-submit-report-data.test.js index fe272762a..4f5aee01a 100644 --- a/test/0.8.9/oracle/accounting-oracle-submit-report-data.test.js +++ b/test/0.8.9/oracle/accounting-oracle-submit-report-data.test.js @@ -17,7 +17,7 @@ const { SECONDS_PER_SLOT, GENESIS_TIME, ZERO_HASH, - HASH_1 + HASH_1, } = require('./accounting-oracle-deploy.test') contract('AccountingOracle', ([admin, account1, account2, member1, member2, stranger]) => { @@ -49,9 +49,9 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra finalizationShareRate: e27(1), isBunkerMode: true, extraDataFormat: EXTRA_DATA_FORMAT_LIST, - extraDataHash: extraDataHash, + extraDataHash, extraDataItemsCount: extraDataItems.length, - ...override + ...override, }) const deploy = async (options = undefined) => { @@ -62,19 +62,19 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra stuckKeys: [ { moduleId: 1, nodeOpIds: [0], keysCounts: [1] }, { moduleId: 2, nodeOpIds: [0], keysCounts: [2] }, - { moduleId: 3, nodeOpIds: [2], keysCounts: [3] } + { moduleId: 3, nodeOpIds: [2], keysCounts: [3] }, ], exitedKeys: [ { moduleId: 2, nodeOpIds: [1, 2], keysCounts: [1, 3] }, - { moduleId: 3, nodeOpIds: [1], keysCounts: [2] } - ] + { moduleId: 3, nodeOpIds: [1], keysCounts: [2] }, + ], } extraDataItems = encodeExtraDataItems(extraData) extraDataList = packExtraDataList(extraDataItems) extraDataHash = calcExtraDataListHash(extraDataList) reportFields = getReportFields({ - refSlot: +refSlot + refSlot: +refSlot, }) reportItems = getReportDataItems(reportFields) const reportHash = calcReportDataHash(reportItems) @@ -105,7 +105,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra return { newReportFields, newReportItems, - reportHash + reportHash, } } @@ -113,7 +113,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const { refSlot } = await consensus.getCurrentFrame() const next = await prepareNextReport({ ...newReportFields, - refSlot: +refSlot + SLOTS_PER_FRAME + refSlot: +refSlot + SLOTS_PER_FRAME, }) return next } @@ -174,7 +174,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const newReportFields = { ...reportFields, - refSlot: incorrectRefSlot + refSlot: incorrectRefSlot, } const reportItems = getReportDataItems(newReportFields) @@ -213,7 +213,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const newReportFields = { ...reportFields, - consensusVersion: incorrectNextVersion + consensusVersion: incorrectNextVersion, } const reportItems = getReportDataItems(newReportFields) @@ -243,7 +243,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const newReportFields = { ...reportFields, refSlot: nextRefSlot, - consensusVersion: newConsensusVersion + consensusVersion: newConsensusVersion, } const newReportItems = getReportDataItems(newReportFields) const newReportHash = calcReportDataHash(newReportItems) @@ -264,7 +264,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const { newReportItems } = await prepareNextReportInNextFrame({ ...reportFields, stakingModuleIdsWithNewlyExitedValidators: [2, 1], - numExitedValidatorsByStakingModule: [3, 4] + numExitedValidatorsByStakingModule: [3, 4], }) await assert.reverts( @@ -277,7 +277,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const { newReportItems } = await prepareNextReportInNextFrame({ ...reportFields, stakingModuleIdsWithNewlyExitedValidators: [1, 1], - numExitedValidatorsByStakingModule: [3, 4] + numExitedValidatorsByStakingModule: [3, 4], }) await assert.reverts( @@ -290,7 +290,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const { newReportFields, newReportItems } = await prepareNextReportInNextFrame({ ...reportFields, stakingModuleIdsWithNewlyExitedValidators: [1, 2], - numExitedValidatorsByStakingModule: [3, 4] + numExitedValidatorsByStakingModule: [3, 4], }) const tx = await oracle.submitReportData(newReportItems, oracleVersion, { from: member1 }) @@ -302,7 +302,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra it('reverts with UnexpectedDataHash', async () => { const incorrectReportItems = getReportDataItems({ ...reportFields, - numValidators: reportFields.numValidators - 1 + numValidators: reportFields.numValidators - 1, }) const correctDataHash = calcReportDataHash(reportItems) @@ -324,7 +324,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra it('reverts with MaxAccountingExtraDataItemsCountExceeded if data limit exceeds', async () => { const MAX_ACCOUNTING_EXTRA_DATA_LIMIT = 1 await oracleReportSanityChecker.setMaxAccountingExtraDataListItemsCount(MAX_ACCOUNTING_EXTRA_DATA_LIMIT, { - from: admin + from: admin, }) assert.equals( @@ -342,7 +342,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const MAX_ACCOUNTING_EXTRA_DATA_LIMIT = reportFields.extraDataItemsCount await oracleReportSanityChecker.setMaxAccountingExtraDataListItemsCount(MAX_ACCOUNTING_EXTRA_DATA_LIMIT, { - from: admin + from: admin, }) assert.equals( @@ -357,7 +357,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const { newReportItems } = await prepareNextReportInNextFrame({ ...reportFields, stakingModuleIdsWithNewlyExitedValidators: [1, 2], - numExitedValidatorsByStakingModule: [3] + numExitedValidatorsByStakingModule: [3], }) await assert.reverts( oracle.submitReportData(newReportItems, oracleVersion, { from: member1 }), @@ -369,7 +369,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const { newReportItems } = await prepareNextReportInNextFrame({ ...reportFields, stakingModuleIdsWithNewlyExitedValidators: [1, 2], - numExitedValidatorsByStakingModule: [3, 0] + numExitedValidatorsByStakingModule: [3, 0], }) await assert.reverts( oracle.submitReportData(newReportItems, oracleVersion, { from: member1 }), @@ -461,7 +461,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const { newReportItems, newReportFields } = await prepareNextReportInNextFrame({ ...reportFields, stakingModuleIdsWithNewlyExitedValidators: [], - numExitedValidatorsByStakingModule: [] + numExitedValidatorsByStakingModule: [], }) const tx = await oracle.submitReportData(newReportItems, oracleVersion, { from: member1 }) assert.emits(tx, 'ProcessingStarted', { refSlot: newReportFields.refSlot }) @@ -502,7 +502,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra { refSlot: prevRefSlot, processedItemsCount: 0, - itemsCount: extraDataItems.length + itemsCount: extraDataItems.length, }, { abi: AccountingOracleAbi } ) @@ -518,13 +518,13 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const changedReportItems = getReportDataItems({ ...reportFields, refSlot: nextRefSlot, - extraDataFormat: EXTRA_DATA_FORMAT_LIST + 1 + extraDataFormat: EXTRA_DATA_FORMAT_LIST + 1, }) const changedReportHash = calcReportDataHash(changedReportItems) await consensus.advanceTimeToNextFrameStart() await consensus.submitReport(nextRefSlot, changedReportHash, CONSENSUS_VERSION, { - from: member1 + from: member1, }) await assert.revertsWithCustomError( @@ -538,7 +538,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const { refSlot } = await consensus.getCurrentFrame() const reportFields = getReportFields({ refSlot: +refSlot, - extraDataItemsCount: 0 + extraDataItemsCount: 0, }) const reportItems = getReportDataItems(reportFields) const reportHash = calcReportDataHash(reportItems) @@ -554,7 +554,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const { refSlot } = await consensus.getCurrentFrame() const reportFields = getReportFields({ refSlot: +refSlot, - extraDataHash: ZERO_HASH + extraDataHash: ZERO_HASH, }) const reportItems = getReportDataItems(reportFields) const reportHash = calcReportDataHash(reportItems) @@ -576,7 +576,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra isBunkerMode: false, extraDataFormat: EXTRA_DATA_FORMAT_EMPTY, extraDataHash: nonZeroHash, - extraDataItemsCount: 0 + extraDataItemsCount: 0, }) const reportItems = getReportDataItems(reportFields) const reportHash = calcReportDataHash(reportItems) @@ -595,7 +595,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra isBunkerMode: false, extraDataFormat: EXTRA_DATA_FORMAT_EMPTY, extraDataHash: ZERO_HASH, - extraDataItemsCount: 10 + extraDataItemsCount: 10, }) const reportItems = getReportDataItems(reportFields) const reportHash = calcReportDataHash(reportItems) diff --git a/test/0.8.9/oracle/accounting-oracle-submit-report-extra-data.test.js b/test/0.8.9/oracle/accounting-oracle-submit-report-extra-data.test.js index f1f9a3c71..b187dedf9 100644 --- a/test/0.8.9/oracle/accounting-oracle-submit-report-extra-data.test.js +++ b/test/0.8.9/oracle/accounting-oracle-submit-report-extra-data.test.js @@ -13,19 +13,19 @@ const { ZERO_HASH, EXTRA_DATA_FORMAT_EMPTY, EXTRA_DATA_FORMAT_LIST, - EXTRA_DATA_TYPE_STUCK_VALIDATORS + EXTRA_DATA_TYPE_STUCK_VALIDATORS, } = require('./accounting-oracle-deploy.test') const getDefaultExtraData = () => ({ stuckKeys: [ { moduleId: 1, nodeOpIds: [0], keysCounts: [1] }, { moduleId: 2, nodeOpIds: [0], keysCounts: [2] }, - { moduleId: 3, nodeOpIds: [2], keysCounts: [3] } + { moduleId: 3, nodeOpIds: [2], keysCounts: [3] }, ], exitedKeys: [ { moduleId: 2, nodeOpIds: [1, 2], keysCounts: [1, 3] }, - { moduleId: 3, nodeOpIds: [1], keysCounts: [2] } - ] + { moduleId: 3, nodeOpIds: [1], keysCounts: [2] }, + ], }) const getDefaultReportFields = (overrides) => ({ @@ -43,7 +43,7 @@ const getDefaultReportFields = (overrides) => ({ // required override: refSlot, // required override: extraDataHash, // required override: extraDataItemsCount - ...overrides + ...overrides, }) contract('AccountingOracle', ([admin, account1, account2, member1, member2, stranger]) => { @@ -67,7 +67,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra function getReportData({ extraData: extraDataArg, extraDataItems: extraDataItemsArgs, - reportFields: reportFieldsArg + reportFields: reportFieldsArg, } = {}) { const extraData = extraDataArg || getDefaultExtraData() const extraDataItems = extraDataItemsArgs || encodeExtraDataItems(extraData) @@ -77,7 +77,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const reportFields = getDefaultReportFields({ extraDataHash, extraDataItemsCount: extraDataItems.length, - ...reportFieldsArg + ...reportFieldsArg, }) const reportItems = getReportDataItems(reportFields) @@ -90,7 +90,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra extraDataHash, reportFields, reportItems, - reportHash + reportHash, } } @@ -104,7 +104,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra return { ...data, - deadline + deadline, } } @@ -115,8 +115,8 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra ...prepareArgs, reportFields: { ...reportFields, - refSlot - } + refSlot, + }, }) return next } @@ -200,7 +200,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra it('reverts with UnexpectedExtraDataItemsCount if there was wrong amount of items', async () => { const wrongItemsCount = 1 const reportFields = { - extraDataItemsCount: wrongItemsCount + extraDataItemsCount: wrongItemsCount, } const { extraDataList, extraDataItems } = await prepareNextReportInNextFrame({ reportFields }) await assert.reverts( @@ -215,7 +215,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const reportFields = { extraDataHash: ZERO_HASH, extraDataFormat: EXTRA_DATA_FORMAT_EMPTY, - extraDataItemsCount: 0 + extraDataItemsCount: 0, } const { extraDataList } = await prepareNextReportInNextFrame({ reportFields }) await assert.reverts( @@ -235,15 +235,15 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra stuckKeys: [ ...extraDataDefault.stuckKeys, { moduleId: 4, nodeOpIds: [1], keysCounts: [2] }, - { moduleId: 4, nodeOpIds: [1], keysCounts: [2] } - ] + { moduleId: 4, nodeOpIds: [1], keysCounts: [2] }, + ], } const { extraDataList } = await prepareNextReportInNextFrame({ extraData: invalidExtraData }) await assert.reverts( oracle.submitReportExtraDataList(extraDataList, { - from: member1 + from: member1, }), 'InvalidExtraDataSortOrder(4)' ) @@ -256,15 +256,15 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra exitedKeys: [ ...extraDataDefault.exitedKeys, { moduleId: 4, nodeOpIds: [1], keysCounts: [2] }, - { moduleId: 4, nodeOpIds: [1], keysCounts: [2] } - ] + { moduleId: 4, nodeOpIds: [1], keysCounts: [2] }, + ], } const { extraDataList } = await prepareNextReportInNextFrame({ extraData: invalidExtraData }) await assert.reverts( oracle.submitReportExtraDataList(extraDataList, { - from: member1 + from: member1, }), 'InvalidExtraDataSortOrder(6)' ) @@ -276,13 +276,13 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra stuckKeys: [ ...extraDataDefault.stuckKeys, { moduleId: 4, nodeOpIds: [1], keysCounts: [2] }, - { moduleId: 5, nodeOpIds: [1], keysCounts: [2] } + { moduleId: 5, nodeOpIds: [1], keysCounts: [2] }, ], exitedKeys: [ ...extraDataDefault.exitedKeys, { moduleId: 4, nodeOpIds: [1], keysCounts: [2] }, - { moduleId: 5, nodeOpIds: [1], keysCounts: [2] } - ] + { moduleId: 5, nodeOpIds: [1], keysCounts: [2] }, + ], } const { extraDataList, reportFields } = await prepareNextReportInNextFrame({ extraData: invalidExtraData }) @@ -310,7 +310,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra extraData, extraDataItems, lastIndexDefault: itemsCount - 1, - lastIndexCustom + lastIndexCustom, } } @@ -363,7 +363,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const getExtraWithCustomType = (typeCustom) => { const extraData = { stuckKeys: [{ moduleId: 1, nodeOpIds: [1], keysCounts: [2] }], - exitedKeys: [] + exitedKeys: [], } const item = extraData.stuckKeys[0] const extraDataItems = [] @@ -372,7 +372,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra extraData, extraDataItems, wrongTypedIndex: 0, - typeCustom + typeCustom, } } @@ -414,7 +414,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const problematicItemIdx = 0 const extraData = { stuckKeys: [{ moduleId: 1, nodeOpIds: [1, 2], keysCounts: [2, 3] }], - exitedKeys: [] + exitedKeys: [], } const problematicItemsCount = extraData.stuckKeys[problematicItemIdx].nodeOpIds.length const { extraDataList } = await prepareNextReportInNextFrame({ extraData }) @@ -429,7 +429,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const problematicItemIdx = 0 const extraData = { stuckKeys: [{ moduleId: 1, nodeOpIds: [1, 2], keysCounts: [2, 3] }], - exitedKeys: [] + exitedKeys: [], } const problematicItemsCount = extraData.stuckKeys[problematicItemIdx].nodeOpIds.length const { extraDataList, reportFields } = await prepareNextReportInNextFrame({ extraData }) @@ -445,9 +445,9 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const extraData = { stuckKeys: [ { moduleId: 1, nodeOpIds: [1], keysCounts: [2] }, - { moduleId: 2, nodeOpIds: [1], keysCounts: [2] } + { moduleId: 2, nodeOpIds: [1], keysCounts: [2] }, ], - exitedKeys: [] + exitedKeys: [], } const extraDataItems = encodeExtraDataItems(extraData) // Cutting item to provoke error on early stage @@ -466,9 +466,9 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const extraData = { stuckKeys: [ { moduleId: 1, nodeOpIds: [1], keysCounts: [2] }, - { moduleId: 2, nodeOpIds: [1, 2, 3, 4], keysCounts: [2] } + { moduleId: 2, nodeOpIds: [1, 2, 3, 4], keysCounts: [2] }, ], - exitedKeys: [] + exitedKeys: [], } const extraDataItems = encodeExtraDataItems(extraData) // Providing long items and cutting them from end to provoke error on late stage @@ -487,9 +487,9 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const extraData = { stuckKeys: [ { moduleId: 1, nodeOpIds: [1], keysCounts: [2] }, - { moduleId: 0, nodeOpIds: [1], keysCounts: [2] } + { moduleId: 0, nodeOpIds: [1], keysCounts: [2] }, ], - exitedKeys: [] + exitedKeys: [], } const { extraDataList } = await prepareNextReportInNextFrame({ extraData }) await assert.reverts( @@ -505,9 +505,9 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const extraData = { stuckKeys: [ { moduleId: 1, nodeOpIds: [], keysCounts: [2] }, - { moduleId: 2, nodeOpIds: [1], keysCounts: [2] } + { moduleId: 2, nodeOpIds: [1], keysCounts: [2] }, ], - exitedKeys: [] + exitedKeys: [], } const extraDataItems = encodeExtraDataItems(extraData) const { extraDataList } = await prepareNextReportInNextFrame({ extraData, extraDataItems }) @@ -529,14 +529,14 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const reportFields = getDefaultReportFields({ extraDataHash, extraDataItemsCount: extraDataItems.length, - refSlot + refSlot, }) const reportItems = getReportDataItems(reportFields) const reportHash = calcReportDataHash(reportItems) await consensus.submitReport(reportFields.refSlot, reportHash, CONSENSUS_VERSION, { - from: member1 + from: member1, }) await oracle.submitReportData(reportItems, oracleVersion, { from: member1 }) diff --git a/test/0.8.9/oracle/base-oracle-access-control.test.js b/test/0.8.9/oracle/base-oracle-access-control.test.js index 640093f26..d66a5be4b 100644 --- a/test/0.8.9/oracle/base-oracle-access-control.test.js +++ b/test/0.8.9/oracle/base-oracle-access-control.test.js @@ -10,7 +10,7 @@ const { INITIAL_EPOCH, CONSENSUS_VERSION, HASH_1, - SLOTS_PER_FRAME + SLOTS_PER_FRAME, } = require('./base-oracle-deploy.test') const MockConsensusContract = artifacts.require('MockConsensusContract') diff --git a/test/0.8.9/oracle/base-oracle-deploy.test.js b/test/0.8.9/oracle/base-oracle-deploy.test.js index e4fadd4ed..60774f9fc 100644 --- a/test/0.8.9/oracle/base-oracle-deploy.test.js +++ b/test/0.8.9/oracle/base-oracle-deploy.test.js @@ -43,7 +43,7 @@ async function deployBaseOracle( epochsPerFrame = EPOCHS_PER_FRAME, fastLaneLengthSlots = INITIAL_FAST_LANE_LENGTH_SLOTS, initialEpoch = INITIAL_EPOCH, - mockMember = admin + mockMember = admin, } = {} ) { if (!consensusContract) { @@ -92,7 +92,7 @@ module.exports = { HASH_5, CONSENSUS_VERSION, UNREACHABLE_QUORUM, - deployBaseOracle + deployBaseOracle, } contract('BaseOracle', ([admin, member1]) => { diff --git a/test/0.8.9/oracle/base-oracle-set-consensus.test.js b/test/0.8.9/oracle/base-oracle-set-consensus.test.js index e771a7fe5..df42be8f1 100644 --- a/test/0.8.9/oracle/base-oracle-set-consensus.test.js +++ b/test/0.8.9/oracle/base-oracle-set-consensus.test.js @@ -11,7 +11,7 @@ const { HASH_1, HASH_2, CONSENSUS_VERSION, - deployBaseOracle + deployBaseOracle, } = require('./base-oracle-deploy.test') contract('BaseOracle', ([admin, member, notMember]) => { diff --git a/test/0.8.9/oracle/base-oracle-submit-report.test.js b/test/0.8.9/oracle/base-oracle-submit-report.test.js index feb145ea2..25f0b6be0 100644 --- a/test/0.8.9/oracle/base-oracle-submit-report.test.js +++ b/test/0.8.9/oracle/base-oracle-submit-report.test.js @@ -36,7 +36,7 @@ contract('BaseOracle', ([admin]) => { { refSlot: initialRefSlot, hash: HASH_1, - processingDeadlineTime: initialRefSlot + SLOTS_PER_FRAME + processingDeadlineTime: initialRefSlot + SLOTS_PER_FRAME, }, { abi: baseOracleAbi } ) @@ -84,7 +84,7 @@ contract('BaseOracle', ([admin]) => { 'WarnProcessingMissed', { refSlot: initialRefSlot + 10 }, { - abi: baseOracleAbi + abi: baseOracleAbi, } ) assert.equal(+(await baseOracle.getConsensusReportLastCall()).callCount, 3) @@ -119,7 +119,7 @@ contract('BaseOracle', ([admin]) => { tx, 'WarnProcessingMissed', { - refSlot: initialRefSlot + refSlot: initialRefSlot, }, { abi: baseOracleAbi } ) @@ -134,7 +134,7 @@ contract('BaseOracle', ([admin]) => { const nextRefSlot = initialRefSlot + 1 const tx = await consensus.submitReportAsConsensus(HASH_3, nextRefSlot, nextRefSlot + SLOTS_PER_FRAME + 10) assert.emitsNumberOfEvents(tx, 'WarnProcessingMissed', 0, { - abi: baseOracleAbi + abi: baseOracleAbi, }) const report = await baseOracle.getConsensusReport() assert.equal(report.hash, HASH_3) diff --git a/test/0.8.9/oracle/hash-consensus-deploy.test.js b/test/0.8.9/oracle/hash-consensus-deploy.test.js index f8bcd930a..8d8b258ee 100644 --- a/test/0.8.9/oracle/hash-consensus-deploy.test.js +++ b/test/0.8.9/oracle/hash-consensus-deploy.test.js @@ -43,7 +43,7 @@ async function deployHashConsensus( genesisTime = GENESIS_TIME, epochsPerFrame = EPOCHS_PER_FRAME, fastLaneLengthSlots = INITIAL_FAST_LANE_LENGTH_SLOTS, - initialEpoch = INITIAL_EPOCH + initialEpoch = INITIAL_EPOCH, } = {} ) { if (!reportProcessor) { @@ -97,7 +97,7 @@ module.exports = { HASH_5, CONSENSUS_VERSION, UNREACHABLE_QUORUM, - deployHashConsensus + deployHashConsensus, } contract('HashConsensus', ([admin, member1]) => { @@ -127,7 +127,8 @@ contract('HashConsensus', ([admin, member1]) => { }) it('reverts if report processor address is zero', async () => { - await assert.revertsWithCustomError(HashConsensus.new( + await assert.revertsWithCustomError( + HashConsensus.new( SLOTS_PER_EPOCH, SECONDS_PER_SLOT, GENESIS_TIME, @@ -144,7 +145,8 @@ contract('HashConsensus', ([admin, member1]) => { it('reverts if admin address is zero', async () => { const reportProcessor = await MockReportProcessor.new(CONSENSUS_VERSION, { from: admin }) - await assert.revertsWithCustomError(HashConsensus.new( + await assert.revertsWithCustomError( + HashConsensus.new( SLOTS_PER_EPOCH, SECONDS_PER_SLOT, GENESIS_TIME, diff --git a/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js b/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js index a0df239f9..581cdd886 100644 --- a/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js +++ b/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js @@ -3,13 +3,28 @@ const { toNum } = require('../../helpers/utils') const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') const { - SLOTS_PER_EPOCH, SECONDS_PER_SLOT, GENESIS_TIME, EPOCHS_PER_FRAME, - SECONDS_PER_EPOCH, SECONDS_PER_FRAME, SLOTS_PER_FRAME, - computeSlotAt, computeEpochAt, computeEpochFirstSlot, computeEpochFirstSlotAt, - computeTimestampAtSlot, computeTimestampAtEpoch, - ZERO_HASH, HASH_1, HASH_2, HASH_3, HASH_4, HASH_5, - CONSENSUS_VERSION, deployHashConsensus} = require('./hash-consensus-deploy.test') - + SLOTS_PER_EPOCH, + SECONDS_PER_SLOT, + GENESIS_TIME, + EPOCHS_PER_FRAME, + SECONDS_PER_EPOCH, + SECONDS_PER_FRAME, + SLOTS_PER_FRAME, + computeSlotAt, + computeEpochAt, + computeEpochFirstSlot, + computeEpochFirstSlotAt, + computeTimestampAtSlot, + computeTimestampAtEpoch, + ZERO_HASH, + HASH_1, + HASH_2, + HASH_3, + HASH_4, + HASH_5, + CONSENSUS_VERSION, + deployHashConsensus, +} = require('./hash-consensus-deploy.test') contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, stranger]) => { context('Fast-lane members', async () => { @@ -22,10 +37,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, const setTimeToFrame0 = async () => { await consensus.setTimeInEpochs((await consensus.getFrameConfig()).initialEpoch) - assert.equal( - +await consensus.getTimeInSlots(), - +(await consensus.getCurrentFrame()).refSlot + 1 - ) + assert.equal(+(await consensus.getTimeInSlots()), +(await consensus.getCurrentFrame()).refSlot + 1) } context('State after initialization', () => { @@ -49,166 +61,156 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, const fastLaneLengthSlots = 10 const frames = [ - {fastLaneMembers: [member1, member2, member3], restMembers: [member4, member5]}, - {fastLaneMembers: [member2, member3, member4], restMembers: [member5, member1]}, - {fastLaneMembers: [member3, member4, member5], restMembers: [member1, member2]}, - {fastLaneMembers: [member4, member5, member1], restMembers: [member2, member3]}, - {fastLaneMembers: [member5, member1, member2], restMembers: [member3, member4]}, - {fastLaneMembers: [member1, member2, member3], restMembers: [member4, member5]}, - {fastLaneMembers: [member2, member3, member4], restMembers: [member5, member1]}, - {fastLaneMembers: [member3, member4, member5], restMembers: [member1, member2]}, - {fastLaneMembers: [member4, member5, member1], restMembers: [member2, member3]}, - {fastLaneMembers: [member5, member1, member2], restMembers: [member3, member4]}, - {fastLaneMembers: [member1, member2, member3], restMembers: [member4, member5]}, - {fastLaneMembers: [member2, member3, member4], restMembers: [member5, member1]}, + { fastLaneMembers: [member1, member2, member3], restMembers: [member4, member5] }, + { fastLaneMembers: [member2, member3, member4], restMembers: [member5, member1] }, + { fastLaneMembers: [member3, member4, member5], restMembers: [member1, member2] }, + { fastLaneMembers: [member4, member5, member1], restMembers: [member2, member3] }, + { fastLaneMembers: [member5, member1, member2], restMembers: [member3, member4] }, + { fastLaneMembers: [member1, member2, member3], restMembers: [member4, member5] }, + { fastLaneMembers: [member2, member3, member4], restMembers: [member5, member1] }, + { fastLaneMembers: [member3, member4, member5], restMembers: [member1, member2] }, + { fastLaneMembers: [member4, member5, member1], restMembers: [member2, member3] }, + { fastLaneMembers: [member5, member1, member2], restMembers: [member3, member4] }, + { fastLaneMembers: [member1, member2, member3], restMembers: [member4, member5] }, + { fastLaneMembers: [member2, member3, member4], restMembers: [member5, member1] }, ] before(async () => { - await deploy({fastLaneLengthSlots}) + await deploy({ fastLaneLengthSlots }) - await consensus.addMember(member1, 1, {from: admin}) - await consensus.addMember(member2, 2, {from: admin}) - await consensus.addMember(member3, 2, {from: admin}) - await consensus.addMember(member4, 3, {from: admin}) - await consensus.addMember(member5, 3, {from: admin}) + await consensus.addMember(member1, 1, { from: admin }) + await consensus.addMember(member2, 2, { from: admin }) + await consensus.addMember(member3, 2, { from: admin }) + await consensus.addMember(member4, 3, { from: admin }) + await consensus.addMember(member5, 3, { from: admin }) }) before(setTimeToFrame0) - const testFrame = ({fastLaneMembers, restMembers}, index) => context(`frame ${index}`, () => { - let frame + const testFrame = ({ fastLaneMembers, restMembers }, index) => + context(`frame ${index}`, () => { + let frame - before(async () => { - frame = await consensus.getCurrentFrame() - }) + before(async () => { + frame = await consensus.getCurrentFrame() + }) - after(async () => { - await consensus.advanceTimeToNextFrameStart() - }) + after(async () => { + await consensus.advanceTimeToNextFrameStart() + }) - it(`fast lane members are calculated correctly`, async () => { - assert.isTrue(await consensus.getIsFastLaneMember(fastLaneMembers[0])) - assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[0])).isFastLane) + it(`fast lane members are calculated correctly`, async () => { + assert.isTrue(await consensus.getIsFastLaneMember(fastLaneMembers[0])) + assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[0])).isFastLane) - assert.isTrue(await consensus.getIsFastLaneMember(fastLaneMembers[1])) - assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[1])).isFastLane) + assert.isTrue(await consensus.getIsFastLaneMember(fastLaneMembers[1])) + assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[1])).isFastLane) - assert.isTrue(await consensus.getIsFastLaneMember(fastLaneMembers[2])) - assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[2])).isFastLane) + assert.isTrue(await consensus.getIsFastLaneMember(fastLaneMembers[2])) + assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[2])).isFastLane) - assert.isFalse(await consensus.getIsFastLaneMember(restMembers[0])) - assert.isFalse((await consensus.getConsensusStateForMember(restMembers[0])).isFastLane) + assert.isFalse(await consensus.getIsFastLaneMember(restMembers[0])) + assert.isFalse((await consensus.getConsensusStateForMember(restMembers[0])).isFastLane) - assert.isFalse(await consensus.getIsFastLaneMember(restMembers[1])) - assert.isFalse((await consensus.getConsensusStateForMember(restMembers[1])).isFastLane) + assert.isFalse(await consensus.getIsFastLaneMember(restMembers[1])) + assert.isFalse((await consensus.getConsensusStateForMember(restMembers[1])).isFastLane) - assert.sameMembers( - (await consensus.getFastLaneMembers()).addresses, - fastLaneMembers - ) + assert.sameMembers((await consensus.getFastLaneMembers()).addresses, fastLaneMembers) - assert.sameMembers( - (await consensus.getMembers()).addresses, - [member1, member2, member3, member4, member5] - ) - }) + assert.sameMembers((await consensus.getMembers()).addresses, [member1, member2, member3, member4, member5]) + }) - it('non-members are not in the fast lane set', async () => { - assert.isFalse(await consensus.getIsFastLaneMember(stranger)) - assert.isFalse((await consensus.getConsensusStateForMember(stranger)).isFastLane) - }) + it('non-members are not in the fast lane set', async () => { + assert.isFalse(await consensus.getIsFastLaneMember(stranger)) + assert.isFalse((await consensus.getConsensusStateForMember(stranger)).isFastLane) + }) - it(`fast lane members can submit a report in the first part of the frame`, async () => { - assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[0])).canReport) - await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, {from: fastLaneMembers[0]}) + it(`fast lane members can submit a report in the first part of the frame`, async () => { + assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[0])).canReport) + await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: fastLaneMembers[0] }) - assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[1])).canReport) - await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, {from: fastLaneMembers[1]}) + assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[1])).canReport) + await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: fastLaneMembers[1] }) - await consensus.advanceTimeBySlots(fastLaneLengthSlots - 1) + await consensus.advanceTimeBySlots(fastLaneLengthSlots - 1) - assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[2])).canReport) - await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, {from: fastLaneMembers[2]}) + assert.isTrue((await consensus.getConsensusStateForMember(fastLaneMembers[2])).canReport) + await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: fastLaneMembers[2] }) - assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) - }) + assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) + }) - it(`non-fast lane members cannot submit a report in the first part of the frame`, async () => { - assert.isFalse((await consensus.getConsensusStateForMember(restMembers[0])).canReport) - await assert.reverts( - consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, {from: restMembers[0]}), - 'NonFastLaneMemberCannotReportWithinFastLaneInterval()' - ) - - assert.isFalse((await consensus.getConsensusStateForMember(restMembers[1])).canReport) - await assert.reverts( - consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, {from: restMembers[1]}), - 'NonFastLaneMemberCannotReportWithinFastLaneInterval()' - ) - }) + it(`non-fast lane members cannot submit a report in the first part of the frame`, async () => { + assert.isFalse((await consensus.getConsensusStateForMember(restMembers[0])).canReport) + await assert.reverts( + consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: restMembers[0] }), + 'NonFastLaneMemberCannotReportWithinFastLaneInterval()' + ) + + assert.isFalse((await consensus.getConsensusStateForMember(restMembers[1])).canReport) + await assert.reverts( + consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: restMembers[1] }), + 'NonFastLaneMemberCannotReportWithinFastLaneInterval()' + ) + }) - it(`non-fast lane members can submit a report during the rest of the frame`, async () => { - await consensus.advanceTimeBySlots(1) + it(`non-fast lane members can submit a report during the rest of the frame`, async () => { + await consensus.advanceTimeBySlots(1) - assert.isTrue((await consensus.getConsensusStateForMember(restMembers[0])).canReport) - await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, {from: restMembers[0]}) + assert.isTrue((await consensus.getConsensusStateForMember(restMembers[0])).canReport) + await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: restMembers[0] }) - assert.isTrue((await consensus.getConsensusStateForMember(restMembers[1])).canReport) - await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, {from: restMembers[1]}) + assert.isTrue((await consensus.getConsensusStateForMember(restMembers[1])).canReport) + await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: restMembers[1] }) - const variants = await consensus.getReportVariants() - assert.sameOrderedMembers(variants.variants, [HASH_1]) - assert.sameOrderedMembers(toNum(variants.support), [5]) + const variants = await consensus.getReportVariants() + assert.sameOrderedMembers(variants.variants, [HASH_1]) + assert.sameOrderedMembers(toNum(variants.support), [5]) + }) }) - }) frames.forEach(testFrame) }) context('Quorum size equal to total members', () => { before(async () => { - await deploy({fastLaneLengthSlots: 10}) + await deploy({ fastLaneLengthSlots: 10 }) - await consensus.addMember(member1, 3, {from: admin}) - await consensus.addMember(member2, 3, {from: admin}) - await consensus.addMember(member3, 3, {from: admin}) + await consensus.addMember(member1, 3, { from: admin }) + await consensus.addMember(member2, 3, { from: admin }) + await consensus.addMember(member3, 3, { from: admin }) }) before(setTimeToFrame0) - const testFrame = (frameIndex) => context(`frame ${frameIndex}`, () => { - after(async () => { - await consensus.advanceTimeToNextFrameStart() - }) + const testFrame = (frameIndex) => + context(`frame ${frameIndex}`, () => { + after(async () => { + await consensus.advanceTimeToNextFrameStart() + }) - it(`all members are in the fast lane set`, async () => { - assert.isTrue(await consensus.getIsFastLaneMember(member1)) - assert.isTrue((await consensus.getConsensusStateForMember(member1)).isFastLane) + it(`all members are in the fast lane set`, async () => { + assert.isTrue(await consensus.getIsFastLaneMember(member1)) + assert.isTrue((await consensus.getConsensusStateForMember(member1)).isFastLane) - assert.isTrue(await consensus.getIsFastLaneMember(member2)) - assert.isTrue((await consensus.getConsensusStateForMember(member2)).isFastLane) + assert.isTrue(await consensus.getIsFastLaneMember(member2)) + assert.isTrue((await consensus.getConsensusStateForMember(member2)).isFastLane) - assert.isTrue(await consensus.getIsFastLaneMember(member3)) - assert.isTrue((await consensus.getConsensusStateForMember(member3)).isFastLane) + assert.isTrue(await consensus.getIsFastLaneMember(member3)) + assert.isTrue((await consensus.getConsensusStateForMember(member3)).isFastLane) - assert.sameMembers( - (await consensus.getFastLaneMembers()).addresses, - [member1, member2, member3] - ) + assert.sameMembers((await consensus.getFastLaneMembers()).addresses, [member1, member2, member3]) - assert.sameMembers( - (await consensus.getMembers()).addresses, - [member1, member2, member3] - ) - }) + assert.sameMembers((await consensus.getMembers()).addresses, [member1, member2, member3]) + }) - it('non-members are not in the fast lane set', async () => { - assert.isFalse(await consensus.getIsFastLaneMember(stranger)) - assert.isFalse((await consensus.getConsensusStateForMember(stranger)).isFastLane) + it('non-members are not in the fast lane set', async () => { + assert.isFalse(await consensus.getIsFastLaneMember(stranger)) + assert.isFalse((await consensus.getConsensusStateForMember(stranger)).isFastLane) + }) }) - }) - Array.from({length: 10}, (_, i) => i).forEach(testFrame) + Array.from({ length: 10 }, (_, i) => i).forEach(testFrame) }) }) }) diff --git a/test/0.8.9/oracle/hash-consensus-frames.js b/test/0.8.9/oracle/hash-consensus-frames.js index ec788d6e0..4fc6fdf80 100644 --- a/test/0.8.9/oracle/hash-consensus-frames.js +++ b/test/0.8.9/oracle/hash-consensus-frames.js @@ -16,7 +16,7 @@ const { ZERO_HASH, HASH_1, CONSENSUS_VERSION, - deployHashConsensus + deployHashConsensus, } = require('./hash-consensus-deploy.test') const getFrameIndex = (time, epochsPerFrame, initialEpoch) => diff --git a/test/0.8.9/oracle/hash-consensus-happy-path.test.js b/test/0.8.9/oracle/hash-consensus-happy-path.test.js index 188239d04..d65afe5b0 100644 --- a/test/0.8.9/oracle/hash-consensus-happy-path.test.js +++ b/test/0.8.9/oracle/hash-consensus-happy-path.test.js @@ -4,11 +4,27 @@ const { assertRevert } = require('../../helpers/assertThrow') const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') const { - SLOTS_PER_EPOCH, SECONDS_PER_SLOT, GENESIS_TIME, EPOCHS_PER_FRAME, SECONDS_PER_EPOCH, - SECONDS_PER_FRAME, SLOTS_PER_FRAME, computeSlotAt, computeEpochAt, computeEpochFirstSlotAt, - computeTimestampAtEpoch, computeTimestampAtSlot, - ZERO_HASH, HASH_1, HASH_2, HASH_3, HASH_4, HASH_5, CONSENSUS_VERSION, - deployHashConsensus } = require('./hash-consensus-deploy.test') + SLOTS_PER_EPOCH, + SECONDS_PER_SLOT, + GENESIS_TIME, + EPOCHS_PER_FRAME, + SECONDS_PER_EPOCH, + SECONDS_PER_FRAME, + SLOTS_PER_FRAME, + computeSlotAt, + computeEpochAt, + computeEpochFirstSlotAt, + computeTimestampAtEpoch, + computeTimestampAtSlot, + ZERO_HASH, + HASH_1, + HASH_2, + HASH_3, + HASH_4, + HASH_5, + CONSENSUS_VERSION, + deployHashConsensus, +} = require('./hash-consensus-deploy.test') const HashConsensus = artifacts.require('HashConsensusTimeTravellable') const MockReportProcessor = artifacts.require('MockReportProcessor') @@ -21,7 +37,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { const INITIAL_EPOCH = 3 it('deploying hash consensus', async () => { - const deployed = await deployHashConsensus(admin, {initialEpoch: INITIAL_EPOCH}) + const deployed = await deployHashConsensus(admin, { initialEpoch: INITIAL_EPOCH }) consensus = deployed.consensus reportProcessor = deployed.reportProcessor }) @@ -29,28 +45,28 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { it('adding members', async () => { await consensus.addMember(member1, 1, { from: admin }) assert.equal(await consensus.getIsMember(member1), true) - assert.equal(+await consensus.getQuorum(), 1) + assert.equal(+(await consensus.getQuorum()), 1) await consensus.addMember(member2, 2, { from: admin }) assert.equal(await consensus.getIsMember(member2), true) - assert.equal(+await consensus.getQuorum(), 2) + assert.equal(+(await consensus.getQuorum()), 2) await consensus.addMember(member3, 2, { from: admin }) assert.equal(await consensus.getIsMember(member3), true) - assert.equal(+await consensus.getQuorum(), 2) + assert.equal(+(await consensus.getQuorum()), 2) }) it('some fraction of the reporting frame passes', async () => { - assert.equal(+await consensus.getTime(), computeTimestampAtEpoch(INITIAL_EPOCH)) + assert.equal(+(await consensus.getTime()), computeTimestampAtEpoch(INITIAL_EPOCH)) await consensus.advanceTimeBySlots(3) - assert.equal(+await consensus.getTime(), computeTimestampAtEpoch(INITIAL_EPOCH) + 3 * SECONDS_PER_SLOT) + assert.equal(+(await consensus.getTime()), computeTimestampAtEpoch(INITIAL_EPOCH) + 3 * SECONDS_PER_SLOT) }) let frame it('reporting frame changes as more time passes', async () => { const frame1 = await consensus.getCurrentFrame() - const time = +await consensus.getTime() + const time = +(await consensus.getTime()) const expectedRefSlot = computeEpochFirstSlotAt(time) - 1 const expectedDeadlineSlot = expectedRefSlot + EPOCHS_PER_FRAME * SLOTS_PER_EPOCH @@ -221,7 +237,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { assert.equal(consensusState.consensusReport, ZERO_HASH) assert.isFalse(consensusState.isReportProcessing) - let checkMember = async (member) => { + const checkMember = async (member) => { const memberInfo = await consensus.getConsensusStateForMember(member) assert.equal(+memberInfo.currentFrameRefSlot, +newFrame.refSlot) assert.equal(memberInfo.currentFrameConsensusReport, ZERO_HASH) @@ -259,7 +275,9 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { it('first member votes for hash 2', async () => { const tx = await consensus.submitReport(newFrame.refSlot, HASH_2, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ReportReceived', { expectedArgs: { refSlot: newFrame.refSlot, member: member1, report: HASH_2 } }) + assertEvent(tx, 'ReportReceived', { + expectedArgs: { refSlot: newFrame.refSlot, member: member1, report: HASH_2 }, + }) assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) const memberInfo = await consensus.getConsensusStateForMember(member1) diff --git a/test/0.8.9/oracle/hash-consensus-members.test.js b/test/0.8.9/oracle/hash-consensus-members.test.js index 2eb434140..7008755ef 100644 --- a/test/0.8.9/oracle/hash-consensus-members.test.js +++ b/test/0.8.9/oracle/hash-consensus-members.test.js @@ -5,12 +5,28 @@ const { assertRevert } = require('../../helpers/assertThrow') const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') const { - SLOTS_PER_EPOCH, SECONDS_PER_SLOT, GENESIS_TIME, EPOCHS_PER_FRAME, - SECONDS_PER_EPOCH, SECONDS_PER_FRAME, SLOTS_PER_FRAME, - computeSlotAt, computeEpochAt, computeEpochFirstSlot, computeEpochFirstSlotAt, - computeTimestampAtSlot, computeTimestampAtEpoch, - ZERO_HASH, HASH_1, HASH_2, HASH_3, HASH_4, HASH_5, - CONSENSUS_VERSION, deployHashConsensus} = require('./hash-consensus-deploy.test') + SLOTS_PER_EPOCH, + SECONDS_PER_SLOT, + GENESIS_TIME, + EPOCHS_PER_FRAME, + SECONDS_PER_EPOCH, + SECONDS_PER_FRAME, + SLOTS_PER_FRAME, + computeSlotAt, + computeEpochAt, + computeEpochFirstSlot, + computeEpochFirstSlotAt, + computeTimestampAtSlot, + computeTimestampAtEpoch, + ZERO_HASH, + HASH_1, + HASH_2, + HASH_3, + HASH_4, + HASH_5, + CONSENSUS_VERSION, + deployHashConsensus, +} = require('./hash-consensus-deploy.test') const HashConsensus = artifacts.require('HashConsensusTimeTravellable') const MockReportProcessor = artifacts.require('MockReportProcessor') @@ -47,7 +63,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, }) it('quorum is zero', async () => { - assert.equal(+await consensus.getQuorum(), 0) + assert.equal(+(await consensus.getQuorum()), 0) }) }) @@ -56,16 +72,16 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, it('reverts if member address equals zero', async () => { await assert.revertsWithCustomError( - consensus.addMember(ZERO_ADDRESS, 1, {from: admin}), + consensus.addMember(ZERO_ADDRESS, 1, { from: admin }), 'AddressCannotBeZero()' ) }) it('allows to add a member, setting the new quorum', async () => { const newQuorum = 1 - const tx = await consensus.addMember(member1, newQuorum, {from: admin}) + const tx = await consensus.addMember(member1, newQuorum, { from: admin }) - assertEvent(tx, 'MemberAdded', {expectedArgs: {addr: member1, newTotalMembers: 1, newQuorum: 1}}) + assertEvent(tx, 'MemberAdded', { expectedArgs: { addr: member1, newTotalMembers: 1, newQuorum: 1 } }) assert.isTrue(await consensus.getIsMember(member1)) const membersInfo = await consensus.getMembers() @@ -78,44 +94,38 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, assert.equal(+member1Info.lastMemberReportRefSlot, 0) assert.equal(member1Info.currentFrameMemberReport, ZERO_HASH) - assert.equal(+await consensus.getQuorum(), 1) + assert.equal(+(await consensus.getQuorum()), 1) }) it(`doesn't allow to add the same member twice`, async () => { - await assertRevert( - consensus.addMember(member1, 2, {from: admin}), - 'DuplicateMember()' - ) + await assertRevert(consensus.addMember(member1, 2, { from: admin }), 'DuplicateMember()') }) it(`requires quorum to be more than half of the total members count`, async () => { - await assertRevert( - consensus.addMember(member2, 1, {from: admin}), - 'QuorumTooSmall(2, 1)' - ) + await assertRevert(consensus.addMember(member2, 1, { from: admin }), 'QuorumTooSmall(2, 1)') }) it(`allows setting the quorum more than total members count`, async () => { - const tx = await consensus.addMember(member2, 3, {from: admin}) - assertEvent(tx, 'MemberAdded', {expectedArgs: {addr: member2, newTotalMembers: 2, newQuorum: 3}}) + const tx = await consensus.addMember(member2, 3, { from: admin }) + assertEvent(tx, 'MemberAdded', { expectedArgs: { addr: member2, newTotalMembers: 2, newQuorum: 3 } }) assert.isTrue(await consensus.getIsMember(member2)) - assert.equal(+await consensus.getQuorum(), 3) + assert.equal(+(await consensus.getQuorum()), 3) }) it(`lowering the quorum while adding a member may trigger consensus`, async () => { - await consensus.addMember(member3, 3, {from: admin}) - await consensus.addMember(member4, 4, {from: admin}) + await consensus.addMember(member3, 3, { from: admin }) + await consensus.addMember(member4, 4, { from: admin }) - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member1}) - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member2}) - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member3}) + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member3 }) assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) - const tx = await consensus.addMember(member5, 3, {from: admin}) - assertEvent(tx, 'MemberAdded', {expectedArgs: {addr: member5, newTotalMembers: 5, newQuorum: 3}}) - assertEvent(tx, 'ConsensusReached', {expectedArgs: {refSlot, report: HASH_1, support: 3}}) + const tx = await consensus.addMember(member5, 3, { from: admin }) + assertEvent(tx, 'MemberAdded', { expectedArgs: { addr: member5, newTotalMembers: 5, newQuorum: 3 } }) + assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 3 } }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) }) }) @@ -124,11 +134,11 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, beforeEach(deploy) beforeEach(async () => { - await consensus.addMember(member1, 4, {from: admin}) - await consensus.addMember(member2, 4, {from: admin}) - await consensus.addMember(member3, 4, {from: admin}) - await consensus.addMember(member4, 4, {from: admin}) - await consensus.addMember(member5, 4, {from: admin}) + await consensus.addMember(member1, 4, { from: admin }) + await consensus.addMember(member2, 4, { from: admin }) + await consensus.addMember(member3, 4, { from: admin }) + await consensus.addMember(member4, 4, { from: admin }) + await consensus.addMember(member5, 4, { from: admin }) const membersInfo = await consensus.getMembers() assert.sameMembers(membersInfo.addresses, [member1, member2, member3, member4, member5]) @@ -136,11 +146,11 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, }) it('removes a member, setting the new quorum', async () => { - tx = await consensus.removeMember(member1, 3, {from: admin}) + tx = await consensus.removeMember(member1, 3, { from: admin }) - assertEvent(tx, 'MemberRemoved', {expectedArgs: {addr: member1, newTotalMembers: 4, newQuorum: 3}}) + assertEvent(tx, 'MemberRemoved', { expectedArgs: { addr: member1, newTotalMembers: 4, newQuorum: 3 } }) assert.isFalse(await consensus.getIsMember(member1)) - assert.equal(+await consensus.getQuorum(), 3) + assert.equal(+(await consensus.getQuorum()), 3) const member1Info = await consensus.getConsensusStateForMember(member1) assert.isFalse(member1Info.isMember) @@ -149,52 +159,46 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, }) it(`doesn't allow removing a non-member`, async () => { - await assertRevert( - consensus.removeMember(stranger, 4, {from: admin}), - 'NonMember()' - ) + await assertRevert(consensus.removeMember(stranger, 4, { from: admin }), 'NonMember()') }) it(`doesn't allow removing an already removed member`, async () => { - await consensus.removeMember(member1, 4, {from: admin}) - await assertRevert( - consensus.removeMember(member1, 4, {from: admin}), - 'NonMember()' - ) + await consensus.removeMember(member1, 4, { from: admin }) + await assertRevert(consensus.removeMember(member1, 4, { from: admin }), 'NonMember()') }) it('allows removing all members', async () => { - await consensus.removeMember(member1, 3, {from: admin}) + await consensus.removeMember(member1, 3, { from: admin }) assert.sameMembers((await consensus.getMembers()).addresses, [member2, member3, member4, member5]) - assert.equal(+await consensus.getQuorum(), 3) + assert.equal(+(await consensus.getQuorum()), 3) - await consensus.removeMember(member3, 2, {from: admin}) + await consensus.removeMember(member3, 2, { from: admin }) assert.sameMembers((await consensus.getMembers()).addresses, [member2, member4, member5]) - assert.equal(+await consensus.getQuorum(), 2) + assert.equal(+(await consensus.getQuorum()), 2) - await consensus.removeMember(member4, 2, {from: admin}) + await consensus.removeMember(member4, 2, { from: admin }) assert.sameMembers((await consensus.getMembers()).addresses, [member2, member5]) - assert.equal(+await consensus.getQuorum(), 2) + assert.equal(+(await consensus.getQuorum()), 2) - await consensus.removeMember(member5, 1, {from: admin}) + await consensus.removeMember(member5, 1, { from: admin }) assert.sameMembers((await consensus.getMembers()).addresses, [member2]) - assert.equal(+await consensus.getQuorum(), 1) + assert.equal(+(await consensus.getQuorum()), 1) - await consensus.removeMember(member2, 1, {from: admin}) + await consensus.removeMember(member2, 1, { from: admin }) assert.isEmpty((await consensus.getMembers()).addresses) - assert.equal(+await consensus.getQuorum(), 1) + assert.equal(+(await consensus.getQuorum()), 1) }) it(`removing a member who didn't vote doesn't decrease any report variant's support`, async () => { - const {refSlot} = await consensus.getCurrentFrame() - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member1}) - await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member4}) + const { refSlot } = await consensus.getCurrentFrame() + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) + await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member4 }) let reportVariants = await consensus.getReportVariants() assert.sameOrderedMembers(reportVariants.variants, [HASH_1, HASH_2]) assert.sameOrderedMembers(reportVariants.support.map(toNum), [1, 1]) - await consensus.removeMember(member2, 3, {from: admin}) + await consensus.removeMember(member2, 3, { from: admin }) reportVariants = await consensus.getReportVariants() assert.sameOrderedMembers(reportVariants.variants, [HASH_1, HASH_2]) @@ -202,33 +206,33 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, }) it(`removing a member who didn't vote can trigger consensus`, async () => { - const {refSlot} = await consensus.getCurrentFrame() - await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member1}) - await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member3}) - await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member4}) + const { refSlot } = await consensus.getCurrentFrame() + await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member1 }) + await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member3 }) + await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member4 }) - let reportVariants = await consensus.getReportVariants() + const reportVariants = await consensus.getReportVariants() assert.sameOrderedMembers(reportVariants.variants, [HASH_2]) assert.sameOrderedMembers(reportVariants.support.map(toNum), [3]) - tx = await consensus.removeMember(member2, 3, {from: admin}) + tx = await consensus.removeMember(member2, 3, { from: admin }) - assertEvent(tx, 'ConsensusReached', {expectedArgs: {refSlot, report: HASH_2, support: 3}}) + assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_2, support: 3 } }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_2) }) it(`removing a member who voted decreases the voted variant's support`, async () => { - const {refSlot} = await consensus.getCurrentFrame() - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member1}) - await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member2}) - await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member4}) - await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member5}) + const { refSlot } = await consensus.getCurrentFrame() + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) + await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member2 }) + await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member4 }) + await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member5 }) let reportVariants = await consensus.getReportVariants() assert.sameOrderedMembers(reportVariants.variants, [HASH_1, HASH_2]) assert.sameOrderedMembers(reportVariants.support.map(toNum), [1, 3]) - await consensus.removeMember(member2, 3, {from: admin}) + await consensus.removeMember(member2, 3, { from: admin }) reportVariants = await consensus.getReportVariants() assert.sameOrderedMembers(reportVariants.variants, [HASH_1, HASH_2]) @@ -238,10 +242,10 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, }) it(`allows to remove a member that's the only one who voted for a variant`, async () => { - const {refSlot} = await consensus.getCurrentFrame() - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member1}) + const { refSlot } = await consensus.getCurrentFrame() + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - await consensus.removeMember(member1, 3, {from: admin}) + await consensus.removeMember(member1, 3, { from: admin }) reportVariants = await consensus.getReportVariants() assert.sameOrderedMembers(reportVariants.variants, [HASH_1]) @@ -253,132 +257,132 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, beforeEach(deploy) it(`scenario 1`, async () => { - await consensus.addMember(member1, 1, {from: admin}) - await consensus.addMember(member2, 2, {from: admin}) + await consensus.addMember(member1, 1, { from: admin }) + await consensus.addMember(member2, 2, { from: admin }) - const {refSlot} = await consensus.getCurrentFrame() - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member2}) - let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member1}) + const { refSlot } = await consensus.getCurrentFrame() + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) + let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ConsensusReached', {expectedArgs: {refSlot, report: HASH_1, support: 2}}) + assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 2 } }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) - tx = await consensus.addMember(member3, 3, {from: admin}) - assertAmountOfEvents(tx, 'ConsensusReached', {expectedAmount: 0}) + tx = await consensus.addMember(member3, 3, { from: admin }) + assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) - tx = await consensus.removeMember(member3, 2, {from: admin}) - assertAmountOfEvents(tx, 'ConsensusReached', {expectedAmount: 0}) + tx = await consensus.removeMember(member3, 2, { from: admin }) + assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) }) it(`scenario 2`, async () => { - await consensus.addMember(member1, 1, {from: admin}) - await consensus.addMember(member2, 2, {from: admin}) + await consensus.addMember(member1, 1, { from: admin }) + await consensus.addMember(member2, 2, { from: admin }) - const {refSlot} = await consensus.getCurrentFrame() - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member2}) - let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member1}) + const { refSlot } = await consensus.getCurrentFrame() + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) + let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ConsensusReached', {expectedArgs: {refSlot, report: HASH_1, support: 2}}) + assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 2 } }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) - tx = await consensus.addMember(member3, 2, {from: admin}) - assertAmountOfEvents(tx, 'ConsensusReached', {expectedAmount: 0}) + tx = await consensus.addMember(member3, 2, { from: admin }) + assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) - tx = await consensus.removeMember(member3, 2, {from: admin}) - assertAmountOfEvents(tx, 'ConsensusReached', {expectedAmount: 0}) + tx = await consensus.removeMember(member3, 2, { from: admin }) + assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) }) it(`scenario 3`, async () => { - await consensus.addMember(member1, 1, {from: admin}) - await consensus.addMember(member2, 2, {from: admin}) + await consensus.addMember(member1, 1, { from: admin }) + await consensus.addMember(member2, 2, { from: admin }) - const {refSlot} = await consensus.getCurrentFrame() - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member2}) - let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member1}) + const { refSlot } = await consensus.getCurrentFrame() + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) + let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ConsensusReached', {expectedArgs: {refSlot, report: HASH_1, support: 2}}) + assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 2 } }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) - tx = await consensus.addMember(member3, 3, {from: admin}) - assertAmountOfEvents(tx, 'ConsensusReached', {expectedAmount: 0}) + tx = await consensus.addMember(member3, 3, { from: admin }) + assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) // TODO: is this really ok? assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) - tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member3}) - assertAmountOfEvents(tx, 'ConsensusReached', {expectedAmount: 0}) + tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member3 }) + assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) - tx = await consensus.removeMember(member3, 2, {from: admin}) - assertAmountOfEvents(tx, 'ConsensusReached', {expectedAmount: 0}) + tx = await consensus.removeMember(member3, 2, { from: admin }) + assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) }) it(`scenario 4`, async () => { - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() - await consensus.addMember(member1, 1, {from: admin}) - await consensus.addMember(member2, 2, {from: admin}) - await consensus.addMember(member3, 2, {from: admin}) + await consensus.addMember(member1, 1, { from: admin }) + await consensus.addMember(member2, 2, { from: admin }) + await consensus.addMember(member3, 2, { from: admin }) - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member1}) - let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member2}) + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) + let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) - assertEvent(tx, 'ConsensusReached', {expectedArgs: {refSlot, report: HASH_1, support: 2}}) + assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 2 } }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) - tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member3}) - assertAmountOfEvents(tx, 'ConsensusReached', {expectedAmount: 0}) + tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member3 }) + assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) - await consensus.addMember(member4, 3, {from: admin}) + await consensus.addMember(member4, 3, { from: admin }) assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) - await consensus.addMember(member5, 3, {from: admin}) + await consensus.addMember(member5, 3, { from: admin }) assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) - await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member4}) + await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member4 }) assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) - tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member5}) - assertEvent(tx, 'ConsensusReached', {expectedArgs: {refSlot, report: HASH_2, support: 3}}) + tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member5 }) + assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_2, support: 3 } }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_2) }) it(`scenario 5`, async () => { - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() - await consensus.addMember(member1, 1, {from: admin}) - await consensus.addMember(member2, 2, {from: admin}) - await consensus.addMember(member3, 2, {from: admin}) + await consensus.addMember(member1, 1, { from: admin }) + await consensus.addMember(member2, 2, { from: admin }) + await consensus.addMember(member3, 2, { from: admin }) - await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member1}) - let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, {from: member2}) + await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) + let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) - assertEvent(tx, 'ConsensusReached', {expectedArgs: {refSlot, report: HASH_1, support: 2}}) + assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 2 } }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) - tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member3}) - assertAmountOfEvents(tx, 'ConsensusReached', {expectedAmount: 0}) + tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member3 }) + assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) - await consensus.addMember(member4, 3, {from: admin}) + await consensus.addMember(member4, 3, { from: admin }) assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) - await consensus.addMember(member5, 4, {from: admin}) + await consensus.addMember(member5, 4, { from: admin }) assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) - await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member4}) + await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member4 }) assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) - tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, {from: member5}) + tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member5 }) assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) - tx = await consensus.removeMember(member2, 3, {from: admin}) - assertEvent(tx, 'ConsensusReached', {expectedArgs: {refSlot, report: HASH_2, support: 3}}) + tx = await consensus.removeMember(member2, 3, { from: admin }) + assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_2, support: 3 } }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_2) }) }) diff --git a/test/0.8.9/oracle/hash-consensus-report-processor.test.js b/test/0.8.9/oracle/hash-consensus-report-processor.test.js index 982ad4b72..89fd55353 100644 --- a/test/0.8.9/oracle/hash-consensus-report-processor.test.js +++ b/test/0.8.9/oracle/hash-consensus-report-processor.test.js @@ -1,11 +1,7 @@ const { assert } = require('../../helpers/assert') const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') -const { - HASH_1, - CONSENSUS_VERSION, - deployHashConsensus, -} = require('./hash-consensus-deploy.test') +const { HASH_1, CONSENSUS_VERSION, deployHashConsensus } = require('./hash-consensus-deploy.test') const { toNum } = require('../../helpers/utils') const HashConsensus = artifacts.require('HashConsensusTimeTravellable') @@ -55,7 +51,7 @@ contract('HashConsensus', ([admin, member1, member2, stranger]) => { const tx = await consensus.setReportProcessor(reportProcessor2.address) assert.emits(tx, 'ReportProcessorSet', { processor: reportProcessor2.address, - prevProcessor: reportProcessor1.address + prevProcessor: reportProcessor1.address, }) }) diff --git a/test/0.8.9/oracle/hash-consensus-set-quorum.js b/test/0.8.9/oracle/hash-consensus-set-quorum.js index 2a14c2d05..f49459cd9 100644 --- a/test/0.8.9/oracle/hash-consensus-set-quorum.js +++ b/test/0.8.9/oracle/hash-consensus-set-quorum.js @@ -14,7 +14,7 @@ const { HASH_1, HASH_3, CONSENSUS_VERSION, - deployHashConsensus + deployHashConsensus, } = require('./hash-consensus-deploy.test') contract('HashConsensus', ([admin, member1, member2, member3]) => { @@ -96,7 +96,7 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { it('disableConsensus updated quorum value and emits events', async () => { const tx = await consensus.disableConsensus() assertEvent(tx, 'QuorumSet', { - expectedArgs: { newQuorum: UNREACHABLE_QUORUM.toString(10), totalMembers: 0, prevQuorum: 0 } + expectedArgs: { newQuorum: UNREACHABLE_QUORUM.toString(10), totalMembers: 0, prevQuorum: 0 }, }) assertBn(await consensus.getQuorum(), UNREACHABLE_QUORUM) }) @@ -126,12 +126,12 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { await consensus.setQuorum(2) const tx1 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) assertEvent(tx1, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 } + expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 }, }) assertAmountOfEvents(tx1, 'ConsensusReached', { expectedAmount: 0 }) const tx2 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) assertEvent(tx2, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 } + expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 }, }) assertAmountOfEvents(tx2, 'ConsensusReached', { expectedAmount: 1 }) assert.equal(+(await reportProcessor.getLastCall_submitReport()).callCount, 1) @@ -159,13 +159,13 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { it('2/3 reports come in', async () => { const tx1 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) assertEvent(tx1, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 } + expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 }, }) assertAmountOfEvents(tx1, 'ConsensusReached', { expectedAmount: 0 }) const tx2 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) assertEvent(tx2, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 } + expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 }, }) assertAmountOfEvents(tx2, 'ConsensusReached', { expectedAmount: 0 }) }) @@ -185,13 +185,13 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { await consensus.setQuorum(2) const tx1 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) assertEvent(tx1, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 } + expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 }, }) assertAmountOfEvents(tx1, 'ConsensusReached', { expectedAmount: 0 }) const tx2 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) assertEvent(tx2, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 } + expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 }, }) assertAmountOfEvents(tx2, 'ConsensusReached', { expectedAmount: 1 }) assert.equal(+(await reportProcessor.getLastCall_submitReport()).callCount, 1) @@ -223,13 +223,13 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { await consensus.setQuorum(2) const tx1 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) assertEvent(tx1, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 } + expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 }, }) assertAmountOfEvents(tx1, 'ConsensusReached', { expectedAmount: 0 }) const tx2 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) assertEvent(tx2, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 } + expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 }, }) assertAmountOfEvents(tx2, 'ConsensusReached', { expectedAmount: 1 }) }) diff --git a/test/0.8.9/oracle/validators-exit-bus-oracle-access-control.test.js b/test/0.8.9/oracle/validators-exit-bus-oracle-access-control.test.js index 684e59a81..ba7e0a1f4 100644 --- a/test/0.8.9/oracle/validators-exit-bus-oracle-access-control.test.js +++ b/test/0.8.9/oracle/validators-exit-bus-oracle-access-control.test.js @@ -7,12 +7,12 @@ const { getReportDataItems, calcReportDataHash, encodeExitRequestsDataList, - deployExitBusOracle + deployExitBusOracle, } = require('./validators-exit-bus-oracle-deploy.test') const PUBKEYS = [ '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', - '0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' + '0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', ] contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, account1, stranger]) => { @@ -32,7 +32,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, account1 const getReportFields = (override = {}) => ({ consensusVersion: CONSENSUS_VERSION, dataFormat: DATA_FORMAT_LIST, - ...override + ...override, }) const deploy = async () => { const deployed = await deployExitBusOracle(admin, { resumeAfterDeploy: true }) @@ -50,13 +50,13 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, account1 exitRequests = [ { moduleId: 1, nodeOpId: 0, valIndex: 0, valPubkey: PUBKEYS[0] }, { moduleId: 1, nodeOpId: 0, valIndex: 2, valPubkey: PUBKEYS[1] }, - { moduleId: 2, nodeOpId: 0, valIndex: 1, valPubkey: PUBKEYS[2] } + { moduleId: 2, nodeOpId: 0, valIndex: 1, valPubkey: PUBKEYS[2] }, ] reportFields = getReportFields({ refSlot: +refSlot, requestsCount: exitRequests.length, - data: encodeExitRequestsDataList(exitRequests) + data: encodeExitRequestsDataList(exitRequests), }) reportItems = getReportDataItems(reportFields) @@ -95,7 +95,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, account1 const resumer = ZERO_ADDRESS await assert.reverts( oracle.initialize(ZERO_ADDRESS, pauser, resumer, consensus.address, CONSENSUS_VERSION, 0, { - from: admin + from: admin, }), 'AdminCannotBeZero()' ) diff --git a/test/0.8.9/oracle/validators-exit-bus-oracle-deploy.test.js b/test/0.8.9/oracle/validators-exit-bus-oracle-deploy.test.js index 35148c5b7..d8a2f3050 100644 --- a/test/0.8.9/oracle/validators-exit-bus-oracle-deploy.test.js +++ b/test/0.8.9/oracle/validators-exit-bus-oracle-deploy.test.js @@ -3,7 +3,7 @@ const { hex, strip0x } = require('../../helpers/utils') const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') const { updateLocatorImplementation, - deployLocatorWithDummyAddressesImplementation + deployLocatorWithDummyAddressesImplementation, } = require('../../helpers/locator-deploy') const { @@ -19,7 +19,7 @@ const { computeTimestampAtEpoch, ZERO_HASH, CONSENSUS_VERSION, - deployHashConsensus + deployHashConsensus, } = require('./hash-consensus-deploy.test') const ValidatorsExitBusOracle = artifacts.require('ValidatorsExitBusTimeTravellable') @@ -76,7 +76,7 @@ module.exports = { encodeExitRequestHex, encodeExitRequestsDataList, deployExitBusOracle, - deployOracleReportSanityCheckerForExitBus + deployOracleReportSanityCheckerForExitBus, } async function deployOracleReportSanityCheckerForExitBus(lidoLocator, admin) { const maxValidatorExitRequestsPerReport = 2000 @@ -91,7 +91,7 @@ async function deployOracleReportSanityCheckerForExitBus(lidoLocator, admin) { limitsList, managersRoster, { - from: admin + from: admin, } ) return oracleReportSanityChecker @@ -104,7 +104,7 @@ async function deployExitBusOracle( lastProcessingRefSlot = 0, resumeAfterDeploy = false, pauser = ZERO_ADDRESS, - resumer = ZERO_ADDRESS + resumer = ZERO_ADDRESS, } = {} ) { const locator = (await deployLocatorWithDummyAddressesImplementation(admin)).address @@ -113,13 +113,13 @@ async function deployExitBusOracle( const { consensus } = await deployHashConsensus(admin, { epochsPerFrame: EPOCHS_PER_FRAME, - reportProcessor: oracle + reportProcessor: oracle, }) const oracleReportSanityChecker = await deployOracleReportSanityCheckerForExitBus(locator, admin) await updateLocatorImplementation(locator, admin, { validatorsExitBusOracle: oracle.address, - oracleReportSanityChecker: oracleReportSanityChecker.address + oracleReportSanityChecker: oracleReportSanityChecker.address, }) const initTx = await oracle.initialize( @@ -137,12 +137,12 @@ async function deployExitBusOracle( assert.emits(initTx, 'RoleGranted', { role: await consensus.DEFAULT_ADMIN_ROLE(), account: admin, - sender: admin + sender: admin, }) assert.emits(initTx, 'ConsensusHashContractSet', { addr: consensus.address, - prevAddr: ZERO_ADDRESS + prevAddr: ZERO_ADDRESS, }) assert.emits(initTx, 'ConsensusVersionSet', { version: CONSENSUS_VERSION, prevVersion: 0 }) diff --git a/test/0.8.9/oracle/validators-exit-bus-oracle-gas.test.js b/test/0.8.9/oracle/validators-exit-bus-oracle-gas.test.js index 9478f9008..83f850e15 100644 --- a/test/0.8.9/oracle/validators-exit-bus-oracle-gas.test.js +++ b/test/0.8.9/oracle/validators-exit-bus-oracle-gas.test.js @@ -6,18 +6,35 @@ const { toNum, processNamedTuple } = require('../../helpers/utils') const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') const { - SLOTS_PER_EPOCH, SECONDS_PER_SLOT, GENESIS_TIME, SECONDS_PER_EPOCH, - EPOCHS_PER_FRAME, SLOTS_PER_FRAME, SECONDS_PER_FRAME, - MAX_REQUESTS_PER_REPORT, MAX_REQUESTS_LIST_LENGTH, - MAX_REQUESTS_PER_DAY, RATE_LIMIT_WINDOW_SLOTS, RATE_LIMIT_THROUGHPUT, - computeSlotAt, computeEpochAt, computeEpochFirstSlotAt, - computeEpochFirstSlot, computeTimestampAtSlot, computeTimestampAtEpoch, - ZERO_HASH, CONSENSUS_VERSION, DATA_FORMAT_LIST, getReportDataItems, calcReportDataHash, - encodeExitRequestHex, encodeExitRequestsDataList, deployExitBusOracle, + SLOTS_PER_EPOCH, + SECONDS_PER_SLOT, + GENESIS_TIME, + SECONDS_PER_EPOCH, + EPOCHS_PER_FRAME, + SLOTS_PER_FRAME, + SECONDS_PER_FRAME, + MAX_REQUESTS_PER_REPORT, + MAX_REQUESTS_LIST_LENGTH, + MAX_REQUESTS_PER_DAY, + RATE_LIMIT_WINDOW_SLOTS, + RATE_LIMIT_THROUGHPUT, + computeSlotAt, + computeEpochAt, + computeEpochFirstSlotAt, + computeEpochFirstSlot, + computeTimestampAtSlot, + computeTimestampAtEpoch, + ZERO_HASH, + CONSENSUS_VERSION, + DATA_FORMAT_LIST, + getReportDataItems, + calcReportDataHash, + encodeExitRequestHex, + encodeExitRequestsDataList, + deployExitBusOracle, deployOracleReportSanityCheckerForExitBus, } = require('./validators-exit-bus-oracle-deploy.test') - const PUBKEYS = [ '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', @@ -26,28 +43,26 @@ const PUBKEYS = [ '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', ] - contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger]) => { - context('Gas test', () => { let consensus let oracle let oracleVersion before(async () => { - const deployed = await deployExitBusOracle(admin, {resumeAfterDeploy: true}) + const deployed = await deployExitBusOracle(admin, { resumeAfterDeploy: true }) consensus = deployed.consensus oracle = deployed.oracle - oracleVersion = +await oracle.getContractVersion() + oracleVersion = +(await oracle.getContractVersion()) - await consensus.addMember(member1, 1, {from: admin}) - await consensus.addMember(member2, 2, {from: admin}) - await consensus.addMember(member3, 2, {from: admin}) + await consensus.addMember(member1, 1, { from: admin }) + await consensus.addMember(member2, 2, { from: admin }) + await consensus.addMember(member3, 2, { from: admin }) }) async function triggerConsensusOnHash(hash) { - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() await consensus.submitReport(refSlot, hash, CONSENSUS_VERSION, { from: member1 }) await consensus.submitReport(refSlot, hash, CONSENSUS_VERSION, { from: member3 }) assert.equal((await consensus.getConsensusState()).consensusReport, hash) @@ -69,25 +84,26 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const nodeOpId = Math.floor((i - moduleId * requestsPerModule) / requestsPerNodeOp) const valIndex = nextValIndex++ const valPubkey = PUBKEYS[valIndex % PUBKEYS.length] - requests.push({moduleId: moduleId + 1, nodeOpId, valIndex, valPubkey}) + requests.push({ moduleId: moduleId + 1, nodeOpId, valIndex, valPubkey }) } - return {requests, requestsPerModule, requestsPerNodeOp} + return { requests, requestsPerModule, requestsPerNodeOp } } // pre-heating testGas(NUM_MODULES * NODE_OPS_PER_MODULE, () => {}) - const gasUsages = []; - [10, 50, 100, 1000, 2000].forEach(n => testGas(n, r => gasUsages.push(r))) + const gasUsages = [] + ;[10, 50, 100, 1000, 2000].forEach((n) => testGas(n, (r) => gasUsages.push(r))) after(async () => { - gasUsages.forEach(({totalRequests, requestsPerModule, requestsPerNodeOp, gasUsed}) => + gasUsages.forEach(({ totalRequests, requestsPerModule, requestsPerNodeOp, gasUsed }) => console.log( `${totalRequests} requests (per module ${requestsPerModule}, ` + - `per node op ${requestsPerNodeOp}): total gas ${gasUsed}, ` + - `gas per request: ${Math.round(gasUsed / totalRequests)}` - )) + `per node op ${requestsPerNodeOp}): total gas ${gasUsed}, ` + + `gas per request: ${Math.round(gasUsed / totalRequests)}` + ) + ) }) function testGas(totalRequests, reportGas) { @@ -97,9 +113,8 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger let reportHash describe(`Total requests: ${totalRequests}`, () => { - it('initially, consensus report is not being processed', async () => { - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() const report = await oracle.getConsensusReport() assert.isAbove(+refSlot, +report.refSlot) @@ -110,7 +125,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger }) it('committee reaches consensus on a report hash', async () => { - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() exitRequests = generateExitRequests(totalRequests) @@ -132,10 +147,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const report = await oracle.getConsensusReport() assert.equal(report.hash, reportHash) assert.equal(+report.refSlot, +reportFields.refSlot) - assert.equal( - +report.processingDeadlineTime, - computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME) - ) + assert.equal(+report.processingDeadlineTime, computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME)) assert.isFalse(report.processingStarted) const procState = await oracle.getProcessingState() @@ -151,25 +163,28 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger }) it(`a committee member submits the report data, exit requests are emitted`, async () => { - const tx = await oracle.submitReportData(reportItems, oracleVersion, {from: member1}) - assertEvent(tx, 'ProcessingStarted', {expectedArgs: {refSlot: reportFields.refSlot}}) + const tx = await oracle.submitReportData(reportItems, oracleVersion, { from: member1 }) + assertEvent(tx, 'ProcessingStarted', { expectedArgs: { refSlot: reportFields.refSlot } }) assert.isTrue((await oracle.getConsensusReport()).processingStarted) const timestamp = await oracle.getTime() - const {requests, requestsPerModule, requestsPerNodeOp} = exitRequests + const { requests, requestsPerModule, requestsPerNodeOp } = exitRequests for (let i = 0; i < requests.length; ++i) { - assertEvent(tx, 'ValidatorExitRequest', {index: i, expectedArgs: { - stakingModuleId: requests[i].moduleId, - nodeOperatorId: requests[i].nodeOpId, - validatorIndex: requests[i].valIndex, - validatorPubkey: requests[i].valPubkey, - timestamp - }}) + assertEvent(tx, 'ValidatorExitRequest', { + index: i, + expectedArgs: { + stakingModuleId: requests[i].moduleId, + nodeOperatorId: requests[i].nodeOpId, + validatorIndex: requests[i].valIndex, + validatorPubkey: requests[i].valPubkey, + timestamp, + }, + }) } - const {gasUsed} = tx.receipt - reportGas({totalRequests, requestsPerModule, requestsPerNodeOp, gasUsed}) + const { gasUsed } = tx.receipt + reportGas({ totalRequests, requestsPerModule, requestsPerNodeOp, gasUsed }) }) it(`reports are marked as processed`, async () => { diff --git a/test/0.8.9/oracle/validators-exit-bus-oracle-happy-path.test.js b/test/0.8.9/oracle/validators-exit-bus-oracle-happy-path.test.js index 9aa1f7fbc..9eeb4228d 100644 --- a/test/0.8.9/oracle/validators-exit-bus-oracle-happy-path.test.js +++ b/test/0.8.9/oracle/validators-exit-bus-oracle-happy-path.test.js @@ -6,17 +6,34 @@ const { toNum } = require('../../helpers/utils') const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') const { - SLOTS_PER_EPOCH, SECONDS_PER_SLOT, GENESIS_TIME, SECONDS_PER_EPOCH, - EPOCHS_PER_FRAME, SLOTS_PER_FRAME, SECONDS_PER_FRAME, - MAX_REQUESTS_PER_REPORT, MAX_REQUESTS_LIST_LENGTH, - MAX_REQUESTS_PER_DAY, RATE_LIMIT_WINDOW_SLOTS, RATE_LIMIT_THROUGHPUT, - computeSlotAt, computeEpochAt, computeEpochFirstSlotAt, - computeEpochFirstSlot, computeTimestampAtSlot, computeTimestampAtEpoch, - ZERO_HASH, CONSENSUS_VERSION, DATA_FORMAT_LIST, getReportDataItems, calcReportDataHash, - encodeExitRequestHex, encodeExitRequestsDataList, deployExitBusOracle, + SLOTS_PER_EPOCH, + SECONDS_PER_SLOT, + GENESIS_TIME, + SECONDS_PER_EPOCH, + EPOCHS_PER_FRAME, + SLOTS_PER_FRAME, + SECONDS_PER_FRAME, + MAX_REQUESTS_PER_REPORT, + MAX_REQUESTS_LIST_LENGTH, + MAX_REQUESTS_PER_DAY, + RATE_LIMIT_WINDOW_SLOTS, + RATE_LIMIT_THROUGHPUT, + computeSlotAt, + computeEpochAt, + computeEpochFirstSlotAt, + computeEpochFirstSlot, + computeTimestampAtSlot, + computeTimestampAtEpoch, + ZERO_HASH, + CONSENSUS_VERSION, + DATA_FORMAT_LIST, + getReportDataItems, + calcReportDataHash, + encodeExitRequestHex, + encodeExitRequestsDataList, + deployExitBusOracle, } = require('./validators-exit-bus-oracle-deploy.test') - const PUBKEYS = [ '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', @@ -26,7 +43,6 @@ const PUBKEYS = [ ] contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger]) => { - context('Happy path', () => { const LAST_PROCESSING_REF_SLOT = 1 @@ -42,21 +58,21 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger before(async () => { const deployed = await deployExitBusOracle(admin, { lastProcessingRefSlot: LAST_PROCESSING_REF_SLOT, - resumeAfterDeploy: true + resumeAfterDeploy: true, }) consensus = deployed.consensus oracle = deployed.oracle - oracleVersion = +await oracle.getContractVersion() + oracleVersion = +(await oracle.getContractVersion()) - await consensus.addMember(member1, 1, {from: admin}) - await consensus.addMember(member2, 2, {from: admin}) - await consensus.addMember(member3, 2, {from: admin}) + await consensus.addMember(member1, 1, { from: admin }) + await consensus.addMember(member2, 2, { from: admin }) + await consensus.addMember(member3, 2, { from: admin }) }) async function triggerConsensusOnHash(hash) { - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() await consensus.submitReport(refSlot, hash, CONSENSUS_VERSION, { from: member1 }) await consensus.submitReport(refSlot, hash, CONSENSUS_VERSION, { from: member3 }) assert.equal((await consensus.getConsensusState()).consensusReport, hash) @@ -81,20 +97,22 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger assert.equal(+procState.requestsSubmitted, 0) }) - it(`reference slot of the empty initial consensus report is set to the last processing slot ` + - `passed to the initialize function`, async () => - { - const report = await oracle.getConsensusReport() - assert.equal(+report.refSlot, LAST_PROCESSING_REF_SLOT) - }) + it( + `reference slot of the empty initial consensus report is set to the last processing slot ` + + `passed to the initialize function`, + async () => { + const report = await oracle.getConsensusReport() + assert.equal(+report.refSlot, LAST_PROCESSING_REF_SLOT) + } + ) it('committee reaches consensus on a report hash', async () => { - const {refSlot} = await consensus.getCurrentFrame() + const { refSlot } = await consensus.getCurrentFrame() exitRequests = [ - {moduleId: 1, nodeOpId: 0, valIndex: 0, valPubkey: PUBKEYS[0] }, - {moduleId: 1, nodeOpId: 0, valIndex: 2, valPubkey: PUBKEYS[1] }, - {moduleId: 2, nodeOpId: 0, valIndex: 1, valPubkey: PUBKEYS[2] }, + { moduleId: 1, nodeOpId: 0, valIndex: 0, valPubkey: PUBKEYS[0] }, + { moduleId: 1, nodeOpId: 0, valIndex: 2, valPubkey: PUBKEYS[1] }, + { moduleId: 2, nodeOpId: 0, valIndex: 1, valPubkey: PUBKEYS[2] }, ] reportFields = { @@ -115,10 +133,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const report = await oracle.getConsensusReport() assert.equal(report.hash, reportHash) assert.equal(+report.refSlot, +reportFields.refSlot) - assert.equal( - +report.processingDeadlineTime, - computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME) - ) + assert.equal(+report.processingDeadlineTime, computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME)) assert.isFalse(report.processingStarted) const frame = await consensus.getCurrentFrame() @@ -126,10 +141,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger assert.equal(procState.currentFrameRefSlot, +frame.refSlot) assert.equal(procState.dataHash, reportHash) - assert.equal( - procState.processingDeadlineTime, - computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot) - ) + assert.equal(procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.isFalse(procState.dataSubmitted) assert.equal(+procState.dataFormat, 0) assert.equal(+procState.requestsCount, 0) @@ -141,15 +153,12 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger }) it('non-member cannot submit the data', async () => { - await assertRevert( - oracle.submitReportData(reportItems, oracleVersion, {from: stranger}), - 'SenderNotAllowed()' - ) + await assertRevert(oracle.submitReportData(reportItems, oracleVersion, { from: stranger }), 'SenderNotAllowed()') }) it('the data cannot be submitted passing a different contract version', async () => { await assertRevert( - oracle.submitReportData(reportItems, oracleVersion - 1, {from: member1}), + oracle.submitReportData(reportItems, oracleVersion - 1, { from: member1 }), `UnexpectedContractVersion(${oracleVersion}, ${oracleVersion - 1})` ) }) @@ -158,7 +167,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const invalidReport = { ...reportFields, consensusVersion: CONSENSUS_VERSION + 1 } const invalidReportItems = getReportDataItems(invalidReport) await assertRevert( - oracle.submitReportData(invalidReport, oracleVersion, {from: member1}), + oracle.submitReportData(invalidReport, oracleVersion, { from: member1 }), `UnexpectedConsensusVersion(${CONSENSUS_VERSION}, ${CONSENSUS_VERSION + 1})` ) }) @@ -168,26 +177,29 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const invalidReportItems = getReportDataItems(invalidReport) const invalidReportHash = calcReportDataHash(invalidReportItems) await assertRevert( - oracle.submitReportData(invalidReportItems, oracleVersion, {from: member1}), + oracle.submitReportData(invalidReportItems, oracleVersion, { from: member1 }), `UnexpectedDataHash("${reportHash}", "${invalidReportHash}")` ) }) it(`a committee member submits the report data, exit requests are emitted`, async () => { - const tx = await oracle.submitReportData(reportItems, oracleVersion, {from: member1}) - assertEvent(tx, 'ProcessingStarted', {expectedArgs: {refSlot: reportFields.refSlot}}) + const tx = await oracle.submitReportData(reportItems, oracleVersion, { from: member1 }) + assertEvent(tx, 'ProcessingStarted', { expectedArgs: { refSlot: reportFields.refSlot } }) assert.isTrue((await oracle.getConsensusReport()).processingStarted) const timestamp = await oracle.getTime() for (let i = 0; i < exitRequests.length; ++i) { - assertEvent(tx, 'ValidatorExitRequest', {index: i, expectedArgs: { - stakingModuleId: exitRequests[i].moduleId, - nodeOperatorId: exitRequests[i].nodeOpId, - validatorIndex: exitRequests[i].valIndex, - validatorPubkey: exitRequests[i].valPubkey, - timestamp - }}) + assertEvent(tx, 'ValidatorExitRequest', { + index: i, + expectedArgs: { + stakingModuleId: exitRequests[i].moduleId, + nodeOperatorId: exitRequests[i].nodeOpId, + validatorIndex: exitRequests[i].valIndex, + validatorPubkey: exitRequests[i].valPubkey, + timestamp, + }, + }) } }) @@ -197,10 +209,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger assert.equal(procState.currentFrameRefSlot, +frame.refSlot) assert.equal(procState.dataHash, reportHash) - assert.equal( - procState.processingDeadlineTime, - computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot) - ) + assert.equal(procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.isTrue(procState.dataSubmitted) assert.equal(+procState.dataFormat, DATA_FORMAT_LIST) assert.equal(+procState.requestsCount, exitRequests.length) @@ -216,7 +225,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it(`no data can be submitted for the same reference slot again`, async () => { await assert.reverts( - oracle.submitReportData(reportItems, oracleVersion, {from: member2}), + oracle.submitReportData(reportItems, oracleVersion, { from: member2 }), 'RefSlotAlreadyProcessing()' ) }) diff --git a/test/0.8.9/oracle/validators-exit-bus-oracle-submit-report-data.test.js b/test/0.8.9/oracle/validators-exit-bus-oracle-submit-report-data.test.js index e33f2de5a..e8d581405 100644 --- a/test/0.8.9/oracle/validators-exit-bus-oracle-submit-report-data.test.js +++ b/test/0.8.9/oracle/validators-exit-bus-oracle-submit-report-data.test.js @@ -8,7 +8,7 @@ const { encodeExitRequestsDataList, deployExitBusOracle, computeTimestampAtSlot, - ZERO_HASH + ZERO_HASH, } = require('./validators-exit-bus-oracle-deploy.test') const PUBKEYS = [ @@ -16,7 +16,7 @@ const PUBKEYS = [ '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', '0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', '0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd', - '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' + '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', ] function assertEqualsObject(state, desired) { @@ -39,7 +39,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger async function setup() { const deployed = await deployExitBusOracle(admin, { lastProcessingRefSlot: LAST_PROCESSING_REF_SLOT, - resumeAfterDeploy: true + resumeAfterDeploy: true, }) consensus = deployed.consensus @@ -66,7 +66,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger // required override: refSlot // required override: requestsCount // required override: data - ...overrides + ...overrides, }) async function prepareReportAndSubmitHash( @@ -80,7 +80,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger refSlot: +refSlot, requestsCount: exitRequests.length, data: encodeExitRequestsDataList(exitRequests), - ...reportFieldsArg + ...reportFieldsArg, }) const reportItems = getReportDataItems(reportFields) @@ -128,7 +128,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it('dataFormat = 1 pass', async () => { const report = await prepareReportAndSubmitHash([ - { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] } + { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] }, ]) await oracle.submitReportData(report, oracleVersion, { from: member1 }) }) @@ -141,7 +141,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const reportFields = getDefaultReportFields({ refSlot: +refSlot, requestsCount: exitRequests.length, - data: encodeExitRequestsDataList(exitRequests) + data: encodeExitRequestsDataList(exitRequests), }) reportFields.data += 'aaaaaaaaaaaaaaaaaa' @@ -161,7 +161,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const reportFields = getDefaultReportFields({ refSlot: +refSlot, requestsCount: exitRequests.length, - data: encodeExitRequestsDataList(exitRequests) + data: encodeExitRequestsDataList(exitRequests), }) reportFields.data = reportFields.data.slice(0, reportFields.data.length - 18) @@ -177,7 +177,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it('pass if there is exact amount of data', async () => { const report = await prepareReportAndSubmitHash([ - { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] } + { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] }, ]) await oracle.submitReportData(report, oracleVersion, { from: member1 }) }) @@ -189,7 +189,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger await oracleReportSanityChecker.setMaxExitRequestsPerOracleReport(exitRequestsLimit) const report = await prepareReportAndSubmitHash([ { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[2] }, - { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[3] } + { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[3] }, ]) await assert.reverts( oracle.submitReportData(report, oracleVersion, { from: member1 }), @@ -201,7 +201,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const exitRequestsLimit = 1 await oracleReportSanityChecker.setMaxExitRequestsPerOracleReport(exitRequestsLimit) const report = await prepareReportAndSubmitHash([ - { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[2] } + { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[2] }, ]) await oracle.submitReportData(report, oracleVersion, { from: member1 }) }) @@ -222,7 +222,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it('reverts if moduleId equals zero', async () => { const report = await prepareReportAndSubmitHash([ - { moduleId: 0, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] } + { moduleId: 0, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] }, ]) await assert.reverts(oracle.submitReportData(report, oracleVersion, { from: member1 }), 'InvalidRequestsData()') }) @@ -230,7 +230,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it('emits ValidatorExitRequest events', async () => { const requests = [ { moduleId: 4, nodeOpId: 2, valIndex: 2, valPubkey: PUBKEYS[2] }, - { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[3] } + { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[3] }, ] const report = await prepareReportAndSubmitHash(requests) const tx = await oracle.submitReportData(report, oracleVersion, { from: member1 }) @@ -241,7 +241,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger nodeOperatorId: requests[0].nodeOpId, validatorIndex: requests[0].valIndex, validatorPubkey: requests[0].valPubkey, - timestamp + timestamp, }) assert.emits(tx, 'ValidatorExitRequest', { @@ -249,7 +249,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger nodeOperatorId: requests[1].nodeOpId, validatorIndex: requests[1].valIndex, validatorPubkey: requests[1].valPubkey, - timestamp + timestamp, }) }) @@ -263,7 +263,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const { refSlot } = await consensus.getCurrentFrame() const requests = [ { moduleId: 4, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[2] }, - { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[3] } + { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[3] }, ] const report = await prepareReportAndSubmitHash(requests) await oracle.submitReportData(report, oracleVersion, { from: member1 }) @@ -292,7 +292,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger await consensus.advanceTimeToNextFrameStart() const requestsStep2 = [ { moduleId: 4, nodeOpId: 2, valIndex: 2, valPubkey: PUBKEYS[2] }, - { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[3] } + { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[3] }, ] const reportStep2 = await prepareReportAndSubmitHash(requestsStep2) await oracle.submitReportData(reportStep2, oracleVersion, { from: member1 }) @@ -317,7 +317,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it(`requesting NO 5-3 to exit validator 0`, async () => { await consensus.advanceTimeToNextFrameStart() const report = await prepareReportAndSubmitHash([ - { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] } + { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] }, ]) await oracle.submitReportData(report, oracleVersion, { from: member1 }) assert.equal(await getLastRequestedValidatorIndex(5, 3), 0) @@ -326,7 +326,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it(`cannot request NO 5-3 to exit validator 0 again`, async () => { await consensus.advanceTimeToNextFrameStart() const report = await prepareReportAndSubmitHash([ - { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] } + { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] }, ]) await assert.reverts( oracle.submitReportData(report, oracleVersion, { from: member1 }), @@ -337,7 +337,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it(`requesting NO 5-3 to exit validator 1`, async () => { await consensus.advanceTimeToNextFrameStart() const report = await prepareReportAndSubmitHash([ - { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[1] } + { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[1] }, ]) await oracle.submitReportData(report, oracleVersion, { from: member1 }) assert.equal(await getLastRequestedValidatorIndex(5, 3), 1) @@ -346,7 +346,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it(`cannot request NO 5-3 to exit validator 1 again`, async () => { await consensus.advanceTimeToNextFrameStart() const report = await prepareReportAndSubmitHash([ - { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[1] } + { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[1] }, ]) await assert.reverts( oracle.submitReportData(report, oracleVersion, { from: member1 }), @@ -357,7 +357,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it(`cannot request NO 5-3 to exit validator 0 again`, async () => { await consensus.advanceTimeToNextFrameStart() const report = await prepareReportAndSubmitHash([ - { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] } + { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] }, ]) await assert.reverts( oracle.submitReportData(report, oracleVersion, { from: member1 }), @@ -369,7 +369,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger await consensus.advanceTimeToNextFrameStart() const report = await prepareReportAndSubmitHash([ { moduleId: 5, nodeOpId: 1, valIndex: 10, valPubkey: PUBKEYS[0] }, - { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[0] } + { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[0] }, ]) await assert.reverts( oracle.submitReportData(report, oracleVersion, { from: member1 }), @@ -382,7 +382,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const report = await prepareReportAndSubmitHash([ { moduleId: 5, nodeOpId: 1, valIndex: 10, valPubkey: PUBKEYS[2] }, { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[3] }, - { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[4] } + { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[4] }, ]) await assert.reverts( oracle.submitReportData(report, oracleVersion, { from: member1 }), @@ -394,7 +394,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger await consensus.advanceTimeToNextFrameStart() const report = await prepareReportAndSubmitHash([ { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[2] }, - { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[3] } + { moduleId: 5, nodeOpId: 3, valIndex: 2, valPubkey: PUBKEYS[3] }, ]) await assert.reverts( oracle.submitReportData(report, oracleVersion, { from: member1 }), @@ -480,7 +480,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it('should increase after report', async () => { const report = await prepareReportAndSubmitHash([ - { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] } + { moduleId: 5, nodeOpId: 3, valIndex: 0, valPubkey: PUBKEYS[0] }, ]) await oracle.submitReportData(report, oracleVersion, { from: member1 }) requestCount += 1 @@ -491,7 +491,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger await consensus.advanceTimeToNextFrameStart() const report = await prepareReportAndSubmitHash([ { moduleId: 5, nodeOpId: 1, valIndex: 10, valPubkey: PUBKEYS[0] }, - { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[0] } + { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[0] }, ]) await oracle.submitReportData(report, oracleVersion, { from: member1 }) requestCount += 2 @@ -521,14 +521,14 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger dataSubmitted: false, dataFormat: 0, requestsCount: 0, - requestsSubmitted: 0 + requestsSubmitted: 0, }) }) it('consensus report submitted', async () => { report = await prepareReportAndSubmitHash([ { moduleId: 5, nodeOpId: 1, valIndex: 10, valPubkey: PUBKEYS[2] }, - { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[3] } + { moduleId: 5, nodeOpId: 3, valIndex: 1, valPubkey: PUBKEYS[3] }, ]) hash = calcReportDataHash(report) const state = await oracle.getProcessingState() @@ -541,7 +541,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger dataSubmitted: false, dataFormat: 0, requestsCount: 0, - requestsSubmitted: 0 + requestsSubmitted: 0, }) }) @@ -557,7 +557,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger dataSubmitted: true, dataFormat: DATA_FORMAT_LIST, requestsCount: 2, - requestsSubmitted: 2 + requestsSubmitted: 2, }) }) @@ -571,7 +571,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger dataSubmitted: false, dataFormat: 0, requestsCount: 0, - requestsSubmitted: 0 + requestsSubmitted: 0, }) }) }) diff --git a/test/0.8.9/pausable-until.test.js b/test/0.8.9/pausable-until.test.js index 4f56f1f1e..c6d98d169 100644 --- a/test/0.8.9/pausable-until.test.js +++ b/test/0.8.9/pausable-until.test.js @@ -7,15 +7,12 @@ const { assert } = require('../helpers/assert') const PausableUntil = artifacts.require('PausableUntilPrivateExposed') - - - contract('PausableUntil', ([deployer, _, anotherAccount]) => { let pausable let PAUSE_INFINITELY before('deploy lido with dao', async () => { - pausable = await PausableUntil.new( { from: deployer }) + pausable = await PausableUntil.new({ from: deployer }) PAUSE_INFINITELY = await pausable.PAUSE_INFINITELY() snapshot = new EvmSnapshot(hre.ethers.provider) @@ -29,7 +26,7 @@ contract('PausableUntil', ([deployer, _, anotherAccount]) => { /// Check views, modifiers and capability to pause/resume async function assertPausedState(resumeSinceTimestamp = undefined) { assert.isTrue(await pausable.isPaused()) - assert.isTrue(await pausable.getResumeSinceTimestamp() > await getCurrentBlockTimestamp()) + assert.isTrue((await pausable.getResumeSinceTimestamp()) > (await getCurrentBlockTimestamp())) assert.equals(await pausable.stubUnderModifierWhenPaused(), bn(42)) if (resumeSinceTimestamp !== undefined) { assert.equals(await pausable.getResumeSinceTimestamp(), resumeSinceTimestamp) @@ -42,7 +39,7 @@ contract('PausableUntil', ([deployer, _, anotherAccount]) => { /// Check views, modifiers and capability to pause/resume async function assertResumedState() { assert.isFalse(await pausable.isPaused()) - assert.isTrue(await pausable.getResumeSinceTimestamp() <= await getCurrentBlockTimestamp()) + assert.isTrue((await pausable.getResumeSinceTimestamp()) <= (await getCurrentBlockTimestamp())) assert.equals(await pausable.stubUnderModifierWhenResumed(), bn(42)) await assert.revertsWithCustomError(pausable.stubUnderModifierWhenPaused(), `PausedExpected()`) await assert.revertsWithCustomError(pausable.resume(), `PausedExpected()`) @@ -77,7 +74,7 @@ contract('PausableUntil', ([deployer, _, anotherAccount]) => { const pauseDuration = 3 * 60 await pausable.pause(pauseDuration) - const resumeSinceTimestamp = await getCurrentBlockTimestamp() + pauseDuration + const resumeSinceTimestamp = (await getCurrentBlockTimestamp()) + pauseDuration await assertPausedState(resumeSinceTimestamp) await advanceChainTime(Math.floor(pauseDuration / 2)) diff --git a/test/0.8.9/positive-token-rebase-limiter.test.js b/test/0.8.9/positive-token-rebase-limiter.test.js index d0d8fad06..49df2664d 100644 --- a/test/0.8.9/positive-token-rebase-limiter.test.js +++ b/test/0.8.9/positive-token-rebase-limiter.test.js @@ -188,6 +188,6 @@ contract('PositiveTokenRebaseLimiter', ([account1]) => { assert.emits(ethTx, 'ReturnValue', { retValue: ETH(2) }) const maxSharesToBurn = await limiter.getSharesToBurnLimit() - assert.equals(maxSharesToBurn, 0); + assert.equals(maxSharesToBurn, 0) }) }) diff --git a/test/0.8.9/staking-router-allocation-combinations.test.js b/test/0.8.9/staking-router-allocation-combinations.test.js index e190e267c..c455a9213 100644 --- a/test/0.8.9/staking-router-allocation-combinations.test.js +++ b/test/0.8.9/staking-router-allocation-combinations.test.js @@ -19,7 +19,7 @@ contract('StakingRouter', (accounts) => { stakingRouter = await StakingRouter.new(depositContract.address, { from: deployer }) const mocks = await Promise.all([ StakingModuleMock.new({ from: deployer }), - StakingModuleMock.new({ from: deployer }) + StakingModuleMock.new({ from: deployer }), ]) StakingModule1 = mocks[0] @@ -33,7 +33,7 @@ contract('StakingRouter', (accounts) => { await Promise.all([ stakingRouter.MANAGE_WITHDRAWAL_CREDENTIALS_ROLE(), stakingRouter.STAKING_MODULE_PAUSE_ROLE(), - stakingRouter.STAKING_MODULE_MANAGE_ROLE() + stakingRouter.STAKING_MODULE_MANAGE_ROLE(), ]) await stakingRouter.grantRole(MANAGE_WITHDRAWAL_CREDENTIALS_ROLE, admin, { from: admin }) @@ -51,7 +51,7 @@ contract('StakingRouter', (accounts) => { const TWO_MODULES_TARGET_SHARES_CASES = [ [100_00, 0], [50_00, 50_00], - [99_99, 1] + [99_99, 1], ] const MAX_DEPOSITABLE_KEYS_CASES = [0, 1, 10_000] const MODULE_AVAILABLE_KEYS_CASES = [0, 1, 10_000] @@ -99,8 +99,12 @@ contract('StakingRouter', (accounts) => { describe(`Target shares: ${module1TargetShare} and ${module2TargetShare}`, async () => { beforeEach(async () => { await Promise.all([ - await stakingRouter.addStakingModule('Module1', StakingModule1.address, module1TargetShare, 5_000, 5_000, { from: admin }), - await stakingRouter.addStakingModule('Module2', StakingModule2.address, module2TargetShare, 5_000, 5_000, { from: admin }) + await stakingRouter.addStakingModule('Module1', StakingModule1.address, module1TargetShare, 5_000, 5_000, { + from: admin, + }), + await stakingRouter.addStakingModule('Module2', StakingModule2.address, module2TargetShare, 5_000, 5_000, { + from: admin, + }), ]) }) diff --git a/test/0.8.9/staking-router-deposits-allocation.test.js b/test/0.8.9/staking-router-deposits-allocation.test.js index eb496d4d9..729bdf608 100644 --- a/test/0.8.9/staking-router-deposits-allocation.test.js +++ b/test/0.8.9/staking-router-deposits-allocation.test.js @@ -17,18 +17,19 @@ contract('StakingRouter', (accounts) => { ;[curatedStakingModuleMock, soloStakingModuleMock] = await Promise.all([ StakingModuleMock.new({ from: deployer }), StakingModuleMock.new({ from: deployer }), - StakingModuleMock.new({ from: deployer }) + StakingModuleMock.new({ from: deployer }), ]) const wc = '0x'.padEnd(66, '1234') await stakingRouter.initialize(admin, lido, wc, { from: deployer }) // Set up the staking router permissions. - const [MANAGE_WITHDRAWAL_CREDENTIALS_ROLE, STAKING_MODULE_PAUSE_ROLE, STAKING_MODULE_MANAGE_ROLE] = await Promise.all([ - stakingRouter.MANAGE_WITHDRAWAL_CREDENTIALS_ROLE(), - stakingRouter.STAKING_MODULE_PAUSE_ROLE(), - stakingRouter.STAKING_MODULE_MANAGE_ROLE() - ]) + const [MANAGE_WITHDRAWAL_CREDENTIALS_ROLE, STAKING_MODULE_PAUSE_ROLE, STAKING_MODULE_MANAGE_ROLE] = + await Promise.all([ + stakingRouter.MANAGE_WITHDRAWAL_CREDENTIALS_ROLE(), + stakingRouter.STAKING_MODULE_PAUSE_ROLE(), + stakingRouter.STAKING_MODULE_MANAGE_ROLE(), + ]) await stakingRouter.grantRole(MANAGE_WITHDRAWAL_CREDENTIALS_ROLE, admin, { from: admin }) await stakingRouter.grantRole(STAKING_MODULE_PAUSE_ROLE, admin, { from: admin }) diff --git a/test/0.8.9/staking-router-deposits.test.js b/test/0.8.9/staking-router-deposits.test.js index d02528e31..42a9499a8 100644 --- a/test/0.8.9/staking-router-deposits.test.js +++ b/test/0.8.9/staking-router-deposits.test.js @@ -20,7 +20,7 @@ contract('StakingRouter', ([depositor, stranger]) => { const deployed = await deployProtocol({ depositSecurityModuleFactory: async () => { return { address: depositor } - } + }, }) lido = deployed.pool @@ -98,7 +98,7 @@ contract('StakingRouter', ([depositor, stranger]) => { await operators.setNodeOperatorStakingLimit(1, 100000, { from: voting }) const receipt = await lido.methods[`deposit(uint256,uint256,bytes)`](maxDepositsCount, curated.id, '0x', { - from: depositor + from: depositor, }) assert.equals(await depositContract.totalCalls(), 100, 'invalid deposits count') diff --git a/test/0.8.9/staking-router-keys-reporting.test.js b/test/0.8.9/staking-router-keys-reporting.test.js index 5da7ef45f..da54cda06 100644 --- a/test/0.8.9/staking-router-keys-reporting.test.js +++ b/test/0.8.9/staking-router-keys-reporting.test.js @@ -7,7 +7,6 @@ const StakingRouter = artifacts.require('StakingRouterMock.sol') const StakingModuleMock = artifacts.require('StakingModuleMock.sol') const DepositContractMock = artifacts.require('DepositContractMock.sol') - contract('StakingRouter', ([deployer, lido, admin]) => { const evmSnapshot = new EvmSnapshot(hre.ethers.provider) @@ -17,10 +16,9 @@ contract('StakingRouter', ([deployer, lido, admin]) => { before(async () => { depositContract = await DepositContractMock.new({ from: deployer }) router = await StakingRouter.new(depositContract.address, { from: deployer }) - ;[module1, module2] = await Promise.all([ StakingModuleMock.new({ from: deployer }), - StakingModuleMock.new({ from: deployer }) + StakingModuleMock.new({ from: deployer }), ]) const wc = '0x'.padEnd(66, '1234') @@ -40,8 +38,8 @@ contract('StakingRouter', ([deployer, lido, admin]) => { updateStuckValidatorsCount: callCountToNum(await sModule.lastCall_updateStuckValidatorsCount()), updateExitedValidatorsCount: callCountToNum(await sModule.lastCall_updateExitedValidatorsCount()), onExitedAndStuckValidatorsCountsUpdated: { - callCount: +await sModule.callCount_onExitedAndStuckValidatorsCountsUpdated() - } + callCount: +(await sModule.callCount_onExitedAndStuckValidatorsCountsUpdated()), + }, } } @@ -58,7 +56,6 @@ contract('StakingRouter', ([deployer, lido, admin]) => { const revert = () => evmSnapshot.revert() describe('exited/stuck keys reporting', () => { - describe('one staking module', async () => { before(snapshot) after(revert) @@ -117,16 +114,17 @@ contract('StakingRouter', ([deployer, lido, admin]) => { assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) }) - it(`calling onValidatorsCountsByNodeOperatorReportingFinished doesn't call ` + - `anything on the module`, async () => - { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it( + `calling onValidatorsCountsByNodeOperatorReportingFinished doesn't call ` + `anything on the module`, + async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo = await getCallInfo(module1) - assert.equal(callInfo.updateStuckValidatorsCount.callCount, 0) - assert.equal(callInfo.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - }) + const callInfo = await getCallInfo(module1) + assert.equal(callInfo.updateStuckValidatorsCount.callCount, 0) + assert.equal(callInfo.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + } + ) it('reporting stuck validators by node op of a non-existent module reverts', async () => { const nonExistentModuleId = module1Id + 1 @@ -134,7 +132,9 @@ contract('StakingRouter', ([deployer, lido, admin]) => { const validatorsCountsData = hexConcat(hex(1, 16)) await assert.reverts( router.reportStakingModuleStuckValidatorsCountByNodeOperator( - nonExistentModuleId, nodeOpIdsData, validatorsCountsData, + nonExistentModuleId, + nodeOpIdsData, + validatorsCountsData, { from: admin } ), 'StakingModuleUnregistered()' @@ -143,10 +143,7 @@ contract('StakingRouter', ([deployer, lido, admin]) => { it('passing empty data while reporting stuck validators by node operator reverts', async () => { await assert.reverts( - router.reportStakingModuleStuckValidatorsCountByNodeOperator( - module1Id, '0x', '0x', - { from: admin } - ), + router.reportStakingModuleStuckValidatorsCountByNodeOperator(module1Id, '0x', '0x', { from: admin }), 'InvalidReportData(1)' ) }) @@ -170,17 +167,24 @@ contract('StakingRouter', ([deployer, lido, admin]) => { }, ] - it('passing data with mismatched length while reporting stuck validators by node operator ' + - 'reverts', async () => - { - await Promise.all(mismatchedLengthData.map(data => assert.reverts( - router.reportStakingModuleStuckValidatorsCountByNodeOperator( - module1Id, data.nodeOpIds, data.validatorsCounts, - { from: admin } - ), - 'InvalidReportData(2)' - ))) - }) + it( + 'passing data with mismatched length while reporting stuck validators by node operator ' + 'reverts', + async () => { + await Promise.all( + mismatchedLengthData.map((data) => + assert.reverts( + router.reportStakingModuleStuckValidatorsCountByNodeOperator( + module1Id, + data.nodeOpIds, + data.validatorsCounts, + { from: admin } + ), + 'InvalidReportData(2)' + ) + ) + ) + } + ) const invalidLengthData = [ { @@ -225,27 +229,36 @@ contract('StakingRouter', ([deployer, lido, admin]) => { }, ] - it('passing data with invalid length while reporting stuck validators by node operator ' + - 'reverts', async () => - { - await Promise.all(invalidLengthData.map(data => assert.reverts( - router.reportStakingModuleStuckValidatorsCountByNodeOperator( - module1Id, data.nodeOpIds, data.validatorsCounts, - { from: admin } - ), - 'InvalidReportData(3)' - ))) - }) + it( + 'passing data with invalid length while reporting stuck validators by node operator ' + 'reverts', + async () => { + await Promise.all( + invalidLengthData.map((data) => + assert.reverts( + router.reportStakingModuleStuckValidatorsCountByNodeOperator( + module1Id, + data.nodeOpIds, + data.validatorsCounts, + { from: admin } + ), + 'InvalidReportData(3)' + ) + ) + ) + } + ) it('reporting stuck validators by node operator passes the info to the module', async () => { const nodeOpIds = [3, 5] const validatorsCounts = [1, 1] - const nodeOpIdsData = hexConcat(...nodeOpIds.map(i => hex(i, 8))) - const validatorsCountsData = hexConcat(...validatorsCounts.map(c => hex(c, 16))) + const nodeOpIdsData = hexConcat(...nodeOpIds.map((i) => hex(i, 8))) + const validatorsCountsData = hexConcat(...validatorsCounts.map((c) => hex(c, 16))) await router.reportStakingModuleStuckValidatorsCountByNodeOperator( - module1Id, nodeOpIdsData, validatorsCountsData, + module1Id, + nodeOpIdsData, + validatorsCountsData, { from: admin } ) @@ -258,17 +271,18 @@ contract('StakingRouter', ([deployer, lido, admin]) => { assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) }) - it(`calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + - `anything on the module`, async () => - { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it( + `calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + `anything on the module`, + async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo = await getCallInfo(module1) - assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + const callInfo = await getCallInfo(module1) + assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo.updateExitedValidatorsCount.callCount, 0) - }) + assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo.updateExitedValidatorsCount.callCount, 0) + } + ) it('reporting exited validators by node op of a non-existent module reverts', async () => { const nonExistentModuleId = module1Id + 1 @@ -276,7 +290,9 @@ contract('StakingRouter', ([deployer, lido, admin]) => { const validatorsCountsData = hexConcat(hex(1, 16)) await assert.reverts( router.reportStakingModuleExitedValidatorsCountByNodeOperator( - nonExistentModuleId, nodeOpIdsData, validatorsCountsData, + nonExistentModuleId, + nodeOpIdsData, + validatorsCountsData, { from: admin } ), 'StakingModuleUnregistered()' @@ -285,49 +301,60 @@ contract('StakingRouter', ([deployer, lido, admin]) => { it('passing empty data while reporting exited validators by node operator reverts', async () => { await assert.reverts( - router.reportStakingModuleExitedValidatorsCountByNodeOperator( - module1Id, '0x', '0x', - { from: admin } - ), + router.reportStakingModuleExitedValidatorsCountByNodeOperator(module1Id, '0x', '0x', { from: admin }), 'InvalidReportData(1)' ) }) - it('passing data with mismatched length while reporting exited validators by node operator ' + - 'reverts', async () => - { - await Promise.all(mismatchedLengthData.map(data => assert.reverts( - router.reportStakingModuleExitedValidatorsCountByNodeOperator( - module1Id, data.nodeOpIds, data.validatorsCounts, - { from: admin } - ), - 'InvalidReportData(2)' - ))) - }) - - it('passing data with invalid length while reporting exited validators by node operator ' + - 'reverts', async () => - { - await Promise.all(invalidLengthData.map(data => assert.reverts( - router.reportStakingModuleExitedValidatorsCountByNodeOperator( - module1Id, data.nodeOpIds, data.validatorsCounts, - { from: admin } - ), - 'InvalidReportData(3)' - ))) - }) - - it('reporting exited validators by node operator (total 2) passes the info to the module', - async () => - { + it( + 'passing data with mismatched length while reporting exited validators by node operator ' + 'reverts', + async () => { + await Promise.all( + mismatchedLengthData.map((data) => + assert.reverts( + router.reportStakingModuleExitedValidatorsCountByNodeOperator( + module1Id, + data.nodeOpIds, + data.validatorsCounts, + { from: admin } + ), + 'InvalidReportData(2)' + ) + ) + ) + } + ) + + it( + 'passing data with invalid length while reporting exited validators by node operator ' + 'reverts', + async () => { + await Promise.all( + invalidLengthData.map((data) => + assert.reverts( + router.reportStakingModuleExitedValidatorsCountByNodeOperator( + module1Id, + data.nodeOpIds, + data.validatorsCounts, + { from: admin } + ), + 'InvalidReportData(3)' + ) + ) + ) + } + ) + + it('reporting exited validators by node operator (total 2) passes the info to the module', async () => { const nodeOpIds = [1, 2] const validatorsCounts = [1, 1] - const nodeOpIdsData = hexConcat(...nodeOpIds.map(i => hex(i, 8))) - const validatorsCountsData = hexConcat(...validatorsCounts.map(c => hex(c, 16))) + const nodeOpIdsData = hexConcat(...nodeOpIds.map((i) => hex(i, 8))) + const validatorsCountsData = hexConcat(...validatorsCounts.map((c) => hex(c, 16))) await router.reportStakingModuleExitedValidatorsCountByNodeOperator( - module1Id, nodeOpIdsData, validatorsCountsData, + module1Id, + nodeOpIdsData, + validatorsCountsData, { from: admin } ) @@ -350,29 +377,30 @@ contract('StakingRouter', ([deployer, lido, admin]) => { assert.equal(+totalExited, 3) }) - it(`calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + - `anything on the module`, async () => - { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it( + `calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + `anything on the module`, + async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo = await getCallInfo(module1) - assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + const callInfo = await getCallInfo(module1) + assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo.updateExitedValidatorsCount.callCount, 1) - }) + assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo.updateExitedValidatorsCount.callCount, 1) + } + ) - it('reporting one more exited validator by node operator passes the info to the module', - async () => - { + it('reporting one more exited validator by node operator passes the info to the module', async () => { const nodeOpIds = [3] const validatorsCounts = [1] - const nodeOpIdsData = hexConcat(...nodeOpIds.map(i => hex(i, 8))) - const validatorsCountsData = hexConcat(...validatorsCounts.map(c => hex(c, 16))) + const nodeOpIdsData = hexConcat(...nodeOpIds.map((i) => hex(i, 8))) + const validatorsCountsData = hexConcat(...validatorsCounts.map((c) => hex(c, 16))) await router.reportStakingModuleExitedValidatorsCountByNodeOperator( - module1Id, nodeOpIdsData, validatorsCountsData, + module1Id, + nodeOpIdsData, + validatorsCountsData, { from: admin } ) @@ -390,30 +418,34 @@ contract('StakingRouter', ([deployer, lido, admin]) => { await module1.setTotalExitedValidatorsCount(3) }) - it(`now that exited validators totals in the router and in the module match, calling` + - `onValidatorsCountsByNodeOperatorReportingFinished calls ` + - `onExitedAndStuckValidatorsCountsUpdated on the module`, async () => - { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it( + `now that exited validators totals in the router and in the module match, calling` + + `onValidatorsCountsByNodeOperatorReportingFinished calls ` + + `onExitedAndStuckValidatorsCountsUpdated on the module`, + async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo = await getCallInfo(module1) - assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 1) + const callInfo = await getCallInfo(module1) + assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 1) - assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo.updateExitedValidatorsCount.callCount, 2) - }) + assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo.updateExitedValidatorsCount.callCount, 2) + } + ) - it(`calling onValidatorsCountsByNodeOperatorReportingFinished one more time calls ` + - `onExitedAndStuckValidatorsCountsUpdated on the module again`, async () => - { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it( + `calling onValidatorsCountsByNodeOperatorReportingFinished one more time calls ` + + `onExitedAndStuckValidatorsCountsUpdated on the module again`, + async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo = await getCallInfo(module1) - assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 2) + const callInfo = await getCallInfo(module1) + assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 2) - assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo.updateExitedValidatorsCount.callCount, 2) - }) + assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo.updateExitedValidatorsCount.callCount, 2) + } + ) }) describe('two staking modules', async () => { @@ -482,31 +514,34 @@ contract('StakingRouter', ([deployer, lido, admin]) => { assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) }) - it(`calling onValidatorsCountsByNodeOperatorReportingFinished doesn't call ` + - `anything on any module`, async () => - { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it( + `calling onValidatorsCountsByNodeOperatorReportingFinished doesn't call ` + `anything on any module`, + async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo1 = await getCallInfo(module1) - assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 0) - assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + const callInfo1 = await getCallInfo(module1) + assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 0) + assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - const callInfo2 = await getCallInfo(module2) - assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 0) - assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - }) + const callInfo2 = await getCallInfo(module2) + assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 0) + assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + } + ) it('reporting stuck validators by node operator passes the info to the module 1', async () => { const nodeOpIds = [1] const validatorsCounts = [3] - const nodeOpIdsData = hexConcat(...nodeOpIds.map(i => hex(i, 8))) - const validatorsCountsData = hexConcat(...validatorsCounts.map(c => hex(c, 16))) + const nodeOpIdsData = hexConcat(...nodeOpIds.map((i) => hex(i, 8))) + const validatorsCountsData = hexConcat(...validatorsCounts.map((c) => hex(c, 16))) await router.reportStakingModuleStuckValidatorsCountByNodeOperator( - moduleIds[0], nodeOpIdsData, validatorsCountsData, + moduleIds[0], + nodeOpIdsData, + validatorsCountsData, { from: admin } ) @@ -528,11 +563,13 @@ contract('StakingRouter', ([deployer, lido, admin]) => { const nodeOpIds = [33] const validatorsCounts = [7] - const nodeOpIdsData = hexConcat(...nodeOpIds.map(i => hex(i, 8))) - const validatorsCountsData = hexConcat(...validatorsCounts.map(c => hex(c, 16))) + const nodeOpIdsData = hexConcat(...nodeOpIds.map((i) => hex(i, 8))) + const validatorsCountsData = hexConcat(...validatorsCounts.map((c) => hex(c, 16))) await router.reportStakingModuleStuckValidatorsCountByNodeOperator( - moduleIds[1], nodeOpIdsData, validatorsCountsData, + moduleIds[1], + nodeOpIdsData, + validatorsCountsData, { from: admin } ) @@ -550,31 +587,34 @@ contract('StakingRouter', ([deployer, lido, admin]) => { assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) }) - it(`calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + - `anything on any module`, async () => - { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it( + `calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + `anything on any module`, + async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo1 = await getCallInfo(module1) - assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + const callInfo1 = await getCallInfo(module1) + assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - const callInfo2 = await getCallInfo(module2) - assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - }) + const callInfo2 = await getCallInfo(module2) + assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + } + ) it('reporting exited validators by node operator passes the info to the module 1', async () => { const nodeOpIds = [3, 4] const validatorsCounts = [1, 1] - const nodeOpIdsData = hexConcat(...nodeOpIds.map(i => hex(i, 8))) - const validatorsCountsData = hexConcat(...validatorsCounts.map(c => hex(c, 16))) + const nodeOpIdsData = hexConcat(...nodeOpIds.map((i) => hex(i, 8))) + const validatorsCountsData = hexConcat(...validatorsCounts.map((c) => hex(c, 16))) await router.reportStakingModuleExitedValidatorsCountByNodeOperator( - moduleIds[0], nodeOpIdsData, validatorsCountsData, + moduleIds[0], + nodeOpIdsData, + validatorsCountsData, { from: admin } ) @@ -596,31 +636,34 @@ contract('StakingRouter', ([deployer, lido, admin]) => { await module1.setTotalExitedValidatorsCount(2) }) - it(`calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + - `anything on any module`, async () => - { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it( + `calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + `anything on any module`, + async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo1 = await getCallInfo(module1) - assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 1) - assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + const callInfo1 = await getCallInfo(module1) + assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 1) + assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - const callInfo2 = await getCallInfo(module2) - assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - }) + const callInfo2 = await getCallInfo(module2) + assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + } + ) it('reporting exited validators by node operator passes the info to the module 2', async () => { const nodeOpIds = [20] const validatorsCounts = [1] - const nodeOpIdsData = hexConcat(...nodeOpIds.map(i => hex(i, 8))) - const validatorsCountsData = hexConcat(...validatorsCounts.map(c => hex(c, 16))) + const nodeOpIdsData = hexConcat(...nodeOpIds.map((i) => hex(i, 8))) + const validatorsCountsData = hexConcat(...validatorsCounts.map((c) => hex(c, 16))) await router.reportStakingModuleExitedValidatorsCountByNodeOperator( - moduleIds[1], nodeOpIdsData, validatorsCountsData, + moduleIds[1], + nodeOpIdsData, + validatorsCountsData, { from: admin } ) @@ -642,34 +685,38 @@ contract('StakingRouter', ([deployer, lido, admin]) => { await module2.setTotalExitedValidatorsCount(2) }) - it(`now that router's view on exited validators total match the module 2's view,` + - `calling onValidatorsCountsByNodeOperatorReportingFinished calls ` + - `onExitedAndStuckValidatorsCountsUpdated on the module 2`, async () => - { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it( + `now that router's view on exited validators total match the module 2's view,` + + `calling onValidatorsCountsByNodeOperatorReportingFinished calls ` + + `onExitedAndStuckValidatorsCountsUpdated on the module 2`, + async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo1 = await getCallInfo(module1) - const callInfo2 = await getCallInfo(module2) + const callInfo1 = await getCallInfo(module1) + const callInfo2 = await getCallInfo(module2) - assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 1) + assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 1) - assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 1) - assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 1) + assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 1) - assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) - }) + assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 1) + assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) + } + ) it('reporting exited validators by node operator passes the info to the module 1', async () => { const nodeOpIds = [55] const validatorsCounts = [1] - const nodeOpIdsData = hexConcat(...nodeOpIds.map(i => hex(i, 8))) - const validatorsCountsData = hexConcat(...validatorsCounts.map(c => hex(c, 16))) + const nodeOpIdsData = hexConcat(...nodeOpIds.map((i) => hex(i, 8))) + const validatorsCountsData = hexConcat(...validatorsCounts.map((c) => hex(c, 16))) await router.reportStakingModuleExitedValidatorsCountByNodeOperator( - moduleIds[0], nodeOpIdsData, validatorsCountsData, + moduleIds[0], + nodeOpIdsData, + validatorsCountsData, { from: admin } ) @@ -691,24 +738,26 @@ contract('StakingRouter', ([deployer, lido, admin]) => { await module1.setTotalExitedValidatorsCount(3) }) - it(`now that router's view on exited validators total match the both modules' view,` + - `calling onValidatorsCountsByNodeOperatorReportingFinished calls ` + - `onExitedAndStuckValidatorsCountsUpdated on both modules`, async () => - { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it( + `now that router's view on exited validators total match the both modules' view,` + + `calling onValidatorsCountsByNodeOperatorReportingFinished calls ` + + `onExitedAndStuckValidatorsCountsUpdated on both modules`, + async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo1 = await getCallInfo(module1) - const callInfo2 = await getCallInfo(module2) + const callInfo1 = await getCallInfo(module1) + const callInfo2 = await getCallInfo(module2) - assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 1) - assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 2) + assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 1) + assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 2) - assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 2) - assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 2) + assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 1) - assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) - }) + assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 1) + assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) + } + ) }) }) }) diff --git a/test/0.8.9/staking-router.test.js b/test/0.8.9/staking-router.test.js index 17e514e48..d050c8fe9 100644 --- a/test/0.8.9/staking-router.test.js +++ b/test/0.8.9/staking-router.test.js @@ -26,7 +26,7 @@ const UINT24_MAX = new BN(2).pow(new BN(24)) const StakingModuleStatus = { Active: 0, // deposits and rewards allowed DepositsPaused: 1, // deposits NOT allowed, rewards allowed - Stopped: 2 // deposits and rewards NOT allowed + Stopped: 2, // deposits and rewards NOT allowed } contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { @@ -44,8 +44,14 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { }) it('init fails on wrong input', async () => { - await assert.revertsWithCustomError(app.initialize(ZERO_ADDRESS, lido, wc, { from: deployer }), 'ZeroAddress("_admin")') - await assert.revertsWithCustomError(app.initialize(admin, ZERO_ADDRESS, wc, { from: deployer }), 'ZeroAddress("_lido")') + await assert.revertsWithCustomError( + app.initialize(ZERO_ADDRESS, lido, wc, { from: deployer }), + 'ZeroAddress("_admin")' + ) + await assert.revertsWithCustomError( + app.initialize(admin, ZERO_ADDRESS, wc, { from: deployer }), + 'ZeroAddress("_lido")' + ) }) it('initialized correctly', async () => { @@ -86,7 +92,11 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { assert.equals(await app.hasRole(MANAGE_WITHDRAWAL_CREDENTIALS_ROLE, appManager), true) assert.equals(tx.logs.length, 1) - await assert.emits(tx, 'RoleGranted', { role: MANAGE_WITHDRAWAL_CREDENTIALS_ROLE, account: appManager, sender: admin }) + await assert.emits(tx, 'RoleGranted', { + role: MANAGE_WITHDRAWAL_CREDENTIALS_ROLE, + account: appManager, + sender: admin, + }) }) it('grant role STAKING_MODULE_PAUSE_ROLE', async () => { @@ -188,7 +198,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModule = await StakingModuleMock.new({ from: deployer }) await app.addStakingModule('Test module', stakingModule.address, 100, 1000, 2000, { - from: appManager + from: appManager, }) await stakingModule.setAvailableKeysCount(100, { from: deployer }) @@ -202,14 +212,8 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('reverts if module address exists', async () => { await assert.revertsWithCustomError( - app.addStakingModule( - 'Test', - stakingModule.address, - 100, - 1000, - 2000, - { from: appManager}), - 'StakingModuleAddressExists()' + app.addStakingModule('Test', stakingModule.address, 100, 1000, 2000, { from: appManager }), + 'StakingModuleAddressExists()' ) }) @@ -250,7 +254,10 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { }) it('getStakingModuleActiveValidatorsCount reverts when staking module id too large', async () => { - await assert.revertsWithCustomError(app.getStakingModuleActiveValidatorsCount(UINT24_MAX), 'StakingModuleIdTooLarge()') + await assert.revertsWithCustomError( + app.getStakingModuleActiveValidatorsCount(UINT24_MAX), + 'StakingModuleIdTooLarge()' + ) }) it('getStakingModuleActiveValidatorsCount', async () => { @@ -263,7 +270,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { const anotherStakingModule = await StakingModuleMock.new({ from: deployer }) await app.addStakingModule('Test module 2', anotherStakingModule.address, 100, 1000, 2000, { - from: appManager + from: appManager, }) await app.getStakingRewardsDistribution() @@ -279,9 +286,9 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { await snapshot.revert() }) it('staking modules limit is 32', async () => { - for (var i = 0; i < 32; i++) { + for (let i = 0; i < 32; i++) { const stakingModule = await StakingModuleMock.new({ from: deployer }) - let tx = await app.addStakingModule('Test module', stakingModule.address, 100, 100, 100, { from: appManager }) + const tx = await app.addStakingModule('Test module', stakingModule.address, 100, 100, 100, { from: appManager }) } const oneMoreStakingModule = await StakingModuleMock.new({ from: deployer }) @@ -302,7 +309,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModuleFee: 2000, treasuryFee: 200, expectedModuleId: 1, - address: null + address: null, }, { name: 'Test module 1', @@ -310,8 +317,8 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModuleFee: 2000, treasuryFee: 200, expectedModuleId: 2, - address: null - } + address: null, + }, ] before(async () => { @@ -358,9 +365,16 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('addStakingModule fails on fees > 100%', async () => { await assert.revertsWithCustomError( - app.addStakingModule(stakingModulesParams[0].name, stakingModule1.address, stakingModulesParams[0].targetShare, 5000, 5001, { - from: appManager - }), + app.addStakingModule( + stakingModulesParams[0].name, + stakingModule1.address, + stakingModulesParams[0].targetShare, + 5000, + 5001, + { + from: appManager, + } + ), `ValueOver100Percent("_stakingModuleFee + _treasuryFee")` ) }) @@ -374,7 +388,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModulesParams[0].stakingModuleFee, stakingModulesParams[0].treasuryFee, { - from: appManager + from: appManager, } ), `ZeroAddress("_stakingModuleAddress")` @@ -391,7 +405,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModulesParams[0].stakingModuleFee, stakingModulesParams[0].treasuryFee, { - from: appManager + from: appManager, } ), `StakingModuleWrongName()` @@ -406,7 +420,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModulesParams[0].stakingModuleFee, stakingModulesParams[0].treasuryFee, { - from: appManager + from: appManager, } ), `StakingModuleWrongName()` @@ -421,7 +435,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModulesParams[0].stakingModuleFee, stakingModulesParams[0].treasuryFee, { - from: appManager + from: appManager, } ) assert.equals(tx.logs.length, 3) @@ -429,22 +443,25 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModuleId: stakingModulesParams[0].expectedModuleId, stakingModule: stakingModule1.address, name: stakingModulesParams[0].name, - createdBy: appManager + createdBy: appManager, }) await assert.emits(tx, 'StakingModuleTargetShareSet', { stakingModuleId: stakingModulesParams[0].expectedModuleId, targetShare: stakingModulesParams[0].targetShare, - setBy: appManager + setBy: appManager, }) await assert.emits(tx, 'StakingModuleFeesSet', { stakingModuleId: stakingModulesParams[0].expectedModuleId, stakingModuleFee: stakingModulesParams[0].stakingModuleFee, treasuryFee: stakingModulesParams[0].treasuryFee, - setBy: appManager + setBy: appManager, }) assert.equals(await app.getStakingModulesCount(), 1) - assert.equals(await app.getStakingModuleStatus(stakingModulesParams[0].expectedModuleId), StakingModuleStatus.Active) + assert.equals( + await app.getStakingModuleStatus(stakingModulesParams[0].expectedModuleId), + StakingModuleStatus.Active + ) assert.equals(await app.getStakingModuleIsStopped(stakingModulesParams[0].expectedModuleId), false) assert.equals(await app.getStakingModuleIsDepositsPaused(stakingModulesParams[0].expectedModuleId), false) assert.equals(await app.getStakingModuleIsActive(stakingModulesParams[0].expectedModuleId), true) @@ -475,7 +492,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModulesParams[1].stakingModuleFee, stakingModulesParams[1].treasuryFee, { - from: appManager + from: appManager, } ) @@ -484,22 +501,25 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModuleId: stakingModulesParams[1].expectedModuleId, stakingModule: stakingModule2.address, name: stakingModulesParams[1].name, - createdBy: appManager + createdBy: appManager, }) await assert.emits(tx, 'StakingModuleTargetShareSet', { stakingModuleId: stakingModulesParams[1].expectedModuleId, targetShare: stakingModulesParams[1].targetShare, - setBy: appManager + setBy: appManager, }) await assert.emits(tx, 'StakingModuleFeesSet', { stakingModuleId: stakingModulesParams[1].expectedModuleId, stakingModuleFee: stakingModulesParams[1].stakingModuleFee, treasuryFee: stakingModulesParams[1].treasuryFee, - setBy: appManager + setBy: appManager, }) assert.equals(await app.getStakingModulesCount(), 2) - assert.equals(await app.getStakingModuleStatus(stakingModulesParams[1].expectedModuleId), StakingModuleStatus.Active) + assert.equals( + await app.getStakingModuleStatus(stakingModulesParams[1].expectedModuleId), + StakingModuleStatus.Active + ) assert.equals(await app.getStakingModuleIsStopped(stakingModulesParams[1].expectedModuleId), false) assert.equals(await app.getStakingModuleIsDepositsPaused(stakingModulesParams[1].expectedModuleId), false) assert.equals(await app.getStakingModuleIsActive(stakingModulesParams[1].expectedModuleId), true) @@ -548,7 +568,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModulesParams[0].stakingModuleFee + 1, stakingModulesParams[0].treasuryFee + 1, { - from: stranger + from: stranger, } ), `AccessControl: account ${stranger.toLowerCase()} is missing role ${STAKING_MODULE_MANAGE_ROLE}` @@ -563,7 +583,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModulesParams[0].stakingModuleFee + 1, stakingModulesParams[0].treasuryFee + 1, { - from: appManager + from: appManager, } ), `StakingModuleIdTooLarge()` @@ -578,7 +598,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModulesParams[0].stakingModuleFee + 1, stakingModulesParams[0].treasuryFee + 1, { - from: appManager + from: appManager, } ), `ValueOver100Percent("_targetShare")` @@ -587,9 +607,15 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('update staking module fails on fees > 100%', async () => { await assert.revertsWithCustomError( - app.updateStakingModule(stakingModulesParams[0].expectedModuleId, stakingModulesParams[0].targetShare + 1, 5000, 5001, { - from: appManager - }), + app.updateStakingModule( + stakingModulesParams[0].expectedModuleId, + stakingModulesParams[0].targetShare + 1, + 5000, + 5001, + { + from: appManager, + } + ), `ValueOver100Percent("_stakingModuleFee + _treasuryFee")` ) }) @@ -599,7 +625,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { id: stakingModulesParams[0].expectedModuleId, targetShare: stakingModulesParams[0].targetShare + 1, stakingModuleFee: stakingModulesParams[0].stakingModuleFee + 1, - treasuryFee: stakingModulesParams[0].treasuryFee + 1 + treasuryFee: stakingModulesParams[0].treasuryFee + 1, } const tx = await app.updateStakingModule( @@ -608,7 +634,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { stakingModuleNewParams.stakingModuleFee, stakingModuleNewParams.treasuryFee, { - from: appManager + from: appManager, } ) @@ -617,20 +643,20 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { await assert.emits(tx, 'StakingModuleTargetShareSet', { stakingModuleId: stakingModuleNewParams.id, targetShare: stakingModuleNewParams.targetShare, - setBy: appManager + setBy: appManager, }) await assert.emits(tx, 'StakingModuleFeesSet', { stakingModuleId: stakingModuleNewParams.id, stakingModuleFee: stakingModuleNewParams.stakingModuleFee, treasuryFee: stakingModuleNewParams.treasuryFee, - setBy: appManager + setBy: appManager, }) }) it('set staking module status does not allowed without role', async () => { await assert.reverts( app.setStakingModuleStatus(stakingModulesParams[0].expectedModuleId, StakingModuleStatus.Stopped, { - from: stranger + from: stranger, }), `AccessControl: account ${stranger.toLowerCase()} is missing role ${STAKING_MODULE_MANAGE_ROLE}` ) @@ -639,7 +665,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('set staking module status reverts if staking module id too large', async () => { await assert.revertsWithCustomError( app.setStakingModuleStatus(UINT24_MAX, StakingModuleStatus.Stopped, { - from: appManager + from: appManager, }), `StakingModuleIdTooLarge()` ) @@ -649,28 +675,32 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { const module = await app.getStakingModule(stakingModulesParams[0].expectedModuleId) await assert.revertsWithCustomError( app.setStakingModuleStatus(stakingModulesParams[0].expectedModuleId, module.status, { - from: appManager + from: appManager, }), `StakingModuleStatusTheSame()` ) }) it('set staking module status', async () => { - const tx = await app.setStakingModuleStatus(stakingModulesParams[0].expectedModuleId, StakingModuleStatus.Stopped, { - from: appManager - }) + const tx = await app.setStakingModuleStatus( + stakingModulesParams[0].expectedModuleId, + StakingModuleStatus.Stopped, + { + from: appManager, + } + ) await assert.emits(tx, 'StakingModuleStatusSet', { stakingModuleId: stakingModulesParams[0].expectedModuleId, status: StakingModuleStatus.Stopped, - setBy: appManager + setBy: appManager, }) }) it('pause staking module does not allowed without role', async () => { await assert.reverts( app.pauseStakingModule(stakingModulesParams[0].expectedModuleId, { - from: stranger + from: stranger, }), `AccessControl: account ${stranger.toLowerCase()} is missing role ${STAKING_MODULE_PAUSE_ROLE}` ) @@ -679,7 +709,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('pause staking module reverts when staking module too large', async () => { await assert.revertsWithCustomError( app.pauseStakingModule(UINT24_MAX, { - from: appManager + from: appManager, }), `StakingModuleIdTooLarge()` ) @@ -687,24 +717,24 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('pause staking module does not allowed at not active staking module', async () => { await app.setStakingModuleStatus(stakingModulesParams[0].expectedModuleId, StakingModuleStatus.Active, { - from: appManager + from: appManager, }) await app.setStakingModuleStatus(stakingModulesParams[0].expectedModuleId, StakingModuleStatus.Stopped, { - from: appManager + from: appManager, }) await assert.revertsWithCustomError( app.pauseStakingModule(stakingModulesParams[0].expectedModuleId, { - from: appManager + from: appManager, }), `StakingModuleNotActive()` ) await app.setStakingModuleStatus(stakingModulesParams[0].expectedModuleId, StakingModuleStatus.DepositsPaused, { - from: appManager + from: appManager, }) await assert.revertsWithCustomError( app.pauseStakingModule(stakingModulesParams[0].expectedModuleId, { - from: appManager + from: appManager, }), `StakingModuleNotActive()` ) @@ -712,16 +742,16 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('pause staking module', async () => { await app.setStakingModuleStatus(stakingModulesParams[0].expectedModuleId, StakingModuleStatus.Active, { - from: appManager + from: appManager, }) const tx = await app.pauseStakingModule(stakingModulesParams[0].expectedModuleId, { - from: appManager + from: appManager, }) await assert.emits(tx, 'StakingModuleStatusSet', { stakingModuleId: stakingModulesParams[0].expectedModuleId, status: StakingModuleStatus.DepositsPaused, - setBy: appManager + setBy: appManager, }) }) @@ -749,7 +779,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('resume staking module does not allowed without role', async () => { await assert.reverts( app.resumeStakingModule(stakingModulesParams[0].expectedModuleId, { - from: stranger + from: stranger, }), `AccessControl: account ${stranger.toLowerCase()} is missing role ${STAKING_MODULE_RESUME_ROLE}` ) @@ -758,7 +788,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('resume staking module reverts when staking module id too large', async () => { await assert.revertsWithCustomError( app.resumeStakingModule(UINT24_MAX, { - from: appManager + from: appManager, }), `StakingModuleIdTooLarge()` ) @@ -766,20 +796,20 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('resume staking module does not allowed at not paused staking module', async () => { await app.setStakingModuleStatus(stakingModulesParams[0].expectedModuleId, StakingModuleStatus.Stopped, { - from: appManager + from: appManager, }) await assert.revertsWithCustomError( app.resumeStakingModule(stakingModulesParams[0].expectedModuleId, { - from: appManager + from: appManager, }), `StakingModuleNotPaused()` ) await app.setStakingModuleStatus(stakingModulesParams[0].expectedModuleId, StakingModuleStatus.Active, { - from: appManager + from: appManager, }) await assert.revertsWithCustomError( app.resumeStakingModule(stakingModulesParams[0].expectedModuleId, { - from: appManager + from: appManager, }), `StakingModuleNotPaused()` ) @@ -787,16 +817,16 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('resume staking module', async () => { await app.setStakingModuleStatus(stakingModulesParams[0].expectedModuleId, StakingModuleStatus.DepositsPaused, { - from: appManager + from: appManager, }) const tx = await app.resumeStakingModule(stakingModulesParams[0].expectedModuleId, { - from: appManager + from: appManager, }) await assert.emits(tx, 'StakingModuleStatusSet', { stakingModuleId: stakingModulesParams[0].expectedModuleId, status: StakingModuleStatus.Active, - setBy: appManager + setBy: appManager, }) }) }) diff --git a/test/0.8.9/withdrawal-queue.test.js b/test/0.8.9/withdrawal-queue.test.js index 1601cf401..d0fa4c54e 100644 --- a/test/0.8.9/withdrawal-queue.test.js +++ b/test/0.8.9/withdrawal-queue.test.js @@ -33,7 +33,7 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { await steth.approve(withdrawalQueue.address, StETH(300), { from: user }) await impersonate(ethers.provider, steth.address) - await snapshot.make(); + await snapshot.make() }) afterEach(async () => { @@ -53,14 +53,14 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { context('Request', async () => { it('One can request a withdrawal', async () => { const receipt = await withdrawalQueue.requestWithdrawals([StETH(300)], owner, { from: user }) - const requestId = getEventArgument(receipt, "WithdrawalRequested", "requestId") + const requestId = getEventArgument(receipt, 'WithdrawalRequested', 'requestId') - assert.emits(receipt, "WithdrawalRequested", { + assert.emits(receipt, 'WithdrawalRequested', { requestId: 1, requestor: user.toLowerCase(), owner: owner.toLowerCase(), amountOfStETH: StETH(300), - amountOfShares: shares(1) + amountOfShares: shares(1), }) assert.equals(await withdrawalQueue.getLastRequestId(), requestId) @@ -87,8 +87,10 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { const amount = min.sub(bn(1)) - await assert.reverts(withdrawalQueue.requestWithdrawals([amount], owner, { from: user }), - `RequestAmountTooSmall(${amount})`) + await assert.reverts( + withdrawalQueue.requestWithdrawals([amount], owner, { from: user }), + `RequestAmountTooSmall(${amount})` + ) }) it('One can request MIN', async () => { @@ -96,9 +98,9 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { const shares = await steth.getSharesByPooledEth(min) const receipt = await withdrawalQueue.requestWithdrawals([min], owner, { from: user }) - const requestId = getEventArgument(receipt, "WithdrawalRequested", "requestId") + const requestId = getEventArgument(receipt, 'WithdrawalRequested', 'requestId') - assert.emits(receipt, "WithdrawalRequested", { + assert.emits(receipt, 'WithdrawalRequested', { requestId: 1, requestor: user.toLowerCase(), owner: owner.toLowerCase(), @@ -124,8 +126,10 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { await steth.setTotalPooledEther(amount) await steth.approve(withdrawalQueue.address, amount, { from: user }) - await assert.reverts(withdrawalQueue.requestWithdrawals([amount], owner, { from: user }), - `RequestAmountTooLarge(${amount})`) + await assert.reverts( + withdrawalQueue.requestWithdrawals([amount], owner, { from: user }), + `RequestAmountTooLarge(${amount})` + ) }) it('One can request MAX', async () => { @@ -134,14 +138,14 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { await steth.approve(withdrawalQueue.address, max, { from: user }) const receipt = await withdrawalQueue.requestWithdrawals([max], owner, { from: user }) - const requestId = getEventArgument(receipt, "WithdrawalRequested", "requestId") + const requestId = getEventArgument(receipt, 'WithdrawalRequested', 'requestId') - assert.emits(receipt, "WithdrawalRequested", { + assert.emits(receipt, 'WithdrawalRequested', { requestId: 1, requestor: user.toLowerCase(), owner: owner.toLowerCase(), amountOfStETH: max, - amountOfShares: shares(1) + amountOfShares: shares(1), }) assert.equals(await withdrawalQueue.getLastRequestId(), requestId) @@ -157,15 +161,19 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { }) it('One cant request more than they have', async () => { - await assert.reverts(withdrawalQueue.requestWithdrawals([StETH(400)], owner, { from: user }), - "TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE") + await assert.reverts( + withdrawalQueue.requestWithdrawals([StETH(400)], owner, { from: user }), + 'TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE' + ) }) it('One cant request more than allowed', async () => { await steth.approve(withdrawalQueue.address, StETH(200), { from: user }) - await assert.reverts(withdrawalQueue.requestWithdrawals([StETH(300)], owner, { from: user }), - "TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE") + await assert.reverts( + withdrawalQueue.requestWithdrawals([StETH(300)], owner, { from: user }), + 'TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE' + ) }) }) @@ -184,19 +192,27 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { }) it('Finalizer can finalize a request', async () => { - await assert.reverts(withdrawalQueue.finalize(1, { from: stranger }), - `AccessControl: account ${stranger.toLowerCase()} is missing role ${await withdrawalQueue.FINALIZE_ROLE()}`) + await assert.reverts( + withdrawalQueue.finalize(1, { from: stranger }), + `AccessControl: account ${stranger.toLowerCase()} is missing role ${await withdrawalQueue.FINALIZE_ROLE()}` + ) await withdrawalQueue.finalize(1, { from: steth.address, value: amount }) assert.equals(await withdrawalQueue.getLockedEtherAmount(), amount) - assert.equals(await withdrawalQueue.getLockedEtherAmount(), await ethers.provider.getBalance(withdrawalQueue.address)) + assert.equals( + await withdrawalQueue.getLockedEtherAmount(), + await ethers.provider.getBalance(withdrawalQueue.address) + ) }) it('One can finalize requests with discount', async () => { await withdrawalQueue.finalize(1, { from: steth.address, value: ETH(150) }) assert.equals(await withdrawalQueue.getLockedEtherAmount(), ETH(150)) - assert.equals(await withdrawalQueue.getLockedEtherAmount(), await ethers.provider.getBalance(withdrawalQueue.address)) + assert.equals( + await withdrawalQueue.getLockedEtherAmount(), + await ethers.provider.getBalance(withdrawalQueue.address) + ) }) it('Same discounts is squashed into one', async () => { @@ -226,7 +242,10 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { assert.equals(await withdrawalQueue.getLastRequestId(), 2) assert.equals(await withdrawalQueue.getLastFinalizedRequestId(), 2) assert.equals(await withdrawalQueue.getLockedEtherAmount(), ETH(600)) - assert.equals(await withdrawalQueue.getLockedEtherAmount(), await ethers.provider.getBalance(withdrawalQueue.address)) + assert.equals( + await withdrawalQueue.getLockedEtherAmount(), + await ethers.provider.getBalance(withdrawalQueue.address) + ) }) it('One can finalize part of the queue', async () => { @@ -241,14 +260,20 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { assert.equals(await withdrawalQueue.getLastRequestId(), 2) assert.equals(await withdrawalQueue.getLastFinalizedRequestId(), 1) assert.equals(await withdrawalQueue.getLockedEtherAmount(), ETH(300)) - assert.equals(await withdrawalQueue.getLockedEtherAmount(), await ethers.provider.getBalance(withdrawalQueue.address)) + assert.equals( + await withdrawalQueue.getLockedEtherAmount(), + await ethers.provider.getBalance(withdrawalQueue.address) + ) await withdrawalQueue.finalize(2, { from: steth.address, value: amount }) assert.equals(await withdrawalQueue.getLastRequestId(), 2) assert.equals(await withdrawalQueue.getLastFinalizedRequestId(), 2) assert.equals(await withdrawalQueue.getLockedEtherAmount(), ETH(600)) - assert.equals(await withdrawalQueue.getLockedEtherAmount(), await ethers.provider.getBalance(withdrawalQueue.address)) + assert.equals( + await withdrawalQueue.getLockedEtherAmount(), + await ethers.provider.getBalance(withdrawalQueue.address) + ) }) }) @@ -318,8 +343,14 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { }) it('One cant claim not finalized or not existed request', async () => { - await assert.reverts(withdrawalQueue.claimWithdrawals([1], [1], { from: owner }), `RequestNotFoundOrNotFinalized(1)`) - await assert.reverts(withdrawalQueue.claimWithdrawals([2], [1], { from: owner }), `RequestNotFoundOrNotFinalized(2)`) + await assert.reverts( + withdrawalQueue.claimWithdrawals([1], [1], { from: owner }), + `RequestNotFoundOrNotFinalized(1)` + ) + await assert.reverts( + withdrawalQueue.claimWithdrawals([2], [1], { from: owner }), + `RequestNotFoundOrNotFinalized(2)` + ) }) it('Cant claim request with a wrong hint', async () => { @@ -338,8 +369,7 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { await withdrawalQueue.finalize(1, { from: steth.address, value: amount }) await withdrawalQueue.claimWithdrawal(1, { from: owner }) - await assert.reverts(withdrawalQueue.claimWithdrawal(1, { from: owner }), - 'RequestAlreadyClaimed(1)') + await assert.reverts(withdrawalQueue.claimWithdrawal(1, { from: owner }), 'RequestAlreadyClaimed(1)') }) it('Discounted withdrawals produce less eth', async () => { @@ -382,17 +412,17 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { }) context('findLastFinalizableRequestIdByTimestamp()', async () => { - const numOfRequests = 10; + const numOfRequests = 10 beforeEach(async () => { - for (i = 1; i <= numOfRequests; i++) { + for (let i = 1; i <= numOfRequests; i++) { await withdrawalQueue.requestWithdrawals([ETH(20)], owner, { from: user }) } }) it('works', async () => { for (let i = 1; i <= numOfRequests; i++) { - const timestamp = ((await withdrawalQueue.getWithdrawalStatus([i]))[0]).timestamp; + const timestamp = (await withdrawalQueue.getWithdrawalStatus([i]))[0].timestamp assert.equals(await withdrawalQueue.findLastFinalizableRequestIdByTimestamp(timestamp, 1, 10), i) } }) @@ -402,32 +432,37 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { }) it('return zero if no unfinalized request found', async () => { - const timestamp = ((await withdrawalQueue.getWithdrawalStatus([1]))[0]).timestamp; + const timestamp = (await withdrawalQueue.getWithdrawalStatus([1]))[0].timestamp await withdrawalQueue.finalize(1, { from: steth.address, value: ETH[10] }) assert.equals(await withdrawalQueue.findLastFinalizableRequestIdByTimestamp(timestamp, 2, 10), 0) }) it('checks params', async () => { - await assert.reverts(withdrawalQueue.findLastFinalizableRequestIdByTimestamp(0, 0, 10), - "ZeroTimestamp()") + await assert.reverts(withdrawalQueue.findLastFinalizableRequestIdByTimestamp(0, 0, 10), 'ZeroTimestamp()') - const timestamp = ((await withdrawalQueue.getWithdrawalStatus([2]))[0]).timestamp; + const timestamp = (await withdrawalQueue.getWithdrawalStatus([2]))[0].timestamp - await assert.reverts(withdrawalQueue.findLastFinalizableRequestIdByTimestamp(timestamp, 0, 10), - "InvalidRequestIdRange(0, 10)") + await assert.reverts( + withdrawalQueue.findLastFinalizableRequestIdByTimestamp(timestamp, 0, 10), + 'InvalidRequestIdRange(0, 10)' + ) - await assert.reverts(withdrawalQueue.findLastFinalizableRequestIdByTimestamp(timestamp, 0, 11), - "InvalidRequestIdRange(0, 11)") + await assert.reverts( + withdrawalQueue.findLastFinalizableRequestIdByTimestamp(timestamp, 0, 11), + 'InvalidRequestIdRange(0, 11)' + ) await withdrawalQueue.finalize(1, { from: steth.address, value: ETH(20) }) - await assert.reverts(withdrawalQueue.findLastFinalizableRequestIdByTimestamp(timestamp, 1, 10), - "InvalidRequestIdRange(1, 10)") + await assert.reverts( + withdrawalQueue.findLastFinalizableRequestIdByTimestamp(timestamp, 1, 10), + 'InvalidRequestIdRange(1, 10)' + ) }) }) context('findLastFinalizableRequestIdByBudget()', async () => { - const numOfRequests = 10; + const numOfRequests = 10 beforeEach(async () => { for (let i = 1; i <= numOfRequests; i++) { @@ -440,7 +475,7 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { const rate = shareRate(150) for (let i = 1; i <= numOfRequests; i++) { - const budget = ETH(i * 10 + 5); + const budget = ETH(i * 10 + 5) assert.equals(await withdrawalQueue.findLastFinalizableRequestIdByBudget(budget, rate, 1, 10), i) } }) @@ -455,26 +490,36 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { }) it('checks params', async () => { - await assert.reverts(withdrawalQueue.findLastFinalizableRequestIdByBudget(ETH(0), shareRate(300), 0, 10), - "ZeroAmountOfETH()") + await assert.reverts( + withdrawalQueue.findLastFinalizableRequestIdByBudget(ETH(0), shareRate(300), 0, 10), + 'ZeroAmountOfETH()' + ) - await assert.reverts(withdrawalQueue.findLastFinalizableRequestIdByBudget(ETH(1), shareRate(0), 0, 10), - "ZeroShareRate()") + await assert.reverts( + withdrawalQueue.findLastFinalizableRequestIdByBudget(ETH(1), shareRate(0), 0, 10), + 'ZeroShareRate()' + ) - await assert.reverts(withdrawalQueue.findLastFinalizableRequestIdByBudget(ETH(1), shareRate(300), 0, 10), - "InvalidRequestIdRange(0, 10)") + await assert.reverts( + withdrawalQueue.findLastFinalizableRequestIdByBudget(ETH(1), shareRate(300), 0, 10), + 'InvalidRequestIdRange(0, 10)' + ) - await assert.reverts(withdrawalQueue.findLastFinalizableRequestIdByBudget(ETH(1), shareRate(300), 0, 11), - "InvalidRequestIdRange(0, 11)") + await assert.reverts( + withdrawalQueue.findLastFinalizableRequestIdByBudget(ETH(1), shareRate(300), 0, 11), + 'InvalidRequestIdRange(0, 11)' + ) await withdrawalQueue.finalize(1, { from: steth.address, value: ETH(20) }) - await assert.reverts(withdrawalQueue.findLastFinalizableRequestIdByBudget(ETH(1), shareRate(300), 1, 10), - "InvalidRequestIdRange(1, 10)") + await assert.reverts( + withdrawalQueue.findLastFinalizableRequestIdByBudget(ETH(1), shareRate(300), 1, 10), + 'InvalidRequestIdRange(1, 10)' + ) }) }) context('findLastFinalizableRequestId()', async () => { - const numOfRequests = 10; + const numOfRequests = 10 beforeEach(async () => { for (let i = 1; i <= numOfRequests + 1; i++) { @@ -484,8 +529,8 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { it('works', async () => { for (let i = 1; i <= numOfRequests; i++) { - const budget = ETH(i * 10 + 5); - const timestamp = (await withdrawalQueue.getWithdrawalStatus([i]))[0].timestamp; + const budget = ETH(i * 10 + 5) + const timestamp = (await withdrawalQueue.getWithdrawalStatus([i]))[0].timestamp assert.equals(await withdrawalQueue.findLastFinalizableRequestId(budget, shareRate(150), timestamp), i) } }) @@ -493,26 +538,25 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { it('returns zero if no unfinalized requests', async () => { await withdrawalQueue.finalize(10, { from: steth.address, value: ETH[10] }) - const timestamp = (await withdrawalQueue.getWithdrawalStatus([10]))[0].timestamp; + const timestamp = (await withdrawalQueue.getWithdrawalStatus([10]))[0].timestamp assert.equals(await withdrawalQueue.findLastFinalizableRequestId(ETH(100), shareRate(100), timestamp), 0) }) it('checks params', async () => { - await assert.reverts(withdrawalQueue.findLastFinalizableRequestId(ETH(0), shareRate(300), 1), - "ZeroAmountOfETH()") + await assert.reverts(withdrawalQueue.findLastFinalizableRequestId(ETH(0), shareRate(300), 1), 'ZeroAmountOfETH()') - await assert.reverts(withdrawalQueue.findLastFinalizableRequestId(ETH(1), shareRate(0), 1), - "ZeroShareRate()") + await assert.reverts(withdrawalQueue.findLastFinalizableRequestId(ETH(1), shareRate(0), 1), 'ZeroShareRate()') - await assert.reverts(withdrawalQueue.findLastFinalizableRequestId(ETH(1), shareRate(1), 0), - "ZeroTimestamp()") + await assert.reverts(withdrawalQueue.findLastFinalizableRequestId(ETH(1), shareRate(1), 0), 'ZeroTimestamp()') }) }) context('findCheckpointsHint()', async () => { - const numOfRequests = 10; + const numOfRequests = 10 const requests = Array(numOfRequests).fill(ETH(20)) - const discountedPrices = Array(numOfRequests).fill().map((_, i) => ETH(i)); + const discountedPrices = Array(numOfRequests) + .fill() + .map((_, i) => ETH(i)) beforeEach(async () => { await withdrawalQueue.requestWithdrawals(requests, owner, { from: user }) @@ -520,24 +564,28 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { await withdrawalQueue.finalize(i, { from: steth.address, value: discountedPrices[i] }) } assert.equals(await withdrawalQueue.getLastCheckpointIndex(), numOfRequests) - assert.equals(await withdrawalQueue.findCheckpointHintsUnbounded([await withdrawalQueue.getLastFinalizedRequestId()]), - await withdrawalQueue.getLastCheckpointIndex()) + assert.equals( + await withdrawalQueue.findCheckpointHintsUnbounded([await withdrawalQueue.getLastFinalizedRequestId()]), + await withdrawalQueue.getLastCheckpointIndex() + ) }) it('works unbounded', async () => { - assert.equals(await withdrawalQueue.findCheckpointHintsUnbounded([10]), await withdrawalQueue.getLastCheckpointIndex()) + assert.equals( + await withdrawalQueue.findCheckpointHintsUnbounded([10]), + await withdrawalQueue.getLastCheckpointIndex() + ) }) it('reverts if request is not finalized', async () => { await withdrawalQueue.requestWithdrawals([ETH(1)], owner, { from: user }) - await assert.reverts(withdrawalQueue.findCheckpointHints([11], 1, 10), "RequestNotFoundOrNotFinalized(11)") - await assert.reverts(withdrawalQueue.findCheckpointHintsUnbounded([11]), "RequestNotFoundOrNotFinalized(11)") - + await assert.reverts(withdrawalQueue.findCheckpointHints([11], 1, 10), 'RequestNotFoundOrNotFinalized(11)') + await assert.reverts(withdrawalQueue.findCheckpointHintsUnbounded([11]), 'RequestNotFoundOrNotFinalized(11)') }) it('reverts if there is no such a request', async () => { - await assert.reverts(withdrawalQueue.findCheckpointHints([12], 1, 10), "RequestNotFoundOrNotFinalized(12)") - await assert.reverts(withdrawalQueue.findCheckpointHintsUnbounded([12]), "RequestNotFoundOrNotFinalized(12)") + await assert.reverts(withdrawalQueue.findCheckpointHints([12], 1, 10), 'RequestNotFoundOrNotFinalized(12)') + await assert.reverts(withdrawalQueue.findCheckpointHintsUnbounded([12]), 'RequestNotFoundOrNotFinalized(12)') }) it('range search (found)', async () => { @@ -555,22 +603,28 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { }) it('sequential search', async () => { - for ([idToFind, searchLength] of [[1, 3], [1, 10], [10, 2], [10, 3], [8, 2], [9, 3]]) { + for ([idToFind, searchLength] of [ + [1, 3], + [1, 10], + [10, 2], + [10, 3], + [8, 2], + [9, 3], + ]) { assert.equals(await sequentialSearch(idToFind, searchLength), idToFind) } }) const sequentialSearch = async (requestId, searchLength) => { - let lastIndex = await withdrawalQueue.getLastCheckpointIndex() + const lastIndex = await withdrawalQueue.getLastCheckpointIndex() for (let i = 1; i <= lastIndex; i += searchLength) { let end = i + searchLength - 1 if (end > lastIndex) end = lastIndex - let foundIndex = await withdrawalQueue.findCheckpointHints([requestId], i, end) - if (foundIndex != 0) return foundIndex + const foundIndex = await withdrawalQueue.findCheckpointHints([requestId], i, end) + if (+foundIndex !== 0) return foundIndex } } - }) context('findCheckpointHints()', () => { @@ -777,7 +831,7 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { deadline, // deadline v, r, - s + s, ] const aliceBalancesBefore = await wsteth.balanceOf(alice.address) @@ -802,26 +856,30 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { const senderWithdrawalsBefore = await withdrawalQueue.getWithdrawalRequests(user) const ownerWithdrawalsBefore = await withdrawalQueue.getWithdrawalRequests(owner) - assert.isTrue(senderWithdrawalsBefore.map(v => v.toNumber()).includes(requestId)) - assert.isFalse(ownerWithdrawalsBefore.map(v => v.toNumber()).includes(requestId)) + assert.isTrue(senderWithdrawalsBefore.map((v) => v.toNumber()).includes(requestId)) + assert.isFalse(ownerWithdrawalsBefore.map((v) => v.toNumber()).includes(requestId)) await withdrawalQueue.transferFrom(user, owner, requestId, { from: user }) const senderWithdrawalAfter = await withdrawalQueue.getWithdrawalRequests(user) const ownerWithdrawalsAfter = await withdrawalQueue.getWithdrawalRequests(owner) - assert.isFalse(senderWithdrawalAfter.map(v => v.toNumber()).includes(requestId)) - assert.isTrue(ownerWithdrawalsAfter.map(v => v.toNumber()).includes(requestId)) + assert.isFalse(senderWithdrawalAfter.map((v) => v.toNumber()).includes(requestId)) + assert.isTrue(ownerWithdrawalsAfter.map((v) => v.toNumber()).includes(requestId)) }) it("One can't change someone else's request", async () => { - await assert.reverts(withdrawalQueue.transferFrom(user, owner, requestId, { from: stranger }), - `NotOwnerOrApproved("${stranger}")`) + await assert.reverts( + withdrawalQueue.transferFrom(user, owner, requestId, { from: stranger }), + `NotOwnerOrApproved("${stranger}")` + ) }) it("One can't pass zero owner", async () => { - await assert.reverts(withdrawalQueue.transferFrom(user, ZERO_ADDRESS, requestId, { from: user }), - 'TransferToZeroAddress()') + await assert.reverts( + withdrawalQueue.transferFrom(user, ZERO_ADDRESS, requestId, { from: user }), + 'TransferToZeroAddress()' + ) }) it("One can't pass zero requestId", async () => { @@ -832,13 +890,18 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { await withdrawalQueue.finalize(requestId, { from: steth.address, value: amount }) await withdrawalQueue.claimWithdrawal(requestId, { from: user }) - await assert.reverts(withdrawalQueue.transferFrom(user, owner, requestId, { from: user }), `RequestAlreadyClaimed(1)`) + await assert.reverts( + withdrawalQueue.transferFrom(user, owner, requestId, { from: user }), + `RequestAlreadyClaimed(1)` + ) }) it("Changing owner doesn't work with wrong request id", async () => { const wrongRequestId = requestId + 1 - await assert.reverts(withdrawalQueue.transferFrom(user, owner, wrongRequestId, { from: user }), - `InvalidRequestId(${wrongRequestId})`) + await assert.reverts( + withdrawalQueue.transferFrom(user, owner, wrongRequestId, { from: user }), + `InvalidRequestId(${wrongRequestId})` + ) }) }) @@ -852,12 +915,14 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { for (let i = 0; i < firstRequestCount; i++) { await withdrawalQueue.requestWithdrawals([ETH(1 / secondRequestCount)], user, { from: user }) } - const firstGasUsed = (await withdrawalQueue.changeRecipient(firstRequestCount - 1, owner, { from: user })).receipt.gasUsed + const firstGasUsed = (await withdrawalQueue.changeRecipient(firstRequestCount - 1, owner, { from: user })).receipt + .gasUsed for (let i = firstRequestCount; i < secondRequestCount; i++) { await withdrawalQueue.requestWithdrawals([ETH(1 / secondRequestCount)], user, { from: user }) } - const secondGasUsed = (await withdrawalQueue.changeRecipient(secondRequestCount / 2, owner, { from: user })).receipt.gasUsed + const secondGasUsed = (await withdrawalQueue.changeRecipient(secondRequestCount / 2, owner, { from: user })) + .receipt.gasUsed assert.isTrue(firstGasUsed >= secondGasUsed) }) diff --git a/test/0.8.9/withdrawal-request-nft.test.js b/test/0.8.9/withdrawal-request-nft.test.js index d38a37440..d45a4d596 100644 --- a/test/0.8.9/withdrawal-request-nft.test.js +++ b/test/0.8.9/withdrawal-request-nft.test.js @@ -21,7 +21,7 @@ hre.contract( wstETH = await WstETH.new(stETH.address, { from: deployer }) erc721ReceiverMock = await ERC721ReceiverMock.new({ from: deployer }) - withdrawalQueueERC721 = (await withdrawals.deploy(deployer, wstETH.address, "Lido TEST Request", "unstEsT")).queue + withdrawalQueueERC721 = (await withdrawals.deploy(deployer, wstETH.address, 'Lido TEST Request', 'unstEsT')).queue await withdrawalQueueERC721.initialize( deployer, // owner deployer, // pauser @@ -52,8 +52,8 @@ hre.contract( describe('ERC721Metadata', () => { it('Initial properties', async () => { - assert.equals(await withdrawalQueueERC721.symbol(), "unstEsT") - assert.equals(await withdrawalQueueERC721.name(), "Lido TEST Request") + assert.equals(await withdrawalQueueERC721.symbol(), 'unstEsT') + assert.equals(await withdrawalQueueERC721.name(), 'Lido TEST Request') }) }) @@ -145,7 +145,7 @@ hre.contract( it('reverts with message "NotOwnerOrApproved()" when approvalNotSet and not owner', async () => { await assert.reverts( withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: stranger + from: stranger, }), `NotOwnerOrApproved("${stranger}")` ) @@ -154,7 +154,7 @@ hre.contract( it('transfers if called by owner', async () => { assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: nftHolderStETH + from: nftHolderStETH, }) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) }) @@ -163,7 +163,7 @@ hre.contract( await withdrawalQueueERC721.approve(recipient, nftHolderStETHTokenIds[0], { from: nftHolderStETH }) assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: recipient + from: recipient, }) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) }) @@ -173,10 +173,10 @@ hre.contract( assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: recipient + from: recipient, }) await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[1], { - from: recipient + from: recipient, }) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) @@ -185,7 +185,7 @@ hre.contract( it('reverts with message "TransferToNonIERC721Receiver()" when transfer to contract that not implements IERC721Receiver interface', async () => { await assert.reverts( withdrawalQueueERC721.safeTransferFrom(nftHolderWstETH, stETH.address, nftHolderWstETHTokenIds[0], { - from: nftHolderWstETH + from: nftHolderWstETH, }), `TransferToNonIERC721Receiver("${stETH.address}")` ) @@ -194,9 +194,14 @@ hre.contract( it('reverts with propagated error message when recipient contract implements ERC721Receiver and reverts on onERC721Received call', async () => { await erc721ReceiverMock.setDoesAcceptTokens(false, { from: deployer }) await assert.reverts( - withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, erc721ReceiverMock.address, nftHolderStETHTokenIds[0], { - from: nftHolderStETH - }), + withdrawalQueueERC721.safeTransferFrom( + nftHolderStETH, + erc721ReceiverMock.address, + nftHolderStETHTokenIds[0], + { + from: nftHolderStETH, + } + ), 'ERC721_NOT_ACCEPT_TOKENS' ) }) @@ -209,7 +214,7 @@ hre.contract( erc721ReceiverMock.address, nftHolderStETHTokenIds[0], { - from: nftHolderStETH + from: nftHolderStETH, } ) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), erc721ReceiverMock.address) @@ -226,10 +231,9 @@ hre.contract( it('reverts when transfer to the same address', async () => { await assert.reverts( - withdrawalQueueERC721.transferFrom( - nftHolderWstETH, nftHolderWstETH, nftHolderWstETHTokenIds[0], - {from: nftHolderWstETH } - ), + withdrawalQueueERC721.transferFrom(nftHolderWstETH, nftHolderWstETH, nftHolderWstETHTokenIds[0], { + from: nftHolderWstETH, + }), 'TransferToThemselves()' ) }) @@ -239,7 +243,7 @@ hre.contract( await withdrawalQueueERC721.finalize(3, { from: deployer, value: batch.ethToLock }) const ownerETHBefore = await hre.ethers.provider.getBalance(nftHolderStETH) const tx = await withdrawalQueueERC721.methods['claimWithdrawal(uint256)'](nftHolderStETHTokenIds[0], { - from: nftHolderStETH + from: nftHolderStETH, }) const ownerETHAfter = await hre.ethers.provider.getBalance(nftHolderStETH) // adhoc fix for solidity-coverage that ignores gasPrice = 0 @@ -247,7 +251,7 @@ hre.contract( await assert.reverts( withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: nftHolderStETH + from: nftHolderStETH, }), `RequestAlreadyClaimed(${nftHolderStETHTokenIds[0]})` ) @@ -256,7 +260,7 @@ hre.contract( it('transfers if called by owner', async () => { assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), recipient) await withdrawalQueueERC721.transferFrom(nftHolderWstETH, recipient, nftHolderWstETHTokenIds[0], { - from: nftHolderWstETH + from: nftHolderWstETH, }) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), recipient) }) @@ -265,7 +269,7 @@ hre.contract( await withdrawalQueueERC721.approve(recipient, nftHolderStETHTokenIds[0], { from: nftHolderStETH }) assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: recipient + from: recipient, }) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) }) @@ -275,10 +279,10 @@ hre.contract( assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: recipient + from: recipient, }) await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[1], { - from: recipient + from: recipient, }) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) @@ -286,7 +290,7 @@ hre.contract( it('can claim request after transfer', async () => { await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: nftHolderStETH + from: nftHolderStETH, }) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) @@ -295,7 +299,7 @@ hre.contract( const recipientETHBefore = await hre.ethers.provider.getBalance(recipient) const tx = await withdrawalQueueERC721.methods['claimWithdrawal(uint256)'](nftHolderStETHTokenIds[0], { - from: recipient + from: recipient, }) const recipientETHAfter = await hre.ethers.provider.getBalance(recipient) // adhoc fix for solidity-coverage that ignores gasPrice = 0 @@ -305,7 +309,7 @@ hre.contract( it("doesn't reverts when transfer to contract that not implements IERC721Receiver interface", async () => { assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), nftHolderWstETH) await withdrawalQueueERC721.transferFrom(nftHolderWstETH, stETH.address, nftHolderWstETHTokenIds[0], { - from: nftHolderWstETH + from: nftHolderWstETH, }) assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), stETH.address) }) @@ -313,16 +317,16 @@ hre.contract( describe('Burn', () => { it('balanceOf decreases after claim', async () => { - const balanceBefore = await withdrawalQueueERC721.balanceOf(nftHolderStETH); + const balanceBefore = await withdrawalQueueERC721.balanceOf(nftHolderStETH) const batch = await withdrawalQueueERC721.finalizationBatch(3, shareRate(1)) await withdrawalQueueERC721.finalize(3, { from: deployer, value: batch.ethToLock }) await withdrawalQueueERC721.methods['claimWithdrawal(uint256)'](nftHolderStETHTokenIds[0], { - from: nftHolderStETH + from: nftHolderStETH, }) - assert.equals(balanceBefore - await withdrawalQueueERC721.balanceOf(nftHolderStETH), 1) + assert.equals(balanceBefore - (await withdrawalQueueERC721.balanceOf(nftHolderStETH)), 1) }) }) } diff --git a/test/common/lib/min-first-allocation-strategy.test.js b/test/common/lib/min-first-allocation-strategy.test.js index 642876eb2..4d18a0616 100644 --- a/test/common/lib/min-first-allocation-strategy.test.js +++ b/test/common/lib/min-first-allocation-strategy.test.js @@ -8,10 +8,10 @@ const MinFirstAlgorithmModernConsumer = hre.artifacts.require('MinFirstAllocatio contract('MinFirstAllocationStrategy', (accounts) => { for (const [consumerVersion, consumerFactory] of [ ['Legacy (Solidity 0.4.24)', MinFirstAlgorithmLegacyConsumer], - ['Modern (Solidity 0.8.9)', MinFirstAlgorithmModernConsumer] + ['Modern (Solidity 0.8.9)', MinFirstAlgorithmModernConsumer], ]) { describe(consumerVersion, async function () { - this.timeout(0, 'Test suite takes too long') //it takes even longer in coverage tests, so disable timeout here + this.timeout(0, 'Test suite takes too long') // it takes even longer in coverage tests, so disable timeout here let minFirstAllocationStrategy const [deployer] = accounts let evmSnapshotId @@ -113,20 +113,20 @@ contract('MinFirstAllocationStrategy', (accounts) => { const edgeCases = [ { input: [[0, 0, 0, 0], [0, 0, 0, 0], 100], - output: [0, [0, 0, 0, 0]] + output: [0, [0, 0, 0, 0]], }, { input: [[100, 100, 100], [200, 300, 600], 600], - output: [100, [200, 100, 100]] + output: [100, [200, 100, 100]], }, { input: [[0, 0], [10, 20], 100], - output: [10, [10, 0]] + output: [10, [10, 0]], }, { input: [[9998, 70, 0], [10099, 101, 100], 101], - output: [70, [9998, 70, 70]] - } + output: [70, [9998, 70, 70]], + }, ] // covering multiple cases in a single unit test to prevent terminal output flooding @@ -248,24 +248,24 @@ contract('MinFirstAllocationStrategy', (accounts) => { const edgeCases = [ { input: [[0, 0, 0, 0], [0, 0, 0, 0], 100], - output: [0, [0, 0, 0, 0]] + output: [0, [0, 0, 0, 0]], }, { input: [[100, 100, 100], [200, 300, 600], 600], - output: [600, [200, 300, 400]] + output: [600, [200, 300, 400]], }, { input: [[0, 0], [10, 20], 100], - output: [30, [10, 20]] + output: [30, [10, 20]], }, { input: [[9998, 70, 0], [10099, 101, 100], 101], - output: [101, [9998, 86, 85]] + output: [101, [9998, 86, 85]], }, { input: [[3379, 495, 5572], [7185, 1061, 3265], 1007], - output: [1007, [3820, 1061, 5572]] - } + output: [1007, [3820, 1061, 5572]], + }, ] // covering multiple cases in a single unit test to prevent terminal output flooding // if this test fails, try zeroing in on the specific case by moving `it()` function inside of the deepest loop @@ -305,7 +305,7 @@ function getAssertMessage(allocations, capacities, maxAllocationSize, expectedNe return [ `Allocations mismatch: [${allocations}] [${capacities}] ${maxAllocationSize}.`, `Expected: [${expectedNewAllocations}]`, - `Actual [${actualAllocations}]` + `Actual [${actualAllocations}]`, ].join(' ') } diff --git a/test/deposit.test.js b/test/deposit.test.js index f9906c3cb..2e630d307 100644 --- a/test/deposit.test.js +++ b/test/deposit.test.js @@ -45,18 +45,18 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d targetShares: 10000, moduleFee: 500, treasuryFee: 500, - } + }, ] }, depositSecurityModuleFactory: async () => { return { address: depositor } }, - depositContractFactory: depositContractFactory, + depositContractFactory, postSetup: async ({ pool, lidoLocator, eip712StETH, withdrawalQueue, appManager, voting }) => { await pool.initialize(lidoLocator.address, eip712StETH.address, { value: ETH(1) }) await withdrawalQueue.updateBunkerMode(false, 0, { from: appManager.address }) await pool.resumeProtocolAndStaking({ from: voting.address }) - } + }, }) app = deployed.pool @@ -209,16 +209,28 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d // id: 2 await nodeOperators.addNodeOperator( operators, - { name: 'deactivated', rewardAddress: ADDRESS_3, totalSigningKeysCount: 2, vettedSigningKeysCount: 2, isActive: false }, + { + name: 'deactivated', + rewardAddress: ADDRESS_3, + totalSigningKeysCount: 2, + vettedSigningKeysCount: 2, + isActive: false, + }, { from: voting } ) // id: 3 - await nodeOperators.addNodeOperator(operators, { name: 'short on keys', rewardAddress: ADDRESS_4 }, { from: voting }) + await nodeOperators.addNodeOperator( + operators, + { name: 'short on keys', rewardAddress: ADDRESS_4 }, + { from: voting } + ) // Deposit huge chunk - await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(32 * 3 + 50 - 1/* initial */) }) - tx = await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) + await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(32 * 3 + 50 - 1 /* initial */) }) + tx = await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { + from: depositor, + }) // assertEvent(tx, 'StakingRouterTransferReceived') @@ -343,12 +355,22 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d // id: 2 await nodeOperators.addNodeOperator( operators, - { name: 'deactivated', rewardAddress: ADDRESS_3, totalSigningKeysCount: 2, vettedSigningKeysCount: 2, isActive: false }, + { + name: 'deactivated', + rewardAddress: ADDRESS_3, + totalSigningKeysCount: 2, + vettedSigningKeysCount: 2, + isActive: false, + }, { from: voting } ) // id: 3 - await nodeOperators.addNodeOperator(operators, { name: 'short on keys', rewardAddress: ADDRESS_4 }, { from: voting }) + await nodeOperators.addNodeOperator( + operators, + { name: 'short on keys', rewardAddress: ADDRESS_4 }, + { from: voting } + ) // Small deposits for (let i = 0; i < 14; i++) await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(10) }) @@ -459,21 +481,39 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await stakingRouter.setWithdrawalCredentials(pad('0x0202', 32), { from: voting }) await operators.addNodeOperator('good', ADDRESS_1, { from: voting }) // 0 - await operators.addSigningKeys(0, 2, hexConcat(pad('0x0001', 48), pad('0x0002', 48)), hexConcat(pad('0x01', 96), pad('0x01', 96)), { - from: voting - }) + await operators.addSigningKeys( + 0, + 2, + hexConcat(pad('0x0001', 48), pad('0x0002', 48)), + hexConcat(pad('0x01', 96), pad('0x01', 96)), + { + from: voting, + } + ) await operators.setNodeOperatorStakingLimit(0, UNLIMITED, { from: voting }) await operators.addNodeOperator('2nd good', ADDRESS_2, { from: voting }) // 1 - await operators.addSigningKeys(1, 2, hexConcat(pad('0x0101', 48), pad('0x0102', 48)), hexConcat(pad('0x01', 96), pad('0x01', 96)), { - from: voting - }) + await operators.addSigningKeys( + 1, + 2, + hexConcat(pad('0x0101', 48), pad('0x0102', 48)), + hexConcat(pad('0x01', 96), pad('0x01', 96)), + { + from: voting, + } + ) await operators.setNodeOperatorStakingLimit(1, UNLIMITED, { from: voting }) await operators.addNodeOperator('deactivated', ADDRESS_3, { from: voting }) // 2 - await operators.addSigningKeys(2, 2, hexConcat(pad('0x0201', 48), pad('0x0202', 48)), hexConcat(pad('0x01', 96), pad('0x01', 96)), { - from: voting - }) + await operators.addSigningKeys( + 2, + 2, + hexConcat(pad('0x0201', 48), pad('0x0202', 48)), + hexConcat(pad('0x01', 96), pad('0x01', 96)), + { + from: voting, + } + ) await operators.setNodeOperatorStakingLimit(2, UNLIMITED, { from: voting }) await operators.deactivateNodeOperator(2, { from: voting }) @@ -496,9 +536,15 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d // Reactivation of #2 - has the smallest stake await operators.activateNodeOperator(2, { from: voting }) - await operators.addSigningKeys(2, 2, hexConcat(pad('0x0201', 48), pad('0x0202', 48)), hexConcat(pad('0x01', 96), pad('0x01', 96)), { - from: voting - }) + await operators.addSigningKeys( + 2, + 2, + hexConcat(pad('0x0201', 48), pad('0x0202', 48)), + hexConcat(pad('0x01', 96), pad('0x01', 96)), + { + from: voting, + } + ) await operators.setNodeOperatorStakingLimit(2, UNLIMITED, { from: voting }) await web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(36) }) @@ -527,11 +573,11 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d const keysCount = 100 const keys1 = { keys: [...Array(keysCount)].map((v, i) => pad('0xaa01' + i.toString(16), 48)), - sigs: [...Array(keysCount)].map((v, i) => pad('0x' + i.toString(16), 96)) + sigs: [...Array(keysCount)].map((v, i) => pad('0x' + i.toString(16), 96)), } const keys2 = { keys: [...Array(keysCount)].map((v, i) => pad('0xaa02' + i.toString(16), 48)), - sigs: [...Array(keysCount)].map((v, i) => pad('0x' + i.toString(16), 96)) + sigs: [...Array(keysCount)].map((v, i) => pad('0x' + i.toString(16), 96)), } await operators.addSigningKeys(0, keysCount, hexConcat(...keys1.keys), hexConcat(...keys1.sigs), { from: voting }) await operators.addSigningKeys(1, keysCount, hexConcat(...keys2.keys), hexConcat(...keys2.sigs), { from: voting }) @@ -541,7 +587,10 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(amountToDeposit - 1) }) - await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor, gas: 20000000 }) + await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { + from: depositor, + gas: 20000000, + }) assertBn(await app.getTotalPooledEther(), ETH(amountToDeposit)) assertBn(await app.getBufferedEther(), ETH(31)) @@ -559,11 +608,11 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d const keysCount = 100 const keys1 = { keys: [...Array(keysCount)].map((v, i) => pad('0xaa01' + i.toString(16), 48)), - sigs: [...Array(keysCount)].map((v, i) => pad('0x' + i.toString(16), 96)) + sigs: [...Array(keysCount)].map((v, i) => pad('0x' + i.toString(16), 96)), } const keys2 = { keys: [...Array(keysCount)].map((v, i) => pad('0xaa02' + i.toString(16), 48)), - sigs: [...Array(keysCount)].map((v, i) => pad('0x' + i.toString(16), 96)) + sigs: [...Array(keysCount)].map((v, i) => pad('0x' + i.toString(16), 96)), } await operators.addSigningKeys(0, keysCount, hexConcat(...keys1.keys), hexConcat(...keys1.sigs), { from: voting }) await operators.addSigningKeys(1, keysCount, hexConcat(...keys2.keys), hexConcat(...keys2.sigs), { from: voting }) @@ -575,7 +624,10 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await web3.eth.sendTransaction({ to: user1, from: user2, value: ETH(2000) }) await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(amountToDeposit - 1 /* initial */) }) - await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor, gas: 20000000 }) + await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { + from: depositor, + gas: 20000000, + }) assertBn(await app.getTotalPooledEther(), ETH(amountToDeposit)) assertBn(await app.getBufferedEther(), ETH(33)) diff --git a/test/helpers/assert.js b/test/helpers/assert.js index b48d07fad..a1304ca1d 100644 --- a/test/helpers/assert.js +++ b/test/helpers/assert.js @@ -11,33 +11,37 @@ chai.util.addMethod(chai.assert, 'emits', function (receipt, eventName, args = { }) chai.util.addMethod( - chai.assert, 'emitsNumberOfEvents', function (receipt, eventName, numberOfEvents = {}, options = {} -) { - const events = getEvents(receipt, eventName, options.abi) - this.equal( - events.length, - numberOfEvents, - `${eventName}: ${numberOfEvents} events expected, but found ${events.length}` - ) -}) - -chai.util.addMethod( - chai.assert, 'revertsOZAccessControl', async function (receipt, address, role) { - try { - await receipt - } catch (error) { - const msg = error.message.toUpperCase() - const reason = `AccessControl: account ${web3.utils.toChecksumAddress(address)} is missing role ${web3.utils.keccak256(role)}` - - chai.expect(msg).to.equal(`VM Exception while processing transaction: reverted with reason string '${reason}'`.toUpperCase()) - return - } - throw new Error( - `Transaction has been executed without revert. Expected access control error for ${address} without role: ${role}` + chai.assert, + 'emitsNumberOfEvents', + function (receipt, eventName, numberOfEvents = {}, options = {}) { + const events = getEvents(receipt, eventName, options.abi) + this.equal( + events.length, + numberOfEvents, + `${eventName}: ${numberOfEvents} events expected, but found ${events.length}` ) } ) +chai.util.addMethod(chai.assert, 'revertsOZAccessControl', async function (receipt, address, role) { + try { + await receipt + } catch (error) { + const msg = error.message.toUpperCase() + const reason = `AccessControl: account ${web3.utils.toChecksumAddress( + address + )} is missing role ${web3.utils.keccak256(role)}` + + chai + .expect(msg) + .to.equal(`VM Exception while processing transaction: reverted with reason string '${reason}'`.toUpperCase()) + return + } + throw new Error( + `Transaction has been executed without revert. Expected access control error for ${address} without role: ${role}` + ) +}) + chai.util.addMethod(chai.assert, 'notEmits', function (receipt, eventName, args = {}, options = {}) { const { abi } = options const event = getEvent(receipt, eventName, args, abi) @@ -56,13 +60,23 @@ chai.util.addMethod(chai.assert, 'equalsDelta', function (actual, expected, delt const diff = toBN(actual).sub(toBN(expected)).abs() chai.assert( diff.lte(toBN(delta)), - () => `${errorMsg ? `${errorMsg}: ` : ''}Expected ${actual} to be close to ${expected} with max diff ${delta}, actual diff ${diff}`, - () => `${errorMsg ? `${errorMsg}: ` : ''}Expected ${actual} not to be close to ${expected} with min diff ${delta}, actual diff ${diff}`, + () => + `${ + errorMsg ? `${errorMsg}: ` : '' + }Expected ${actual} to be close to ${expected} with max diff ${delta}, actual diff ${diff}`, + () => + `${ + errorMsg ? `${errorMsg}: ` : '' + }Expected ${actual} not to be close to ${expected} with min diff ${delta}, actual diff ${diff}` ) }) chai.util.addMethod(chai.assert, 'notEquals', function (actual, expected, errorMsg) { - this.notEqual(actual.toString(), expected.toString(), `${errorMsg || ""} expected ${expected.toString()} to not equal ${actual.toString()}`) + this.notEqual( + actual.toString(), + expected.toString(), + `${errorMsg || ''} expected ${expected.toString()} to not equal ${actual.toString()}` + ) }) chai.util.addMethod(chai.assert, 'addressEqual', function (actual, expected, errorMsg) { @@ -73,7 +87,9 @@ chai.util.addMethod(chai.assert, 'revertsWithCustomError', async function (recei try { await receipt } catch (error) { - chai.expect(error.message).to.equal(`VM Exception while processing transaction: reverted with custom error '${reason}'`) + chai + .expect(error.message) + .to.equal(`VM Exception while processing transaction: reverted with custom error '${reason}'`) return } throw new Error(`Transaction has been executed without revert. Expected revert reason ${reason}`) diff --git a/test/helpers/assertThrow.js b/test/helpers/assertThrow.js index 7a34b6aaa..ce8267734 100644 --- a/test/helpers/assertThrow.js +++ b/test/helpers/assertThrow.js @@ -10,27 +10,16 @@ const THROW_PREFIX = 'VM Exception while processing transaction: revert' const THROW_PREFIX_V2 = 'VM Exception while processing transaction: reverted with reason string' const THROW_PREFIX_CUSTOM = 'VM Exception while processing transaction: reverted with custom error' -async function assertThrows( - blockOrPromise, - expectedErrorCode, - expectedReason, - ctx -) { +async function assertThrows(blockOrPromise, expectedErrorCode, expectedReason, ctx) { try { - typeof blockOrPromise === 'function' - ? await blockOrPromise() - : await blockOrPromise + typeof blockOrPromise === 'function' ? await blockOrPromise() : await blockOrPromise } catch (error) { if (await isGeth(ctx)) { // With geth, we are only provided the transaction receipt and have to decode the failure // ourselves. const status = error.receipt.status - assert.equal( - status, - '0x0', - `Expected transaction to revert but it executed with status ${status}` - ) + assert.equal(status, '0x0', `Expected transaction to revert but it executed with status ${status}`) if (!expectedReason.length) { // Note that it is difficult to ascertain invalid jumps or out of gas scenarios // and so we simply pass if no revert message is given @@ -48,18 +37,14 @@ async function assertThrows( return error } else { const errorMatchesExpected = error.message.search(expectedErrorCode) > -1 - assert( - errorMatchesExpected, - `Expected error code "${expectedErrorCode}" but failed with "${error}" instead.` - ) + assert(errorMatchesExpected, `Expected error code "${expectedErrorCode}" but failed with "${error}" instead.`) return error } } // assert.fail() for some reason does not have its error string printed 🤷 assert( false, - `Expected "${expectedErrorCode}"${expectedReason ? ` (with reason: "${expectedReason}")` : '' - } but it did not fail` + `Expected "${expectedErrorCode}"${expectedReason ? ` (with reason: "${expectedReason}")` : ''} but it did not fail` ) } @@ -77,12 +62,7 @@ async function assertOutOfGas(blockOrPromise, ctx) { // version of @aragon/contract-helpers-test assertRevert, but with custom errors support async function assertRevert(blockOrPromise, expectedReason, ctx) { - const error = await assertThrows( - blockOrPromise, - 'revert', - expectedReason, - ctx - ) + const error = await assertThrows(blockOrPromise, 'revert', expectedReason, ctx) if (!expectedReason) { return @@ -96,19 +76,16 @@ async function assertRevert(blockOrPromise, expectedReason, ctx) { .replace(THROW_PREFIX_V2, '') .replace(THROW_PREFIX, '') .trim() - .replace(/^'|'$/g, "") + .replace(/^'|'$/g, '') } // Truffle v5 sometimes adds an extra ' -- Reason given: reason.' to the error message 🤷 - error.reason = error.reason - .replace(` -- Reason given: ${expectedReason}.`, '') - .trim() + error.reason = error.reason.replace(` -- Reason given: ${expectedReason}.`, '').trim() assert.equal( error.reason, expectedReason, - `Expected revert reason "${expectedReason}" but failed with "${error.reason || 'no reason' - }" instead.` + `Expected revert reason "${expectedReason}" but failed with "${error.reason || 'no reason'}" instead.` ) } diff --git a/test/helpers/blockchain.js b/test/helpers/blockchain.js index c6ce77081..9a6284490 100644 --- a/test/helpers/blockchain.js +++ b/test/helpers/blockchain.js @@ -70,5 +70,5 @@ module.exports = { getCurrentBlockTimestamp, impersonate, getBalance, - setBalance + setBalance, } diff --git a/test/helpers/config.js b/test/helpers/config.js index c13fa9692..451c89a02 100644 --- a/test/helpers/config.js +++ b/test/helpers/config.js @@ -9,14 +9,14 @@ const DEFAULT_DEPLOY_PARAMS = { guardians: { '0x5fc0e75bf6502009943590492b02a1d08eac9c43': '0x3578665169e03e05a26bd5c565ffd12c81a1e0df7d0679f8aee4153110a83c8c', '0x8516cbb5abe73d775bfc0d21af226e229f7181a3': '0x88868f0fb667cfe50261bb385be8987e0ce62faee934af33c3026cf65f25f09e', - '0xdaead0e0194abd565d28c1013399801d79627c14': '0x75e6f508b637327debc90962cd38943ddb9cfc1fc4a8572fc5e3d0984e1261de' + '0xdaead0e0194abd565d28c1013399801d79627c14': '0x75e6f508b637327debc90962cd38943ddb9cfc1fc4a8572fc5e3d0984e1261de', }, depositRoot: '0xd151867719c94ad8458feaf491809f9bc8096c702a72747403ecaac30c179137', genesisTime: ~~(+new Date() / 1000) - SECONDS_PER_EPOCH * 675, lastCompletedEpoch: 1, v1OracleLastCompletedEpoch: 1, hashConsensus: { - fastLaneLengthSlots: 0 + fastLaneLengthSlots: 0, }, oracleReportSanityChecker: { limitsList: { @@ -41,8 +41,8 @@ const DEFAULT_DEPLOY_PARAMS = { maxNodeOperatorsPerExtraDataItemCountManagers: [], requestTimestampMarginManagers: [], maxPositiveTokenRebaseManagers: [], - } - } + }, + }, } const DEFAULT_FACTORIES = { @@ -74,5 +74,5 @@ const DEFAULT_FACTORIES = { module.exports = { DEFAULT_FACTORIES, - DEFAULT_DEPLOY_PARAMS + DEFAULT_DEPLOY_PARAMS, } diff --git a/test/helpers/constants.js b/test/helpers/constants.js index fcddbf468..ae016dacd 100644 --- a/test/helpers/constants.js +++ b/test/helpers/constants.js @@ -13,7 +13,6 @@ const SECONDS_PER_EPOCH = SLOTS_PER_EPOCH * SECONDS_PER_SLOT const SECONDS_PER_FRAME = SECONDS_PER_EPOCH * EPOCHS_PER_FRAME const SLOTS_PER_FRAME = EPOCHS_PER_FRAME * SLOTS_PER_EPOCH - module.exports = { ZERO_ADDRESS, ZERO_BYTES32, diff --git a/test/helpers/dao.js b/test/helpers/dao.js index 27e3f0c58..144743a74 100644 --- a/test/helpers/dao.js +++ b/test/helpers/dao.js @@ -62,7 +62,7 @@ class AragonDAO { const initPayload = config.initPayload || '0x' const receipt = await this.kernel.newAppInstance(hash(`${name}.aragonpm.test`), base.address, initPayload, false, { - from: this.appManager + from: this.appManager, }) const logs = receipt.logs const log = logs.find((l) => l.event === 'NewAppProxy') @@ -82,7 +82,7 @@ class AragonDAO { async createPermission(entityAddress, app, permissionName) { const permission = await app[permissionName]() return await this.acl.createPermission(entityAddress, app.address, permission, this.appManager, { - from: this.appManager + from: this.appManager, }) } @@ -136,5 +136,5 @@ const newApp = async (dao, appName, baseAppAddress, rootAccount) => { module.exports = { AragonDAO, newDao, - newApp + newApp, } diff --git a/test/helpers/factories.js b/test/helpers/factories.js index 896c97b18..f1974ae0a 100644 --- a/test/helpers/factories.js +++ b/test/helpers/factories.js @@ -2,14 +2,9 @@ const withdrawals = require('./withdrawals') const { newApp } = require('./dao') const { artifacts } = require('hardhat') const { deployLocatorWithDummyAddressesImplementation } = require('./locator-deploy') -const { ETH } = require("./utils") +const { ETH } = require('./utils') -const { - SLOTS_PER_EPOCH, - SECONDS_PER_SLOT, - EPOCHS_PER_FRAME, - CONSENSUS_VERSION -} = require('./constants') +const { SLOTS_PER_EPOCH, SECONDS_PER_SLOT, EPOCHS_PER_FRAME, CONSENSUS_VERSION } = require('./constants') const OssifiableProxy = artifacts.require('OssifiableProxy') const LidoMock = artifacts.require('LidoMock') @@ -49,17 +44,17 @@ async function lidoMockFactory({ dao, appManager, acl, voting }) { async function grantLidoRoles(pool, acl, voting, appManager) { await Promise.all([ acl.createPermission(voting.address, pool.address, await pool.PAUSE_ROLE(), appManager.address, { - from: appManager.address + from: appManager.address, }), acl.createPermission(voting.address, pool.address, await pool.RESUME_ROLE(), appManager.address, { - from: appManager.address + from: appManager.address, }), acl.createPermission(voting.address, pool.address, await pool.STAKING_PAUSE_ROLE(), appManager.address, { - from: appManager.address + from: appManager.address, }), acl.createPermission(voting.address, pool.address, await pool.STAKING_CONTROL_ROLE(), appManager.address, { - from: appManager.address - }) + from: appManager.address, + }), ]) } @@ -153,7 +148,7 @@ async function hashConsensusTimeTravellableFactory({ oracle, signers, deployParams, - lidoLocator + lidoLocator, }) { const initialEpoch = +(await legacyOracle.getLastCompletedEpochId()) + EPOCHS_PER_FRAME const consensus = await HashConsensusTimeTravellable.new( @@ -204,34 +199,34 @@ async function stakingRouterFactory({ depositContract, dao, appManager, voting, await stakingRouter.initialize(appManager.address, pool.address, withdrawalCredentials, { from: appManager.address }) await stakingRouter.grantRole(await stakingRouter.MANAGE_WITHDRAWAL_CREDENTIALS_ROLE(), pool.address, { - from: appManager.address + from: appManager.address, }) await stakingRouter.grantRole(await stakingRouter.MANAGE_WITHDRAWAL_CREDENTIALS_ROLE(), voting.address, { - from: appManager.address + from: appManager.address, }) await stakingRouter.grantRole(await stakingRouter.STAKING_MODULE_PAUSE_ROLE(), voting.address, { - from: appManager.address + from: appManager.address, }) await stakingRouter.grantRole(await stakingRouter.STAKING_MODULE_RESUME_ROLE(), voting.address, { - from: appManager.address + from: appManager.address, }) await stakingRouter.grantRole(await stakingRouter.STAKING_MODULE_MANAGE_ROLE(), voting.address, { - from: appManager.address + from: appManager.address, }) await stakingRouter.grantRole(await stakingRouter.REPORT_EXITED_VALIDATORS_ROLE(), voting.address, { - from: appManager.address + from: appManager.address, }) await stakingRouter.grantRole(await stakingRouter.REPORT_EXITED_VALIDATORS_ROLE(), oracle.address, { - from: appManager.address + from: appManager.address, }) await stakingRouter.grantRole(await stakingRouter.UNSAFE_SET_EXITED_VALIDATORS_ROLE(), voting.address, { - from: appManager.address + from: appManager.address, }) await stakingRouter.grantRole(await stakingRouter.REPORT_REWARDS_MINTED_ROLE(), voting.address, { - from: appManager.address + from: appManager.address, }) await stakingRouter.grantRole(await stakingRouter.REPORT_REWARDS_MINTED_ROLE(), pool.address, { - from: appManager.address + from: appManager.address, }) return stakingRouter @@ -243,7 +238,7 @@ async function depositSecurityModuleFactory({ stakingRouter, appManager, guardians, - deployParams + deployParams, }) { const depositSecurityModule = await DepositSecurityModule.new( pool.address, @@ -295,7 +290,7 @@ async function stakingModulesFactory(_) { async function guardiansFactory({ deployParams }) { return { privateKeys: deployParams.guardians, - addresses: Object.keys(deployParams.guardians) + addresses: Object.keys(deployParams.guardians), } } @@ -304,7 +299,7 @@ async function burnerFactory({ appManager, treasury, pool, voting }) { const [REQUEST_BURN_MY_STETH_ROLE, RECOVER_ASSETS_ROLE] = await Promise.all([ burner.REQUEST_BURN_MY_STETH_ROLE(), - burner.RECOVER_ASSETS_ROLE() + burner.RECOVER_ASSETS_ROLE(), ]) await burner.grantRole(REQUEST_BURN_MY_STETH_ROLE, voting.address, { from: appManager.address }) @@ -354,7 +349,7 @@ async function postSetup({ voting, deployParams, legacyOracle, - consensusContract + consensusContract, }) { await pool.initialize(lidoLocator.address, eip712StETH.address, { value: ETH(1) }) @@ -394,5 +389,5 @@ module.exports = { lidoLocatorFactory, oracleReportSanityCheckerFactory, validatorExitBusFactory, - oracleReportSanityCheckerStubFactory + oracleReportSanityCheckerStubFactory, } diff --git a/test/helpers/locator-deploy.js b/test/helpers/locator-deploy.js index 0ddd3e0ca..cd030663f 100644 --- a/test/helpers/locator-deploy.js +++ b/test/helpers/locator-deploy.js @@ -16,15 +16,14 @@ const invalidButNonZeroLocatorConfig = { validatorsExitBusOracle: DUMMY_ADDRESS, withdrawalQueue: DUMMY_ADDRESS, withdrawalVault: DUMMY_ADDRESS, - oracleDaemonConfig: DUMMY_ADDRESS + oracleDaemonConfig: DUMMY_ADDRESS, } - -async function deployBehindOssifiableProxy(artifactName, proxyOwner, constructorArgs=[]) { +async function deployBehindOssifiableProxy(artifactName, proxyOwner, constructorArgs = []) { const Contract = await artifacts.require(artifactName) const implementation = (await Contract.new(...constructorArgs, { from: proxyOwner })).address - const OssifiableProxy = await artifacts.require("OssifiableProxy") + const OssifiableProxy = await artifacts.require('OssifiableProxy') const proxy = await OssifiableProxy.new(implementation, proxyOwner, [], { from: proxyOwner }) return proxy @@ -41,7 +40,6 @@ async function updateProxyImplementation(proxyAddress, artifactName, proxyOwner, } async function getLocatorConfig(locatorAddress) { - const locator = await LidoLocator.at(locatorAddress) const config = { accountingOracle: await locator.accountingOracle(), @@ -57,7 +55,7 @@ async function getLocatorConfig(locatorAddress) { validatorsExitBusOracle: await locator.validatorsExitBusOracle(), withdrawalQueue: await locator.withdrawalQueue(), withdrawalVault: await locator.withdrawalVault(), - oracleDaemonConfig: await locator.oracleDaemonConfig() + oracleDaemonConfig: await locator.oracleDaemonConfig(), } return config } @@ -71,9 +69,9 @@ async function deployLocatorWithDummyAddressesImplementation(admin) { return await LidoLocator.at(proxy.address) } -///! Not specified in configUpdate values are set to dummy non zero addresses -async function updateLocatorImplementation(locatorAddress, admin, configUpdate={}) { - let config = await getLocatorConfig(locatorAddress) +/// ! Not specified in configUpdate values are set to dummy non zero addresses +async function updateLocatorImplementation(locatorAddress, admin, configUpdate = {}) { + const config = await getLocatorConfig(locatorAddress) Object.assign(config, configUpdate) await updateProxyImplementation(locatorAddress, 'LidoLocator', admin, [config]) } diff --git a/test/helpers/locator.js b/test/helpers/locator.js index 7b44d1897..0bb3d3621 100644 --- a/test/helpers/locator.js +++ b/test/helpers/locator.js @@ -15,7 +15,7 @@ const locatorServices = [ 'withdrawalQueue', 'withdrawalVault', 'postTokenRebaseReceiver', - 'oracleDaemonConfig' + 'oracleDaemonConfig', ] function getRandomLocatorConfig(overrides = {}) { @@ -31,5 +31,5 @@ function generateRandomAddress() { module.exports = { getRandomLocatorConfig, - locatorServices + locatorServices, } diff --git a/test/helpers/node-operators.js b/test/helpers/node-operators.js index 76dd4b44b..f99ffa861 100644 --- a/test/helpers/node-operators.js +++ b/test/helpers/node-operators.js @@ -120,5 +120,5 @@ module.exports = { addNodeOperator, findNodeOperatorId, getAllNodeOperators, - filterNodeOperators + filterNodeOperators, } diff --git a/test/helpers/oracle.js b/test/helpers/oracle.js index 704abed4a..6f9b9f89a 100644 --- a/test/helpers/oracle.js +++ b/test/helpers/oracle.js @@ -16,14 +16,14 @@ function getReportDataItems(r) { r.isBunkerMode, r.extraDataFormat, r.extraDataHash, - r.extraDataItemsCount + r.extraDataItemsCount, ] } function calcReportDataHash(reportItems) { const data = web3.eth.abi.encodeParameters( [ - '(uint256,uint256,uint256,uint256,uint256[],uint256[],uint256,uint256,uint256,uint256,bool,uint256,bytes32,uint256)' + '(uint256,uint256,uint256,uint256,uint256[],uint256[],uint256,uint256,uint256,uint256,bool,uint256,bytes32,uint256)', ], [reportItems] ) @@ -43,8 +43,8 @@ async function pushOracleReport(consensus, oracle, numValidators, clBalance, elR const { refSlot } = await consensus.getCurrentFrame() const reportFields = { consensusVersion: 1, - refSlot: refSlot, - numValidators: numValidators, + refSlot, + numValidators, clBalanceGwei: clBalance / 1e9, stakingModuleIdsWithNewlyExitedValidators: [], numExitedValidatorsByStakingModule: [], @@ -55,7 +55,7 @@ async function pushOracleReport(consensus, oracle, numValidators, clBalance, elR isBunkerMode: false, extraDataFormat: 0, extraDataHash: ZERO_BYTES32, - extraDataItemsCount: 0 + extraDataItemsCount: 0, } const reportItems = getReportDataItems(reportFields) const reportHash = calcReportDataHash(reportItems) diff --git a/test/helpers/protocol.js b/test/helpers/protocol.js index 2649da274..b338acef1 100644 --- a/test/helpers/protocol.js +++ b/test/helpers/protocol.js @@ -33,7 +33,7 @@ async function deployProtocol(factories = {}, deployParams = {}) { await updateLocatorImplementation(protocol.lidoLocator.address, protocol.appManager.address, { lido: protocol.pool.address, - burner: protocol.burner.address + burner: protocol.burner.address, }) protocol.validatorExitBus = await protocol.factories.validatorExitBusFactory(protocol) @@ -59,7 +59,7 @@ async function deployProtocol(factories = {}, deployParams = {}) { postTokenRebaseReceiver: protocol.legacyOracle.address, accountingOracle: protocol.oracle.address, oracleReportSanityChecker: protocol.oracleReportSanityChecker.address, - validatorsExitBusOracle: protocol.validatorExitBus.address + validatorsExitBusOracle: protocol.validatorExitBus.address, }) protocol.consensusContract = await protocol.factories.hashConsensusFactory(protocol) @@ -67,7 +67,7 @@ async function deployProtocol(factories = {}, deployParams = {}) { protocol.withdrawalQueue = await protocol.factories.withdrawalQueueFactory(protocol) await updateLocatorImplementation(protocol.lidoLocator.address, protocol.appManager.address, { - withdrawalQueue: protocol.withdrawalQueue.address + withdrawalQueue: protocol.withdrawalQueue.address, }) await protocol.factories.postSetup(protocol) @@ -93,5 +93,5 @@ async function addStakingModules(stakingModulesFactory, protocol) { } module.exports = { - deployProtocol + deployProtocol, } diff --git a/test/helpers/signatures.js b/test/helpers/signatures.js index 99e3990da..1a4ee3564 100644 --- a/test/helpers/signatures.js +++ b/test/helpers/signatures.js @@ -70,7 +70,9 @@ class DSMPauseMessage extends DSMMessage { } get hash() { - return keccak256(hexToBytes(strip0x(this.messagePrefix) + encodeBN(this.blockNumber) + encodeBN(this.stakingModule))) + return keccak256( + hexToBytes(strip0x(this.messagePrefix) + encodeBN(this.blockNumber) + encodeBN(this.stakingModule)) + ) } } @@ -81,7 +83,9 @@ function signPauseData(pauseMessagePrefix, pauseMessage, guardianPrivateKey) { function encodePauseData(pauseMessagePrefix, pauseMessage) { const uint256Size = 64 - return hexToBytes(strip0x(pauseMessagePrefix) + encodeBN(pauseMessage.blockNumber) + encodeBN(pauseMessage.stakingModule)) + return hexToBytes( + strip0x(pauseMessagePrefix) + encodeBN(pauseMessage.blockNumber) + encodeBN(pauseMessage.stakingModule) + ) } function encodeBN(value) { @@ -101,7 +105,9 @@ function signDepositData( calldata, guardianPrivateKey ) { - const hash = keccak256(encodeAttestMessage(attestMessagePrefix, blockNumber, blockHash, depositRoot, StakingModuleId, keysOpIndex)) + const hash = keccak256( + encodeAttestMessage(attestMessagePrefix, blockNumber, blockHash, depositRoot, StakingModuleId, keysOpIndex) + ) return toEip2098(ecSign(hash, guardianPrivateKey)) } @@ -128,5 +134,5 @@ module.exports = { signDepositData, signPauseData, DSMPauseMessage, - DSMAttestMessage + DSMAttestMessage, } diff --git a/test/helpers/signing-keys.js b/test/helpers/signing-keys.js index dffd9a4f8..db0e72266 100644 --- a/test/helpers/signing-keys.js +++ b/test/helpers/signing-keys.js @@ -75,5 +75,5 @@ module.exports = { EMPTY_SIGNATURE, FakeValidatorKeys, splitPublicKeysBatch, - splitSignaturesBatch + splitSignaturesBatch, } diff --git a/test/helpers/staking-modules.js b/test/helpers/staking-modules.js index a6b645266..636f88354 100644 --- a/test/helpers/staking-modules.js +++ b/test/helpers/staking-modules.js @@ -24,12 +24,12 @@ async function setupNodeOperatorsRegistry({ dao, acl, lidoLocator, stakingRouter NODE_OPERATOR_REGISTRY_MANAGE_SIGNING_KEYS, NODE_OPERATOR_REGISTRY_MANAGE_NODE_OPERATOR_ROLE, NODE_OPERATOR_REGISTRY_SET_NODE_OPERATOR_LIMIT_ROLE, - NODE_OPERATOR_REGISTRY_STAKING_ROUTER_ROLE + NODE_OPERATOR_REGISTRY_STAKING_ROUTER_ROLE, ] = await Promise.all([ nodeOperatorsRegistry.MANAGE_SIGNING_KEYS(), nodeOperatorsRegistry.MANAGE_NODE_OPERATOR_ROLE(), nodeOperatorsRegistry.SET_NODE_OPERATOR_LIMIT_ROLE(), - nodeOperatorsRegistry.STAKING_ROUTER_ROLE() + nodeOperatorsRegistry.STAKING_ROUTER_ROLE(), ]) await Promise.all([ @@ -40,7 +40,7 @@ async function setupNodeOperatorsRegistry({ dao, acl, lidoLocator, stakingRouter NODE_OPERATOR_REGISTRY_MANAGE_SIGNING_KEYS, appManager.address, { - from: appManager.address + from: appManager.address, } ), acl.createPermission( @@ -49,7 +49,7 @@ async function setupNodeOperatorsRegistry({ dao, acl, lidoLocator, stakingRouter NODE_OPERATOR_REGISTRY_MANAGE_NODE_OPERATOR_ROLE, appManager.address, { - from: appManager.address + from: appManager.address, } ), @@ -59,7 +59,7 @@ async function setupNodeOperatorsRegistry({ dao, acl, lidoLocator, stakingRouter NODE_OPERATOR_REGISTRY_SET_NODE_OPERATOR_LIMIT_ROLE, appManager.address, { - from: appManager.address + from: appManager.address, } ), acl.createPermission( @@ -68,7 +68,7 @@ async function setupNodeOperatorsRegistry({ dao, acl, lidoLocator, stakingRouter NODE_OPERATOR_REGISTRY_STAKING_ROUTER_ROLE, appManager.address, { from: appManager.address } - ) + ), ]) await acl.grantPermission( @@ -82,5 +82,5 @@ async function setupNodeOperatorsRegistry({ dao, acl, lidoLocator, stakingRouter } module.exports = { - setupNodeOperatorsRegistry + setupNodeOperatorsRegistry, } diff --git a/test/helpers/stubs/generic.stub.js b/test/helpers/stubs/generic.stub.js index b74a44b8c..474a89673 100644 --- a/test/helpers/stubs/generic.stub.js +++ b/test/helpers/stubs/generic.stub.js @@ -7,7 +7,7 @@ class GenericStub { LOG1: 1, LOG2: 2, LOG3: 3, - LOG4: 4 + LOG4: 4, }) static GenericStubContract = hre.artifacts.require('GenericStub') @@ -73,7 +73,7 @@ class GenericStub { } module.exports = { - GenericStub + GenericStub, } class GenericStubConfigParser { @@ -84,7 +84,7 @@ class GenericStubConfigParser { logs: this._parseLogs(config), forwardETH: this._parseForwardETH(config), isRevert: this._parseIsRevert(config), - nextState: this._parseNextState(config) + nextState: this._parseNextState(config), } } @@ -127,7 +127,7 @@ class GenericStubConfigParser { .map((i) => [args.type[i], args.value[i]]) .reduce((args, [type, value]) => ({ type: [...args.type, type], value: [...args.value, value] }), { type: [], - value: [] + value: [], }) const logType = topics.length + 1 // first topic is event signature @@ -137,7 +137,7 @@ class GenericStubConfigParser { signature, logType >= 2 ? topics[0] : '0x0', logType >= 3 ? topics[1] : '0x0', - logType === 4 ? topics[2] : '0x0' + logType === 4 ? topics[2] : '0x0', ] }) } diff --git a/test/helpers/stubs/staking-module.stub.js b/test/helpers/stubs/staking-module.stub.js index 224d5bc00..e333f50b5 100644 --- a/test/helpers/stubs/staking-module.stub.js +++ b/test/helpers/stubs/staking-module.stub.js @@ -13,8 +13,8 @@ class StakingModuleStub extends GenericStub { await GenericStub.stub(stakingModuleStub, 'getStakingModuleSummary', { return: { type: ['uint256', 'uint256', 'uint256'], - value: [totalExitedValidators, totalDepositedValidators, availableValidatorsCount] - } + value: [totalExitedValidators, totalDepositedValidators, availableValidatorsCount], + }, }) } @@ -47,13 +47,13 @@ class StakingModuleStub extends GenericStub { type: ['bytes', 'bytes'], value: [ config.return.publicKeysBatch || defaultPublicKeysBatch, - config.return.signaturesBatch || defaultSignaturesBatch - ] - } + config.return.signaturesBatch || defaultSignaturesBatch, + ], + }, }) } } module.exports = { - StakingModuleStub + StakingModuleStub, } diff --git a/test/helpers/utils.js b/test/helpers/utils.js index 01f0bb3f7..9c2f5acb2 100644 --- a/test/helpers/utils.js +++ b/test/helpers/utils.js @@ -65,21 +65,25 @@ function hex(n, byteLen) { } function strip0x(s) { - return s.substr(0, 2) == '0x' ? s.substr(2) : s + return s.substr(0, 2) === '0x' ? s.substr(2) : s } // transforms all object entries -const transformEntries = (obj, tr) => Object.fromEntries( - Object.entries(obj).map(tr).filter(x => x !== undefined) -) +const transformEntries = (obj, tr) => + Object.fromEntries( + Object.entries(obj) + .map(tr) + .filter((x) => x !== undefined) + ) // converts all object BN keys to strings, drops numeric keys and the __length__ key -const processNamedTuple = (obj) => transformEntries(obj, ([k, v]) => { - return /^(\d+|__length__)$/.test(k) ? undefined : [k, BN.isBN(v) ? v.toString() : v] -}) +const processNamedTuple = (obj) => + transformEntries(obj, ([k, v]) => { + return /^(\d+|__length__)$/.test(k) ? undefined : [k, BN.isBN(v) ? v.toString() : v] + }) const printEvents = (tx) => { - console.log(tx.receipt.logs.map(({event, args}) => ({event, args: processNamedTuple(args)}))) + console.log(tx.receipt.logs.map(({ event, args }) => ({ event, args: processNamedTuple(args) }))) } // Divides a BN by 1e15 @@ -95,7 +99,7 @@ const shares = e18 const shareRate = e27 const bnE9 = new BN(10).pow(new BN(9)) -const ethToGwei = valueEth => toBN(valueEth).div(bnE9).toString() +const ethToGwei = (valueEth) => toBN(valueEth).div(bnE9).toString() function formatWei(weiString) { return ethers.utils.formatEther(ethers.utils.parseUnits(weiString, 'wei'), { commify: true }) + ' ETH' @@ -123,7 +127,7 @@ function assertBnClose(x, y, maxDiff, msg = undefined) { assert( diff.lte(new BN(maxDiff)), () => `Expected ${x} to be close to ${y} with max diff ${maxDiff}, actual diff ${diff}`, - () => `Expected ${x} not to be close to ${y} with min diff ${maxDiff}, actual diff ${diff}`, + () => `Expected ${x} not to be close to ${y} with min diff ${maxDiff}, actual diff ${diff}` ) } @@ -138,8 +142,8 @@ const changeEndianness = (string) => { return '0x' + result.join('') } -const toNum = (x) => Array.isArray(x) ? x.map(toNum) : +x -const toStr = (x) => Array.isArray(x) ? x.map(toStr) : `${x}` +const toNum = (x) => (Array.isArray(x) ? x.map(toNum) : +x) +const toStr = (x) => (Array.isArray(x) ? x.map(toStr) : `${x}`) const setBalance = async (address, value) => { await hre.network.provider.send('hardhat_setBalance', [address, web3.utils.numberToHex(value)]) @@ -150,7 +154,7 @@ const prepIdsCountsPayload = (ids, counts) => { if (!Array.isArray(counts)) counts = [counts] return { operatorIds: '0x' + ids.map((id) => hex(id, 8)).join(''), - keysCounts: '0x' + counts.map((count) => hex(count, 16)).join('') + keysCounts: '0x' + counts.map((count) => hex(count, 16)).join(''), } } @@ -165,7 +169,6 @@ const calcSharesMintedAsFees = (rewards, fee, feePoints, prevTotalShares, newTot ) } - module.exports = { ZERO_HASH, pad, @@ -201,5 +204,5 @@ module.exports = { toStr, setBalance, prepIdsCountsPayload, - calcSharesMintedAsFees + calcSharesMintedAsFees, } diff --git a/test/helpers/wei.js b/test/helpers/wei.js index f15da3916..7cb93aac2 100644 --- a/test/helpers/wei.js +++ b/test/helpers/wei.js @@ -94,5 +94,5 @@ function parseWeiExpression(expression) { } module.exports = { - wei + wei, } diff --git a/test/helpers/withdrawals.js b/test/helpers/withdrawals.js index 9a247fc80..af1065517 100644 --- a/test/helpers/withdrawals.js +++ b/test/helpers/withdrawals.js @@ -3,7 +3,7 @@ const { utils } = require('ethers') const OssifiableProxy = artifacts.require('OssifiableProxy.sol') const WithdrawalQueueERC721 = artifacts.require('WithdrawalQueueERC721.sol') -async function deploy(ownerAddress, wstethAddress, name = "Lido: Withdrawal Request NFT", symbol = "unstETH") { +async function deploy(ownerAddress, wstethAddress, name = 'Lido: Withdrawal Request NFT', symbol = 'unstETH') { const impl = await WithdrawalQueueERC721.new(wstethAddress, name, symbol) const proxy = await OssifiableProxy.new(impl.address, ownerAddress, '0x') const queue = await WithdrawalQueueERC721.at(proxy.address) @@ -11,10 +11,10 @@ async function deploy(ownerAddress, wstethAddress, name = "Lido: Withdrawal Requ return { impl, proxy, - queue + queue, } } module.exports = { - deploy + deploy, } diff --git a/test/scenario/changing_oracles_during_epoch.js b/test/scenario/changing_oracles_during_epoch.js index 53d8495be..67f658e8d 100644 --- a/test/scenario/changing_oracles_during_epoch.js +++ b/test/scenario/changing_oracles_during_epoch.js @@ -9,9 +9,10 @@ const { initAccountingOracle, deployMockLegacyOracle, CONSENSUS_VERSION, - HASH_1, ZERO_HASH, + HASH_1, + ZERO_HASH, getReportDataItems, - calcReportDataHash + calcReportDataHash, } = require('../0.8.9/oracle/accounting-oracle-deploy.test') const SLOTS_PER_EPOCH = 32 @@ -40,7 +41,7 @@ contract('AccountingOracle', ([appManager, voting, malicious1, malicious2, membe isBunkerMode: false, extraDataFormat: 0, extraDataHash: ZERO_HASH, - extraDataItemsCount: 0 + extraDataItemsCount: 0, } const BAD_DATA = { @@ -59,16 +60,16 @@ contract('AccountingOracle', ([appManager, voting, malicious1, malicious2, membe const deployed = await deployAccountingOracleSetup(voting, { ...timeConfig, - getLegacyOracle: () => deployMockLegacyOracle({...timeConfig, lastCompletedEpochId: 0}) + getLegacyOracle: () => deployMockLegacyOracle({ ...timeConfig, lastCompletedEpochId: 0 }), }) lido = deployed.lido consensus = deployed.consensus oracle = deployed.oracle - await initAccountingOracle({...deployed, admin: voting}) + await initAccountingOracle({ ...deployed, admin: voting }) - assert.equal(+await oracle.getTime(), GENESIS_TIME + SECONDS_PER_FRAME) + assert.equal(+(await oracle.getTime()), GENESIS_TIME + SECONDS_PER_FRAME) await consensus.addMember(member1, 4, { from: voting }) await consensus.addMember(member2, 4, { from: voting }) @@ -76,18 +77,15 @@ contract('AccountingOracle', ([appManager, voting, malicious1, malicious2, membe it('reverts with zero ref. slot', async () => { assertBn((await consensus.getCurrentFrame()).refSlot, 1 * SLOTS_PER_FRAME - 1) - await assertRevert( - consensus.submitReport(0, HASH_1, CONSENSUS_VERSION, { from: member1 }), - 'InvalidSlot()' - ) + await assertRevert(consensus.submitReport(0, HASH_1, CONSENSUS_VERSION, { from: member1 }), 'InvalidSlot()') }) it('oracle conract handles changing the oracles during epoch', async () => { await consensus.addMember(malicious1, 4, { from: voting }) await consensus.addMember(malicious2, 4, { from: voting }) - const goodDataItems = getReportDataItems({...GOOD_DATA, refSlot: SLOTS_PER_FRAME - 1}) - const badDataItems = getReportDataItems({...BAD_DATA, refSlot: SLOTS_PER_FRAME - 1}) + const goodDataItems = getReportDataItems({ ...GOOD_DATA, refSlot: SLOTS_PER_FRAME - 1 }) + const badDataItems = getReportDataItems({ ...BAD_DATA, refSlot: SLOTS_PER_FRAME - 1 }) const goodDataHash = calcReportDataHash(goodDataItems) const badDataHash = calcReportDataHash(badDataItems) @@ -100,14 +98,11 @@ contract('AccountingOracle', ([appManager, voting, malicious1, malicious2, membe await consensus.removeMember(malicious2, 3, { from: voting }) await consensus.addMember(member3, 3, { from: voting }) - let tx = await consensus.submitReport( - SLOTS_PER_FRAME - 1, - goodDataHash, - CONSENSUS_VERSION, - { from: member3 } - ) + let tx = await consensus.submitReport(SLOTS_PER_FRAME - 1, goodDataHash, CONSENSUS_VERSION, { from: member3 }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot: SLOTS_PER_FRAME - 1, report: goodDataHash, support: 3 } }) + assertEvent(tx, 'ConsensusReached', { + expectedArgs: { refSlot: SLOTS_PER_FRAME - 1, report: goodDataHash, support: 3 }, + }) tx = await oracle.submitReportData(goodDataItems, await oracle.getContractVersion(), { from: member3 }) diff --git a/test/scenario/deposit_distribution.js b/test/scenario/deposit_distribution.js index 780881545..ddbbace42 100644 --- a/test/scenario/deposit_distribution.js +++ b/test/scenario/deposit_distribution.js @@ -21,20 +21,20 @@ contract('StakingRouter', ([depositor, stranger1, address1, address2]) => { name: 'curated', targetShares: 10000, moduleFee: 1000, - treasuryFee: 5000 + treasuryFee: 5000, }, { module: anotherCuratedModule, name: 'another curated', targetShares: 10000, moduleFee: 1000, - treasuryFee: 5000 - } + treasuryFee: 5000, + }, ] }, depositSecurityModuleFactory: async () => { return { address: depositor } - } + }, }) depositContract = deployed.depositContract diff --git a/test/scenario/execution_layer_rewards_after_the_merge.js b/test/scenario/execution_layer_rewards_after_the_merge.js index 6634af78e..701809e9d 100644 --- a/test/scenario/execution_layer_rewards_after_the_merge.js +++ b/test/scenario/execution_layer_rewards_after_the_merge.js @@ -13,15 +13,15 @@ const { SLOTS_PER_FRAME } = require('../helpers/constants') const NodeOperatorsRegistry = artifacts.require('NodeOperatorsRegistry') -const TOTAL_BASIS_POINTS = 10**4 -const MAX_POSITIVE_REBASE_PRECISION_POINTS = 10**9 +const TOTAL_BASIS_POINTS = 10 ** 4 +const MAX_POSITIVE_REBASE_PRECISION_POINTS = 10 ** 9 const CURATED_MODULE_ID = 1 -const makeAccountingReport = ({refSlot, numValidators, clBalanceGwei, elRewardsVaultBalance}) => ({ +const makeAccountingReport = ({ refSlot, numValidators, clBalanceGwei, elRewardsVaultBalance }) => ({ refSlot, consensusVersion: 1, - numValidators: numValidators, - clBalanceGwei: clBalanceGwei, + numValidators, + clBalanceGwei, stakingModuleIdsWithNewlyExitedValidators: [], numExitedValidatorsByStakingModule: [], withdrawalVaultBalance: 0, @@ -46,7 +46,7 @@ contract.skip('Lido: merge acceptance', (addresses) => { // unrelated address nobody, // Execution layer rewards source - userELRewards + userELRewards, ] = addresses let pool, nodeOperatorsRegistry, token @@ -69,9 +69,9 @@ contract.skip('Lido: merge acceptance', (addresses) => { validators: [ { key: pad('0x010101', 48), - sig: pad('0x01', 96) - } - ] + sig: pad('0x01', 96), + }, + ], } // NO with 1 validator @@ -81,9 +81,9 @@ contract.skip('Lido: merge acceptance', (addresses) => { validators: [ { key: pad('0x020202', 48), - sig: pad('0x02', 96) - } - ] + sig: pad('0x02', 96), + }, + ], } before('deploy base stuff', async () => { @@ -96,10 +96,10 @@ contract.skip('Lido: merge acceptance', (addresses) => { name: 'Curated', targetShares: 10000, moduleFee: 500, - treasuryFee: 500 - } + treasuryFee: 500, + }, ] - } + }, }) // contracts/StETH.sol @@ -131,14 +131,20 @@ contract.skip('Lido: merge acceptance', (addresses) => { await stakingRouter.setWithdrawalCredentials(withdrawalCredentials, { from: voting }) // Withdrawal credentials were set - assert.equal(await stakingRouter.getWithdrawalCredentials({ from: nobody }), withdrawalCredentials, 'withdrawal credentials') + assert.equal( + await stakingRouter.getWithdrawalCredentials({ from: nobody }), + withdrawalCredentials, + 'withdrawal credentials' + ) // How many validators can this node operator register const validatorsLimit = 100000000 let txn = await nodeOperatorsRegistry.addNodeOperator(nodeOperator1.name, nodeOperator1.address, { from: voting }) // Some Truffle versions fail to decode logs here, so we're decoding them explicitly using a helper - nodeOperator1.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi }) + nodeOperator1.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { + decodeForAbi: NodeOperatorsRegistry._json.abi, + }) assertBn(nodeOperator1.id, 0, 'operator id') assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') @@ -151,7 +157,7 @@ contract.skip('Lido: merge acceptance', (addresses) => { nodeOperator1.validators[0].key, nodeOperator1.validators[0].sig, { - from: nodeOperator1.address + from: nodeOperator1.address, } ) @@ -170,7 +176,9 @@ contract.skip('Lido: merge acceptance', (addresses) => { txn = await nodeOperatorsRegistry.addNodeOperator(nodeOperator2.name, nodeOperator2.address, { from: voting }) // Some Truffle versions fail to decode logs here, so we're decoding them explicitly using a helper - nodeOperator2.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi }) + nodeOperator2.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { + decodeForAbi: NodeOperatorsRegistry._json.abi, + }) assertBn(nodeOperator2.id, 1, 'operator id') assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators') @@ -181,7 +189,7 @@ contract.skip('Lido: merge acceptance', (addresses) => { nodeOperator2.validators[0].key, nodeOperator2.validators[0].sig, { - from: nodeOperator2.address + from: nodeOperator2.address, } ) @@ -205,10 +213,16 @@ contract.skip('Lido: merge acceptance', (addresses) => { DSMAttestMessage.setMessagePrefix(await depositSecurityModule.ATTEST_MESSAGE_PREFIX()) DSMPauseMessage.setMessagePrefix(await depositSecurityModule.PAUSE_MESSAGE_PREFIX()) - const validAttestMessage = new DSMAttestMessage(block.number, block.hash, depositRoot, CURATED_MODULE_ID, keysOpIndex) + const validAttestMessage = new DSMAttestMessage( + block.number, + block.hash, + depositRoot, + CURATED_MODULE_ID, + keysOpIndex + ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, @@ -248,10 +262,16 @@ contract.skip('Lido: merge acceptance', (addresses) => { DSMAttestMessage.setMessagePrefix(await depositSecurityModule.ATTEST_MESSAGE_PREFIX()) DSMPauseMessage.setMessagePrefix(await depositSecurityModule.PAUSE_MESSAGE_PREFIX()) - const validAttestMessage = new DSMAttestMessage(block.number, block.hash, depositRoot, CURATED_MODULE_ID, keysOpIndex) + const validAttestMessage = new DSMAttestMessage( + block.number, + block.hash, + depositRoot, + CURATED_MODULE_ID, + keysOpIndex + ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, @@ -300,10 +320,16 @@ contract.skip('Lido: merge acceptance', (addresses) => { DSMAttestMessage.setMessagePrefix(await depositSecurityModule.ATTEST_MESSAGE_PREFIX()) DSMPauseMessage.setMessagePrefix(await depositSecurityModule.PAUSE_MESSAGE_PREFIX()) - const validAttestMessage = new DSMAttestMessage(block.number, block.hash, depositRoot, CURATED_MODULE_ID, keysOpIndex) + const validAttestMessage = new DSMAttestMessage( + block.number, + block.hash, + depositRoot, + CURATED_MODULE_ID, + keysOpIndex + ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] assertBn(await depositContractMock.totalCalls(), 1) @@ -367,12 +393,15 @@ contract.skip('Lido: merge acceptance', (addresses) => { // Reporting 1.5-fold balance increase (64 => 96) - await oracleMock.submitReportData(makeAccountingReport({ - refSlot: frame * SLOTS_PER_FRAME - 1, - numValidators: 2, - clBalanceGwei: gwei(96), - elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), - }), 1) + await oracleMock.submitReportData( + makeAccountingReport({ + refSlot: frame * SLOTS_PER_FRAME - 1, + numValidators: 2, + clBalanceGwei: gwei(96), + elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), + }), + 1 + ) // Execution layer rewards just claimed assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') @@ -430,7 +459,9 @@ contract.skip('Lido: merge acceptance', (addresses) => { // Real minted amount should be a bit less than calculated caused by round errors on mint and transfer operations assert( mintedAmount - .sub(new BN(0).add(await token.balanceOf(treasuryAddr)).add(await token.balanceOf(nodeOperatorsRegistry.address))) + .sub( + new BN(0).add(await token.balanceOf(treasuryAddr)).add(await token.balanceOf(nodeOperatorsRegistry.address)) + ) .lt(mintedAmount.divn(100)) ) }) @@ -465,12 +496,15 @@ contract.skip('Lido: merge acceptance', (addresses) => { assertBn(oldTotalPooledEther, ETH(138), 'total pooled ether') // Reporting the same balance as it was before (96ETH => 96ETH) - await oracleMock.submitReportData(makeAccountingReport({ - refSlot: frame * SLOTS_PER_FRAME - 1, - numValidators: 2, - clBalanceGwei: gwei(96), - elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), - }), 1) + await oracleMock.submitReportData( + makeAccountingReport({ + refSlot: frame * SLOTS_PER_FRAME - 1, + numValidators: 2, + clBalanceGwei: gwei(96), + elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), + }), + 1 + ) // Execution layer rewards just claimed assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') @@ -533,12 +567,15 @@ contract.skip('Lido: merge acceptance', (addresses) => { assertBn(oldTotalPooledEther, ETH(145), 'total pooled ether') // Reporting balance decrease (96ETH => 94ETH) - await oracleMock.submitReportData(makeAccountingReport({ - refSlot: frame * SLOTS_PER_FRAME - 1, - numValidators: 2, - clBalanceGwei: gwei(94), - elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), - }), 1) + await oracleMock.submitReportData( + makeAccountingReport({ + refSlot: frame * SLOTS_PER_FRAME - 1, + numValidators: 2, + clBalanceGwei: gwei(94), + elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), + }), + 1 + ) // Execution layer rewards just claimed assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') @@ -594,12 +631,15 @@ contract.skip('Lido: merge acceptance', (addresses) => { assertBn(oldTotalPooledEther, ETH(148), 'total pooled ether') // Reporting balance decrease (94ETH => 91ETH) - await oracleMock.submitReportData(makeAccountingReport({ - refSlot: frame * SLOTS_PER_FRAME - 1, - numValidators: 2, - clBalanceGwei: gwei(91), - elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), - }), 1) + await oracleMock.submitReportData( + makeAccountingReport({ + refSlot: frame * SLOTS_PER_FRAME - 1, + numValidators: 2, + clBalanceGwei: gwei(91), + elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), + }), + 1 + ) // Execution layer rewards just claimed assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') @@ -653,12 +693,15 @@ contract.skip('Lido: merge acceptance', (addresses) => { assertBn(oldTotalPooledEther, ETH(148), 'total pooled ether') // Reporting balance decrease (91ETH => 83ETH) - await oracleMock.submitReportData(makeAccountingReport({ - refSlot: frame * SLOTS_PER_FRAME - 1, - numValidators: 2, - clBalanceGwei: gwei(83), - elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), - }), 1) + await oracleMock.submitReportData( + makeAccountingReport({ + refSlot: frame * SLOTS_PER_FRAME - 1, + numValidators: 2, + clBalanceGwei: gwei(83), + elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), + }), + 1 + ) // Execution layer rewards just claimed assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') @@ -712,12 +755,15 @@ contract.skip('Lido: merge acceptance', (addresses) => { assertBn(oldTotalPooledEther, ETH(142), 'total pooled ether') // Reporting balance increase (83ETH => 85ETH) - await oracleMock.submitReportData(makeAccountingReport({ - refSlot: frame * SLOTS_PER_FRAME - 1, - numValidators: 2, - clBalanceGwei: gwei(85), - elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), - }), 1) + await oracleMock.submitReportData( + makeAccountingReport({ + refSlot: frame * SLOTS_PER_FRAME - 1, + numValidators: 2, + clBalanceGwei: gwei(85), + elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), + }), + 1 + ) // Execution layer rewards just claimed assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') @@ -751,10 +797,14 @@ contract.skip('Lido: merge acceptance', (addresses) => { // and node operators // treasuryTokenBalance = (oldTreasuryShares + mintedRewardShares * treasuryFeePoints / 10000) * sharePrice assertBn((await token.balanceOf(treasuryAddr)).divn(10), new BN('242626811594202898'), 'treasury tokens') - assertBn((await token.balanceOf(nodeOperatorsRegistry.address)).divn(10), new BN('242626811594202898'), 'module1 tokens') + assertBn( + (await token.balanceOf(nodeOperatorsRegistry.address)).divn(10), + new BN('242626811594202898'), + 'module1 tokens' + ) }) - //TODO: Revive + // TODO: Revive it.skip('collect 0.1 ETH execution layer rewards to elRewardsVault and withdraw it entirely by means of multiple oracle reports (+1 ETH)', async () => { // Specify different withdrawal limits for a few epochs to test different values const getMaxPositiveRebaseForFrame = (_frame) => { @@ -794,19 +844,22 @@ contract.skip('Lido: merge acceptance', (addresses) => { maxPositiveRebase = await pool.getMaxPositiveTokenRebase() const clIncurredRebase = beaconBalanceInc.mul(toBN(MAX_POSITIVE_REBASE_PRECISION_POINTS)).div(totalPooledEther) - const maxELRewardsAmountPerWithdrawal = totalPooledEther.mul( - maxPositiveRebase.sub(clIncurredRebase) - ).div(toBN(MAX_POSITIVE_REBASE_PRECISION_POINTS)) + const maxELRewardsAmountPerWithdrawal = totalPooledEther + .mul(maxPositiveRebase.sub(clIncurredRebase)) + .div(toBN(MAX_POSITIVE_REBASE_PRECISION_POINTS)) const elRewardsToWithdraw = BN.min(maxELRewardsAmountPerWithdrawal, elRewardsVaultBalance) // Reporting balance increase - await oracleMock.submitReportData(makeAccountingReport({ - refSlot: frame * SLOTS_PER_FRAME - 1, - numValidators: 2, - clBalanceGwei: ethToGwei(lastBeaconBalance.add(beaconBalanceInc)), - elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), - }), 1) + await oracleMock.submitReportData( + makeAccountingReport({ + refSlot: frame * SLOTS_PER_FRAME - 1, + numValidators: 2, + clBalanceGwei: ethToGwei(lastBeaconBalance.add(beaconBalanceInc)), + elRewardsVaultBalance: await web3.eth.getBalance(elRewardsVault.address), + }), + 1 + ) assertBn( await web3.eth.getBalance(elRewardsVault.address), @@ -814,8 +867,16 @@ contract.skip('Lido: merge acceptance', (addresses) => { 'Execution layer rewards vault balance' ) - assertBn(await pool.getTotalPooledEther(), totalPooledEther.add(beaconBalanceInc).add(elRewardsToWithdraw), 'total pooled ether') - assertBn(await pool.totalSupply(), totalSupply.add(beaconBalanceInc).add(elRewardsToWithdraw), 'token total supply') + assertBn( + await pool.getTotalPooledEther(), + totalPooledEther.add(beaconBalanceInc).add(elRewardsToWithdraw), + 'total pooled ether' + ) + assertBn( + await pool.totalSupply(), + totalSupply.add(beaconBalanceInc).add(elRewardsToWithdraw), + 'token total supply' + ) assertBn(await pool.getBufferedEther(), bufferedEther.add(elRewardsToWithdraw), 'buffered ether') elRewardsVaultBalance = toBN(await web3.eth.getBalance(elRewardsVault.address)) diff --git a/test/scenario/helpers/deploy.js b/test/scenario/helpers/deploy.js index 5089a1507..febfd0f92 100644 --- a/test/scenario/helpers/deploy.js +++ b/test/scenario/helpers/deploy.js @@ -22,7 +22,7 @@ const GUARDIAN3 = '0xdaEAd0E0194abd565d28c1013399801d79627c14' const GUARDIAN_PRIVATE_KEYS = { [GUARDIAN1]: '0x3578665169e03e05a26bd5c565ffd12c81a1e0df7d0679f8aee4153110a83c8c', [GUARDIAN2]: '0x88868f0fb667cfe50261bb385be8987e0ce62faee934af33c3026cf65f25f09e', - [GUARDIAN3]: '0x75e6f508b637327debc90962cd38943ddb9cfc1fc4a8572fc5e3d0984e1261de' + [GUARDIAN3]: '0x75e6f508b637327debc90962cd38943ddb9cfc1fc4a8572fc5e3d0984e1261de', } const DEPOSIT_ROOT = '0xd151867719c94ad8458feaf491809f9bc8096c702a72747403ecaac30c179137' @@ -43,7 +43,7 @@ async function deployDaoAndPool(appManager, voting) { const [{ dao, acl }, depositContractMock, poolBase] = await Promise.all([ newDao(appManager), DepositContractMock.new(), - Lido.new() + Lido.new(), ]) const stakingRouter = await StakingRouter.new(depositContractMock.address) @@ -74,7 +74,7 @@ async function deployDaoAndPool(appManager, voting) { pool.RESUME_ROLE(), pool.STAKING_PAUSE_ROLE(), pool.STAKING_CONTROL_ROLE(), - pool.MANAGE_PROTOCOL_CONTRACTS_ROLE() + pool.MANAGE_PROTOCOL_CONTRACTS_ROLE(), ]) await Promise.all([ @@ -83,7 +83,7 @@ async function deployDaoAndPool(appManager, voting) { acl.createPermission(voting, pool.address, POOL_RESUME_ROLE, appManager, { from: appManager }), acl.createPermission(voting, pool.address, STAKING_PAUSE_ROLE, appManager, { from: appManager }), acl.createPermission(voting, pool.address, STAKING_CONTROL_ROLE, appManager, { from: appManager }), - acl.createPermission(voting, pool.address, MANAGE_PROTOCOL_CONTRACTS_ROLE, appManager, { from: appManager }) + acl.createPermission(voting, pool.address, MANAGE_PROTOCOL_CONTRACTS_ROLE, appManager, { from: appManager }), ]) const elRewardsVault = await LidoELRewardsVault.new(pool.address, treasury.address) @@ -104,12 +104,12 @@ async function deployDaoAndPool(appManager, voting) { MANAGE_WITHDRAWAL_CREDENTIALS_ROLE, STAKING_MODULE_PAUSE_ROLE, STAKING_MODULE_MANAGE_ROLE, - REPORT_REWARDS_MINTED_ROLE + REPORT_REWARDS_MINTED_ROLE, ] = await Promise.all([ stakingRouter.MANAGE_WITHDRAWAL_CREDENTIALS_ROLE(), stakingRouter.STAKING_MODULE_PAUSE_ROLE(), stakingRouter.STAKING_MODULE_MANAGE_ROLE(), - stakingRouter.REPORT_REWARDS_MINTED_ROLE() + stakingRouter.REPORT_REWARDS_MINTED_ROLE(), ]) await stakingRouter.grantRole(REPORT_REWARDS_MINTED_ROLE, pool.address, { from: appManager }) @@ -162,9 +162,9 @@ async function deployDaoAndPool(appManager, voting) { depositSecurityModule, guardians: { privateKeys: GUARDIAN_PRIVATE_KEYS, - addresses: [GUARDIAN1, GUARDIAN2, GUARDIAN3] + addresses: [GUARDIAN1, GUARDIAN2, GUARDIAN3], }, - stakingRouter + stakingRouter, } } @@ -181,12 +181,12 @@ async function setupNodeOperatorsRegistry(dao, acl, voting, token, appManager, s NODE_OPERATOR_REGISTRY_MANAGE_SIGNING_KEYS, NODE_OPERATOR_REGISTRY_MANAGE_NODE_OPERATOR_ROLE, NODE_OPERATOR_REGISTRY_SET_NODE_OPERATOR_LIMIT_ROLE, - NODE_OPERATOR_REGISTRY_STAKING_ROUTER_ROLE + NODE_OPERATOR_REGISTRY_STAKING_ROUTER_ROLE, ] = await Promise.all([ nodeOperatorsRegistry.MANAGE_SIGNING_KEYS(), nodeOperatorsRegistry.MANAGE_NODE_OPERATOR_ROLE(), nodeOperatorsRegistry.SET_NODE_OPERATOR_LIMIT_ROLE(), - nodeOperatorsRegistry.STAKING_ROUTER_ROLE() + nodeOperatorsRegistry.STAKING_ROUTER_ROLE(), ]) await Promise.all([ // Allow voting to manage node operators registry @@ -196,7 +196,7 @@ async function setupNodeOperatorsRegistry(dao, acl, voting, token, appManager, s NODE_OPERATOR_REGISTRY_MANAGE_SIGNING_KEYS, appManager, { - from: appManager + from: appManager, } ), acl.createPermission( @@ -205,7 +205,7 @@ async function setupNodeOperatorsRegistry(dao, acl, voting, token, appManager, s NODE_OPERATOR_REGISTRY_MANAGE_NODE_OPERATOR_ROLE, appManager, { - from: appManager + from: appManager, } ), acl.createPermission( @@ -214,7 +214,7 @@ async function setupNodeOperatorsRegistry(dao, acl, voting, token, appManager, s NODE_OPERATOR_REGISTRY_SET_NODE_OPERATOR_LIMIT_ROLE, appManager, { - from: appManager + from: appManager, } ), acl.createPermission( @@ -223,7 +223,7 @@ async function setupNodeOperatorsRegistry(dao, acl, voting, token, appManager, s NODE_OPERATOR_REGISTRY_STAKING_ROUTER_ROLE, appManager, { from: appManager } - ) + ), ]) await acl.grantPermission( @@ -244,5 +244,5 @@ module.exports = { GENESIS_TIME, EPOCHS_PER_FRAME, SLOTS_PER_FRAME, - SECONDS_PER_FRAME + SECONDS_PER_FRAME, } diff --git a/test/scenario/lido_deposit_iteration_limit.js b/test/scenario/lido_deposit_iteration_limit.js index 78dee023e..bc694116a 100644 --- a/test/scenario/lido_deposit_iteration_limit.js +++ b/test/scenario/lido_deposit_iteration_limit.js @@ -29,10 +29,10 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = name: 'Curated', targetShares: 10000, moduleFee: 500, - treasuryFee: 500 - } + treasuryFee: 500, + }, ] - } + }, }) pool = deployed.pool @@ -56,7 +56,7 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = // Some Truffle versions fail to decode logs here, so we're decoding them explicitly using a helper const nodeOperatorId = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { - decodeForAbi: NodeOperatorsRegistry._json.abi + decodeForAbi: NodeOperatorsRegistry._json.abi, }) assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') @@ -65,7 +65,7 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = const n = 1 + 10 * i return { key: pad(`0x${n.toString(16)}`, 48), - sig: pad(`0x${n.toString(16)}`, 96) + sig: pad(`0x${n.toString(16)}`, 96), } }) @@ -109,7 +109,7 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, @@ -147,7 +147,7 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, @@ -182,7 +182,7 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, @@ -227,7 +227,7 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, @@ -264,7 +264,7 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, diff --git a/test/scenario/lido_happy_path.js b/test/scenario/lido_happy_path.js index 70a3ba5ff..e8eb6d5a2 100644 --- a/test/scenario/lido_happy_path.js +++ b/test/scenario/lido_happy_path.js @@ -26,7 +26,7 @@ contract('Lido: happy path', (addresses) => { user2, user3, // unrelated address - nobody + nobody, ] = addresses let pool, nodeOperatorsRegistry, token @@ -36,7 +36,9 @@ contract('Lido: happy path', (addresses) => { let withdrawalCredentials, stakingRouter let consensus - before('DAO, node operators registry, token, pool and deposit security module are deployed and initialized', async () => { + before( + 'DAO, node operators registry, token, pool and deposit security module are deployed and initialized', + async () => { const deployed = await deployProtocol({ stakingModulesFactory: async (protocol) => { const curatedModule = await setupNodeOperatorsRegistry(protocol) @@ -46,10 +48,10 @@ contract('Lido: happy path', (addresses) => { name: 'Curated', targetShares: 10000, moduleFee: 500, - treasuryFee: 500 - } + treasuryFee: 500, + }, ] - } + }, }) // contracts/StETH.sol @@ -105,7 +107,11 @@ contract('Lido: happy path', (addresses) => { // Withdrawal credentials were set - assert.equal(await stakingRouter.getWithdrawalCredentials({ from: nobody }), withdrawalCredentials, 'withdrawal credentials') + assert.equal( + await stakingRouter.getWithdrawalCredentials({ from: nobody }), + withdrawalCredentials, + 'withdrawal credentials' + ) }) // Each node operator has its Ethereum 1 address, a name and a set of registered @@ -116,16 +122,18 @@ contract('Lido: happy path', (addresses) => { validators: [ { key: pad('0x010101', 48), - sig: pad('0x01', 96) - } - ] + sig: pad('0x01', 96), + }, + ], } it('voting adds the first node operator', async () => { const txn = await nodeOperatorsRegistry.addNodeOperator(nodeOperator1.name, nodeOperator1.address, { from: voting }) // Some Truffle versions fail to decode logs here, so we're decoding them explicitly using a helper - nodeOperator1.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi }) + nodeOperator1.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { + decodeForAbi: NodeOperatorsRegistry._json.abi, + }) assertBn(nodeOperator1.id, 0, 'operator id') assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') @@ -142,7 +150,7 @@ contract('Lido: happy path', (addresses) => { nodeOperator1.validators[0].key, nodeOperator1.validators[0].sig, { - from: nodeOperator1.address + from: nodeOperator1.address, } ) @@ -167,10 +175,16 @@ contract('Lido: happy path', (addresses) => { DSMAttestMessage.setMessagePrefix(await depositSecurityModule.ATTEST_MESSAGE_PREFIX()) DSMPauseMessage.setMessagePrefix(await depositSecurityModule.PAUSE_MESSAGE_PREFIX()) - const validAttestMessage = new DSMAttestMessage(block.number, block.hash, depositRoot, CURATED_MODULE_ID, keysOpIndex) + const validAttestMessage = new DSMAttestMessage( + block.number, + block.hash, + depositRoot, + CURATED_MODULE_ID, + keysOpIndex + ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, @@ -210,10 +224,16 @@ contract('Lido: happy path', (addresses) => { DSMAttestMessage.setMessagePrefix(await depositSecurityModule.ATTEST_MESSAGE_PREFIX()) DSMPauseMessage.setMessagePrefix(await depositSecurityModule.PAUSE_MESSAGE_PREFIX()) - const validAttestMessage = new DSMAttestMessage(block.number, block.hash, depositRoot, CURATED_MODULE_ID, keysOpIndex) + const validAttestMessage = new DSMAttestMessage( + block.number, + block.hash, + depositRoot, + CURATED_MODULE_ID, + keysOpIndex + ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, @@ -264,9 +284,9 @@ contract('Lido: happy path', (addresses) => { validators: [ { key: pad('0x020202', 48), - sig: pad('0x02', 96) - } - ] + sig: pad('0x02', 96), + }, + ], } it('voting adds the second node operator who registers one validator', async () => { @@ -276,7 +296,9 @@ contract('Lido: happy path', (addresses) => { const txn = await nodeOperatorsRegistry.addNodeOperator(nodeOperator2.name, nodeOperator2.address, { from: voting }) // Some Truffle versions fail to decode logs here, so we're decoding them explicitly using a helper - nodeOperator2.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi }) + nodeOperator2.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { + decodeForAbi: NodeOperatorsRegistry._json.abi, + }) assertBn(nodeOperator2.id, 1, 'operator id') assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators') @@ -289,7 +311,7 @@ contract('Lido: happy path', (addresses) => { nodeOperator2.validators[0].key, nodeOperator2.validators[0].sig, { - from: nodeOperator2.address + from: nodeOperator2.address, } ) @@ -315,10 +337,16 @@ contract('Lido: happy path', (addresses) => { DSMAttestMessage.setMessagePrefix(await depositSecurityModule.ATTEST_MESSAGE_PREFIX()) DSMPauseMessage.setMessagePrefix(await depositSecurityModule.PAUSE_MESSAGE_PREFIX()) - const validAttestMessage = new DSMAttestMessage(block.number, block.hash, depositRoot, CURATED_MODULE_ID, keysOpIndex) + const validAttestMessage = new DSMAttestMessage( + block.number, + block.hash, + depositRoot, + CURATED_MODULE_ID, + keysOpIndex + ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, @@ -361,7 +389,6 @@ contract('Lido: happy path', (addresses) => { }) it('the oracle reports balance increase on Ethereum2 side', async () => { - // Total shares are equal to deposited eth before ratio change and fee mint const oldTotalShares = await token.getTotalShares() @@ -446,8 +473,8 @@ contract('Lido: happy path', (addresses) => { address: operator_3, validators: [...Array(10).keys()].map((i) => ({ key: pad('0xaa01' + i.toString(16), 48), - sig: pad('0x' + i.toString(16), 96) - })) + sig: pad('0x' + i.toString(16), 96), + })), } it('nodeOperator3 registered in NodeOperatorsRegistry and adds 10 signing keys', async () => { @@ -459,7 +486,7 @@ contract('Lido: happy path', (addresses) => { hexConcat(...nodeOperator3.validators.map((v) => v.key)), hexConcat(...nodeOperator3.validators.map((v) => v.sig)), { - from: nodeOperator3.address + from: nodeOperator3.address, } ) await nodeOperatorsRegistry.setNodeOperatorStakingLimit(nodeOperator3.id, validatorsCount, { from: voting }) @@ -467,7 +494,9 @@ contract('Lido: happy path', (addresses) => { it('nodeOperator3 removes signing key with id 5', async () => { const signingKeyIndexToRemove = 5 - await nodeOperatorsRegistry.removeSigningKeyOperatorBH(nodeOperator3.id, signingKeyIndexToRemove, { from: nodeOperator3.address }) + await nodeOperatorsRegistry.removeSigningKeyOperatorBH(nodeOperator3.id, signingKeyIndexToRemove, { + from: nodeOperator3.address, + }) const nodeOperatorInfo = await nodeOperatorsRegistry.getNodeOperator(nodeOperator3.id, false) assertBn(nodeOperatorInfo.stakingLimit, 5) }) @@ -482,10 +511,16 @@ contract('Lido: happy path', (addresses) => { DSMAttestMessage.setMessagePrefix(await depositSecurityModule.ATTEST_MESSAGE_PREFIX()) DSMPauseMessage.setMessagePrefix(await depositSecurityModule.PAUSE_MESSAGE_PREFIX()) - const validAttestMessage = new DSMAttestMessage(block.number, block.hash, depositRoot, CURATED_MODULE_ID, keysOpIndex) + const validAttestMessage = new DSMAttestMessage( + block.number, + block.hash, + depositRoot, + CURATED_MODULE_ID, + keysOpIndex + ) const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( block.number, diff --git a/test/scenario/lido_penalties_slashing.js b/test/scenario/lido_penalties_slashing.js index 67772eafa..d5d6721d5 100644 --- a/test/scenario/lido_penalties_slashing.js +++ b/test/scenario/lido_penalties_slashing.js @@ -22,7 +22,7 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { // users who deposit Ether to the pool user1, // unrelated address - nobody + nobody, ] = addresses let pool, nodeOperatorsRegistry, token @@ -33,51 +33,54 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { let stakingRouter, consensus let elRewardsVault - before('DAO, node operators registry, token, pool and deposit security module are deployed and initialized', async () => { - const deployed = await deployProtocol({ - oracleReportSanityCheckerFactory: oracleReportSanityCheckerStubFactory, - stakingModulesFactory: async (protocol) => { - const curatedModule = await setupNodeOperatorsRegistry(protocol) - return [ - { - module: curatedModule, - name: 'Curated', - targetShares: 10000, - moduleFee: 500, - treasuryFee: 500 - } - ] - } - }) - - // contracts/StETH.sol - token = deployed.pool - - // contracts/Lido.sol - pool = deployed.pool - - // contracts/nos/NodeOperatorsRegistry.sol - nodeOperatorsRegistry = deployed.stakingModules[0] - - // mocks - oracle = deployed.oracle - consensus = deployed.consensusContract - depositContractMock = deployed.depositContract - - stakingRouter = deployed.stakingRouter - - // addresses - treasuryAddr = deployed.treasury.address - depositSecurityModule = deployed.depositSecurityModule - guardians = deployed.guardians - voting = deployed.voting.address - elRewardsVault = deployed.elRewardsVault - - depositRoot = await depositContractMock.get_deposit_root() - withdrawalCredentials = pad('0x0202', 32) - - await stakingRouter.setWithdrawalCredentials(withdrawalCredentials, { from: voting }) - }) + before( + 'DAO, node operators registry, token, pool and deposit security module are deployed and initialized', + async () => { + const deployed = await deployProtocol({ + oracleReportSanityCheckerFactory: oracleReportSanityCheckerStubFactory, + stakingModulesFactory: async (protocol) => { + const curatedModule = await setupNodeOperatorsRegistry(protocol) + return [ + { + module: curatedModule, + name: 'Curated', + targetShares: 10000, + moduleFee: 500, + treasuryFee: 500, + }, + ] + }, + }) + + // contracts/StETH.sol + token = deployed.pool + + // contracts/Lido.sol + pool = deployed.pool + + // contracts/nos/NodeOperatorsRegistry.sol + nodeOperatorsRegistry = deployed.stakingModules[0] + + // mocks + oracle = deployed.oracle + consensus = deployed.consensusContract + depositContractMock = deployed.depositContract + + stakingRouter = deployed.stakingRouter + + // addresses + treasuryAddr = deployed.treasury.address + depositSecurityModule = deployed.depositSecurityModule + guardians = deployed.guardians + voting = deployed.voting.address + elRewardsVault = deployed.elRewardsVault + + depositRoot = await depositContractMock.get_deposit_root() + withdrawalCredentials = pad('0x0202', 32) + + await stakingRouter.setWithdrawalCredentials(withdrawalCredentials, { from: voting }) + } + ) const pushReport = async (clValidators, clBalance) => { const elRewards = await web3.eth.getBalance(elRewardsVault.address) @@ -87,7 +90,7 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { } // storing incremental calculated values that changes all across the test suite - let expectedTotalShares = shares(0) + const expectedTotalShares = shares(0) let expectedUser1Balance = StETH(0) let expectedUser1Shares = shares(0) @@ -99,20 +102,22 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { validators: [ { key: pad('0x010101', 48), - sig: pad('0x01', 96) + sig: pad('0x01', 96), }, { key: pad('0x030303', 48), - sig: pad('0x03', 96) - } - ] + sig: pad('0x03', 96), + }, + ], } it('voting adds the first node operator', async () => { const txn = await nodeOperatorsRegistry.addNodeOperator(nodeOperator1.name, nodeOperator1.address, { from: voting }) // Some Truffle versions fail to decode logs here, so we're decoding them explicitly using a helper - nodeOperator1.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi }) + nodeOperator1.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { + decodeForAbi: NodeOperatorsRegistry._json.abi, + }) assertBn(nodeOperator1.id, 0, 'operator id') assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') @@ -127,7 +132,7 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { nodeOperator1.validators[0].key, nodeOperator1.validators[0].sig, { - from: nodeOperator1.address + from: nodeOperator1.address, } ) @@ -168,9 +173,17 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { keysOpIndex, '0x00', guardians.privateKeys[guardians.addresses[1]] - ) + ), ] - await depositSecurityModule.depositBufferedEther(block.number, block.hash, depositRoot, 1, keysOpIndex, '0x00', signatures) + await depositSecurityModule.depositBufferedEther( + block.number, + block.hash, + depositRoot, + 1, + keysOpIndex, + '0x00', + signatures + ) // No Ether was deposited yet to the validator contract @@ -186,13 +199,19 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { expectedUser1Balance = StETH(32) expectedUser1Shares = shares(32) - assertBn(await token.sharesOf(user1), shares(32), "User1 holds 32 shares") - assertBn(await token.balanceOf(user1), expectedUser1Balance, - 'The amount of tokens corresponding to the deposited ETH value was minted to the user') + assertBn(await token.sharesOf(user1), shares(32), 'User1 holds 32 shares') + assertBn( + await token.balanceOf(user1), + expectedUser1Balance, + 'The amount of tokens corresponding to the deposited ETH value was minted to the user' + ) assertBn(await token.totalSupply(), StETH(33), 'token total supply') - assertBn(await token.getTotalShares(), shares(33), - 'Total shares are equal to deposited eth before ratio change and fee mint') + assertBn( + await token.getTotalShares(), + shares(33), + 'Total shares are equal to deposited eth before ratio change and fee mint' + ) }) it(`voting grants first operator right to have one validator`, async () => { @@ -228,15 +247,27 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { keysOpIndex, '0x00', guardians.privateKeys[guardians.addresses[1]] - ) + ), ] - await depositSecurityModule.depositBufferedEther(block.number, block.hash, depositRoot, 1, keysOpIndex, '0x00', signatures) + await depositSecurityModule.depositBufferedEther( + block.number, + block.hash, + depositRoot, + 1, + keysOpIndex, + '0x00', + signatures + ) }) it('new validator gets the 32 ETH deposit from the pool', async () => { assertBn(await pool.getBufferedEther(), ETH(1), `only initial eth is left`) assertBn(await pool.getTotalPooledEther(), ETH(33), 'total pooled ether') - assertBn(await nodeOperatorsRegistry.getUnusedSigningKeyCount(0), 0, 'no more available keys for the first validator') + assertBn( + await nodeOperatorsRegistry.getUnusedSigningKeyCount(0), + 0, + 'no more available keys for the first validator' + ) }) it('first oracle report is taken as-is for Lido', async () => { @@ -245,8 +276,7 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { // Reporting 1 ETH balance loss (32 => 31) await pushReport(1, ETH(31)) - assertBn(await token.getTotalShares(), shares(33), - 'Total shares stay the same because no fee shares are added') + assertBn(await token.getTotalShares(), shares(33), 'Total shares stay the same because no fee shares are added') assertBn(await pool.getTotalPooledEther(), ETH(32), 'Total pooled Ether decreased') @@ -257,7 +287,7 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { assertBn(await pool.getBufferedEther(), ETH(1), 'Initial stake remains in the buffer') assertBn(await token.totalSupply(), StETH(32), 'Token total supply penalized') - assertBn(await token.sharesOf(user1), shares(32), "User1 still holds 32 shares") + assertBn(await token.sharesOf(user1), shares(32), 'User1 still holds 32 shares') expectedUser1Balance = bn(shares(32)).muln(32).divn(33) // 32/33 ETH/share is a new price assertBn(await token.balanceOf(user1), expectedUser1Balance, `Token user balances decreased`) @@ -266,16 +296,21 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { }) it('the oracle reports balance loss on CL side', async () => { - assertBn(await token.getTotalShares(), shares(33), - 'Total shares are equal to deposited eth before ratio change and fee mint') - assertBn(await pool.getTotalPooledEther(), ETH(32), - 'Old total pooled Ether 31 ETH od previous report + 1 ETH initial') + assertBn( + await token.getTotalShares(), + shares(33), + 'Total shares are equal to deposited eth before ratio change and fee mint' + ) + assertBn( + await pool.getTotalPooledEther(), + ETH(32), + 'Old total pooled Ether 31 ETH od previous report + 1 ETH initial' + ) // Reporting 2 ETH balance loss (31 => 29) await pushReport(1, ETH(29)) - assertBn(await token.getTotalShares(), shares(33), - `Total shares stay the same because no fee shares are added`) + assertBn(await token.getTotalShares(), shares(33), `Total shares stay the same because no fee shares are added`) assertBn(await pool.getTotalPooledEther(), ETH(30), 'Total pooled Ether decreased') const ether2Stat = await pool.getBeaconStat() @@ -298,9 +333,9 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { validators: [ { key: pad('0x020202', 48), - sig: pad('0x02', 96) - } - ] + sig: pad('0x02', 96), + }, + ], } it('voting adds the second node operator who registers one validator', async () => { @@ -309,7 +344,9 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { const txn = await nodeOperatorsRegistry.addNodeOperator(nodeOperator2.name, nodeOperator2.address, { from: voting }) // Some Truffle versions fail to decode logs here, so we're decoding them explicitly using a helper - nodeOperator2.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi }) + nodeOperator2.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { + decodeForAbi: NodeOperatorsRegistry._json.abi, + }) assertBn(nodeOperator2.id, 1, 'correct operator id added') assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators updated') @@ -322,7 +359,7 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { nodeOperator2.validators[0].key, nodeOperator2.validators[0].sig, { - from: nodeOperator2.address + from: nodeOperator2.address, } ) @@ -366,9 +403,17 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { keysOpIndex, '0x00', guardians.privateKeys[guardians.addresses[1]] - ) + ), ] - await depositSecurityModule.depositBufferedEther(block.number, block.hash, depositRoot, 1, keysOpIndex, '0x00', signatures) + await depositSecurityModule.depositBufferedEther( + block.number, + block.hash, + depositRoot, + 1, + keysOpIndex, + '0x00', + signatures + ) assertBn(await depositContractMock.totalCalls(), 2) @@ -381,10 +426,16 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { assertBn(await token.totalSupply(), StETH(62), 'token total supply') // 32 ETH deposit to shares if price is 30/33 ETH/shares - const sharesAdded = bn(ETH(32)).mul(bn(ETH(33))).div(bn(shares(30))) + const sharesAdded = bn(ETH(32)) + .mul(bn(ETH(33))) + .div(bn(shares(30))) expectedUser1Shares = bn(expectedUser1Shares).add(sharesAdded) - assertBn(await token.sharesOf(user1), expectedUser1Shares, "User1 acquires new shares by new share price") - assertBn(await token.getTotalShares(), bn(shares(1)).add(expectedUser1Shares), 'total shares are changed proportionally') + assertBn(await token.sharesOf(user1), expectedUser1Shares, 'User1 acquires new shares by new share price') + assertBn( + await token.getTotalShares(), + bn(shares(1)).add(expectedUser1Shares), + 'total shares are changed proportionally' + ) expectedUser1Balance = bn(expectedUser1Balance).add(bn(StETH(32))) assertBn(await token.balanceOf(user1), expectedUser1Balance, 'user1 tokens') @@ -398,8 +449,11 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { // Reporting 1 ETH balance loss ( total pooled 61 => 60) await pushReport(1, ETH(28)) - assertBn(await token.getTotalShares(), bn(shares(1)).add(expectedUser1Shares), - 'Total shares stay the same because no fee shares are added') + assertBn( + await token.getTotalShares(), + bn(shares(1)).add(expectedUser1Shares), + 'Total shares stay the same because no fee shares are added' + ) assertBn(await pool.getTotalPooledEther(), ETH(61), 'Total pooled Ether decreased') const ether2Stat = await pool.getBeaconStat() @@ -432,7 +486,7 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { await web3.eth.sendTransaction({ to: pool.address, from: user1, value: ETH(32) }) - await hre.network.provider.send("hardhat_mine", ['0x100']) + await hre.network.provider.send('hardhat_mine', ['0x100']) const block = await web3.eth.getBlock('latest') const keysOpIndex = await nodeOperatorsRegistry.getKeysOpIndex() @@ -444,7 +498,7 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( @@ -464,15 +518,23 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { assertBn(await pool.getTotalPooledEther(), ETH(93), 'Total pooled Ether') assertBn(await token.totalSupply(), StETH(93), 'token total supply') - const sharesAdded = bn(ETH(32)).mul(oldTotalShares).div(bn(ETH(61))) - assertBn(await token.getTotalShares(), oldTotalShares.add(sharesAdded), - 'Total shares are equal to deposited eth before ratio change and fee mint') + const sharesAdded = bn(ETH(32)) + .mul(oldTotalShares) + .div(bn(ETH(61))) + assertBn( + await token.getTotalShares(), + oldTotalShares.add(sharesAdded), + 'Total shares are equal to deposited eth before ratio change and fee mint' + ) expectedUser1Shares = bn(expectedUser1Shares).add(sharesAdded) - assertBn(await token.sharesOf(user1), expectedUser1Shares, "User1 bought shares on 32 ETH") + assertBn(await token.sharesOf(user1), expectedUser1Shares, 'User1 bought shares on 32 ETH') expectedUser1Balance = expectedUser1Balance.add(bn(StETH(32))) - assertBn(await token.balanceOf(user1), expectedUser1Balance, - 'The amount of tokens corresponding to the deposited ETH value was minted to the user') + assertBn( + await token.balanceOf(user1), + expectedUser1Balance, + 'The amount of tokens corresponding to the deposited ETH value was minted to the user' + ) }) it(`voting stops the staking module`, async () => { @@ -489,13 +551,15 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { nodeOperator1.validators[1].key, nodeOperator1.validators[1].sig, { - from: nodeOperator1.address + from: nodeOperator1.address, } ) // The key was added - const totalFirstOperatorKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator1.id, { from: nobody }) + const totalFirstOperatorKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator1.id, { + from: nobody, + }) assertBn(totalFirstOperatorKeys, 2, 'added one signing key to total') const unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator1.id, { from: nobody }) @@ -548,11 +612,7 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { const totalFeeToDistribute = bn(beaconBalanceIncrement.toString()).mul(bn(totalFeePoints)).div(tenKBN) const totalPooledEther = await pool.getTotalPooledEther() - let sharesToMint = totalFeeToDistribute - .mul(prevTotalShares) - .div( - totalPooledEther.sub(totalFeeToDistribute) - ) + const sharesToMint = totalFeeToDistribute.mul(prevTotalShares).div(totalPooledEther.sub(totalFeeToDistribute)) assertBn(treasurySharesAfter.sub(treasurySharesBefore), sharesToMint, 'treasury got the total fee') }) diff --git a/test/scenario/lido_rewards_distribution_math.js b/test/scenario/lido_rewards_distribution_math.js index 0a1d43672..819db2ce5 100644 --- a/test/scenario/lido_rewards_distribution_math.js +++ b/test/scenario/lido_rewards_distribution_math.js @@ -19,7 +19,7 @@ const initialHolderBalanceETH = 1 const StakingModuleStatus = { Active: 0, // deposits and rewards allowed DepositsPaused: 1, // deposits NOT allowed, rewards allowed - Stopped: 2 // deposits and rewards NOT allowed + Stopped: 2, // deposits and rewards NOT allowed } contract('Lido: rewards distribution math', (addresses) => { @@ -40,13 +40,13 @@ contract('Lido: rewards distribution math', (addresses) => { validators: [ { key: pad('0x010101', 48), - sig: pad('0x01', 96) + sig: pad('0x01', 96), }, { key: pad('0x030303', 48), - sig: pad('0x03', 96) - } - ] + sig: pad('0x03', 96), + }, + ], } const nodeOperator2 = { @@ -55,9 +55,9 @@ contract('Lido: rewards distribution math', (addresses) => { validators: [ { key: pad('0x020202', 48), - sig: pad('0x02', 96) - } - ] + sig: pad('0x02', 96), + }, + ], } const nodeOperator3 = { @@ -65,8 +65,8 @@ contract('Lido: rewards distribution math', (addresses) => { address: operator_3, validators: [...Array(10).keys()].map((i) => ({ key: pad('0xaa01' + i.toString(16), 48), - sig: pad('0x' + i.toString(16), 96) - })) + sig: pad('0x' + i.toString(16), 96), + })), } async function reportBeacon(validatorsCount, balance) { @@ -88,10 +88,10 @@ contract('Lido: rewards distribution math', (addresses) => { name: 'curated', targetShares: 10000, moduleFee: 500, - treasuryFee: 500 - } + treasuryFee: 500, + }, ] - } + }, }) // contracts/StETH.sol @@ -139,7 +139,7 @@ contract('Lido: rewards distribution math', (addresses) => { nodeOperator1.validators[0].key, nodeOperator1.validators[0].sig, { - from: nodeOperator1.address + from: nodeOperator1.address, } ) @@ -184,13 +184,12 @@ contract('Lido: rewards distribution math', (addresses) => { assertBn(await token.balanceOf(treasuryAddr), new BN(0), 'treasury balance is zero') assertBn(await token.balanceOf(nodeOperator1.address), new BN(0), 'nodeOperator1 balance is zero') - }) it(`the first deposit gets deployed`, async () => { const [curated] = await stakingRouter.getStakingModules() - await ethers.provider.send('evm_increaseTime', [SECONDS_PER_FRAME *2]) + await ethers.provider.send('evm_increaseTime', [SECONDS_PER_FRAME * 2]) await ethers.provider.send('evm_mine') const block = await ethers.provider.getBlock('latest') @@ -203,7 +202,7 @@ contract('Lido: rewards distribution math', (addresses) => { const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] await depositSecurityModule.depositBufferedEther( @@ -288,7 +287,7 @@ contract('Lido: rewards distribution math', (addresses) => { 'Transfer', { to: nodeOperatorsRegistry.address, - value: nodeOperatorsFeeToMint + value: nodeOperatorsFeeToMint, }, { abi: Lido.abi } ) @@ -297,7 +296,7 @@ contract('Lido: rewards distribution math', (addresses) => { 'Transfer', { to: treasuryAddr, - value: treasuryFeeMint + value: treasuryFeeMint, }, { abi: Lido.abi } ) @@ -306,7 +305,7 @@ contract('Lido: rewards distribution math', (addresses) => { 'TransferShares', { to: nodeOperatorsRegistry.address, - sharesValue: nodeOperatorsSharesToMint + sharesValue: nodeOperatorsSharesToMint, }, { abi: Lido.abi } ) @@ -315,7 +314,7 @@ contract('Lido: rewards distribution math', (addresses) => { 'TransferShares', { to: treasuryAddr, - sharesValue: treasurySharesToMint + sharesValue: treasurySharesToMint, }, { abi: Lido.abi } ) @@ -325,7 +324,7 @@ contract('Lido: rewards distribution math', (addresses) => { { from: nodeOperatorsRegistry.address, to: nodeOperator1.address, - value: nodeOperatorsFeeToMint + value: nodeOperatorsFeeToMint, }, { abi: Lido.abi } ) @@ -335,7 +334,7 @@ contract('Lido: rewards distribution math', (addresses) => { { from: nodeOperatorsRegistry.address, to: nodeOperator1.address, - sharesValue: nodeOperatorsSharesToMint.toString() + sharesValue: nodeOperatorsSharesToMint.toString(), }, { abi: Lido.abi } ) @@ -364,7 +363,7 @@ contract('Lido: rewards distribution math', (addresses) => { nodeOperator2.validators[0].key, nodeOperator2.validators[0].sig, { - from: nodeOperator2.address + from: nodeOperator2.address, } ) await nodeOperatorsRegistry.setNodeOperatorStakingLimit(nodeOperator2.id, 1, { from: voting }) @@ -421,7 +420,7 @@ contract('Lido: rewards distribution math', (addresses) => { nodeOperator2.validators[0].key, nodeOperator2.validators[0].sig, { - from: nodeOperator2.address + from: nodeOperator2.address, } ) const keysOpIndex = await nodeOperatorsRegistry.getKeysOpIndex() @@ -446,7 +445,7 @@ contract('Lido: rewards distribution math', (addresses) => { keysOpIndex, '0x00', guardians.privateKeys[guardians.addresses[1]] - ) + ), ] const [_, deltas] = await getSharesTokenDeltas( @@ -559,7 +558,7 @@ contract('Lido: rewards distribution math', (addresses) => { 'Transfer', { to: nodeOperatorsRegistry.address, - value: nodeOperatorsFeeToMint + value: nodeOperatorsFeeToMint, }, { abi: Lido.abi } ) @@ -568,7 +567,7 @@ contract('Lido: rewards distribution math', (addresses) => { 'Transfer', { to: treasuryAddr, - value: treasuryFeeMint + value: treasuryFeeMint, }, { abi: Lido.abi } ) @@ -577,7 +576,7 @@ contract('Lido: rewards distribution math', (addresses) => { 'TransferShares', { to: nodeOperatorsRegistry.address, - sharesValue: nodeOperatorsSharesToMint + sharesValue: nodeOperatorsSharesToMint, }, { abi: Lido.abi } ) @@ -586,7 +585,7 @@ contract('Lido: rewards distribution math', (addresses) => { 'TransferShares', { to: treasuryAddr, - sharesValue: treasurySharesToMint + sharesValue: treasurySharesToMint, }, { abi: Lido.abi } ) @@ -596,7 +595,7 @@ contract('Lido: rewards distribution math', (addresses) => { { from: nodeOperatorsRegistry.address, to: nodeOperator1.address, - value: nodeOperatorFeeToMint + value: nodeOperatorFeeToMint, }, { abi: Lido.abi } ) @@ -606,7 +605,7 @@ contract('Lido: rewards distribution math', (addresses) => { { from: nodeOperatorsRegistry.address, to: nodeOperator1.address, - sharesValue: nodeOperatorSharesToMint + sharesValue: nodeOperatorSharesToMint, }, { abi: Lido.abi } ) @@ -616,7 +615,7 @@ contract('Lido: rewards distribution math', (addresses) => { { from: nodeOperatorsRegistry.address, to: nodeOperator2.address, - value: nodeOperatorFeeToMint + value: nodeOperatorFeeToMint, }, { abi: Lido.abi } ) @@ -626,7 +625,7 @@ contract('Lido: rewards distribution math', (addresses) => { { from: nodeOperatorsRegistry.address, to: nodeOperator2.address, - sharesValue: nodeOperatorSharesToMint + sharesValue: nodeOperatorSharesToMint, }, { abi: Lido.abi } ) @@ -666,7 +665,7 @@ contract('Lido: rewards distribution math', (addresses) => { hexConcat(...nodeOperator3.validators.map((v) => v.key)), hexConcat(...nodeOperator3.validators.map((v) => v.sig)), { - from: nodeOperator3.address + from: nodeOperator3.address, } ) await anotherCuratedModule.setNodeOperatorStakingLimit(0, validatorsCount, { from: voting }) @@ -695,7 +694,7 @@ contract('Lido: rewards distribution math', (addresses) => { const signatures = [ validAttestMessage.sign(guardians.privateKeys[guardians.addresses[0]]), - validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]) + validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] const user1BalanceBefore = await token.balanceOf(user1) @@ -862,5 +861,4 @@ contract('Lido: rewards distribution math', (addresses) => { const valuesAfter = await Promise.all(addresses.flatMap((addr) => [token.balanceOf(addr), token.sharesOf(addr)])) return [{ receipt, valuesBefore, valuesAfter }, valuesAfter.map((val, i) => val.sub(valuesBefore[i]))] } - }) From a27561a1925f33338be7acb9c5d5d6d6947bc368 Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Tue, 21 Feb 2023 19:54:16 +0200 Subject: [PATCH 06/14] =?UTF-8?q?=F0=9F=A4=96:=20fail=20pre-commit=20hook?= =?UTF-8?q?=20if=20abi=20is=20missing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .husky/pre-commit | 1 + 1 file changed, 1 insertion(+) diff --git a/.husky/pre-commit b/.husky/pre-commit index 265cc9c25..5ea85ee62 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -2,6 +2,7 @@ . "$(dirname -- "$0")/_/husky.sh" yarn compile +git diff --quiet lib/abi yarn lint:sol yarn lint:js:fix From ba9e22322859c0442bb91cfafea1d50307de81ec Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Wed, 22 Feb 2023 01:55:28 +0200 Subject: [PATCH 07/14] =?UTF-8?q?=F0=9F=92=85:=20lint=20warning=20fixes=20?= =?UTF-8?q?and=20other=20stuff?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 5 - gasprofile/tx-deposit.js | 12 +- hardhat.config.js | 1 + .../estimate_deposit_loop_gas.js | 36 +- test/0.4.24/helpers/dao.js | 3 + test/0.4.24/helpers/permit_helpers.js | 1 + test/0.4.24/legacyoracle.test.js | 10 +- test/0.4.24/lido-deposit-scenarios.test.js | 8 +- test/0.4.24/lido-handle-oracle-report.test.js | 12 +- test/0.4.24/lido.test.js | 765 +++++++++--------- .../node-operators-registry-penalty.test.js | 167 ++-- test/0.4.24/node-operators-registry.test.js | 50 +- test/0.4.24/signingkey-lib.test.js | 13 +- test/0.4.24/staking-limit.test.js | 56 +- test/0.4.24/steth.test.js | 467 +++++------ test/0.4.24/stethpermit.test.js | 6 +- test/0.6.12/helpers/permit_helpers.js | 1 + test/0.6.12/wsteth.permit.test.js | 9 +- test/0.6.12/wsteth.test.js | 8 +- test/0.8.9/burner.test.js | 9 +- test/0.8.9/deposit-security-module.test.js | 248 +++--- ... => lido-exec-layer-rewards-vault.test.js} | 99 +-- test/0.8.9/lido-locator.test.js | 12 +- test/0.8.9/oracle-daemon-config.test.js | 8 +- .../oracle-report-sanity-checker.test.js | 16 +- .../accounting-oracle-access-control.test.js | 1 + .../oracle/accounting-oracle-deploy.test.js | 30 +- .../accounting-oracle-happy-path.test.js | 119 ++- ...counting-oracle-submit-report-data.test.js | 17 +- ...ng-oracle-submit-report-extra-data.test.js | 27 +- .../oracle/base-oracle-access-control.test.js | 5 +- test/0.8.9/oracle/base-oracle-deploy.test.js | 3 +- .../oracle/base-oracle-set-consensus.test.js | 4 +- .../oracle/base-oracle-submit-report.test.js | 13 +- .../hash-consensus-access-control.test.js | 34 +- .../oracle/hash-consensus-deploy.test.js | 13 +- .../hash-consensus-fast-lane-length.test.js | 10 +- .../hash-consensus-fast-lane-members.test.js | 30 +- ...rames.js => hash-consensus-frames.test.js} | 121 ++- .../oracle/hash-consensus-happy-path.test.js | 110 ++- .../oracle/hash-consensus-members.test.js | 104 +-- .../hash-consensus-report-processor.test.js | 10 +- ...m.js => hash-consensus-set-quorum.test.js} | 138 ++-- .../hash-consensus-submit-report.test.js | 5 +- ...ors-exit-bus-oracle-access-control.test.js | 5 +- .../validators-exit-bus-oracle-deploy.test.js | 13 +- .../validators-exit-bus-oracle-gas.test.js | 58 +- ...idators-exit-bus-oracle-happy-path.test.js | 88 +- ...exit-bus-oracle-submit-report-data.test.js | 25 +- test/0.8.9/pausable-until.test.js | 10 +- .../positive-token-rebase-limiter.test.js | 8 +- ...ing-router-allocation-combinations.test.js | 37 +- ...staking-router-deposits-allocation.test.js | 46 +- test/0.8.9/staking-router-deposits.test.js | 9 +- .../staking-router-keys-reporting.test.js | 286 +++---- test/0.8.9/staking-router.test.js | 8 +- test/0.8.9/withdrawal-queue.test.js | 13 +- test/0.8.9/withdrawal-request-nft.test.js | 542 ++++++------- .../lib/min-first-allocation-strategy.test.js | 45 +- test/helpers/assert.js | 20 +- test/helpers/blockchain.js | 18 +- test/helpers/dao.js | 2 + test/helpers/factories.js | 3 +- test/helpers/locator-deploy.js | 2 + test/helpers/node-operators.js | 23 +- test/helpers/oracle.js | 2 + test/helpers/signatures.js | 8 +- test/helpers/staking-modules.js | 2 + test/helpers/utils.js | 66 +- test/helpers/withdrawals.js | 2 +- ... => changing_oracles_during_epoch.test.js} | 29 +- test/{ => scenario}/deposit.test.js | 356 ++++---- ...bution.js => deposit_distribution.test.js} | 7 +- ...ion_layer_rewards_after_the_merge.test.js} | 296 ++++--- test/scenario/helpers/deploy.js | 2 +- ...s => lido_deposit_iteration_limit.test.js} | 50 +- ..._happy_path.js => lido_happy_path.test.js} | 114 +-- ...ing.js => lido_penalties_slashing.test.js} | 215 ++--- ...=> lido_rewards_distribution_math.test.js} | 121 ++- 79 files changed, 2544 insertions(+), 2803 deletions(-) rename estimate_deposit_loop_gas.js => scripts/estimate_deposit_loop_gas.js (83%) rename test/0.8.9/{lido-exec-layer-rewards-vault.js => lido-exec-layer-rewards-vault.test.js} (61%) rename test/0.8.9/oracle/{hash-consensus-frames.js => hash-consensus-frames.test.js} (66%) rename test/0.8.9/oracle/{hash-consensus-set-quorum.js => hash-consensus-set-quorum.test.js} (62%) rename test/scenario/{changing_oracles_during_epoch.js => changing_oracles_during_epoch.test.js} (75%) rename test/{ => scenario}/deposit.test.js (58%) rename test/scenario/{deposit_distribution.js => deposit_distribution.test.js} (97%) rename test/scenario/{execution_layer_rewards_after_the_merge.js => execution_layer_rewards_after_the_merge.test.js} (68%) rename test/scenario/{lido_deposit_iteration_limit.js => lido_deposit_iteration_limit.test.js} (81%) rename test/scenario/{lido_happy_path.js => lido_happy_path.test.js} (80%) rename test/scenario/{lido_penalties_slashing.js => lido_penalties_slashing.test.js} (69%) rename test/scenario/{lido_rewards_distribution_math.js => lido_rewards_distribution_math.test.js} (85%) diff --git a/.eslintrc b/.eslintrc index 26d9bc447..c04d261bc 100644 --- a/.eslintrc +++ b/.eslintrc @@ -33,11 +33,6 @@ "files": ["./scripts/{**/,}*.js", "./test/{**/,}*.js", "./e2e/test/{**/,}*.js"], "env": { "mocha": true - }, - "globals": { - "artifacts": "readonly", - "contract": "readonly", - "web3": "readonly" } } ] diff --git a/gasprofile/tx-deposit.js b/gasprofile/tx-deposit.js index 133b4b56b..84263eb7f 100644 --- a/gasprofile/tx-deposit.js +++ b/gasprofile/tx-deposit.js @@ -23,7 +23,7 @@ async function main() { user1, user2, // an unrelated address - nobody + nobody, ] = addresses const deployed = await deployDaoAndPool(appManager, voting, 100) @@ -38,14 +38,18 @@ async function main() { const numKeys = 3 for (let iProvider = 0; iProvider < numProviders; ++iProvider) { - const nosTx = await nodeOperatorRegistry.addNodeOperator(`NOS-${iProvider}`, nodeOperator, nosValidatorsLimit, { from: voting }) - const nodeOperatorId = getEventArgument(nosTx, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi }) + const nosTx = await nodeOperatorRegistry.addNodeOperator(`NOS-${iProvider}`, nodeOperator, nosValidatorsLimit, { + from: voting, + }) + const nodeOperatorId = getEventArgument(nosTx, 'NodeOperatorAdded', 'nodeOperatorId', { + decodeForAbi: NodeOperatorsRegistry._json.abi, + }) const data = Array.from({ length: numKeys }, (_, iKey) => { const n = arbitraryN.clone().addn(10 * iKey + 1000 * iProvider) return { key: pad(`0x${n.toString(16)}`, 48, 'd'), - sig: pad(`0x${n.toString(16)}`, 96, 'e') + sig: pad(`0x${n.toString(16)}`, 96, 'e'), } }) diff --git a/hardhat.config.js b/hardhat.config.js index b4cf9943a..b7ec8ee9d 100644 --- a/hardhat.config.js +++ b/hardhat.config.js @@ -16,6 +16,7 @@ require('./foundry/skip-sol-tests-compilation') const NETWORK_NAME = getNetworkName() const ETH_ACCOUNT_NAME = process.env.ETH_ACCOUNT_NAME +// eslint-disable-next-line no-undef task('accounts', 'Prints the list of accounts', async (taskArgs, hre) => { const accounts = await hre.ethers.getSigners() diff --git a/estimate_deposit_loop_gas.js b/scripts/estimate_deposit_loop_gas.js similarity index 83% rename from estimate_deposit_loop_gas.js rename to scripts/estimate_deposit_loop_gas.js index 71fba2d0e..15dfe948e 100644 --- a/estimate_deposit_loop_gas.js +++ b/scripts/estimate_deposit_loop_gas.js @@ -1,8 +1,8 @@ -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') const { getEventArgument, ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { assert } = require('../test/helpers/assert') -const { pad, ETH, hexConcat, toBN } = require('./test/helpers/utils') -const { deployDaoAndPool } = require('./test/scenario/helpers/deploy') +const { pad, ETH, hexConcat, toBN } = require('../test/helpers/utils') +const { deployDaoAndPool } = require('../test/scenario/helpers/deploy') const NodeOperatorsRegistry = artifacts.require('NodeOperatorsRegistry') @@ -76,12 +76,12 @@ contract('Lido: deposit loop gas estimate', (addresses) => { await nodeOperatorsRegistry.addSigningKeys(nodeOperatorId, numKeys, keys, sigs, { from: voting }) const totalKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperatorId, { from: nobody }) - assertBn(totalKeys, numKeys, 'total signing keys') + assert.equals(totalKeys, numKeys, 'total signing keys') validatorData.push.apply(validatorData, data) } - assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), numOperators, 'total operators') + assert.equals(await nodeOperatorsRegistry.getNodeOperatorsCount(), numOperators, 'total operators') }) let gasPerMockDeposit @@ -99,7 +99,7 @@ contract('Lido: deposit loop gas estimate', (addresses) => { ) ) - assertBn(await depositContractMock.totalCalls(), validatorData.length) + assert.equals(await depositContractMock.totalCalls(), validatorData.length) const gasUsed = results.map((r) => +r.receipt.gasUsed) console.log('mock deposits gas:', gasUsed.join(', ')) @@ -113,8 +113,8 @@ contract('Lido: deposit loop gas estimate', (addresses) => { it('a user sends 33 ETH', async () => { const result = await pool.submit(ZERO_ADDRESS, { from: user1, value: ETH(33) }) - assertBn(await pool.getTotalPooledEther(), ETH(33), 'total pooled ether') - assertBn((await depositContractMock.totalCalls()) - validatorData.length, 1, 'validators registered') + assert.equals(await pool.getTotalPooledEther(), ETH(33), 'total pooled ether') + assert.equals((await depositContractMock.totalCalls()) - validatorData.length, 1, 'validators registered') console.log('1 validator (initial), gas:', result.receipt.gasUsed) }) @@ -122,8 +122,8 @@ contract('Lido: deposit loop gas estimate', (addresses) => { it('a user submits 32 ETH', async () => { const result = await pool.submit(ZERO_ADDRESS, { from: user2, value: ETH(32) }) - assertBn(await pool.getTotalPooledEther(), ETH(33 + 32), 'total pooled ether') - assertBn((await depositContractMock.totalCalls()) - validatorData.length, 2, 'validators registered') + assert.equals(await pool.getTotalPooledEther(), ETH(33 + 32), 'total pooled ether') + assert.equals((await depositContractMock.totalCalls()) - validatorData.length, 2, 'validators registered') console.log('1 validator, gas:', result.receipt.gasUsed) @@ -133,8 +133,8 @@ contract('Lido: deposit loop gas estimate', (addresses) => { it('a, 1 validator user submits 5 * 32 ETH', async () => { const result = await pool.submit(ZERO_ADDRESS, { from: user2, value: ETH(5 * 32) }) - assertBn(await pool.getTotalPooledEther(), ETH(33 + 32 + 5 * 32), 'total pooled ether') - assertBn((await depositContractMock.totalCalls()) - validatorData.length, 2 + 5, 'validators registered') + assert.equals(await pool.getTotalPooledEther(), ETH(33 + 32 + 5 * 32), 'total pooled ether') + assert.equals((await depositContractMock.totalCalls()) - validatorData.length, 2 + 5, 'validators registered') const gasPerIter = result.receipt.gasUsed / 5 @@ -147,8 +147,8 @@ contract('Lido: deposit loop gas estimate', (addresses) => { it('a user submits 10 * 32 ETH', async () => { const result = await pool.submit(ZERO_ADDRESS, { from: user2, value: ETH(10 * 32) }) - assertBn(await pool.getTotalPooledEther(), ETH(33 + 32 + 5 * 32 + 10 * 32), 'total pooled ether') - assertBn((await depositContractMock.totalCalls()) - validatorData.length, 2 + 5 + 10, 'validators registered') + assert.equals(await pool.getTotalPooledEther(), ETH(33 + 32 + 5 * 32 + 10 * 32), 'total pooled ether') + assert.equals((await depositContractMock.totalCalls()) - validatorData.length, 2 + 5 + 10, 'validators registered') const gasPerIter = result.receipt.gasUsed / 10 @@ -161,8 +161,12 @@ contract('Lido: deposit loop gas estimate', (addresses) => { it('a user submits 30 * 32 ETH', async () => { const result = await pool.submit(ZERO_ADDRESS, { from: user2, value: ETH(30 * 32) }) - assertBn(await pool.getTotalPooledEther(), ETH(33 + 32 + 5 * 32 + 10 * 32 + 30 * 32), 'total pooled ether') - assertBn((await depositContractMock.totalCalls()) - validatorData.length, 2 + 5 + 10 + 30, 'validators registered') + assert.equals(await pool.getTotalPooledEther(), ETH(33 + 32 + 5 * 32 + 10 * 32 + 30 * 32), 'total pooled ether') + assert.equals( + (await depositContractMock.totalCalls()) - validatorData.length, + 2 + 5 + 10 + 30, + 'validators registered' + ) const gasPerIter = result.receipt.gasUsed / 30 diff --git a/test/0.4.24/helpers/dao.js b/test/0.4.24/helpers/dao.js index 144743a74..b0c35882d 100644 --- a/test/0.4.24/helpers/dao.js +++ b/test/0.4.24/helpers/dao.js @@ -1,5 +1,8 @@ +const { artifacts } = require('hardhat') + const { hash } = require('eth-ens-namehash') const { getEventArgument } = require('@aragon/contract-helpers-test') + const Kernel = artifacts.require('@aragon/os/build/contracts/kernel/Kernel') const ACL = artifacts.require('@aragon/os/build/contracts/acl/ACL') const EVMScriptRegistryFactory = artifacts.require('@aragon/os/build/contracts/factory/EVMScriptRegistryFactory') diff --git a/test/0.4.24/helpers/permit_helpers.js b/test/0.4.24/helpers/permit_helpers.js index d8e18b660..948e36c0b 100644 --- a/test/0.4.24/helpers/permit_helpers.js +++ b/test/0.4.24/helpers/permit_helpers.js @@ -1,3 +1,4 @@ +const { web3 } = require('hardhat') const { ecSign, strip0x } = require('./sign_utils') const transferWithAuthorizationTypeHash = web3.utils.keccak256( diff --git a/test/0.4.24/legacyoracle.test.js b/test/0.4.24/legacyoracle.test.js index bfd145e7d..4db9b947c 100644 --- a/test/0.4.24/legacyoracle.test.js +++ b/test/0.4.24/legacyoracle.test.js @@ -1,11 +1,5 @@ -const { assert } = require('chai') -const { newDao, newApp } = require('./helpers/dao') -const { assertBn, assertEvent } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../helpers/assertThrow') +const { contract } = require('hardhat') -const { toBN } = require('../helpers/utils') -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') - -contract('LegacyOracle', ([admin, stranger]) => { +contract('LegacyOracle', () => { it.skip('TODO: legacy compat tests', async () => {}) }) diff --git a/test/0.4.24/lido-deposit-scenarios.test.js b/test/0.4.24/lido-deposit-scenarios.test.js index d60719631..182e941c8 100644 --- a/test/0.4.24/lido-deposit-scenarios.test.js +++ b/test/0.4.24/lido-deposit-scenarios.test.js @@ -1,14 +1,14 @@ -const hre = require('hardhat') +const { contract, ethers } = require('hardhat') const { deployProtocol } = require('../helpers/protocol') const { EvmSnapshot, setBalance, getBalance } = require('../helpers/blockchain') -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { ZERO_ADDRESS } = require('../helpers/constants') const { assert } = require('../helpers/assert') const { wei } = require('../helpers/wei') const { StakingModuleStub } = require('../helpers/stubs/staking-module.stub') const { PUBKEY_LENGTH, FakeValidatorKeys, SIGNATURE_LENGTH } = require('../helpers/signing-keys') const { GenericStub } = require('../helpers/stubs/generic.stub') -hre.contract('Lido deposit scenarios', ([staker, depositor]) => { +contract('Lido deposit scenarios', ([staker, depositor]) => { const CURATED_MODULE_ID = 1 const DEPOSIT_CALLDATA = '0x0' let lido, stakingRouter @@ -41,7 +41,7 @@ hre.contract('Lido deposit scenarios', ([staker, depositor]) => { }) lido = protocol.pool stakingRouter = protocol.stakingRouter - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() }) diff --git a/test/0.4.24/lido-handle-oracle-report.test.js b/test/0.4.24/lido-handle-oracle-report.test.js index eed66e512..ca89fbc6e 100644 --- a/test/0.4.24/lido-handle-oracle-report.test.js +++ b/test/0.4.24/lido-handle-oracle-report.test.js @@ -1,10 +1,12 @@ -const hre = require('hardhat') +const { artifacts, contract, ethers } = require('hardhat') + const { assert } = require('../helpers/assert') -const { ETH, toBN, genKeys, setBalance, StETH, calcSharesMintedAsFees } = require('../helpers/utils') +const { ETH, toBN, genKeys, StETH, calcSharesMintedAsFees } = require('../helpers/utils') const { deployProtocol } = require('../helpers/protocol') -const { EvmSnapshot } = require('../helpers/blockchain') +const { EvmSnapshot, setBalance } = require('../helpers/blockchain') const { ZERO_ADDRESS, INITIAL_HOLDER } = require('../helpers/constants') const { setupNodeOperatorsRegistry } = require('../helpers/staking-modules') + const Lido = artifacts.require('Lido') const ONE_YEAR = 3600 * 24 * 365 @@ -114,7 +116,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another }) await setBalance(deployed.oracle.address, ETH(1)) - await hre.ethers.getImpersonatedSigner(deployed.oracle.address) + await ethers.getImpersonatedSigner(deployed.oracle.address) await curatedModule.addNodeOperator('1', operator, { from: deployed.voting.address }) const keysAmount = 120 @@ -136,7 +138,7 @@ contract('Lido: handleOracleReport', ([appManager, , , , , , , stranger, another await checkStat({ depositedValidators: 0, beaconValidators: 0, beaconBalance: 0 }) - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() }) diff --git a/test/0.4.24/lido.test.js b/test/0.4.24/lido.test.js index e3689e52b..57550ae92 100644 --- a/test/0.4.24/lido.test.js +++ b/test/0.4.24/lido.test.js @@ -1,34 +1,25 @@ -const hre = require('hardhat') +const { artifacts, contract, ethers, web3 } = require('hardhat') +const { assert } = require('../helpers/assert') const { hash } = require('eth-ens-namehash') -const { artifacts, ethers } = require('hardhat') const { getInstalledApp } = require('@aragon/contract-helpers-test/src/aragon-os') -const { assertBn, assertEvent } = require('@aragon/contract-helpers-test/src/asserts') - -const { assertRevert } = require('../helpers/assertThrow') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') -const { waitBlocks, EvmSnapshot, advanceChainTime, getCurrentBlockTimestamp } = require('../helpers/blockchain') +const { bn } = require('@aragon/contract-helpers-test') const { - hexConcat, - pad, - ETH, - tokens, - div15, - assertNoEvent, - StETH, - shares, + waitBlocks, + EvmSnapshot, + advanceChainTime, + getCurrentBlockTimestamp, setBalance, - prepIdsCountsPayload, -} = require('../helpers/utils') -const { assert } = require('../helpers/assert') +} = require('../helpers/blockchain') +const { hexConcat, pad, ETH, tokens, div15, StETH, shares, prepIdsCountsPayload } = require('../helpers/utils') + const nodeOperators = require('../helpers/node-operators') const { deployProtocol } = require('../helpers/protocol') const { setupNodeOperatorsRegistry } = require('../helpers/staking-modules') const { pushOracleReport } = require('../helpers/oracle') -const { SECONDS_PER_FRAME, INITIAL_HOLDER, MAX_UINT256 } = require('../helpers/constants') +const { SECONDS_PER_FRAME, INITIAL_HOLDER, MAX_UINT256, ZERO_ADDRESS } = require('../helpers/constants') const { oracleReportSanityCheckerStubFactory } = require('../helpers/factories') - const { newApp } = require('../helpers/dao') const ERC20Mock = artifacts.require('ERC20Mock.sol') @@ -58,7 +49,6 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody let stakingRouter let anyToken, badToken let eip712StETH - let withdrawalQueue let lidoLocator let snapshot let consensus @@ -108,12 +98,11 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody stakingRouter = deployed.stakingRouter operators = deployed.stakingModules[0] lidoLocator = deployed.lidoLocator - withdrawalQueue = deployed.withdrawalQueue oracle = deployed.oracle consensus = deployed.consensusContract voting = deployed.voting.address - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() }) @@ -129,9 +118,9 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const checkStat = async ({ depositedValidators, beaconValidators, beaconBalance }) => { const stat = await app.getBeaconStat() - assertBn(stat.depositedValidators, depositedValidators, 'depositedValidators check') - assertBn(stat.beaconValidators, beaconValidators, 'beaconValidators check') - assertBn(stat.beaconBalance, beaconBalance, 'beaconBalance check') + assert.equals(stat.depositedValidators, depositedValidators, 'depositedValidators check') + assert.equals(stat.beaconValidators, beaconValidators, 'beaconValidators check') + assert.equals(stat.beaconBalance, beaconBalance, 'beaconBalance check') } // Assert reward distribution. The values must be divided by 1e15. @@ -145,8 +134,8 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody app.balanceOf(ADDRESS_4), ]) - assertBn(div15(treasury_b), treasury, 'treasury token balance check') - assertBn(div15(operators_b.add(a1).add(a2).add(a3).add(a4)), operator, 'node operators token balance check') + assert.equals(div15(treasury_b), treasury, 'treasury token balance check') + assert.equals(div15(operators_b.add(a1).add(a2).add(a3).add(a4)), operator, 'node operators token balance check') } const setupNodeOperatorsForELRewardsVaultTests = async (userAddress, initialDepositAmount) => { @@ -221,9 +210,9 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody beforeEach('set up limits', async () => { // TODO(DZhon): revive // const maxPositiveTokenRebase = bn(1).mul(bn(10).pow(bn(8))) // 10% - // await assertRevert(app.setMaxPositiveTokenRebase(maxPositiveTokenRebase), 'APP_AUTH_FAILED') + // await assert.reverts(app.setMaxPositiveTokenRebase(maxPositiveTokenRebase), 'APP_AUTH_FAILED') // const receipt = await app.setMaxPositiveTokenRebase(maxPositiveTokenRebase, { from: voting }) - // assertEvent(receipt, 'MaxPositiveTokenRebaseSet', { expectedArgs: { maxPositiveTokenRebase: maxPositiveTokenRebase } }) + // assert.emits(receipt, 'MaxPositiveTokenRebaseSet', { maxPositiveTokenRebase: maxPositiveTokenRebase } }) }) it('Execution layer rewards distribution works when zero cl rewards reported', async () => { @@ -240,10 +229,10 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await pushReport(1, ETH(totalDeposit + clRewards)) - assertBn(await app.getTotalPooledEther(), ETH(initialDeposit + user2Deposit + totalElRewards + clRewards)) - assertBn(await app.totalSupply(), StETH(initialDeposit + user2Deposit + totalElRewards + clRewards)) - assertBn(await app.balanceOf(user2), StETH(user2Deposit + user2Rewards)) - assertBn(await app.getTotalELRewardsCollected(), ETH(totalElRewards)) + assert.equals(await app.getTotalPooledEther(), ETH(initialDeposit + user2Deposit + totalElRewards + clRewards)) + assert.equals(await app.totalSupply(), StETH(initialDeposit + user2Deposit + totalElRewards + clRewards)) + assert.equals(await app.balanceOf(user2), StETH(user2Deposit + user2Rewards)) + assert.equals(await app.getTotalELRewardsCollected(), ETH(totalElRewards)) }) it('Execution layer rewards distribution works when negative cl rewards reported', async () => { @@ -260,9 +249,9 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await setBalance(elRewardsVault.address, ETH(totalElRewards)) await pushReport(1, ETH(totalDeposit + clRewards)) - assertBn(await app.getTotalPooledEther(), ETH(initialDeposit + user2Deposit + totalElRewards + clRewards)) - assertBn(await app.balanceOf(user2), StETH(user2Deposit + user2Rewards + (clRewards * 31) / 32)) - assertBn(await app.getTotalELRewardsCollected(), ETH(totalElRewards)) + assert.equals(await app.getTotalPooledEther(), ETH(initialDeposit + user2Deposit + totalElRewards + clRewards)) + assert.equals(await app.balanceOf(user2), StETH(user2Deposit + user2Rewards + (clRewards * 31) / 32)) + assert.equals(await app.getTotalELRewardsCollected(), ETH(totalElRewards)) }) it('Execution layer rewards distribution works when positive cl rewards reported', async () => { @@ -278,22 +267,22 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await setBalance(elRewardsVault.address, ETH(totalElRewards)) await pushReport(1, ETH(totalDeposit + clRewards)) - assertBn(await app.getTotalPooledEther(), ETH(totalDeposit + totalElRewards + clRewards)) - assertBn(await app.getTotalELRewardsCollected(), ETH(totalElRewards)) + assert.equals(await app.getTotalPooledEther(), ETH(totalDeposit + totalElRewards + clRewards)) + assert.equals(await app.getTotalELRewardsCollected(), ETH(totalElRewards)) const fee = await app.getFee() const stakersReward = ((totalElRewards + clRewards) * (TOTAL_BASIS_POINTS - fee)) / TOTAL_BASIS_POINTS - assertBn(await app.balanceOf(user2), StETH(user2Deposit + (stakersReward * 31) / 32)) + assert.equals(await app.balanceOf(user2), StETH(user2Deposit + (stakersReward * 31) / 32)) }) it('Attempt to set invalid execution layer rewards withdrawal limit', async () => { // TODO: revive // const initialValue = await app.getMaxPositiveTokenRebase() - // assertEvent(await app.setMaxPositiveTokenRebase(1, { from: voting }), 'MaxPositiveTokenRebaseSet', { - // expectedArgs: { maxPositiveTokenRebase: 1 } + // assert.emits(await app.setMaxPositiveTokenRebase(1, { from: voting }), 'MaxPositiveTokenRebaseSet', { + // maxPositiveTokenRebase: 1 } const setupNodeOperatorsForELRewardsVaultTests = async (userAddress, initialDepositAmount) => { await app.setFee(1000, { from: voting }) // 10% @@ -332,10 +321,10 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await setBalance(elRewardsVault.address, ETH(elRewards)) await pushReport(1, ETH(depositAmount + beaconRewards)) - assertBn(await app.getTotalPooledEther(), ETH(depositAmount + elRewards + beaconRewards)) - assertBn(await app.getBufferedEther(), ETH(elRewards)) - assertBn(await app.balanceOf(user2), StETH(depositAmount + elRewards)) - assertBn(await app.getTotalELRewardsCollected(), ETH(elRewards)) + assert.equals(await app.getTotalPooledEther(), ETH(depositAmount + elRewards + beaconRewards)) + assert.equals(await app.getBufferedEther(), ETH(elRewards)) + assert.equals(await app.balanceOf(user2), StETH(depositAmount + elRewards)) + assert.equals(await app.getTotalELRewardsCollected(), ETH(elRewards)) }) it('Execution layer rewards distribution works when negative rewards reported', async () => { @@ -349,10 +338,10 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await setBalance(elRewardsVault.address, ETH(elRewards)) await pushReport(1, ETH(depositAmount + beaconRewards)) - assertBn(await app.getTotalPooledEther(), ETH(depositAmount + elRewards + beaconRewards)) - assertBn(await app.getBufferedEther(), ETH(elRewards)) - assertBn(await app.balanceOf(user2), StETH(depositAmount + elRewards + beaconRewards)) - assertBn(await app.getTotalELRewardsCollected(), ETH(elRewards)) + assert.equals(await app.getTotalPooledEther(), ETH(depositAmount + elRewards + beaconRewards)) + assert.equals(await app.getBufferedEther(), ETH(elRewards)) + assert.equals(await app.balanceOf(user2), StETH(depositAmount + elRewards + beaconRewards)) + assert.equals(await app.getTotalELRewardsCollected(), ETH(elRewards)) }) it('Execution layer rewards distribution works when positive rewards reported', async () => { @@ -368,38 +357,38 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const { totalFee } = await app.getFee() const shareOfRewardsForStakers = (TOTAL_BASIS_POINTS - totalFee) / TOTAL_BASIS_POINTS - assertBn(await app.getTotalPooledEther(), ETH(depositAmount + elRewards + beaconRewards)) - assertBn(await app.getBufferedEther(), ETH(elRewards)) - assertBn( + assert.equals(await app.getTotalPooledEther(), ETH(depositAmount + elRewards + beaconRewards)) + assert.equals(await app.getBufferedEther(), ETH(elRewards)) + assert.equals( await app.balanceOf(user2), StETH(depositAmount + shareOfRewardsForStakers * (elRewards + beaconRewards)) ) - assertBn(await app.getTotalELRewardsCollected(), ETH(elRewards)) + assert.equals(await app.getTotalELRewardsCollected(), ETH(elRewards)) }) it('Attempt to set invalid execution layer rewards withdrawal limit', async () => { const initialValue = await app.getELRewardsWithdrawalLimit() - assertEvent(await app.setELRewardsWithdrawalLimit(1, { from: voting }), 'ELRewardsWithdrawalLimitSet', { - expectedArgs: { limitPoints: 1 }, + assert.emits(await app.setELRewardsWithdrawalLimit(1, { from: voting }), 'ELRewardsWithdrawalLimitSet', { + limitPoints: 1, }) - await assertNoEvent(app.setELRewardsWithdrawalLimit(1, { from: voting }), 'ELRewardsWithdrawalLimitSet') + assert.notEmits(await app.setELRewardsWithdrawalLimit(1, { from: voting }), 'ELRewardsWithdrawalLimitSet') await app.setELRewardsWithdrawalLimit(10000, { from: voting }) - await assertRevert(app.setELRewardsWithdrawalLimit(10001, { from: voting }), 'VALUE_OVER_100_PERCENT') + await assert.reverts(app.setELRewardsWithdrawalLimit(10001, { from: voting }), 'VALUE_OVER_100_PERCENT') await app.setELRewardsWithdrawalLimit(initialValue, { from: voting }) // unable to receive execution layer rewards from arbitrary account - await assertRevert(app.receiveELRewards({ from: user1, value: ETH(1) }), 'EXECUTION_LAYER_REWARDS_VAULT_ONLY') + await assert.reverts(app.receiveELRewards({ from: user1, value: ETH(1) }), 'EXECUTION_LAYER_REWARDS_VAULT_ONLY') }) }) }) describe('receiveELRewards()', async () => { it('unable to receive eth from arbitrary account', async () => { - await assertRevert(app.receiveELRewards({ from: nobody, value: ETH(1) }), 'EXECUTION_LAYER_REWARDS_VAULT_ONLY') + await assert.reverts(app.receiveELRewards({ from: nobody, value: ETH(1) }), 'EXECUTION_LAYER_REWARDS_VAULT_ONLY') }) it('event work', async () => { @@ -408,18 +397,16 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const receipt = await app.receiveELRewards({ from: elRewardsVault.address, value: ETH(2) }) - assertEvent(receipt, 'ELRewardsReceived', { - expectedArgs: { amount: ETH(2) }, - }) + assert.emits(receipt, 'ELRewardsReceived', { amount: ETH(2) }) - assertBn(await app.getTotalELRewardsCollected(), ETH(2)) + assert.equals(await app.getTotalELRewardsCollected(), ETH(2)) }) }) it('setWithdrawalCredentials works', async () => { await stakingRouter.setWithdrawalCredentials(pad('0x0202', 32), { from: voting }) - await assertRevert( + await assert.reverts( stakingRouter.setWithdrawalCredentials(pad('0x0203', 32), { from: user1 }), `AccessControl: account ${user1.toLowerCase()} is missing role ${await stakingRouter.MANAGE_WITHDRAWAL_CREDENTIALS_ROLE()}` ) @@ -448,22 +435,22 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await operators.setNodeOperatorStakingLimit(0, UNLIMITED, { from: voting }) await operators.setNodeOperatorStakingLimit(1, UNLIMITED, { from: voting }) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 1) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 1) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 2) await stakingRouter.setWithdrawalCredentials(pad('0x0203', 32), { from: voting }) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 0) assert.equal(await app.getWithdrawalCredentials({ from: nobody }), pad('0x0203', 32)) }) it('Lido.deposit(uint256,uint256,bytes) reverts when called by account without DEPOSIT_ROLE granted', async () => { - await assertRevert( + await assert.reverts( app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: nobody }), 'APP_AUTH_DSM_FAILED' ) @@ -488,38 +475,38 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await operators.setNodeOperatorStakingLimit(1, UNLIMITED, { from: voting }) // zero deposits revert - await assertRevert(app.submit(ZERO_ADDRESS, { from: user1, value: ETH(0) }), 'ZERO_DEPOSIT') - await assertRevert(web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(0) }), 'ZERO_DEPOSIT') + await assert.reverts(app.submit(ZERO_ADDRESS, { from: user1, value: ETH(0) }), 'ZERO_DEPOSIT') + await assert.reverts(web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(0) }), 'ZERO_DEPOSIT') // Initial balance (1 ETH) - assertBn(await app.getTotalPooledEther(), ETH(1)) - assertBn(await app.getBufferedEther(), ETH(1)) - assertBn(await app.balanceOf(INITIAL_HOLDER), tokens(1)) - assertBn(await app.totalSupply(), tokens(1)) + assert.equals(await app.getTotalPooledEther(), ETH(1)) + assert.equals(await app.getBufferedEther(), ETH(1)) + assert.equals(await app.balanceOf(INITIAL_HOLDER), tokens(1)) + assert.equals(await app.totalSupply(), tokens(1)) // +1 ETH await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(1) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 0, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await depositContract.totalCalls(), 0) - assertBn(await app.getTotalPooledEther(), ETH(2)) - assertBn(await app.getBufferedEther(), ETH(2)) - assertBn(await app.getTotalELRewardsCollected(), 0) - assertBn(await app.balanceOf(user1), tokens(1)) - assertBn(await app.totalSupply(), tokens(2)) + assert.equals(await depositContract.totalCalls(), 0) + assert.equals(await app.getTotalPooledEther(), ETH(2)) + assert.equals(await app.getBufferedEther(), ETH(2)) + assert.equals(await app.getTotalELRewardsCollected(), 0) + assert.equals(await app.balanceOf(user1), tokens(1)) + assert.equals(await app.totalSupply(), tokens(2)) // +2 ETH const receipt = await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2) }) // another form of a deposit call - assertEvent(receipt, 'Transfer', { expectedArgs: { from: ZERO_ADDRESS, to: user2, value: ETH(2) } }) + assert.emits(receipt, 'Transfer', { from: ZERO_ADDRESS, to: user2, value: ETH(2) }) await checkStat({ depositedValidators: 0, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await depositContract.totalCalls(), 0) - assertBn(await app.getTotalPooledEther(), ETH(4)) - assertBn(await app.getBufferedEther(), ETH(4)) - assertBn(await app.getTotalELRewardsCollected(), 0) - assertBn(await app.balanceOf(user2), tokens(2)) - assertBn(await app.totalSupply(), tokens(4)) + assert.equals(await depositContract.totalCalls(), 0) + assert.equals(await app.getTotalPooledEther(), ETH(4)) + assert.equals(await app.getBufferedEther(), ETH(4)) + assert.equals(await app.getTotalELRewardsCollected(), 0) + assert.equals(await app.balanceOf(user2), tokens(2)) + assert.equals(await app.totalSupply(), tokens(4)) // +30 ETH await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(30) }) @@ -534,7 +521,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody // set withdrawalCredentials with keys, because they were trimmed await stakingRouter.setWithdrawalCredentials(pad('0x0202', 32), { from: voting }) - assertBn( + assert.equals( await stakingRouter.getStakingModuleMaxDepositsCount(CURATED_MODULE_ID, await app.getDepositableEther()), 0 ) @@ -549,58 +536,58 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody ) await operators.setNodeOperatorStakingLimit(0, UNLIMITED, { from: voting }) - assertBn( + assert.equals( await stakingRouter.getStakingModuleMaxDepositsCount(CURATED_MODULE_ID, await app.getDepositableEther()), 1 ) - assertBn(await app.getTotalPooledEther(), ETH(34)) - assertBn(await app.getBufferedEther(), ETH(34)) + assert.equals(await app.getTotalPooledEther(), ETH(34)) + assert.equals(await app.getBufferedEther(), ETH(34)) // now deposit works await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 1, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(34)) - assertBn(await app.getBufferedEther(), ETH(2)) - assertBn(await app.balanceOf(user1), tokens(1)) - assertBn(await app.balanceOf(user2), tokens(2)) - assertBn(await app.balanceOf(user3), tokens(30)) - assertBn(await app.totalSupply(), tokens(34)) - - assertBn(await depositContract.totalCalls(), 1) + assert.equals(await app.getTotalPooledEther(), ETH(34)) + assert.equals(await app.getBufferedEther(), ETH(2)) + assert.equals(await app.balanceOf(user1), tokens(1)) + assert.equals(await app.balanceOf(user2), tokens(2)) + assert.equals(await app.balanceOf(user3), tokens(30)) + assert.equals(await app.totalSupply(), tokens(34)) + + assert.equals(await depositContract.totalCalls(), 1) const c0 = await depositContract.calls.call(0) assert.equal(c0.pubkey, pad('0x010203', 48)) assert.equal(c0.withdrawal_credentials, pad('0x0202', 32)) assert.equal(c0.signature, pad('0x01', 96)) - assertBn(c0.value, ETH(32)) + assert.equals(c0.value, ETH(32)) // +100 ETH, test partial unbuffering await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(100) }) await app.deposit(1, 1, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 2, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(134)) - assertBn(await app.getBufferedEther(), ETH(70)) - assertBn(await app.balanceOf(user1), tokens(101)) - assertBn(await app.balanceOf(user2), tokens(2)) - assertBn(await app.balanceOf(user3), tokens(30)) - assertBn(await app.totalSupply(), tokens(134)) + assert.equals(await app.getTotalPooledEther(), ETH(134)) + assert.equals(await app.getBufferedEther(), ETH(70)) + assert.equals(await app.balanceOf(user1), tokens(101)) + assert.equals(await app.balanceOf(user2), tokens(2)) + assert.equals(await app.balanceOf(user3), tokens(30)) + assert.equals(await app.totalSupply(), tokens(134)) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 4, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(134)) - assertBn(await app.getBufferedEther(), ETH(6)) - assertBn(await app.balanceOf(user1), tokens(101)) - assertBn(await app.balanceOf(user2), tokens(2)) - assertBn(await app.balanceOf(user3), tokens(30)) - assertBn(await app.totalSupply(), tokens(134)) - - assertBn(await depositContract.totalCalls(), 4) + assert.equals(await app.getTotalPooledEther(), ETH(134)) + assert.equals(await app.getBufferedEther(), ETH(6)) + assert.equals(await app.balanceOf(user1), tokens(101)) + assert.equals(await app.balanceOf(user2), tokens(2)) + assert.equals(await app.balanceOf(user3), tokens(30)) + assert.equals(await app.totalSupply(), tokens(134)) + + assert.equals(await depositContract.totalCalls(), 4) const calls = {} for (const i of [1, 2, 3]) { calls[i] = await depositContract.calls.call(i) assert.equal(calls[i].withdrawal_credentials, pad('0x0202', 32)) assert.equal(calls[i].signature, pad('0x01', 96)) - assertBn(calls[i].value, ETH(32)) + assert.equals(calls[i].value, ETH(32)) } assert.equal(calls[1].pubkey, pad('0x010204', 48)) assert.equal(calls[2].pubkey, pad('0x010205', 48)) @@ -631,15 +618,15 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(32) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) - assertBn(await depositContract.totalCalls(), 1, 'first submit: total deposits') + assert.equals(await depositContract.totalCalls(), 1, 'first submit: total deposits') await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2 * 32) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) - assertBn(await depositContract.totalCalls(), 3, 'second submit: total deposits') + assert.equals(await depositContract.totalCalls(), 3, 'second submit: total deposits') await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(3 * 32) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) - assertBn(await depositContract.totalCalls(), 6, 'third submit: total deposits') + assert.equals(await depositContract.totalCalls(), 6, 'third submit: total deposits') const calls = await Promise.all(Array.from({ length: 6 }, (_, i) => depositContract.calls(i))) const keys = [...op0.keys, ...op1.keys] @@ -669,16 +656,16 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(32) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) - assertBn(await depositContract.totalCalls(), 1) + assert.equals(await depositContract.totalCalls(), 1) }) it('submits with zero and non-zero referrals work', async () => { const REFERRAL = '0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF' let receipt receipt = await app.submit(REFERRAL, { from: user2, value: ETH(2) }) - assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user2, amount: ETH(2), referral: REFERRAL } }) + assert.emits(receipt, 'Submitted', { sender: user2, amount: ETH(2), referral: REFERRAL }) receipt = await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(5) }) - assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user2, amount: ETH(5), referral: ZERO_ADDRESS } }) + assert.emits(receipt, 'Submitted', { sender: user2, amount: ETH(5), referral: ZERO_ADDRESS }) }) const verifyStakeLimitState = async ( @@ -688,28 +675,22 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody expectedIsStakingPaused, expectedIsStakingLimited ) => { - currentStakeLimit = await app.getCurrentStakeLimit() - assertBn(currentStakeLimit, expectedCurrentStakeLimit) + assert.equals(await app.getCurrentStakeLimit(), expectedCurrentStakeLimit) - isStakingPaused = await app.isStakingPaused() - assert.equal(isStakingPaused, expectedIsStakingPaused) - ;({ - isStakingPaused, - isStakingLimitSet, - currentStakeLimit, - maxStakeLimit, - maxStakeLimitGrowthBlocks, - prevStakeLimit, - prevStakeBlockNumber, - } = await app.getStakeLimitFullInfo()) - - assertBn(currentStakeLimit, expectedCurrentStakeLimit) - assertBn(maxStakeLimit, expectedMaxStakeLimit) + assert.equal(await app.isStakingPaused(), expectedIsStakingPaused) + const { isStakingPaused, isStakingLimitSet, currentStakeLimit, maxStakeLimit, maxStakeLimitGrowthBlocks } = + await app.getStakeLimitFullInfo() + + assert.equals(currentStakeLimit, expectedCurrentStakeLimit) + assert.equals(maxStakeLimit, expectedMaxStakeLimit) assert.equal(isStakingPaused, expectedIsStakingPaused) assert.equal(isStakingLimitSet, expectedIsStakingLimited) if (isStakingLimitSet) { - assertBn(maxStakeLimitGrowthBlocks, expectedLimitIncrease > 0 ? expectedMaxStakeLimit / expectedLimitIncrease : 0) + assert.equals( + maxStakeLimitGrowthBlocks, + expectedLimitIncrease > 0 ? expectedMaxStakeLimit / expectedLimitIncrease : 0 + ) } } @@ -720,24 +701,24 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await verifyStakeLimitState(0, 0, bn(MAX_UINT256), false, false) receipt = await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2) }) - assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user2, amount: ETH(2), referral: ZERO_ADDRESS } }) + assert.emits(receipt, 'Submitted', { sender: user2, amount: ETH(2), referral: ZERO_ADDRESS }) - await assertRevert(app.pauseStaking(), 'APP_AUTH_FAILED') + await assert.reverts(app.pauseStaking(), 'APP_AUTH_FAILED') receipt = await app.pauseStaking({ from: voting }) - assertEvent(receipt, 'StakingPaused') + assert.emits(receipt, 'StakingPaused') await verifyStakeLimitState(0, 0, 0, true, false) - await assertRevert(web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(2) }), `STAKING_PAUSED`) - await assertRevert(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2) }), `STAKING_PAUSED`) + await assert.reverts(web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(2) }), `STAKING_PAUSED`) + await assert.reverts(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2) }), `STAKING_PAUSED`) - await assertRevert(app.resumeStaking(), 'APP_AUTH_FAILED') + await assert.reverts(app.resumeStaking(), 'APP_AUTH_FAILED') receipt = await app.resumeStaking({ from: voting }) - assertEvent(receipt, 'StakingResumed') + assert.emits(receipt, 'StakingResumed') await verifyStakeLimitState(0, 0, bn(MAX_UINT256), false, false) await web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(1.1) }) receipt = await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(1.4) }) - assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user2, amount: ETH(1.4), referral: ZERO_ADDRESS } }) + assert.emits(receipt, 'Submitted', { sender: user2, amount: ETH(1.4), referral: ZERO_ADDRESS }) }) it('staking resume with a limit works', async () => { @@ -748,22 +729,20 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const limitIncreasePerBlock = bn(expectedMaxStakeLimit).div(bn(blocksToReachMaxStakeLimit)) // 1 * 10**16 receipt = await app.resumeStaking({ from: voting }) - assertEvent(receipt, 'StakingResumed') + assert.emits(receipt, 'StakingResumed') - await assertRevert(app.setStakingLimit(expectedMaxStakeLimit, limitIncreasePerBlock), 'APP_AUTH_FAILED') + await assert.reverts(app.setStakingLimit(expectedMaxStakeLimit, limitIncreasePerBlock), 'APP_AUTH_FAILED') receipt = await app.setStakingLimit(expectedMaxStakeLimit, limitIncreasePerBlock, { from: voting }) - assertEvent(receipt, 'StakingLimitSet', { - expectedArgs: { - maxStakeLimit: expectedMaxStakeLimit, - stakeLimitIncreasePerBlock: limitIncreasePerBlock, - }, + assert.emits(receipt, 'StakingLimitSet', { + maxStakeLimit: expectedMaxStakeLimit, + stakeLimitIncreasePerBlock: limitIncreasePerBlock, }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, expectedMaxStakeLimit, false, true) receipt = await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2) }) - assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user2, amount: ETH(2), referral: ZERO_ADDRESS } }) + assert.emits(receipt, 'Submitted', { sender: user2, amount: ETH(2), referral: ZERO_ADDRESS }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, ETH(1), false, true) - await assertRevert(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2.5) }), `STAKE_LIMIT`) + await assert.reverts(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2.5) }), `STAKE_LIMIT`) await verifyStakeLimitState( expectedMaxStakeLimit, limitIncreasePerBlock, @@ -776,9 +755,9 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody // every revert produces new block, so we need to account that block await waitBlocks(blocksToReachMaxStakeLimit / 2 - 1) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, ETH(2.5), false, true) - await assertRevert(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2.6) }), `STAKE_LIMIT`) + await assert.reverts(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2.6) }), `STAKE_LIMIT`) receipt = await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2.5) }) - assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user2, amount: ETH(2.5), referral: ZERO_ADDRESS } }) + assert.emits(receipt, 'Submitted', { sender: user2, amount: ETH(2.5), referral: ZERO_ADDRESS }) await verifyStakeLimitState( expectedMaxStakeLimit, limitIncreasePerBlock, @@ -787,7 +766,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody true ) - await assertRevert(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(0.1) }), `STAKE_LIMIT`) + await assert.reverts(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(0.1) }), `STAKE_LIMIT`) await verifyStakeLimitState( expectedMaxStakeLimit, limitIncreasePerBlock, @@ -799,7 +778,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await waitBlocks(blocksToReachMaxStakeLimit / 3 - 4) receipt = await app.submit(ZERO_ADDRESS, { from: user1, value: ETH(1) }) - assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user1, amount: ETH(1), referral: ZERO_ADDRESS } }) + assert.emits(receipt, 'Submitted', { sender: user1, amount: ETH(1), referral: ZERO_ADDRESS }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, ETH(0), false, true) // check that limit is restored completely @@ -810,9 +789,9 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await waitBlocks(10) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, expectedMaxStakeLimit, false, true) - await assertRevert(app.setStakingLimit(ETH(0), ETH(0), { from: voting }), `ZERO_MAX_STAKE_LIMIT`) - await assertRevert(app.setStakingLimit(ETH(1), ETH(1.1), { from: voting }), `TOO_LARGE_LIMIT_INCREASE`) - await assertRevert(app.setStakingLimit(ETH(1), bn(10), { from: voting }), `TOO_SMALL_LIMIT_INCREASE`) + await assert.reverts(app.setStakingLimit(ETH(0), ETH(0), { from: voting }), `ZERO_MAX_STAKE_LIMIT`) + await assert.reverts(app.setStakingLimit(ETH(1), ETH(1.1), { from: voting }), `TOO_LARGE_LIMIT_INCREASE`) + await assert.reverts(app.setStakingLimit(ETH(1), bn(10), { from: voting }), `TOO_SMALL_LIMIT_INCREASE`) }) it('resume staking with an one-shot limit works', async () => { @@ -822,23 +801,21 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const limitIncreasePerBlock = 0 receipt = await app.resumeStaking({ from: voting }) - assertEvent(receipt, 'StakingResumed') + assert.emits(receipt, 'StakingResumed') receipt = await app.setStakingLimit(expectedMaxStakeLimit, limitIncreasePerBlock, { from: voting }) - assertEvent(receipt, 'StakingLimitSet', { - expectedArgs: { - maxStakeLimit: expectedMaxStakeLimit, - stakeLimitIncreasePerBlock: limitIncreasePerBlock, - }, + assert.emits(receipt, 'StakingLimitSet', { + maxStakeLimit: expectedMaxStakeLimit, + stakeLimitIncreasePerBlock: limitIncreasePerBlock, }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, expectedMaxStakeLimit, false, true) receipt = await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(5) }) - assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user2, amount: ETH(5), referral: ZERO_ADDRESS } }) + assert.emits(receipt, 'Submitted', { sender: user2, amount: ETH(5), referral: ZERO_ADDRESS }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, ETH(2), false, true) receipt = await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2) }) - assertEvent(receipt, 'Submitted', { expectedArgs: { sender: user2, amount: ETH(2), referral: ZERO_ADDRESS } }) + assert.emits(receipt, 'Submitted', { sender: user2, amount: ETH(2), referral: ZERO_ADDRESS }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, ETH(0), false, true) - await assertRevert(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(0.1) }), `STAKE_LIMIT`) + await assert.reverts(app.submit(ZERO_ADDRESS, { from: user2, value: ETH(0.1) }), `STAKE_LIMIT`) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, ETH(0), false, true) await waitBlocks(100) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, ETH(0), false, true) @@ -851,13 +828,11 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const limitIncreasePerBlock = bn(expectedMaxStakeLimit).divn(100) receipt = await app.resumeStaking({ from: voting }) - assertEvent(receipt, 'StakingResumed') + assert.emits(receipt, 'StakingResumed') receipt = await app.setStakingLimit(expectedMaxStakeLimit, limitIncreasePerBlock, { from: voting }) - assertEvent(receipt, 'StakingLimitSet', { - expectedArgs: { - maxStakeLimit: expectedMaxStakeLimit, - stakeLimitIncreasePerBlock: limitIncreasePerBlock, - }, + assert.emits(receipt, 'StakingLimitSet', { + maxStakeLimit: expectedMaxStakeLimit, + stakeLimitIncreasePerBlock: limitIncreasePerBlock, }) await verifyStakeLimitState(expectedMaxStakeLimit, limitIncreasePerBlock, expectedMaxStakeLimit, false, true) @@ -866,11 +841,9 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const smallerLimitIncreasePerBlock = bn(smallerExpectedMaxStakeLimit).divn(200) receipt = await app.setStakingLimit(smallerExpectedMaxStakeLimit, smallerLimitIncreasePerBlock, { from: voting }) - assertEvent(receipt, 'StakingLimitSet', { - expectedArgs: { - maxStakeLimit: smallerExpectedMaxStakeLimit, - stakeLimitIncreasePerBlock: smallerLimitIncreasePerBlock, - }, + assert.emits(receipt, 'StakingLimitSet', { + maxStakeLimit: smallerExpectedMaxStakeLimit, + stakeLimitIncreasePerBlock: smallerLimitIncreasePerBlock, }) await verifyStakeLimitState( @@ -885,11 +858,9 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const largerLimitIncreasePerBlock = bn(largerExpectedMaxStakeLimit).divn(1000) receipt = await app.setStakingLimit(largerExpectedMaxStakeLimit, largerLimitIncreasePerBlock, { from: voting }) - assertEvent(receipt, 'StakingLimitSet', { - expectedArgs: { - maxStakeLimit: largerExpectedMaxStakeLimit, - stakeLimitIncreasePerBlock: largerLimitIncreasePerBlock, - }, + assert.emits(receipt, 'StakingLimitSet', { + maxStakeLimit: largerExpectedMaxStakeLimit, + stakeLimitIncreasePerBlock: largerLimitIncreasePerBlock, }) await verifyStakeLimitState( @@ -900,20 +871,20 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody true ) - await assertRevert(app.removeStakingLimit(), 'APP_AUTH_FAILED') + await assert.reverts(app.removeStakingLimit(), 'APP_AUTH_FAILED') receipt = await app.removeStakingLimit({ from: voting }) - assertEvent(receipt, 'StakingLimitRemoved') + assert.emits(receipt, 'StakingLimitRemoved') await verifyStakeLimitState(0, 0, bn(2).pow(bn(256)).sub(bn(1)), false, false) }) it('reverts when trying to call unknown function', async () => { const wrongMethodABI = '0x00' - await assertRevert( + await assert.reverts( web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(1), data: wrongMethodABI }), 'NON_EMPTY_DATA' ) - await assertRevert( + await assert.reverts( web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(0), data: wrongMethodABI }), 'NON_EMPTY_DATA' ) @@ -938,19 +909,19 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(33) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) - assertBn(await depositContract.totalCalls(), 1) - await assertRevert(operators.removeSigningKey(0, 0, { from: voting }), 'OUT_OF_RANGE') + assert.equals(await depositContract.totalCalls(), 1) + await assert.reverts(operators.removeSigningKey(0, 0, { from: voting }), 'OUT_OF_RANGE') - assertBn(await app.getBufferedEther(), ETH(2)) + assert.equals(await app.getBufferedEther(), ETH(2)) await operators.removeSigningKey(0, 1, { from: voting }) await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(100) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) - assertBn(await depositContract.totalCalls(), 1) - assertBn(await app.getTotalPooledEther(), ETH(134)) - assertBn(await app.getBufferedEther(), ETH(102)) + assert.equals(await depositContract.totalCalls(), 1) + assert.equals(await app.getTotalPooledEther(), ETH(134)) + assert.equals(await app.getBufferedEther(), ETH(102)) }) it("out of signing keys doesn't revert but buffers", async () => { @@ -967,9 +938,9 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(99) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 1, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await depositContract.totalCalls(), 1) - assertBn(await app.getTotalPooledEther(), ETH(100)) - assertBn(await app.getBufferedEther(), ETH(100 - 32)) + assert.equals(await depositContract.totalCalls(), 1) + assert.equals(await app.getTotalPooledEther(), ETH(100)) + assert.equals(await app.getBufferedEther(), ETH(100 - 32)) // buffer unwinds await operators.addSigningKeys( @@ -986,9 +957,9 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(1) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await depositContract.totalCalls(), 3) - assertBn(await app.getTotalPooledEther(), ETH(101)) - assertBn(await app.getBufferedEther(), ETH(5)) + assert.equals(await depositContract.totalCalls(), 3) + assert.equals(await app.getTotalPooledEther(), ETH(101)) + assert.equals(await app.getBufferedEther(), ETH(5)) }) it('handleOracleReport works', async () => { @@ -1012,7 +983,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 1, beaconValidators: 0, beaconBalance: ETH(0) }) - await assertRevert( + await assert.reverts( app.handleOracleReport(await getCurrentBlockTimestamp(), 1, ETH(30), 0, 0, 0, 0, 0, { from: appManager }), 'APP_AUTH_FAILED' ) @@ -1020,7 +991,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await pushReport(1, ETH(30)) await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(30) }) - await assertRevert( + await assert.reverts( app.handleOracleReport(await getCurrentBlockTimestamp(), 1, ETH(29), 0, 0, 0, 0, 0, { from: nobody }), 'APP_AUTH_FAILED' ) @@ -1054,39 +1025,39 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 1, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await depositContract.totalCalls(), 1) - assertBn(await app.getTotalPooledEther(), ETH(34)) - assertBn(await app.getBufferedEther(), ETH(2)) + assert.equals(await depositContract.totalCalls(), 1) + assert.equals(await app.getTotalPooledEther(), ETH(34)) + assert.equals(await app.getBufferedEther(), ETH(2)) // down await pushReport(1, ETH(15)) await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(15) }) - assertBn(await depositContract.totalCalls(), 1) - assertBn(await app.getTotalPooledEther(), ETH(17)) - assertBn(await app.getBufferedEther(), ETH(2)) - assertBn(await app.totalSupply(), tokens(17)) + assert.equals(await depositContract.totalCalls(), 1) + assert.equals(await app.getTotalPooledEther(), ETH(17)) + assert.equals(await app.getBufferedEther(), ETH(2)) + assert.equals(await app.totalSupply(), tokens(17)) // deposit, ratio is 0.5 await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(2) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(15) }) - assertBn(await depositContract.totalCalls(), 1) - assertBn(await app.getTotalPooledEther(), ETH(19)) - assertBn(await app.getBufferedEther(), ETH(4)) - assertBn(await app.balanceOf(user1), tokens(2)) - assertBn(await app.totalSupply(), tokens(19)) + assert.equals(await depositContract.totalCalls(), 1) + assert.equals(await app.getTotalPooledEther(), ETH(19)) + assert.equals(await app.getBufferedEther(), ETH(4)) + assert.equals(await app.balanceOf(user1), tokens(2)) + assert.equals(await app.totalSupply(), tokens(19)) // up - await assertRevert(pushReport(2, ETH(48)), 'REPORTED_MORE_DEPOSITED') + await assert.reverts(pushReport(2, ETH(48)), 'REPORTED_MORE_DEPOSITED') await pushReport(1, ETH(48)) await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(48) }) - assertBn(await depositContract.totalCalls(), 1) - assertBn(await app.getTotalPooledEther(), ETH(52)) - assertBn(await app.getBufferedEther(), ETH(4)) - assertBn(await app.totalSupply(), tokens(52)) + assert.equals(await depositContract.totalCalls(), 1) + assert.equals(await app.getTotalPooledEther(), ETH(52)) + assert.equals(await app.getBufferedEther(), ETH(4)) + assert.equals(await app.totalSupply(), tokens(52)) }) it('can stop and resume', async () => { @@ -1109,27 +1080,27 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(40) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 1, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getBufferedEther(), ETH(9)) + assert.equals(await app.getBufferedEther(), ETH(9)) - await assertRevert(app.stop({ from: user2 }), 'APP_AUTH_FAILED') + await assert.reverts(app.stop({ from: user2 }), 'APP_AUTH_FAILED') await app.stop({ from: voting }) assert((await app.isStakingPaused()) === true) - await assertRevert(web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(4) }), 'STAKING_PAUSED') - await assertRevert(web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(4) }), 'STAKING_PAUSED') - await assertRevert( + await assert.reverts(web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(4) }), 'STAKING_PAUSED') + await assert.reverts(web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(4) }), 'STAKING_PAUSED') + await assert.reverts( app.submit('0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', { from: user1, value: ETH(4) }), 'STAKING_PAUSED' ) - await assertRevert(app.resume({ from: user2 }), 'APP_AUTH_FAILED') + await assert.reverts(app.resume({ from: user2 }), 'APP_AUTH_FAILED') await app.resume({ from: voting }) assert((await app.isStakingPaused()) === false) await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(4) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 1, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getBufferedEther(), ETH(13)) + assert.equals(await app.getBufferedEther(), ETH(13)) }) it('rewards distribution on module with zero treasury and module fee', async () => { @@ -1153,17 +1124,17 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const [curated] = await stakingRouter.getStakingModules() let module1 = await stakingRouter.getStakingModule(curated.id) - assertBn(module1.targetShare, 10000) - assertBn(module1.stakingModuleFee, 500) - assertBn(module1.treasuryFee, 500) + assert.equals(module1.targetShare, 10000) + assert.equals(module1.stakingModuleFee, 500) + assert.equals(module1.treasuryFee, 500) // stakingModuleId, targetShare, stakingModuleFee, treasuryFee await stakingRouter.updateStakingModule(module1.id, module1.targetShare, 0, 0, { from: voting }) module1 = await stakingRouter.getStakingModule(curated.id) - assertBn(module1.targetShare, 10000) - assertBn(module1.stakingModuleFee, 0) - assertBn(module1.treasuryFee, 0) + assert.equals(module1.targetShare, 10000) + assert.equals(module1.stakingModuleFee, 0) + assert.equals(module1.treasuryFee, 0) // check stat before deposit await checkStat({ depositedValidators: 0, beaconValidators: 0, beaconBalance: 0 }) @@ -1173,7 +1144,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await pushReport(1, ETH(36)) await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(36) }) - assertBn(await app.totalSupply(), ETH(38)) // remote + buffered + assert.equals(await app.totalSupply(), ETH(38)) // remote + buffered await checkRewards({ treasury: 0, operator: 0 }) // return module commission @@ -1182,7 +1153,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody // await pushReport(1, ETH(38)) await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(38) }) - assertBn(await app.totalSupply(), ETH(40)) // remote + buffered + assert.equals(await app.totalSupply(), ETH(40)) // remote + buffered await checkRewards({ treasury: 100, operator: 99 }) }) @@ -1212,7 +1183,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await pushReport(1, ETH(36)) await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(36) }) - assertBn(await app.totalSupply(), ETH(38)) // remote + buffered + assert.equals(await app.totalSupply(), ETH(38)) // remote + buffered await checkRewards({ treasury: 199, operator: 199 }) }) @@ -1241,7 +1212,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(30) }) // ToDo check buffer=2 - assertBn(await app.totalSupply(), tokens(32)) // 30 remote (slashed) + 2 buffered = 32 + assert.equals(await app.totalSupply(), tokens(32)) // 30 remote (slashed) + 2 buffered = 32 await checkRewards({ treasury: 0, operator: 0 }) // rewarded 200 Ether (was 30, became 230) @@ -1252,7 +1223,7 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await pushReport(1, ETH(2230)) await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(2230) }) - assertBn(await app.totalSupply(), tokens(2232)) + assert.equals(await app.totalSupply(), tokens(2232)) // Todo check reward effects // await checkRewards({ treasury: tokens(33), operator: tokens(55) }) }) @@ -1271,11 +1242,11 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(32) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) - assertBn(await app.totalSupply(), StETH(64)) + assert.equals(await app.totalSupply(), StETH(64)) await pushReport(1, ETH(36)) await checkStat({ depositedValidators: 1, beaconValidators: 1, beaconBalance: ETH(36) }) - assertBn(await app.totalSupply(), StETH(68)) + assert.equals(await app.totalSupply(), StETH(68)) await checkRewards({ treasury: 200, operator: 199 }) }) @@ -1320,37 +1291,37 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(32 * 3 + 49) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(146)) - assertBn(await app.getBufferedEther(), ETH(50)) - assertBn(await depositContract.totalCalls(), 3) + assert.equals(await app.getTotalPooledEther(), ETH(146)) + assert.equals(await app.getBufferedEther(), ETH(50)) + assert.equals(await depositContract.totalCalls(), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Next deposit changes nothing await web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(32) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(178)) - assertBn(await app.getBufferedEther(), ETH(82)) - assertBn(await depositContract.totalCalls(), 3) + assert.equals(await app.getTotalPooledEther(), ETH(178)) + assert.equals(await app.getBufferedEther(), ETH(82)) + assert.equals(await depositContract.totalCalls(), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // #1 goes below the limit const { operatorIds, keysCounts } = prepIdsCountsPayload(1, 1) @@ -1358,19 +1329,19 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(1) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(179)) - assertBn(await app.getBufferedEther(), ETH(83)) - assertBn(await depositContract.totalCalls(), 3) + assert.equals(await app.getTotalPooledEther(), ETH(179)) + assert.equals(await app.getBufferedEther(), ETH(83)) + assert.equals(await depositContract.totalCalls(), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Adding a key & setting staking limit will help await operators.addSigningKeys(0, 1, pad('0x0003', 48), pad('0x01', 96), { from: voting }) @@ -1379,38 +1350,38 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(1) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 4, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(180)) - assertBn(await app.getBufferedEther(), ETH(52)) - assertBn(await depositContract.totalCalls(), 4) + assert.equals(await app.getTotalPooledEther(), ETH(180)) + assert.equals(await app.getBufferedEther(), ETH(52)) + assert.equals(await depositContract.totalCalls(), 4) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Reactivation of #2 doesn't change anything cause keys of #2 was trimmed await operators.activateNodeOperator(2, { from: voting }) await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(12) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 4, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(192)) - assertBn(await app.getBufferedEther(), ETH(64)) - assertBn(await depositContract.totalCalls(), 4) - - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await app.getTotalPooledEther(), ETH(192)) + assert.equals(await app.getBufferedEther(), ETH(64)) + assert.equals(await depositContract.totalCalls(), 4) + + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) }) it('Node Operators filtering during deposit works when doing small deposits', async () => { @@ -1457,37 +1428,37 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(146)) - assertBn(await app.getBufferedEther(), ETH(50)) - assertBn(await depositContract.totalCalls(), 3) + assert.equals(await app.getTotalPooledEther(), ETH(146)) + assert.equals(await app.getBufferedEther(), ETH(50)) + assert.equals(await depositContract.totalCalls(), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Next deposit changes nothing await web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(32) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(178)) - assertBn(await app.getBufferedEther(), ETH(82)) - assertBn(await depositContract.totalCalls(), 3) + assert.equals(await app.getTotalPooledEther(), ETH(178)) + assert.equals(await app.getBufferedEther(), ETH(82)) + assert.equals(await depositContract.totalCalls(), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // #1 goes below the limit (doesn't change situation. validator stop decreases limit) const { operatorIds, keysCounts } = prepIdsCountsPayload(1, 1) @@ -1495,19 +1466,19 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(1) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(179)) - assertBn(await app.getBufferedEther(), ETH(83)) - assertBn(await depositContract.totalCalls(), 3) + assert.equals(await app.getTotalPooledEther(), ETH(179)) + assert.equals(await app.getBufferedEther(), ETH(83)) + assert.equals(await depositContract.totalCalls(), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Adding a key & setting staking limit will help await operators.addSigningKeys(0, 1, pad('0x0003', 48), pad('0x01', 96), { from: voting }) @@ -1516,38 +1487,38 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(1) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 4, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(180)) - assertBn(await app.getBufferedEther(), ETH(52)) - assertBn(await depositContract.totalCalls(), 4) + assert.equals(await app.getTotalPooledEther(), ETH(180)) + assert.equals(await app.getBufferedEther(), ETH(52)) + assert.equals(await depositContract.totalCalls(), 4) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Reactivation of #2 (changes nothing, it's not used keys were trimmed) await operators.activateNodeOperator(2, { from: voting }) await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(12) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 4, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(192)) - assertBn(await app.getBufferedEther(), ETH(64)) - assertBn(await depositContract.totalCalls(), 4) - - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await app.getTotalPooledEther(), ETH(192)) + assert.equals(await app.getBufferedEther(), ETH(64)) + assert.equals(await depositContract.totalCalls(), 4) + + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) }) it('Deposit finds the right operator', async () => { @@ -1597,14 +1568,14 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(63) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 2, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(64)) - assertBn(await app.getBufferedEther(), ETH(0)) - assertBn(await depositContract.totalCalls(), 2) + assert.equals(await app.getTotalPooledEther(), ETH(64)) + assert.equals(await app.getBufferedEther(), ETH(0)) + assert.equals(await depositContract.totalCalls(), 2) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Reactivation of #2 & setting staking limit - has the smallest stake await operators.activateNodeOperator(2, { from: voting }) @@ -1622,14 +1593,14 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody await web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(36) }) await app.methods['deposit(uint256,uint256,bytes)'](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconValidators: 0, beaconBalance: ETH(0) }) - assertBn(await app.getTotalPooledEther(), ETH(100)) - assertBn(await app.getBufferedEther(), ETH(4)) - assertBn(await depositContract.totalCalls(), 3) - - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 3) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await app.getTotalPooledEther(), ETH(100)) + assert.equals(await app.getBufferedEther(), ETH(4)) + assert.equals(await depositContract.totalCalls(), 3) + + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 3) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) }) it('burnShares works', async () => { @@ -1639,35 +1610,31 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody const pre1SharePrice = await app.getPooledEthByShares(shares(1)) let receipt = await app.burnShares(user1, shares(1), { from: voting }) const post1SharePrice = await app.getPooledEthByShares(shares(1)) - assertEvent(receipt, 'SharesBurnt', { - expectedArgs: { - account: user1, - preRebaseTokenAmount: pre1SharePrice, - postRebaseTokenAmount: post1SharePrice, - sharesAmount: shares(1), - }, + assert.emits(receipt, 'SharesBurnt', { + account: user1, + preRebaseTokenAmount: pre1SharePrice, + postRebaseTokenAmount: post1SharePrice, + sharesAmount: shares(1), }) const pre2SharePrice = await app.getPooledEthByShares(shares(1)) receipt = await app.burnShares(user1, shares(1), { from: voting }) const post2SharePrice = await app.getPooledEthByShares(shares(1)) - assertEvent(receipt, 'SharesBurnt', { - expectedArgs: { - account: user1, - preRebaseTokenAmount: pre2SharePrice, - postRebaseTokenAmount: post2SharePrice, - sharesAmount: shares(1), - }, + assert.emits(receipt, 'SharesBurnt', { + account: user1, + preRebaseTokenAmount: pre2SharePrice, + postRebaseTokenAmount: post2SharePrice, + sharesAmount: shares(1), }) - assertBn(pre1SharePrice.muln(3), pre2SharePrice.muln(2)) - assertBn(await app.getPooledEthByShares(shares(1)), ETH(3)) + assert.equals(pre1SharePrice.muln(3), pre2SharePrice.muln(2)) + assert.equals(await app.getPooledEthByShares(shares(1)), ETH(3)) // user1 has zero shares after all - assertBn(await app.sharesOf(user1), shares(0)) + assert.equals(await app.sharesOf(user1), shares(0)) // voting can't continue burning if user already has no shares - await assertRevert(app.burnShares(user1, 1, { from: voting }), 'BURN_AMOUNT_EXCEEDS_BALANCE') + await assert.reverts(app.burnShares(user1, 1, { from: voting }), 'BURN_AMOUNT_EXCEEDS_BALANCE') }) context('treasury', () => { @@ -1683,12 +1650,12 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody }) it('reverts when vault is not set', async () => { - await assertRevert(app.transferToVault(anyToken.address, { from: nobody }), 'NOT_SUPPORTED') + await assert.reverts(app.transferToVault(anyToken.address, { from: nobody }), 'NOT_SUPPORTED') }) it('reverts when recover disallowed', async () => { await app.setAllowRecoverability(false) - await assertRevert(app.transferToVault(anyToken.address, { from: nobody }), 'NOT_SUPPORTED') + await assert.reverts(app.transferToVault(anyToken.address, { from: nobody }), 'NOT_SUPPORTED') }) context('reverts when vault is set', () => { @@ -1707,12 +1674,12 @@ contract('Lido', ([appManager, , , , , , , , , , , , user1, user2, user3, nobody }) it('recovery with erc20 tokens reverts', async () => { - await assertRevert(app.transferToVault(anyToken.address, { from: nobody }), 'NOT_SUPPORTED') + await assert.reverts(app.transferToVault(anyToken.address, { from: nobody }), 'NOT_SUPPORTED') }) it('recovery with unaccounted ether reverts', async () => { await app.makeUnaccountedEther({ from: user1, value: ETH(10) }) - await assertRevert(app.transferToVault(ZERO_ADDRESS, { from: nobody }), 'NOT_SUPPORTED') + await assert.reverts(app.transferToVault(ZERO_ADDRESS, { from: nobody }), 'NOT_SUPPORTED') }) }) }) diff --git a/test/0.4.24/node-operators-registry-penalty.test.js b/test/0.4.24/node-operators-registry-penalty.test.js index cc7e0c397..9c810fadf 100644 --- a/test/0.4.24/node-operators-registry-penalty.test.js +++ b/test/0.4.24/node-operators-registry-penalty.test.js @@ -1,7 +1,5 @@ -const hre = require('hardhat') -const { web3 } = require('hardhat') +const { artifacts, contract, ethers, web3 } = require('hardhat') const { bn } = require('@aragon/contract-helpers-test') -const { BN } = require('bn.js') const { assert } = require('../helpers/assert') const { padRight, ETH, prepIdsCountsPayload } = require('../helpers/utils') @@ -13,54 +11,6 @@ const NodeOperatorsRegistry = artifacts.require('NodeOperatorsRegistryMock') const LidoLocator = artifacts.require('LidoLocator') const Burner = artifacts.require('Burner.sol') -const ADDRESS_1 = '0x0000000000000000000000000000000000000001' -const ADDRESS_2 = '0x0000000000000000000000000000000000000002' -const ADDRESS_3 = '0x0000000000000000000000000000000000000003' -const ADDRESS_4 = '0x0000000000000000000000000000000000000005' - -const NODE_OPERATORS = [ - { - name: 'fo o', - rewardAddress: ADDRESS_1, - totalSigningKeysCount: 10, - depositedSigningKeysCount: 5, - exitedSigningKeysCount: 1, - vettedSigningKeysCount: 6, - targetValidatorsLimitActive: false, - targetValidatorsKeysCount: 1, - unavaliableKeysCount: 2, - stuckSigningKeysCount: 3, - refundedSigningKeysCount: 4, - }, - { - name: ' bar', - rewardAddress: ADDRESS_2, - totalSigningKeysCount: 15, - depositedSigningKeysCount: 7, - exitedSigningKeysCount: 0, - vettedSigningKeysCount: 10, - targetValidatorsLimitActive: false, - targetValidatorsKeysCount: 1, - unavaliableKeysCount: 2, - stuckSigningKeysCount: 3, - refundedSigningKeysCount: 4, - }, - { - name: 'deactivated', - isActive: false, - rewardAddress: ADDRESS_3, - totalSigningKeysCount: 10, - depositedSigningKeysCount: 0, - exitedSigningKeysCount: 0, - vettedSigningKeysCount: 5, - targetValidatorsLimitActive: false, - targetValidatorsKeysCount: 1, - unavaliableKeysCount: 2, - stuckSigningKeysCount: 3, - refundedSigningKeysCount: 4, - }, -] - // bytes32 0x63757261746564 const CURATED_TYPE = padRight(web3.utils.fromAscii('curated'), 32) const PENALTY_DELAY = 2 * 24 * 60 * 60 // 2 days @@ -68,8 +18,8 @@ const PENALTY_DELAY = 2 * 24 * 60 * 60 // 2 days const StETH = artifacts.require('StETHMock') contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, user4, no1, treasury]) => { - let appBase, app, pool, steth, dao, locator, burner - const snapshot = new EvmSnapshot(hre.ethers.provider) + let appBase, app, steth, dao, locator, burner + const snapshot = new EvmSnapshot(ethers.provider) before('deploy base app', async () => { // Deploy the app's base contract. @@ -179,7 +129,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use await steth.mintShares(app.address, ETH(10)) // calls distributeRewards() inside - receipt = await app.testing__distributeRewards({ from: voting }) + const receipt = await app.testing__distributeRewards({ from: voting }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(3) }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(7) }) @@ -217,7 +167,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use // perValidatorShare 10*10^18 / 8 = 1250000000000000000 == 1.25 * 10^18 // calls distributeRewards() inside - receipt = await app.testing__distributeRewards({ from: voting }) + const receipt = await app.testing__distributeRewards({ from: voting }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(2 * 1.25) }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(6 * 1.25) }) @@ -257,7 +207,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use // but half goes to burner // calls distributeRewards() inside - receipt = await app.testing__distributeRewards({ from: voting }) + const receipt = await app.testing__distributeRewards({ from: voting }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(1.25) }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(6 * 1.25) }) @@ -276,7 +226,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use await app.updateRefundedValidatorsCount(firstNodeOperator, 1, { from: voting }) // calls distributeRewards() inside - receipt = await app.testing__distributeRewards({ from: voting }) + const receipt = await app.testing__distributeRewards({ from: voting }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(1.25) }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(6 * 1.25) }) @@ -308,7 +258,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use await app.updateRefundedValidatorsCount(firstNodeOperator, 1, { from: voting }) // calls distributeRewards() inside - receipt = await app.testing__distributeRewards({ from: voting }) + const receipt = await app.testing__distributeRewards({ from: voting }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(1) }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(4 * 2) }) assert.notEmits(receipt, 'RewardsDistributed', { rewardAddress: user3, sharesAmount: 0 }) @@ -334,7 +284,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use assert.isFalse(await app.testing_isNodeOperatorPenalized(firstNodeOperator)) // calls distributeRewards() inside - receipt = await app.testing__distributeRewards({ from: voting }) + const receipt = await app.testing__distributeRewards({ from: voting }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(2.5) }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(7.5) }) @@ -359,42 +309,42 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use it('updateTargetValidatorsLimits() - target <= deposited', async () => { let keyStats = await app.getNodeOperatorSummary(3) - assert.equal(+keyStats.isTargetLimitActive, false) - assert.equal(+keyStats.targetValidatorsCount, 0) + assert.equals(keyStats.isTargetLimitActive, false) + assert.equals(keyStats.targetValidatorsCount, 0) await app.updateTargetValidatorsLimits(3, true, 3, { from: voting }) keyStats = await app.getNodeOperatorSummary(3) - assert.equal(+keyStats.isTargetLimitActive, true) - assert.equal(+keyStats.targetValidatorsCount, 3) + assert.equals(keyStats.isTargetLimitActive, true) + assert.equals(keyStats.targetValidatorsCount, 3) }) it('updateTargetValidatorsLimits() - deposited < target < vetted', async () => { let keyStats = await app.getNodeOperatorSummary(3) - assert.equal(+keyStats.isTargetLimitActive, false) - assert.equal(+keyStats.targetValidatorsCount, 0) - assert.equal(+keyStats.depositableValidatorsCount, 5) + assert.equals(keyStats.isTargetLimitActive, false) + assert.equals(keyStats.targetValidatorsCount, 0) + assert.equals(keyStats.depositableValidatorsCount, 5) await app.updateTargetValidatorsLimits(3, true, 11, { from: voting }) keyStats = await app.getNodeOperatorSummary(3) - assert.equal(+keyStats.isTargetLimitActive, true) - assert.equal(+keyStats.targetValidatorsCount, 11) - assert.equal(+keyStats.depositableValidatorsCount, 1) + assert.equals(keyStats.isTargetLimitActive, true) + assert.equals(keyStats.targetValidatorsCount, 11) + assert.equals(keyStats.depositableValidatorsCount, 1) }) it('updateTargetValidatorsLimits() - vetted <= target', async () => { let keyStats = await app.getNodeOperatorSummary(3) - assert.equal(+keyStats.isTargetLimitActive, false) - assert.equal(+keyStats.targetValidatorsCount, 0) - assert.equal(+keyStats.depositableValidatorsCount, 5) + assert.equals(keyStats.isTargetLimitActive, false) + assert.equals(keyStats.targetValidatorsCount, 0) + assert.equals(keyStats.depositableValidatorsCount, 5) await app.updateTargetValidatorsLimits(3, true, 18, { from: voting }) keyStats = await app.getNodeOperatorSummary(3) - assert.equal(+keyStats.isTargetLimitActive, true) - assert.equal(+keyStats.targetValidatorsCount, 18) - assert.equal(+keyStats.depositableValidatorsCount, 5) + assert.equals(keyStats.isTargetLimitActive, true) + assert.equals(keyStats.targetValidatorsCount, 18) + assert.equals(keyStats.depositableValidatorsCount, 5) }) it('updateExitedValidatorsCount() - check if appeared a new deposited keys', async () => { @@ -402,7 +352,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use const keyStats = await app.getNodeOperatorSummary(3) // excess = deposited - stopped - targetLimit - assert.equal(+keyStats.targetValidatorsCount, 5) + assert.equals(keyStats.targetValidatorsCount, 5) // increase _newActiveValidatorsCount by add new depositedKeys await app.increaseNodeOperatorDepositedSigningKeysCount(3, 2) @@ -413,15 +363,15 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use it('updateTargetValidatorsLimits() - try to update to the same active flag', async () => { let keyStats = await app.getNodeOperatorSummary(0) - targetValidatorsCountBefore = keyStats.targetValidatorsCount + let targetValidatorsCountBefore = keyStats.targetValidatorsCount assert.equal(keyStats.isTargetLimitActive, false) - assert.equal(+keyStats.targetValidatorsCount, 0) + assert.equals(keyStats.targetValidatorsCount, 0) await app.updateTargetValidatorsLimits(0, false, 10, { from: voting }) keyStats = await app.getNodeOperatorSummary(0) - targetValidatorsCountAfter = keyStats.targetValidatorsCount + let targetValidatorsCountAfter = keyStats.targetValidatorsCount assert.equal(keyStats.isTargetLimitActive, false) - assert.equal(+targetValidatorsCountBefore, +targetValidatorsCountAfter) + assert.equals(targetValidatorsCountBefore, +targetValidatorsCountAfter) targetValidatorsCountBefore = keyStats.targetValidatorsCount await app.updateTargetValidatorsLimits(0, true, 20, { from: voting }) @@ -434,41 +384,41 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use keyStats = await app.getNodeOperatorSummary(0) targetValidatorsCountAfter = keyStats.targetValidatorsCount assert.equal(keyStats.isTargetLimitActive, true) - assert.equal(+targetValidatorsCountAfter, 30) + assert.equals(targetValidatorsCountAfter, 30) }) it('updateTargetValidatorsLimits()', async () => { await app.updateTargetValidatorsLimits(0, true, 10, { from: voting }) let keysStatTotal = await app.getStakingModuleSummary() - assert.equal(+keysStatTotal.totalExitedValidators, 2) - assert.equal(+keysStatTotal.totalDepositedValidators, 25) - assert.equal(+keysStatTotal.depositableValidatorsCount, 17) + assert.equals(keysStatTotal.totalExitedValidators, 2) + assert.equals(keysStatTotal.totalDepositedValidators, 25) + assert.equals(keysStatTotal.depositableValidatorsCount, 17) let limitStatOp = await app.getNodeOperatorSummary(0) assert.equal(limitStatOp.isTargetLimitActive, true) - assert.equal(+limitStatOp.targetValidatorsCount, 10) + assert.equals(limitStatOp.targetValidatorsCount, 10) let keysStatOp = await app.getNodeOperatorSummary(0) - assert.equal(+keysStatOp.totalExitedValidators, 2) + assert.equals(keysStatOp.totalExitedValidators, 2) assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 8) - assert.equal(+keysStatOp.depositableValidatorsCount, 2) + assert.equals(keysStatOp.depositableValidatorsCount, 2) await app.updateTargetValidatorsLimits(0, false, 10, { from: voting }) keysStatTotal = await app.getStakingModuleSummary() - assert.equal(+keysStatTotal.totalExitedValidators, 2) - assert.equal(+keysStatTotal.totalDepositedValidators, 25) - assert.equal(+keysStatTotal.depositableValidatorsCount, 20) + assert.equals(keysStatTotal.totalExitedValidators, 2) + assert.equals(keysStatTotal.totalDepositedValidators, 25) + assert.equals(keysStatTotal.depositableValidatorsCount, 20) limitStatOp = await app.getNodeOperatorSummary(0) assert.equal(limitStatOp.isTargetLimitActive, false) - assert.equal(+limitStatOp.targetValidatorsCount, 0) + assert.equals(limitStatOp.targetValidatorsCount, 0) keysStatOp = await app.getNodeOperatorSummary(0) - assert.equal(+keysStatOp.totalExitedValidators, 2) + assert.equals(keysStatOp.totalExitedValidators, 2) assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 8) - assert.equal(+keysStatOp.depositableValidatorsCount, 5) + assert.equals(keysStatOp.depositableValidatorsCount, 5) }) it('updateExitedValidatorsCount()', async () => { @@ -477,9 +427,9 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use let keysStatTotal = await app.getStakingModuleSummary() // console.log(o2n(keysStatTotal)) - assert.equal(+keysStatTotal.totalExitedValidators, 2) - assert.equal(+keysStatTotal.totalDepositedValidators, 25) - assert.equal(+keysStatTotal.depositableValidatorsCount, 10) + assert.equals(keysStatTotal.totalExitedValidators, 2) + assert.equals(keysStatTotal.totalDepositedValidators, 25) + assert.equals(keysStatTotal.depositableValidatorsCount, 10) // op 0 let limitStatOp = await app.getNodeOperatorSummary(0) @@ -509,12 +459,12 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use keysStatTotal = await app.getStakingModuleSummary() // console.log(o2n(keysStatTotal)) - assert.equal(+keysStatTotal.totalExitedValidators, 4) + assert.equals(keysStatTotal.totalExitedValidators, 4) assert.equal( keysStatTotal.totalDepositedValidators.toNumber() - keysStatTotal.totalExitedValidators.toNumber(), 25 - (3 + 1) ) - assert.equal(+keysStatTotal.depositableValidatorsCount, 11) + assert.equals(keysStatTotal.depositableValidatorsCount, 11) // op 0 limitStatOp = await app.getNodeOperatorSummary(0) @@ -546,19 +496,19 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use const keysStatTotal = await app.getStakingModuleSummary() // console.log(o2n(keysStatTotal)) - assert.equal(+keysStatTotal.totalExitedValidators, 2) - assert.equal(+keysStatTotal.totalDepositedValidators, 25) - assert.equal(+keysStatTotal.depositableValidatorsCount, 20) + assert.equals(keysStatTotal.totalExitedValidators, 2) + assert.equals(keysStatTotal.totalDepositedValidators, 25) + assert.equals(keysStatTotal.depositableValidatorsCount, 20) // op 0 let limitStatOp = await app.getNodeOperatorSummary(0) assert.equal(limitStatOp.isTargetLimitActive, true) - assert.equal(+limitStatOp.targetValidatorsCount, 10) + assert.equals(limitStatOp.targetValidatorsCount, 10) let keysStatOp = await app.getNodeOperatorSummary(0) - assert.equal(+keysStatOp.totalExitedValidators, 2) + assert.equals(keysStatOp.totalExitedValidators, 2) assert.equal(keysStatOp.totalDepositedValidators.toNumber() - keysStatOp.totalExitedValidators.toNumber(), 8) - assert.equal(+keysStatOp.depositableValidatorsCount, 0) + assert.equals(keysStatOp.depositableValidatorsCount, 0) // op 1 limitStatOp = await app.getNodeOperatorSummary(1) @@ -572,12 +522,3 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, use }) }) }) - -function o2n(o = {}) { - for (const k of Object.keys(o)) { - if (bn.isBN(o[k])) { - o[k] = o[k].toString() - } - } - return o -} diff --git a/test/0.4.24/node-operators-registry.test.js b/test/0.4.24/node-operators-registry.test.js index f8e78c344..65c2f2302 100644 --- a/test/0.4.24/node-operators-registry.test.js +++ b/test/0.4.24/node-operators-registry.test.js @@ -1,17 +1,17 @@ -const hre = require('hardhat') +const { artifacts, contract, ethers, web3 } = require('hardhat') const { assert } = require('../helpers/assert') -const { assertRevert } = require('../helpers/assertThrow') -const { toBN, padRight } = require('../helpers/utils') + +const { randomBytes } = require('crypto') +const { toChecksumAddress } = require('ethereumjs-util') +const { getEventAt } = require('@aragon/contract-helpers-test') + const { AragonDAO } = require('./helpers/dao') const { EvmSnapshot } = require('../helpers/blockchain') -const { ZERO_ADDRESS, getEventAt } = require('@aragon/contract-helpers-test') const nodeOperators = require('../helpers/node-operators') const signingKeys = require('../helpers/signing-keys') -const { prepIdsCountsPayload } = require('../helpers/utils') -const { web3, artifacts } = require('hardhat') +const { prepIdsCountsPayload, ETH, pad, hexConcat, toBN, padRight } = require('../helpers/utils') const { getRandomLocatorConfig } = require('../helpers/locator') -const { randomBytes } = require('crypto') -const { toChecksumAddress } = require('ethereumjs-util') +const { ZERO_ADDRESS } = require('../helpers/constants') const NodeOperatorsRegistry = artifacts.require('NodeOperatorsRegistryMock') const SigningKeys = artifacts.require('SigningKeys') @@ -63,26 +63,11 @@ const NODE_OPERATORS = [ const CURATED_TYPE = padRight(web3.utils.fromAscii('curated'), 32) const PENALTY_DELAY = 2 * 24 * 60 * 60 // 2 days -const pad = (hex, bytesLength) => { - const absentZeroes = bytesLength * 2 + 2 - hex.length - if (absentZeroes > 0) hex = '0x' + '0'.repeat(absentZeroes) + hex.substr(2) - return hex -} - -const hexConcat = (first, ...rest) => { - let result = first.startsWith('0x') ? first : '0x' + first - rest.forEach((item) => { - result += item.startsWith('0x') ? item.substr(2) : item - }) - return result -} - -const ETH = (value) => web3.utils.toWei(value + '', 'ether') const StETH = artifacts.require('StETHMock') contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nobody]) => { let appBase, app, locator, steth, dao - const snapshot = new EvmSnapshot(hre.ethers.provider) + const snapshot = new EvmSnapshot(ethers.provider) before('deploy base app', async () => { // Deploy the app's base contract. @@ -123,7 +108,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob // Implementation initializer reverts because initialization block was set to max(uint256) // in the Autopetrified base contract - await assertRevert(appBase.initialize(locator.address, CURATED_TYPE, PENALTY_DELAY), 'INIT_ALREADY_INITIALIZED') + await assert.reverts(appBase.initialize(locator.address, CURATED_TYPE, PENALTY_DELAY), 'INIT_ALREADY_INITIALIZED') const moduleType = await app.getType() assert.emits(tx, 'ContractVersionSet', { version: 2 }) @@ -2586,19 +2571,12 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob excessValidatorsCount: excessValidatorsCountAfter, } = await app.testing_getTotalTargetStats() - console.log({ - targetValidatorsCountBefore: targetValidatorsCountBefore.toNumber(), - targetValidatorsCountAfter: targetValidatorsCountAfter.toNumber(), - vettedSigningKeysCountBefore: vettedSigningKeysCountBefore.toNumber(), - vettedSigningKeysDecrement, - }) - - assertBn(isTargetLimitActiveAfter, isTargetLimitActiveBefore) - assertBn( + assert.equals(isTargetLimitActiveAfter, isTargetLimitActiveBefore) + assert.equals( targetValidatorsCountAfter, targetValidatorsCountBefore.toNumber() - vettedSigningKeysCountBefore.toNumber() - vettedSigningKeysDecrement ) - assertBn(excessValidatorsCountAfter, excessValidatorsCountBefore) + assert.equals(excessValidatorsCountAfter, excessValidatorsCountBefore) }) it("doesn't modify global vetted signing keys count if key index is equal to vettedSigningKeysCount", async () => { @@ -3295,7 +3273,7 @@ contract('NodeOperatorsRegistry', ([appManager, voting, user1, user2, user3, nob await steth.mintShares(app.address, ETH(10)) // calls distributeRewards() inside - receipt = await app.onExitedAndStuckValidatorsCountsUpdated({ from: voting }) + const receipt = await app.onExitedAndStuckValidatorsCountsUpdated({ from: voting }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user1, sharesAmount: ETH(3) }) assert.emits(receipt, 'RewardsDistributed', { rewardAddress: user2, sharesAmount: ETH(7) }) diff --git a/test/0.4.24/signingkey-lib.test.js b/test/0.4.24/signingkey-lib.test.js index 8f2e42990..b83231908 100644 --- a/test/0.4.24/signingkey-lib.test.js +++ b/test/0.4.24/signingkey-lib.test.js @@ -1,19 +1,19 @@ +const { artifacts, contract, ethers } = require('hardhat') const { assert } = require('../helpers/assert') -const { assertRevert } = require('../helpers/assertThrow') + const { EvmSnapshot } = require('../helpers/blockchain') -const { ZERO_ADDRESS, getEventAt } = require('@aragon/contract-helpers-test') -const { toBN, padRight } = require('../helpers/utils') +const { toBN } = require('../helpers/utils') const signingKeys = require('../helpers/signing-keys') -const { prepIdsCountsPayload } = require('../helpers/utils') + const SigningKeysMock = artifacts.require('SigningKeysMock') const SigningKeys = artifacts.require('SigningKeys') const nodeOpId1 = 1 const nodeOpId2 = 2 -contract('SigningKeys', ([appManager, voting, user1, user2, user3, nobody]) => { +contract('SigningKeys', () => { let app - const snapshot = new EvmSnapshot(hre.ethers.provider) + const snapshot = new EvmSnapshot(ethers.provider) const firstNodeOperatorId = 0 const firstNodeOperatorStartIndex = 0 @@ -22,7 +22,6 @@ contract('SigningKeys', ([appManager, voting, user1, user2, user3, nobody]) => { const secondNodeOperatorId = 1 const secondNodeOperatorStartIndex = 0 const secondNodeOperatorKeys = new signingKeys.FakeValidatorKeys(7, { kFill: 'c', sFill: 'd' }) - const secondNodeOperatorLastIndex = secondNodeOperatorKeys.count - 1 before('deploy base app', async () => { // Deploy the app's base contract. diff --git a/test/0.4.24/staking-limit.test.js b/test/0.4.24/staking-limit.test.js index eff792efa..0b3d7e14a 100644 --- a/test/0.4.24/staking-limit.test.js +++ b/test/0.4.24/staking-limit.test.js @@ -1,14 +1,10 @@ -const { assert } = require('chai') -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../helpers/assertThrow') -const { bn, MAX_UINT256 } = require('@aragon/contract-helpers-test') -const { toBN } = require('../helpers/utils') +const { artifacts, contract, web3 } = require('hardhat') +const { assert } = require('../helpers/assert') +const { toBN, ETH } = require('../helpers/utils') const { waitBlocks } = require('../helpers/blockchain') const StakeLimitUtils = artifacts.require('StakeLimitUtilsMock.sol') -const ETH = (value) => web3.utils.toWei(value + '', 'ether') - // // We need to pack four variables into the same 256bit-wide storage slot // to lower the costs per each staking request. @@ -42,13 +38,13 @@ contract('StakingLimits', ([account1]) => { it('encode zeros', async () => { const slot = await limits.setStorageStakeLimitStruct(0, 0, 0, 0) - assertBn(slot, 0) + assert.equals(slot, 0) const decodedSlot = await limits.getStorageStakeLimit(slot) - assertBn(decodedSlot.prevStakeBlockNumber, 0) - assertBn(decodedSlot.prevStakeLimit, 0) - assertBn(decodedSlot.maxStakeLimitGrowthBlocks, 0) - assertBn(decodedSlot.maxStakeLimit, 0) + assert.equals(decodedSlot.prevStakeBlockNumber, 0) + assert.equals(decodedSlot.prevStakeLimit, 0) + assert.equals(decodedSlot.maxStakeLimitGrowthBlocks, 0) + assert.equals(decodedSlot.maxStakeLimit, 0) }) it('check staking pause at start', async () => { @@ -107,8 +103,8 @@ contract('StakingLimits', ([account1]) => { await limits.setStakingLimit(slot, maxStakeLimit, maxStakeLimitIncreasePerBlock) maxStakeLimit = 5 - maxStakeLimitGrowthBlocks = 6 - await assertRevert( + const maxStakeLimitGrowthBlocks = 6 + await assert.reverts( limits.setStakingLimit(slot, maxStakeLimit, maxStakeLimitGrowthBlocks), 'TOO_LARGE_LIMIT_INCREASE' ) @@ -118,14 +114,14 @@ contract('StakingLimits', ([account1]) => { let maxStakeLimit = toBN(2).pow(toBN(96)) let maxStakeLimitIncreasePerBlock = 1 const slot = await limits.setStorageStakeLimitStruct(0, 0, 0, 0) - await assertRevert( + await assert.reverts( limits.setStakingLimit(slot, maxStakeLimit, maxStakeLimitIncreasePerBlock), 'TOO_LARGE_MAX_STAKE_LIMIT' ) maxStakeLimit = toBN(2).mul(toBN(10).pow(toBN(18))) maxStakeLimitIncreasePerBlock = toBN(10) - await assertRevert( + await assert.reverts( limits.setStakingLimit(slot, maxStakeLimit, maxStakeLimitIncreasePerBlock), `TOO_SMALL_LIMIT_INCREASE` ) @@ -141,17 +137,17 @@ contract('StakingLimits', ([account1]) => { const slot = await limits.setStorageStakeLimitStruct(block.number, 0, maxStakeLimitGrowthBlocks, maxStakeLimit) const currentStakeLimit2 = await limits.calculateCurrentStakeLimit(slot) - assertBn(currentStakeLimit2, 0) + assert.equals(currentStakeLimit2, 0) const block2 = await waitBlocks(1) assert.equal(block2.number, block.number + 1) const currentStakeLimit3 = await limits.calculateCurrentStakeLimit(slot) - assertBn(currentStakeLimit3, 50) + assert.equals(currentStakeLimit3, 50) const block3 = await waitBlocks(3) assert.equal(block3.number, block.number + 1 + 3) const currentStakeLimit4 = await limits.calculateCurrentStakeLimit(slot) - assertBn(currentStakeLimit4, 100) + assert.equals(currentStakeLimit4, 100) }) it('check update stake limit', async () => { @@ -170,7 +166,7 @@ contract('StakingLimits', ([account1]) => { assert.equal(block2.number, block.number + 3) const currentStakeLimit2 = await limits.calculateCurrentStakeLimit(slot) - assertBn(currentStakeLimit2, maxStakeLimit) + assert.equals(currentStakeLimit2, maxStakeLimit) const deposit = 87 const newSlot = await limits.updatePrevStakeLimit(slot, currentStakeLimit2 - deposit) @@ -181,16 +177,14 @@ contract('StakingLimits', ([account1]) => { // checking staking recovery await waitBlocks(1) const currentStakeLimit3 = await limits.calculateCurrentStakeLimit(newSlot) - assertBn(currentStakeLimit3, 13 + increasePerBlock) + assert.equals(currentStakeLimit3, 13 + increasePerBlock) await waitBlocks(1) const currentStakeLimit4 = await limits.calculateCurrentStakeLimit(newSlot) - assertBn(currentStakeLimit4, maxStakeLimit) + assert.equals(currentStakeLimit4, maxStakeLimit) }) it('max values', async () => { - const block = await web3.eth.getBlock('latest') - const max32 = toBN(2).pow(toBN(32)).sub(toBN(1)) // uint32 const max96 = toBN(2).pow(toBN(96)).sub(toBN(1)) // uint96 @@ -208,7 +202,7 @@ contract('StakingLimits', ([account1]) => { maxStakeLimit ) const maxUint256 = toBN(2).pow(toBN(256)).sub(toBN(1)) - assertBn(maxSlot, maxUint256) + assert.equals(maxSlot, maxUint256) const decodedRaw = await limits.getStorageStakeLimit(maxSlot) @@ -217,10 +211,10 @@ contract('StakingLimits', ([account1]) => { const decodedPrevStakeLimit = decodedRaw.prevStakeLimit const decodedPrevStakeBlockNumber = decodedRaw.prevStakeBlockNumber - assertBn(decodedMaxLimit, max96) - assertBn(decodedMaxStakeLimitGrowthBlocks, max32) - assertBn(decodedPrevStakeLimit, max96) - assertBn(decodedPrevStakeBlockNumber, max32) + assert.equals(decodedMaxLimit, max96) + assert.equals(decodedMaxStakeLimitGrowthBlocks, max32) + assert.equals(decodedPrevStakeLimit, max96) + assert.equals(decodedPrevStakeBlockNumber, max32) }) it('constant gas for `calculateCurrentStakeLimit` regardless `block.number`', async () => { @@ -242,8 +236,8 @@ contract('StakingLimits', ([account1]) => { const currentGas = (await limits.emitCurrentStakeLimit(slot)).receipt.gasUsed const currentBlock = (await web3.eth.getBlock('latest')).number - assertBn(currentGas, referenceGas) - assertBn(currentBlock, referenceBlock + i + 1) + assert.equals(currentGas, referenceGas) + assert.equals(currentBlock, referenceBlock + i + 1) } }) }) diff --git a/test/0.4.24/steth.test.js b/test/0.4.24/steth.test.js index 815138db6..b05e4f7a1 100644 --- a/test/0.4.24/steth.test.js +++ b/test/0.4.24/steth.test.js @@ -1,16 +1,16 @@ -const { assert } = require('chai') -const { assertBn, assertEvent, assertAmountOfEvents } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../helpers/assertThrow') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') +const { artifacts, contract, ethers } = require('hardhat') +const { assert } = require('../helpers/assert') + +const { bn } = require('@aragon/contract-helpers-test') const { tokens, ETH } = require('./../helpers/utils') const { EvmSnapshot } = require('../helpers/blockchain') -const { INITIAL_HOLDER } = require('../helpers/constants') +const { INITIAL_HOLDER, ZERO_ADDRESS } = require('../helpers/constants') const StETHMock = artifacts.require('StETHMock') contract('StETH', ([_, __, user1, user2, user3, nobody]) => { let stEth - const snapshot = new EvmSnapshot(hre.ethers.provider) + const snapshot = new EvmSnapshot(ethers.provider) before('deploy mock token', async () => { stEth = await StETHMock.new({ value: ETH(1) }) @@ -32,41 +32,41 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { context('zero supply', async () => { it('initial total supply is correct', async () => { - assertBn(await stEth.totalSupply(), tokens(1)) + assert.equals(await stEth.totalSupply(), tokens(1)) }) it('initial balances are correct', async () => { - assertBn(await stEth.balanceOf(user1), tokens(0)) - assertBn(await stEth.balanceOf(user2), tokens(0)) - assertBn(await stEth.balanceOf(user3), tokens(0)) + assert.equals(await stEth.balanceOf(user1), tokens(0)) + assert.equals(await stEth.balanceOf(user2), tokens(0)) + assert.equals(await stEth.balanceOf(user3), tokens(0)) }) it('initial allowances are correct', async () => { - assertBn(await stEth.allowance(user1, user1), tokens(0)) - assertBn(await stEth.allowance(user1, user2), tokens(0)) - assertBn(await stEth.allowance(user1, user3), tokens(0)) - assertBn(await stEth.allowance(user2, user2), tokens(0)) - assertBn(await stEth.allowance(user2, user1), tokens(0)) - assertBn(await stEth.allowance(user2, user3), tokens(0)) - assertBn(await stEth.allowance(user3, user3), tokens(0)) - assertBn(await stEth.allowance(user3, user1), tokens(0)) - assertBn(await stEth.allowance(user3, user2), tokens(0)) + assert.equals(await stEth.allowance(user1, user1), tokens(0)) + assert.equals(await stEth.allowance(user1, user2), tokens(0)) + assert.equals(await stEth.allowance(user1, user3), tokens(0)) + assert.equals(await stEth.allowance(user2, user2), tokens(0)) + assert.equals(await stEth.allowance(user2, user1), tokens(0)) + assert.equals(await stEth.allowance(user2, user3), tokens(0)) + assert.equals(await stEth.allowance(user3, user3), tokens(0)) + assert.equals(await stEth.allowance(user3, user1), tokens(0)) + assert.equals(await stEth.allowance(user3, user2), tokens(0)) }) it('approve works', async () => { const receipt = await stEth.approve(user2, tokens(1), { from: user1 }) - assertEvent(receipt, 'Approval', { expectedArgs: { owner: user1, spender: user2, value: tokens(1) } }) + assert.emits(receipt, 'Approval', { owner: user1, spender: user2, value: tokens(1) }) - assertBn(await stEth.allowance(user1, user2), tokens(1)) + assert.equals(await stEth.allowance(user1, user2), tokens(1)) }) it(`balances aren't changed even if total pooled ether increased`, async () => { await stEth.setTotalPooledEther(tokens(100)) - assertBn(await stEth.totalSupply(), tokens(100)) + assert.equals(await stEth.totalSupply(), tokens(100)) - assertBn(await stEth.balanceOf(user1), tokens(0)) - assertBn(await stEth.balanceOf(user2), tokens(0)) - assertBn(await stEth.balanceOf(user3), tokens(0)) + assert.equals(await stEth.balanceOf(user1), tokens(0)) + assert.equals(await stEth.balanceOf(user2), tokens(0)) + assert.equals(await stEth.balanceOf(user3), tokens(0)) }) }) @@ -77,80 +77,84 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { }) it('total supply is correct', async () => { - assertBn(await stEth.totalSupply(), tokens(100)) + assert.equals(await stEth.totalSupply(), tokens(100)) }) it('balances are correct', async () => { - assertBn(await stEth.balanceOf(user1), tokens(99)) - assertBn(await stEth.balanceOf(user2), tokens(0)) - assertBn(await stEth.balanceOf(user3), tokens(0)) + assert.equals(await stEth.balanceOf(user1), tokens(99)) + assert.equals(await stEth.balanceOf(user2), tokens(0)) + assert.equals(await stEth.balanceOf(user3), tokens(0)) }) context('transfer', async () => { it('reverts when recipient is the zero address', async () => { - await assertRevert(stEth.transfer(ZERO_ADDRESS, tokens(1), { from: user1 }), 'TRANSFER_TO_THE_ZERO_ADDRESS') + await assert.reverts(stEth.transfer(ZERO_ADDRESS, tokens(1), { from: user1 }), 'TRANSFER_TO_THE_ZERO_ADDRESS') }) it('reverts when the sender does not have enough balance', async () => { - await assertRevert(stEth.transfer(user2, tokens(101), { from: user1 }), 'TRANSFER_AMOUNT_EXCEEDS_BALANCE') - await assertRevert(stEth.transfer(user1, bn('1'), { from: user2 }), 'TRANSFER_AMOUNT_EXCEEDS_BALANCE') + await assert.reverts(stEth.transfer(user2, tokens(101), { from: user1 }), 'TRANSFER_AMOUNT_EXCEEDS_BALANCE') + await assert.reverts(stEth.transfer(user1, bn('1'), { from: user2 }), 'TRANSFER_AMOUNT_EXCEEDS_BALANCE') }) it('transfer all balance works and emits event', async () => { const amount = await stEth.balanceOf(user1) const receipt = await stEth.transfer(user2, amount, { from: user1 }) const sharesAmount = await stEth.getSharesByPooledEth(amount) - assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) - assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: user2, value: amount } }) - assertEvent(receipt, 'TransferShares', { - expectedArgs: { from: user1, to: user2, sharesValue: sharesAmount }, + assert.emitsNumberOfEvents(receipt, 'Transfer', 1) + assert.emitsNumberOfEvents(receipt, 'TransferShares', 1) + assert.emits(receipt, 'Transfer', { from: user1, to: user2, value: amount }) + assert.emits(receipt, 'TransferShares', { + from: user1, + to: user2, + sharesValue: sharesAmount, }) - assertBn(await stEth.balanceOf(user1), tokens(0)) - assertBn(await stEth.balanceOf(user2), tokens(99)) + assert.equals(await stEth.balanceOf(user1), tokens(0)) + assert.equals(await stEth.balanceOf(user2), tokens(99)) }) it('transfer zero tokens works and emits event', async () => { const amount = bn('0') const sharesAmount = bn('0') const receipt = await stEth.transfer(user2, amount, { from: user1 }) - assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) - assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: user2, value: amount } }) - assertEvent(receipt, 'TransferShares', { - expectedArgs: { from: user1, to: user2, sharesValue: sharesAmount }, + assert.emitsNumberOfEvents(receipt, 'Transfer', 1) + assert.emitsNumberOfEvents(receipt, 'TransferShares', 1) + assert.emits(receipt, 'Transfer', { from: user1, to: user2, value: amount }) + assert.emits(receipt, 'TransferShares', { + from: user1, + to: user2, + sharesValue: sharesAmount, }) - assertBn(await stEth.balanceOf(user1), tokens(99)) - assertBn(await stEth.balanceOf(user2), tokens(0)) + assert.equals(await stEth.balanceOf(user1), tokens(99)) + assert.equals(await stEth.balanceOf(user2), tokens(0)) }) }) context('approve', async () => { it('reverts when spender is zero address', async () => { - await assertRevert(stEth.approve(ZERO_ADDRESS, tokens(1), { from: user1 })) + await assert.reverts(stEth.approve(ZERO_ADDRESS, tokens(1), { from: user1 })) }) it('approve without any tokens works', async () => { const amount = tokens(1) const receipt = await stEth.approve(user1, amount, { from: user2 }) - assertEvent(receipt, 'Approval', { expectedArgs: { owner: user2, spender: user1, value: amount } }) - assertBn(await stEth.allowance(user2, user1), amount) + assert.emits(receipt, 'Approval', { owner: user2, spender: user1, value: amount }) + assert.equals(await stEth.allowance(user2, user1), amount) }) context('when the spender had no approved amount before', () => { it('approve requested amount works and emits event', async () => { const amount = tokens(50) const receipt = await stEth.approve(user2, amount, { from: user1 }) - assertEvent(receipt, 'Approval', { expectedArgs: { owner: user1, spender: user2, value: amount } }) - assertBn(await stEth.allowance(user1, user2), amount) + assert.emits(receipt, 'Approval', { owner: user1, spender: user2, value: amount }) + assert.equals(await stEth.allowance(user1, user2), amount) }) context('when the spender had an approved amount', () => { it('approve requested amount replaces old allowance and emits event', async () => { const amount = tokens(100) const receipt = await stEth.approve(user2, amount, { from: user1 }) - assertEvent(receipt, 'Approval', { expectedArgs: { owner: user1, spender: user2, value: amount } }) - assertBn(await stEth.allowance(user1, user2), amount) + assert.emits(receipt, 'Approval', { owner: user1, spender: user2, value: amount }) + assert.equals(await stEth.allowance(user1, user2), amount) }) }) }) @@ -163,63 +167,65 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { }) it('reverts when recipient is zero address', async () => { - await assertRevert( + await assert.reverts( stEth.transferFrom(user1, ZERO_ADDRESS, tokens(1), { from: user2 }), 'TRANSFER_TO_THE_ZERO_ADDRESS' ) }) it('reverts when sender is zero address', async () => { - await assertRevert( + await assert.reverts( stEth.transferFrom(ZERO_ADDRESS, user3, tokens(0), { from: user2 }), 'TRANSFER_FROM_THE_ZERO_ADDRESS' ) }) it('reverts when amount exceeds allowance', async () => { - await assertRevert(stEth.transferFrom(user1, user3, tokens(501), { from: user2 })) + await assert.reverts(stEth.transferFrom(user1, user3, tokens(501), { from: user2 })) }) it('reverts if owner has not any tokens', async () => { - await assertRevert(stEth.transferFrom(user3, user1, tokens(1), { from: user2 })) + await assert.reverts(stEth.transferFrom(user3, user1, tokens(1), { from: user2 })) }) it('transferFrom works and emits events', async () => { const amount = tokens(50) const sharesAmount = await stEth.getSharesByPooledEth(amount) const receipt = await stEth.transferFrom(user1, user3, amount, { from: user2 }) - assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) - assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) - assertAmountOfEvents(receipt, 'Approval', { expectedAmount: 1 }) - assertEvent(receipt, 'Approval', { expectedArgs: { owner: user1, spender: user2, value: bn(0) } }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: user3, value: amount } }) - assertEvent(receipt, 'TransferShares', { - expectedArgs: { from: user1, to: user3, sharesValue: sharesAmount }, + assert.emitsNumberOfEvents(receipt, 'Transfer', 1) + assert.emitsNumberOfEvents(receipt, 'TransferShares', 1) + assert.emitsNumberOfEvents(receipt, 'Approval', 1) + assert.emits(receipt, 'Approval', { owner: user1, spender: user2, value: bn(0) }) + assert.emits(receipt, 'Transfer', { from: user1, to: user3, value: amount }) + assert.emits(receipt, 'TransferShares', { + from: user1, + to: user3, + sharesValue: sharesAmount, }) - assertBn(await stEth.allowance(user2, user1), bn(0)) - assertBn(await stEth.balanceOf(user1), tokens(49)) - assertBn(await stEth.balanceOf(user3), tokens(50)) + assert.equals(await stEth.allowance(user2, user1), bn(0)) + assert.equals(await stEth.balanceOf(user1), tokens(49)) + assert.equals(await stEth.balanceOf(user3), tokens(50)) }) }) context('increase allowance', async () => { it('reverts when spender is zero address', async () => { - await assertRevert(stEth.increaseAllowance(ZERO_ADDRESS, tokens(1), { from: user1 })) + await assert.reverts(stEth.increaseAllowance(ZERO_ADDRESS, tokens(1), { from: user1 })) }) it('increaseAllowance without any tokens works', async () => { const amount = tokens(1) const receipt = await stEth.increaseAllowance(user1, amount, { from: user2 }) - assertEvent(receipt, 'Approval', { expectedArgs: { owner: user2, spender: user1, value: amount } }) - assertBn(await stEth.allowance(user2, user1), amount) + assert.emits(receipt, 'Approval', { owner: user2, spender: user1, value: amount }) + assert.equals(await stEth.allowance(user2, user1), amount) }) context('when the spender had no approved amount before', () => { it('increaseAllowance with requested amount works and emits event', async () => { const amount = tokens(50) const receipt = await stEth.increaseAllowance(user2, amount, { from: user1 }) - assertEvent(receipt, 'Approval', { expectedArgs: { owner: user1, spender: user2, value: amount } }) - assertBn(await stEth.allowance(user1, user2), amount) + assert.emits(receipt, 'Approval', { owner: user1, spender: user2, value: amount }) + assert.equals(await stEth.allowance(user1, user2), amount) }) }) @@ -232,10 +238,12 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { const increase_amount = tokens(50) const increased_amount = tokens(100) const receipt = await stEth.increaseAllowance(user2, increase_amount, { from: user1 }) - assertEvent(receipt, 'Approval', { - expectedArgs: { owner: user1, spender: user2, value: increased_amount }, + assert.emits(receipt, 'Approval', { + owner: user1, + spender: user2, + value: increased_amount, }) - assertBn(await stEth.allowance(user1, user2), increased_amount) + assert.equals(await stEth.allowance(user1, user2), increased_amount) }) }) }) @@ -247,31 +255,31 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { }) it('reverts when spender is zero address', async () => { - await assertRevert(stEth.decreaseAllowance(ZERO_ADDRESS, tokens(1), { from: user1 })) + await assert.reverts(stEth.decreaseAllowance(ZERO_ADDRESS, tokens(1), { from: user1 })) }) it('reverts when requested amount exceeds allowance ', async () => { - await assertRevert(stEth.decreaseAllowance(user2, tokens(101), { from: user1 })) + await assert.reverts(stEth.decreaseAllowance(user2, tokens(101), { from: user1 })) }) it('reverts when the spender had no approved amount', async () => { - await assertRevert(stEth.decreaseAllowance(user3, tokens(1), { from: user1 })) + await assert.reverts(stEth.decreaseAllowance(user3, tokens(1), { from: user1 })) }) it('decreaseAllowance without any tokens works', async () => { const decrease_amount = tokens(50) const decreased_amount = tokens(50) const receipt = await stEth.decreaseAllowance(user1, decrease_amount, { from: user2 }) - assertEvent(receipt, 'Approval', { expectedArgs: { owner: user2, spender: user1, value: decreased_amount } }) - assertBn(await stEth.allowance(user2, user1), decreased_amount) + assert.emits(receipt, 'Approval', { owner: user2, spender: user1, value: decreased_amount }) + assert.equals(await stEth.allowance(user2, user1), decreased_amount) }) it('decreaseAllowance with requested amount subs it from allowance and emits event', async () => { const decrease_amount = tokens(50) const decreased_amount = tokens(50) const receipt = await stEth.decreaseAllowance(user2, decrease_amount, { from: user1 }) - assertEvent(receipt, 'Approval', { expectedArgs: { owner: user1, spender: user2, value: decreased_amount } }) - assertBn(await stEth.allowance(user1, user2), decreased_amount) + assert.emits(receipt, 'Approval', { owner: user1, spender: user2, value: decreased_amount }) + assert.equals(await stEth.allowance(user1, user2), decreased_amount) }) }) }) @@ -287,7 +295,7 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { await stEth.transfer(user2, tokens(2), { from: user1 }) await stEth.approve(user2, tokens(2), { from: user1 }) await stEth.approve(user1, tokens(2), { from: user2 }) - assertBn(await stEth.allowance(user1, user2), tokens(2)) + assert.equals(await stEth.allowance(user1, user2), tokens(2)) assert.equal(await stEth.isStopped(), false) @@ -295,13 +303,13 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { assert(await stEth.isStopped()) // can't stop when stopped - await assertRevert(stEth.stop({ from: user1 })) + await assert.reverts(stEth.stop({ from: user1 })) assert(await stEth.isStopped()) - await assertRevert(stEth.transfer(user2, tokens(2), { from: user1 }), 'CONTRACT_IS_STOPPED') + await assert.reverts(stEth.transfer(user2, tokens(2), { from: user1 }), 'CONTRACT_IS_STOPPED') // NB: can approve if stopped await stEth.approve(user2, tokens(2), { from: user1 }) - await assertRevert(stEth.transferFrom(user2, user3, tokens(2), { from: user1 }), 'CONTRACT_IS_STOPPED') + await assert.reverts(stEth.transferFrom(user2, user3, tokens(2), { from: user1 }), 'CONTRACT_IS_STOPPED') // NB: can change allowance if stopped await stEth.increaseAllowance(user2, tokens(2), { from: user1 }) await stEth.decreaseAllowance(user2, tokens(2), { from: user1 }) @@ -310,12 +318,12 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { assert.equal(await stEth.isStopped(), false) // can't resume when not stopped - await assertRevert(stEth.resume({ from: user1 })) + await assert.reverts(stEth.resume({ from: user1 })) assert.equal(await stEth.isStopped(), false) await stEth.transfer(user2, tokens(2), { from: user1 }) - assertBn(await stEth.balanceOf(user1), tokens(95)) - assertBn(await stEth.balanceOf(user2), tokens(4)) + assert.equals(await stEth.balanceOf(user1), tokens(95)) + assert.equals(await stEth.balanceOf(user2), tokens(4)) }) it('allowance behavior is correct after slashing', async () => { @@ -323,19 +331,19 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { await stEth.setTotalPooledEther(tokens(50)) - assertBn(await stEth.balanceOf(user1), tokens(49.5)) - assertBn(await stEth.sharesOf(user1), tokens(99)) + assert.equals(await stEth.balanceOf(user1), tokens(49.5)) + assert.equals(await stEth.sharesOf(user1), tokens(99)) - assertBn(await stEth.allowance(user1, user2), tokens(75)) + assert.equals(await stEth.allowance(user1, user2), tokens(75)) - await assertRevert(stEth.transferFrom(user1, user2, tokens(75), { from: user2 })) - await assertRevert(stEth.transferFrom(user1, user2, bn(tokens(50)).addn(10), { from: user2 })) + await assert.reverts(stEth.transferFrom(user1, user2, tokens(75), { from: user2 })) + await assert.reverts(stEth.transferFrom(user1, user2, bn(tokens(50)).addn(10), { from: user2 })) await stEth.transferFrom(user1, user2, tokens(49.5), { from: user2 }) - assertBn(await stEth.balanceOf(user1), tokens(0)) - assertBn(await stEth.sharesOf(user1), tokens(0)) - assertBn(await stEth.balanceOf(user2), tokens(49.5)) - assertBn(await stEth.sharesOf(user2), tokens(99)) + assert.equals(await stEth.balanceOf(user1), tokens(0)) + assert.equals(await stEth.sharesOf(user1), tokens(0)) + assert.equals(await stEth.balanceOf(user2), tokens(49.5)) + assert.equals(await stEth.sharesOf(user2), tokens(99)) }) context('mint', () => { @@ -344,26 +352,26 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { await stEth.setTotalPooledEther(tokens(112)) - assertBn(await stEth.totalSupply(), tokens(112)) - assertBn(await stEth.balanceOf(user1), tokens(111)) - assertBn(await stEth.balanceOf(user2), tokens(0)) - assertBn(await stEth.getTotalShares(), tokens(112)) - assertBn(await stEth.sharesOf(user1), tokens(111)) - assertBn(await stEth.sharesOf(user2), tokens(0)) + assert.equals(await stEth.totalSupply(), tokens(112)) + assert.equals(await stEth.balanceOf(user1), tokens(111)) + assert.equals(await stEth.balanceOf(user2), tokens(0)) + assert.equals(await stEth.getTotalShares(), tokens(112)) + assert.equals(await stEth.sharesOf(user1), tokens(111)) + assert.equals(await stEth.sharesOf(user2), tokens(0)) await stEth.mintShares(user2, tokens(4)) await stEth.setTotalPooledEther(tokens(116)) - assertBn(await stEth.totalSupply(), tokens(116)) - assertBn(await stEth.balanceOf(user1), tokens(111)) - assertBn(await stEth.balanceOf(user2), tokens(4)) - assertBn(await stEth.getTotalShares(), tokens(116)) - assertBn(await stEth.sharesOf(user1), tokens(111)) - assertBn(await stEth.sharesOf(user2), tokens(4)) + assert.equals(await stEth.totalSupply(), tokens(116)) + assert.equals(await stEth.balanceOf(user1), tokens(111)) + assert.equals(await stEth.balanceOf(user2), tokens(4)) + assert.equals(await stEth.getTotalShares(), tokens(116)) + assert.equals(await stEth.sharesOf(user1), tokens(111)) + assert.equals(await stEth.sharesOf(user2), tokens(4)) }) it('reverts when mint to zero address', async () => { - await assertRevert(stEth.mintShares(ZERO_ADDRESS, tokens(1))) + await assert.reverts(stEth.mintShares(ZERO_ADDRESS, tokens(1))) }) }) @@ -377,32 +385,30 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { }) it('reverts when burn from zero address', async () => { - await assertRevert(stEth.burnShares(ZERO_ADDRESS, tokens(1), { from: user1 }), 'BURN_FROM_THE_ZERO_ADDRESS') + await assert.reverts(stEth.burnShares(ZERO_ADDRESS, tokens(1), { from: user1 }), 'BURN_FROM_THE_ZERO_ADDRESS') }) it('reverts when burn amount exceeds balance', async () => { - await assertRevert(stEth.burnShares(user1, tokens(101)), 'BURN_AMOUNT_EXCEEDS_BALANCE') + await assert.reverts(stEth.burnShares(user1, tokens(101)), 'BURN_AMOUNT_EXCEEDS_BALANCE') }) it('burning zero value works', async () => { const receipt = await stEth.burnShares(user1, tokens(0)) - assertEvent(receipt, 'SharesBurnt', { - expectedArgs: { - account: user1, - preRebaseTokenAmount: tokens(0), - postRebaseTokenAmount: tokens(0), - sharesAmount: tokens(0), - }, + assert.emits(receipt, 'SharesBurnt', { + account: user1, + preRebaseTokenAmount: tokens(0), + postRebaseTokenAmount: tokens(0), + sharesAmount: tokens(0), }) - assertBn(await stEth.totalSupply(), tokens(300)) - assertBn(await stEth.balanceOf(user1), tokens(99)) - assertBn(await stEth.balanceOf(user2), tokens(100)) - assertBn(await stEth.balanceOf(user3), tokens(100)) - assertBn(await stEth.getTotalShares(), tokens(300)) - assertBn(await stEth.sharesOf(user1), tokens(99)) - assertBn(await stEth.sharesOf(user2), tokens(100)) - assertBn(await stEth.sharesOf(user3), tokens(100)) + assert.equals(await stEth.totalSupply(), tokens(300)) + assert.equals(await stEth.balanceOf(user1), tokens(99)) + assert.equals(await stEth.balanceOf(user2), tokens(100)) + assert.equals(await stEth.balanceOf(user3), tokens(100)) + assert.equals(await stEth.getTotalShares(), tokens(300)) + assert.equals(await stEth.sharesOf(user1), tokens(99)) + assert.equals(await stEth.sharesOf(user2), tokens(100)) + assert.equals(await stEth.sharesOf(user3), tokens(100)) }) it('burning works (redistributes tokens)', async () => { @@ -418,24 +424,22 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { const expectedPreTokenAmount = await stEth.getPooledEthByShares(sharesToBurn) const receipt = await stEth.burnShares(user2, sharesToBurn) const expectedPostTokenAmount = await stEth.getPooledEthByShares(sharesToBurn) - assertEvent(receipt, 'SharesBurnt', { - expectedArgs: { - account: user2, - preRebaseTokenAmount: expectedPreTokenAmount, - postRebaseTokenAmount: expectedPostTokenAmount, - sharesAmount: sharesToBurn, - }, + assert.emits(receipt, 'SharesBurnt', { + account: user2, + preRebaseTokenAmount: expectedPreTokenAmount, + postRebaseTokenAmount: expectedPostTokenAmount, + sharesAmount: sharesToBurn, }) - assertBn(await stEth.totalSupply(), tokens(300)) - assertBn((await stEth.balanceOf(user1)).add(await stEth.balanceOf(INITIAL_HOLDER)), tokens(105)) - assertBn(await stEth.balanceOf(user2), bn(tokens(90)).subn(1)) // expected round error - assertBn(await stEth.balanceOf(user3), tokens(105)) - assertBn(await stEth.getTotalShares(), bn('285714285714285714285')) - assertBn(await stEth.sharesOf(INITIAL_HOLDER), tokens(1)) - assertBn(await stEth.sharesOf(user1), tokens(99)) - assertBn(await stEth.sharesOf(user2), bn('85714285714285714285')) - assertBn(await stEth.sharesOf(user3), tokens(100)) + assert.equals(await stEth.totalSupply(), tokens(300)) + assert.equals((await stEth.balanceOf(user1)).add(await stEth.balanceOf(INITIAL_HOLDER)), tokens(105)) + assert.equals(await stEth.balanceOf(user2), bn(tokens(90)).subn(1)) // expected round error + assert.equals(await stEth.balanceOf(user3), tokens(105)) + assert.equals(await stEth.getTotalShares(), bn('285714285714285714285')) + assert.equals(await stEth.sharesOf(INITIAL_HOLDER), tokens(1)) + assert.equals(await stEth.sharesOf(user1), tokens(99)) + assert.equals(await stEth.sharesOf(user2), bn('85714285714285714285')) + assert.equals(await stEth.sharesOf(user3), tokens(100)) }) it('allowance behavior is correct after burning', async () => { @@ -453,21 +457,19 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { const expectedPreTokenAmount = await stEth.getPooledEthByShares(sharesToBurn) const receipt = await stEth.burnShares(user2, sharesToBurn) const expectedPostTokenAmount = await stEth.getPooledEthByShares(sharesToBurn) - assertEvent(receipt, 'SharesBurnt', { - expectedArgs: { - account: user2, - preRebaseTokenAmount: expectedPreTokenAmount, - postRebaseTokenAmount: expectedPostTokenAmount, - sharesAmount: sharesToBurn, - }, + assert.emits(receipt, 'SharesBurnt', { + account: user2, + preRebaseTokenAmount: expectedPreTokenAmount, + postRebaseTokenAmount: expectedPostTokenAmount, + sharesAmount: sharesToBurn, }) - assertBn(await stEth.balanceOf(user2), tokens(50)) + assert.equals(await stEth.balanceOf(user2), tokens(50)) - assertBn(await stEth.allowance(user2, user3), tokens(75)) + assert.equals(await stEth.allowance(user2, user3), tokens(75)) - await assertRevert(stEth.transferFrom(user2, user3, tokens(75), { from: user3 })) - await assertRevert(stEth.transferFrom(user2, user3, bn(tokens(50)).addn(10), { from: user3 })) + await assert.reverts(stEth.transferFrom(user2, user3, tokens(75), { from: user3 })) + await assert.reverts(stEth.transferFrom(user2, user3, bn(tokens(50)).addn(10), { from: user3 })) await stEth.transferFrom(user2, user3, tokens(50), { from: user3 }) }) }) @@ -476,55 +478,55 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { context('share-related getters and transfers', async () => { context('with initial totalPooledEther (supply)', async () => { it('getTotalSupply', async () => { - assertBn(await stEth.totalSupply({ from: nobody }), tokens(1)) + assert.equals(await stEth.totalSupply({ from: nobody }), tokens(1)) }) it('getTotalShares', async () => { - assertBn(await stEth.getTotalShares(), tokens(1)) + assert.equals(await stEth.getTotalShares(), tokens(1)) }) it('getTotalPooledEther', async () => { - assertBn(await stEth.getTotalPooledEther(), tokens(1)) + assert.equals(await stEth.getTotalPooledEther(), tokens(1)) }) it('sharesOf', async () => { - assertBn(await stEth.sharesOf(nobody), tokens(0)) + assert.equals(await stEth.sharesOf(nobody), tokens(0)) }) it('getPooledEthByShares', async () => { - assertBn(await stEth.getPooledEthByShares(tokens(0)), tokens(0)) - assertBn(await stEth.getPooledEthByShares(tokens(1)), tokens(1)) - assertBn(await stEth.getPooledEthByShares(tokens(100)), tokens(100)) + assert.equals(await stEth.getPooledEthByShares(tokens(0)), tokens(0)) + assert.equals(await stEth.getPooledEthByShares(tokens(1)), tokens(1)) + assert.equals(await stEth.getPooledEthByShares(tokens(100)), tokens(100)) }) it('balanceOf', async () => { - assertBn(await stEth.balanceOf(nobody), tokens(0)) + assert.equals(await stEth.balanceOf(nobody), tokens(0)) }) it('getSharesByPooledEth', async () => { - assertBn(await stEth.getSharesByPooledEth(tokens(1)), tokens(1)) - assertBn(await stEth.getSharesByPooledEth(tokens(0)), tokens(0)) - assertBn(await stEth.getSharesByPooledEth(tokens(100)), tokens(100)) + assert.equals(await stEth.getSharesByPooledEth(tokens(1)), tokens(1)) + assert.equals(await stEth.getSharesByPooledEth(tokens(0)), tokens(0)) + assert.equals(await stEth.getSharesByPooledEth(tokens(100)), tokens(100)) }) it('transferShares', async () => { - assertBn(await stEth.balanceOf(nobody), tokens(0)) + assert.equals(await stEth.balanceOf(nobody), tokens(0)) const receipt = await stEth.transferShares(user1, tokens(0), { from: nobody }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: nobody, to: user1, value: tokens(0) } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: nobody, to: user1, sharesValue: tokens(0) } }) + assert.emits(receipt, 'Transfer', { from: nobody, to: user1, value: tokens(0) }) + assert.emits(receipt, 'TransferShares', { from: nobody, to: user1, sharesValue: tokens(0) }) - assertBn(await stEth.balanceOf(nobody), tokens(0)) + assert.equals(await stEth.balanceOf(nobody), tokens(0)) }) it('transferSharesFrom', async () => { - assertBn(await stEth.balanceOf(nobody), tokens(0)) + assert.equals(await stEth.balanceOf(nobody), tokens(0)) const receipt = await stEth.transferSharesFrom(nobody, user1, tokens(0), { from: user2 }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: nobody, to: user1, value: tokens(0) } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: nobody, to: user1, sharesValue: tokens(0) } }) + assert.emits(receipt, 'Transfer', { from: nobody, to: user1, value: tokens(0) }) + assert.emits(receipt, 'TransferShares', { from: nobody, to: user1, sharesValue: tokens(0) }) - assertBn(await stEth.balanceOf(nobody), tokens(0)) + assert.equals(await stEth.balanceOf(nobody), tokens(0)) }) }) @@ -535,129 +537,132 @@ contract('StETH', ([_, __, user1, user2, user3, nobody]) => { }) it('getTotalSupply', async () => { - assertBn(await stEth.totalSupply(), tokens(100)) + assert.equals(await stEth.totalSupply(), tokens(100)) }) it('getTotalPooledEther', async () => { - assertBn(await stEth.getTotalPooledEther(), tokens(100)) + assert.equals(await stEth.getTotalPooledEther(), tokens(100)) }) it('getTotalShares', async () => { - assertBn(await stEth.getTotalShares(), tokens(100)) + assert.equals(await stEth.getTotalShares(), tokens(100)) }) it('sharesOf', async () => { - assertBn(await stEth.sharesOf(user1), tokens(99)) + assert.equals(await stEth.sharesOf(user1), tokens(99)) }) it('getPooledEthByShares', async () => { - assertBn(await stEth.getPooledEthByShares(tokens(0)), tokens(0)) - assertBn(await stEth.getPooledEthByShares(tokens(1)), tokens(1)) - assertBn(await stEth.getPooledEthByShares(tokens(100)), tokens(100)) + assert.equals(await stEth.getPooledEthByShares(tokens(0)), tokens(0)) + assert.equals(await stEth.getPooledEthByShares(tokens(1)), tokens(1)) + assert.equals(await stEth.getPooledEthByShares(tokens(100)), tokens(100)) }) it('balanceOf', async () => { - assertBn(await stEth.balanceOf(user1), tokens(99)) - assertBn(await stEth.balanceOf(user2), tokens(0)) + assert.equals(await stEth.balanceOf(user1), tokens(99)) + assert.equals(await stEth.balanceOf(user2), tokens(0)) }) it('getSharesByPooledEth', async () => { - assertBn(await stEth.getSharesByPooledEth(tokens(0)), tokens(0)) - assertBn(await stEth.getSharesByPooledEth(tokens(1)), tokens(1)) - assertBn(await stEth.getSharesByPooledEth(tokens(100)), tokens(100)) + assert.equals(await stEth.getSharesByPooledEth(tokens(0)), tokens(0)) + assert.equals(await stEth.getSharesByPooledEth(tokens(1)), tokens(1)) + assert.equals(await stEth.getSharesByPooledEth(tokens(100)), tokens(100)) }) it('transferShares', async () => { - assertBn(await stEth.balanceOf(user1), tokens(99)) - assertBn(await stEth.balanceOf(nobody), tokens(0)) + assert.equals(await stEth.balanceOf(user1), tokens(99)) + assert.equals(await stEth.balanceOf(nobody), tokens(0)) let receipt = await stEth.transferShares(nobody, tokens(0), { from: user1 }) - assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) - assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: nobody, value: tokens(0) } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: user1, to: nobody, sharesValue: tokens(0) } }) + assert.emitsNumberOfEvents(receipt, 'Transfer', 1) + assert.emitsNumberOfEvents(receipt, 'TransferShares', 1) + assert.emits(receipt, 'Transfer', { from: user1, to: nobody, value: tokens(0) }) + assert.emits(receipt, 'TransferShares', { from: user1, to: nobody, sharesValue: tokens(0) }) - assertBn(await stEth.balanceOf(user1), tokens(99)) - assertBn(await stEth.balanceOf(nobody), tokens(0)) + assert.equals(await stEth.balanceOf(user1), tokens(99)) + assert.equals(await stEth.balanceOf(nobody), tokens(0)) receipt = await stEth.transferShares(nobody, tokens(30), { from: user1 }) - assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) - assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: nobody, value: tokens(30) } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: user1, to: nobody, sharesValue: tokens(30) } }) + assert.emitsNumberOfEvents(receipt, 'Transfer', 1) + assert.emitsNumberOfEvents(receipt, 'TransferShares', 1) + assert.emits(receipt, 'Transfer', { from: user1, to: nobody, value: tokens(30) }) + assert.emits(receipt, 'TransferShares', { from: user1, to: nobody, sharesValue: tokens(30) }) - assertBn(await stEth.balanceOf(user1), tokens(69)) - assertBn(await stEth.balanceOf(nobody), tokens(30)) + assert.equals(await stEth.balanceOf(user1), tokens(69)) + assert.equals(await stEth.balanceOf(nobody), tokens(30)) - await assertRevert(stEth.transferShares(nobody, tokens(75), { from: user1 }), 'TRANSFER_AMOUNT_EXCEEDS_BALANCE') + await assert.reverts( + stEth.transferShares(nobody, tokens(75), { from: user1 }), + 'TRANSFER_AMOUNT_EXCEEDS_BALANCE' + ) await stEth.setTotalPooledEther(tokens(120)) const tokensToTransfer = tokens((120 * 69) / 100) receipt = await stEth.transferShares(nobody, tokens(69), { from: user1 }) - assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) - assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: nobody, value: tokensToTransfer } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: user1, to: nobody, sharesValue: tokens(69) } }) + assert.emitsNumberOfEvents(receipt, 'Transfer', 1) + assert.emitsNumberOfEvents(receipt, 'TransferShares', 1) + assert.emits(receipt, 'Transfer', { from: user1, to: nobody, value: tokensToTransfer }) + assert.emits(receipt, 'TransferShares', { from: user1, to: nobody, sharesValue: tokens(69) }) - assertBn(await stEth.balanceOf(user1), tokens(0)) - assertBn(await stEth.balanceOf(nobody), '118800000000000000000') + assert.equals(await stEth.balanceOf(user1), tokens(0)) + assert.equals(await stEth.balanceOf(nobody), '118800000000000000000') }) it('transferSharesFrom', async () => { - assertBn(await stEth.balanceOf(user1), tokens(99)) - assertBn(await stEth.balanceOf(nobody), tokens(0)) + assert.equals(await stEth.balanceOf(user1), tokens(99)) + assert.equals(await stEth.balanceOf(nobody), tokens(0)) let receipt = await stEth.transferSharesFrom(user1, nobody, tokens(0), { from: user2 }) - assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) - assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: nobody, value: tokens(0) } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: user1, to: nobody, sharesValue: tokens(0) } }) + assert.emitsNumberOfEvents(receipt, 'Transfer', 1) + assert.emitsNumberOfEvents(receipt, 'TransferShares', 1) + assert.emits(receipt, 'Transfer', { from: user1, to: nobody, value: tokens(0) }) + assert.emits(receipt, 'TransferShares', { from: user1, to: nobody, sharesValue: tokens(0) }) - assertBn(await stEth.balanceOf(user1), tokens(99)) - assertBn(await stEth.balanceOf(nobody), tokens(0)) + assert.equals(await stEth.balanceOf(user1), tokens(99)) + assert.equals(await stEth.balanceOf(nobody), tokens(0)) - await assertRevert( + await assert.reverts( stEth.transferSharesFrom(user1, nobody, tokens(30), { from: user2 }), `TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE` ) await stEth.approve(user2, tokens(30), { from: user1 }) receipt = await stEth.transferSharesFrom(user1, nobody, tokens(30), { from: user2 }) - assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) - assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: nobody, value: tokens(30) } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: user1, to: nobody, sharesValue: tokens(30) } }) + assert.emitsNumberOfEvents(receipt, 'Transfer', 1) + assert.emitsNumberOfEvents(receipt, 'TransferShares', 1) + assert.emits(receipt, 'Transfer', { from: user1, to: nobody, value: tokens(30) }) + assert.emits(receipt, 'TransferShares', { from: user1, to: nobody, sharesValue: tokens(30) }) - assertBn(await stEth.balanceOf(user1), tokens(69)) - assertBn(await stEth.balanceOf(nobody), tokens(30)) + assert.equals(await stEth.balanceOf(user1), tokens(69)) + assert.equals(await stEth.balanceOf(nobody), tokens(30)) - await assertRevert( + await assert.reverts( stEth.transferSharesFrom(user1, nobody, tokens(75), { from: user2 }), 'TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE' ) await stEth.approve(user2, tokens(75), { from: user1 }) - await assertRevert( + await assert.reverts( stEth.transferSharesFrom(user1, nobody, tokens(75), { from: user2 }), 'TRANSFER_AMOUNT_EXCEEDS_BALANCE' ) await stEth.setTotalPooledEther(tokens(120)) - await assertRevert( + await assert.reverts( stEth.transferSharesFrom(user1, nobody, tokens(70), { from: user2 }), 'TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE' ) await stEth.approve(user2, tokens(84), { from: user1 }) receipt = await stEth.transferSharesFrom(user1, nobody, tokens(69), { from: user2 }) - assertAmountOfEvents(receipt, 'Transfer', { expectedAmount: 1 }) - assertAmountOfEvents(receipt, 'TransferShares', { expectedAmount: 1 }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: user1, to: nobody, value: '82800000000000000000' } }) - assertEvent(receipt, 'TransferShares', { expectedArgs: { from: user1, to: nobody, sharesValue: tokens(69) } }) + assert.emitsNumberOfEvents(receipt, 'Transfer', 1) + assert.emitsNumberOfEvents(receipt, 'TransferShares', 1) + assert.emits(receipt, 'Transfer', { from: user1, to: nobody, value: '82800000000000000000' }) + assert.emits(receipt, 'TransferShares', { from: user1, to: nobody, sharesValue: tokens(69) }) - assertBn(await stEth.balanceOf(user1), tokens(0)) - assertBn(await stEth.balanceOf(nobody), '118800000000000000000') + assert.equals(await stEth.balanceOf(user1), tokens(0)) + assert.equals(await stEth.balanceOf(nobody), '118800000000000000000') }) }) }) diff --git a/test/0.4.24/stethpermit.test.js b/test/0.4.24/stethpermit.test.js index 8ac99a0c9..e5fca0088 100644 --- a/test/0.4.24/stethpermit.test.js +++ b/test/0.4.24/stethpermit.test.js @@ -1,7 +1,9 @@ +const { artifacts, contract, ethers, web3 } = require('hardhat') +const { assert } = require('../helpers/assert') + const crypto = require('crypto') const { ACCOUNTS_AND_KEYS, MAX_UINT256, ZERO_ADDRESS } = require('./helpers/constants') const { bn } = require('@aragon/contract-helpers-test') -const { assert } = require('../helpers/assert') const { signPermit, signTransferAuthorization, makeDomainSeparator } = require('./helpers/permit_helpers') const { hexStringFromBuffer } = require('./helpers/sign_utils') const { ETH } = require('../helpers/utils') @@ -12,7 +14,7 @@ const StETHPermit = artifacts.require('StETHPermitMock') contract('StETHPermit', ([deployer, ...accounts]) => { let stEthPermit, eip712StETH, chainId, domainSeparator - const snapshot = new EvmSnapshot(hre.ethers.provider) + const snapshot = new EvmSnapshot(ethers.provider) before('deploy mock token', async () => { stEthPermit = await StETHPermit.new({ from: deployer, value: ETH(1) }) diff --git a/test/0.6.12/helpers/permit_helpers.js b/test/0.6.12/helpers/permit_helpers.js index 098c6cff2..f083368ac 100644 --- a/test/0.6.12/helpers/permit_helpers.js +++ b/test/0.6.12/helpers/permit_helpers.js @@ -1,3 +1,4 @@ +const { web3 } = require('hardhat') const { ecSign, strip0x } = require('./index') const transferWithAuthorizationTypeHash = web3.utils.keccak256( diff --git a/test/0.6.12/wsteth.permit.test.js b/test/0.6.12/wsteth.permit.test.js index 4ae960131..a29b1655b 100644 --- a/test/0.6.12/wsteth.permit.test.js +++ b/test/0.6.12/wsteth.permit.test.js @@ -1,12 +1,9 @@ +const { artifacts, contract } = require('hardhat') const crypto = require('crypto') +const { expect } = require('chai') const { ACCOUNTS_AND_KEYS, MAX_UINT256, ZERO_ADDRESS } = require('./helpers/constants') const { expectRevert, hexStringFromBuffer } = require('./helpers') -const { - signPermit, - signTransferAuthorization, - permitTypeHash, - makeDomainSeparator, -} = require('./helpers/permit_helpers') +const { signPermit, signTransferAuthorization, makeDomainSeparator } = require('./helpers/permit_helpers') const WstETH = artifacts.require('WstETHMock') const StETH = artifacts.require('StETHMockERC20') diff --git a/test/0.6.12/wsteth.test.js b/test/0.6.12/wsteth.test.js index 06f75eaf0..feb3cd6ce 100644 --- a/test/0.6.12/wsteth.test.js +++ b/test/0.6.12/wsteth.test.js @@ -1,6 +1,8 @@ -const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers') +const { artifacts, contract, ethers, web3 } = require('hardhat') +const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers') const { expect } = require('chai') -const { ZERO_ADDRESS } = constants +const { assert } = require('../helpers/assert') +const { ZERO_ADDRESS } = require('../helpers/constants') const { shouldBehaveLikeERC20 } = require('./helpers/ERC20.behavior') const { EvmSnapshot } = require('../helpers/blockchain') @@ -9,7 +11,7 @@ const WstETH = artifacts.require('WstETHMock') const StETH = artifacts.require('StETHMockERC20') contract('WstETH', function ([deployer, initialHolder, recipient, anotherAccount, ...otherAccounts]) { - const snapshot = new EvmSnapshot(hre.ethers.provider) + const snapshot = new EvmSnapshot(ethers.provider) before(async function () { this.steth = await StETH.new({ from: deployer }) diff --git a/test/0.8.9/burner.test.js b/test/0.8.9/burner.test.js index e6038825c..cd3c4bf46 100644 --- a/test/0.8.9/burner.test.js +++ b/test/0.8.9/burner.test.js @@ -1,11 +1,11 @@ -const hre = require('hardhat') +const { artifacts, contract, ethers, web3 } = require('hardhat') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') +const { bn } = require('@aragon/contract-helpers-test') const { EvmSnapshot } = require('../helpers/blockchain') const { ETH, StETH } = require('../helpers/utils') const { assert } = require('../helpers/assert') const { deployProtocol } = require('../helpers/protocol') -const { INITIAL_HOLDER } = require('../helpers/constants') +const { INITIAL_HOLDER, ZERO_ADDRESS } = require('../helpers/constants') const Burner = artifacts.require('Burner.sol') @@ -24,7 +24,6 @@ contract('Burner', ([deployer, _, anotherAccount]) => { lido = deployed.pool burner = deployed.burner - acl = deployed.acl voting = deployed.voting.address appManager = deployed.appManager.address treasury = deployed.treasury.address @@ -33,7 +32,7 @@ contract('Burner', ([deployer, _, anotherAccount]) => { await ethers.provider.send('hardhat_impersonateAccount', [lido.address]) await ethers.provider.send('hardhat_impersonateAccount', [burner.address]) - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() }) diff --git a/test/0.8.9/deposit-security-module.test.js b/test/0.8.9/deposit-security-module.test.js index 352d7cdd3..023154b47 100644 --- a/test/0.8.9/deposit-security-module.test.js +++ b/test/0.8.9/deposit-security-module.test.js @@ -1,11 +1,8 @@ -const hre = require('hardhat') -const { assertEvent } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../helpers/assertThrow') +const { artifacts, contract, ethers, network, web3 } = require('hardhat') const { assert } = require('../helpers/assert') const { BN } = require('bn.js') const { DSMAttestMessage, DSMPauseMessage } = require('../helpers/signatures') -const { ZERO_ADDRESS, getEventAt } = require('@aragon/contract-helpers-test') -const { artifacts, network } = require('hardhat') +const { ZERO_ADDRESS } = require('../helpers/constants') // generateGuardianSignatures @@ -38,11 +35,6 @@ const UNRELATED_SIGNER_PRIVATE_KEYS = { [UNRELATED_SIGNER2]: '0xbabec7d3867c72f6c275135b1e1423ca8f565d6e21a1947d056a195b1c3cae27', } -const assertNoEvent = (receipt, eventName, msg) => { - const event = getEventAt(receipt, eventName) - assert.equal(event, undefined, msg) -} - // status enum const StakingModuleStatus = { Active: 0, // deposits and rewards allowed @@ -54,6 +46,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { let depositSecurityModule, depositContractMock, stakingRouterMock let evmSnapshotId let block + let lidoMock before('deploy mock contracts', async () => { lidoMock = await LidoMockForDepositSecurityModule.new() @@ -74,12 +67,12 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { DSMPauseMessage.setMessagePrefix(await depositSecurityModule.PAUSE_MESSAGE_PREFIX()) block = await waitBlocks(MIN_DEPOSIT_BLOCK_DISTANCE) - evmSnapshotId = await hre.ethers.provider.send('evm_snapshot', []) + evmSnapshotId = await ethers.provider.send('evm_snapshot', []) }) afterEach(async () => { - await hre.ethers.provider.send('evm_revert', [evmSnapshotId]) - evmSnapshotId = await hre.ethers.provider.send('evm_snapshot', []) + await ethers.provider.send('evm_revert', [evmSnapshotId]) + evmSnapshotId = await ethers.provider.send('evm_snapshot', []) }) async function waitBlocks(numBlocksToMine) { @@ -117,7 +110,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { }) it('deposits are impossible', async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -157,18 +150,22 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { [validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1])], { from: stranger } ) - assertEvent(tx.receipt, 'StakingModuleDeposited', { - expectedArgs: { + assert.emits( + tx.receipt, + 'StakingModuleDeposited', + { maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, stakingModuleId: STAKING_MODULE, depositCalldata: DEPOSIT_CALLDATA, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, - }) + { + abi: StakingRouterMockForDepositSecurityModule.abi, + } + ) }) it('cannot deposit with an unrelated sig', async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -183,7 +180,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { }) it('cannot deposit with no sigs', async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -203,7 +200,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { await depositContractMock.set_deposit_root(newDepositRoot) assert.equal(await depositContractMock.get_deposit_root(), newDepositRoot, 'invariant failed: depositRoot') - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -222,7 +219,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { await stakingRouterMock.setStakingModuleNonce(newNonce) assert.equal(await stakingRouterMock.getStakingModuleNonce(STAKING_MODULE), newNonce, 'invariant failed: nonce') - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -246,7 +243,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { 'invariant failed: last deposit block' ) - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -267,7 +264,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { // pause module await stakingRouterMock.pauseStakingModule(STAKING_MODULE) - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( latestBlock.number, block.hash, @@ -285,7 +282,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const latestBlock = await waitBlocks(1) assert(latestBlock.number > block.number, 'invariant failed: block number') - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( latestBlock.number, block.hash, @@ -301,7 +298,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { it('cannot deposit with zero block hash', async () => { await waitBlocks(255) - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, '0x', @@ -345,14 +342,18 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { { from: stranger } ) - assertEvent(tx.receipt, 'StakingModuleDeposited', { - expectedArgs: { + assert.emits( + tx.receipt, + 'StakingModuleDeposited', + { maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, stakingModuleId: STAKING_MODULE, depositCalldata: DEPOSIT_CALLDATA, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, - }) + { + abi: StakingRouterMockForDepositSecurityModule.abi, + } + ) }) it("can deposit with guardian's sigs (0,1)", async () => { @@ -372,14 +373,18 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { { from: stranger } ) - assertEvent(tx.receipt, 'StakingModuleDeposited', { - expectedArgs: { + assert.emits( + tx.receipt, + 'StakingModuleDeposited', + { maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, stakingModuleId: STAKING_MODULE, depositCalldata: DEPOSIT_CALLDATA, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, - }) + { + abi: StakingRouterMockForDepositSecurityModule.abi, + } + ) }) it("can deposit with guardian's sigs (0,2)", async () => { @@ -399,14 +404,18 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { { from: stranger } ) - assertEvent(tx.receipt, 'StakingModuleDeposited', { - expectedArgs: { + assert.emits( + tx.receipt, + 'StakingModuleDeposited', + { maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, stakingModuleId: STAKING_MODULE, depositCalldata: DEPOSIT_CALLDATA, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, - }) + { + abi: StakingRouterMockForDepositSecurityModule.abi, + } + ) }) it("can deposit with guardian's sigs (1,2)", async () => { @@ -426,18 +435,22 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { { from: stranger } ) - assertEvent(tx.receipt, 'StakingModuleDeposited', { - expectedArgs: { + assert.emits( + tx.receipt, + 'StakingModuleDeposited', + { maxDepositsCount: MAX_DEPOSITS_PER_BLOCK, stakingModuleId: STAKING_MODULE, depositCalldata: DEPOSIT_CALLDATA, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, - }) + { + abi: StakingRouterMockForDepositSecurityModule.abi, + } + ) }) it('cannot deposit with no sigs', async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -457,7 +470,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]), ] - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -478,7 +491,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN1]), validAttestMessage.sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN2]), ] - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -499,7 +512,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { validAttestMessage.sign(UNRELATED_SIGNER_PRIVATE_KEYS[UNRELATED_SIGNER1]), validAttestMessage.sign(UNRELATED_SIGNER_PRIVATE_KEYS[UNRELATED_SIGNER2]), ] - await assertRevert( + await assert.reverts( depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -535,28 +548,36 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { from: guardian, }) - assertEvent(tx, 'StakingModuleStatusSet', { - expectedArgs: { + assert.emits( + tx, + 'StakingModuleStatusSet', + { stakingModuleId: STAKING_MODULE, status: StakingModuleStatus.DepositsPaused, - setBy: depositSecurityModule, + setBy: depositSecurityModule.address, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, - }) + { + abi: StakingRouterMockForDepositSecurityModule.abi, + } + ) }) it('pauses if called by an anon submitting sig of guardian 1 or 2', async () => { const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { from: guardian, }) - assertEvent(tx, 'StakingModuleStatusSet', { - expectedArgs: { + assert.emits( + tx, + 'StakingModuleStatusSet', + { stakingModuleId: STAKING_MODULE, status: StakingModuleStatus.DepositsPaused, - setBy: depositSecurityModule, + setBy: depositSecurityModule.address, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, - }) + { + abi: StakingRouterMockForDepositSecurityModule.abi, + } + ) }) it('reverts if called by an anon submitting an unrelated sig', async () => { @@ -566,19 +587,23 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { validPauseMessage.sign(UNRELATED_SIGNER_PRIVATE_KEYS[UNRELATED_SIGNER1]), { from: guardian } ) - assertEvent(tx, 'StakingModuleStatusSet', { - expectedArgs: { + assert.emits( + tx, + 'StakingModuleStatusSet', + { stakingModuleId: STAKING_MODULE, status: StakingModuleStatus.DepositsPaused, - setBy: depositSecurityModule, + setBy: depositSecurityModule.address, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, - }) + { + abi: StakingRouterMockForDepositSecurityModule.abi, + } + ) }) it('reverts if called by a guardian with an expired blockNumber', async () => { const staleBlockNumber = block.number - PAUSE_INTENT_VALIDITY_PERIOD_BLOCKS - await assertRevert( + await assert.reverts( depositSecurityModule.pauseDeposits( staleBlockNumber, STAKING_MODULE, @@ -590,7 +615,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { }) it("reverts if called by an anon submitting a guardian's sig but with an expired `blockNumber`", async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.pauseDeposits( stalePauseMessage.blockNumber, STAKING_MODULE, @@ -615,7 +640,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { it('reverts if called by a guardian with a future blockNumber', async () => { const futureBlockNumber = block.number + 100 - await assertRevert( + await assert.reverts( depositSecurityModule.pauseDeposits(futureBlockNumber, STAKING_MODULE, ['0x', '0x'], { from: guardian }) ) }) @@ -623,7 +648,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { it("reverts if called by an anon submitting a guardian's sig with a future blockNumber", async () => { const futureBlockNumber = block.number + 100 const sig = new DSMPauseMessage(futureBlockNumber, STAKING_MODULE).sign(GUARDIAN_PRIVATE_KEYS[GUARDIAN2]) - await assertRevert( + await assert.reverts( depositSecurityModule.pauseDeposits(futureBlockNumber, STAKING_MODULE, sig, { from: guardian }) ) }) @@ -632,15 +657,19 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const tx = await depositSecurityModule.pauseDeposits(block.number, STAKING_MODULE, ['0x', '0x'], { from: guardian, }) - assertEvent(tx, 'DepositsPaused', { expectedArgs: { guardian, stakingModuleId: STAKING_MODULE } }) - assertEvent(tx, 'StakingModuleStatusSet', { - expectedArgs: { + assert.emits(tx, 'DepositsPaused', { guardian, stakingModuleId: STAKING_MODULE }) + assert.emits( + tx, + 'StakingModuleStatusSet', + { stakingModuleId: STAKING_MODULE, status: StakingModuleStatus.DepositsPaused, - setBy: depositSecurityModule, + setBy: depositSecurityModule.address, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, - }) + { + abi: StakingRouterMockForDepositSecurityModule.abi, + } + ) }) it("pauseDeposits doesn't emit DepositsPaused(guardianAddr) event if was paused before", async () => { @@ -669,15 +698,19 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { }) it('unpauses paused deposits', async () => { const tx = await depositSecurityModule.unpauseDeposits(STAKING_MODULE, { from: owner }) - assertEvent(tx, 'DepositsUnpaused', { stakingModuleId: STAKING_MODULE }) - assertEvent(tx, 'StakingModuleStatusSet', { - expectedArgs: { + assert.emits(tx, 'DepositsUnpaused', { stakingModuleId: STAKING_MODULE }) + assert.emits( + tx, + 'StakingModuleStatusSet', + { stakingModuleId: STAKING_MODULE, status: StakingModuleStatus.Active, - setBy: depositSecurityModule, + setBy: depositSecurityModule.address, }, - decodeForAbi: StakingRouterMockForDepositSecurityModule._json.abi, - }) + { + abi: StakingRouterMockForDepositSecurityModule.abi, + } + ) }) it('unpauses paused deposits on active modules no events', async () => { @@ -697,7 +730,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { }) it('cannot be called by non-admin', async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.unpauseDeposits(STAKING_MODULE, { from: stranger }), `NotAnOwner("${stranger}")` ) @@ -709,7 +742,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.equal((await depositSecurityModule.getGuardians()).length, 0) }) it(`addGuardian can't be called by non-admin`, async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.addGuardian(GUARDIAN1, 0, { from: stranger }), `NotAnOwner("${stranger}")` ) @@ -745,13 +778,13 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { }) it(`addGuardian doesn't add duplicate`, async () => { await depositSecurityModule.addGuardian(GUARDIAN1, 0, { from: owner }) - await assertRevert( + await assert.reverts( depositSecurityModule.addGuardian(GUARDIAN1, 0, { from: owner }), `DuplicateAddress("${GUARDIAN1}")` ) }) it(`addGuardians can't be called by non-admin`, async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.addGuardians([GUARDIAN1], 0, { from: stranger }), `NotAnOwner("${stranger}")` ) @@ -765,24 +798,24 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.isTrue((await depositSecurityModule.getGuardians()).includes(GUARDIAN2)) }) it(`addGuardians doesn't add a set with duplicate`, async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.addGuardians([GUARDIAN1, GUARDIAN1], 0, { from: owner }), `DuplicateAddress("${GUARDIAN1}")` ) await depositSecurityModule.addGuardians([GUARDIAN1], 0, { from: owner }) - await assertRevert( + await assert.reverts( depositSecurityModule.addGuardians([GUARDIAN1, GUARDIAN2], 0, { from: owner }), `DuplicateAddress("${GUARDIAN1}")` ) }) it(`removeGuardian can't be called by non-admin`, async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.removeGuardian(GUARDIAN1, 0, { from: stranger }), `NotAnOwner("${stranger}")` ) }) it(`removeGuardian reverts on incorrect address`, async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.removeGuardian(GUARDIAN1, 0, { from: owner }), `NotAGuardian("${GUARDIAN1}")` ) @@ -871,7 +904,10 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.isTrue((await depositSecurityModule.getGuardians()).includes(GUARDIAN1)) }) it(`setGuardianQuorum can't be called by non-admin`, async () => { - await assertRevert(depositSecurityModule.setGuardianQuorum(1, { from: stranger }), `NotAnOwner("${stranger}")`) + await assert.reverts( + depositSecurityModule.setGuardianQuorum(1, { from: stranger }), + `NotAnOwner("${stranger}")` + ) }) it(`setGuardianQuorum sets the quorum`, async () => { await depositSecurityModule.setGuardianQuorum(1, { from: owner }) @@ -897,11 +933,9 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const quorum2 = await depositSecurityModule.getGuardianQuorum() assert.equal(quorum2, 2) - assertEvent(tx1, 'GuardianQuorumChanged', { - expectedArgs: { newValue: quorum1 }, - }) + assert.emits(tx1, 'GuardianQuorumChanged', { newValue: quorum1 }) - await assertNoEvent(tx2, 'GuardianQuorumChanged') + await assert.notEmits(tx2, 'GuardianQuorumChanged') }) }) }) @@ -910,21 +944,21 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.equal(await depositSecurityModule.getOwner(), owner, 'wrong initial owner') }) it('not owner cannot change', async () => { - await assertRevert(depositSecurityModule.setOwner(stranger, { from: stranger }), `NotAnOwner("${stranger}")`) + await assert.reverts(depositSecurityModule.setOwner(stranger, { from: stranger }), `NotAnOwner("${stranger}")`) }) it('set new owner to zero address should reverts', async () => { - await assertRevert(depositSecurityModule.setOwner(ZERO_ADDRESS, { from: owner }), 'ZeroAddress("_newOwner")') + await assert.reverts(depositSecurityModule.setOwner(ZERO_ADDRESS, { from: owner }), 'ZeroAddress("_newOwner")') }) it('set new owner by owner', async () => { - assertEvent(await depositSecurityModule.setOwner(stranger, { from: owner }), 'OwnerChanged', { - expectedArgs: { newValue: stranger }, + assert.emits(await depositSecurityModule.setOwner(stranger, { from: owner }), 'OwnerChanged', { + newValue: stranger, }) assert.equal(await depositSecurityModule.getOwner(), stranger, 'owner not changed') }) }) describe('levers', () => { it('pauseIntentValidityPeriodBlocks should be gt 0', async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.setPauseIntentValidityPeriodBlocks(0, { from: owner }), 'ZeroParameter("pauseIntentValidityPeriodBlocks")' ) @@ -944,13 +978,13 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { newPauseIntentValidityPeriodBlocks, 'invalid result: pauseIntentValidityPeriodBlocks' ) - assertEvent(tx, 'PauseIntentValidityPeriodBlocksChanged', { - expectedArgs: { newValue: newPauseIntentValidityPeriodBlocks }, + assert.emits(tx, 'PauseIntentValidityPeriodBlocksChanged', { + newValue: newPauseIntentValidityPeriodBlocks, }) }) it('setPauseIntentValidityPeriodBlocks reverts if called not by owner', async () => { const newPauseIntentValidityPeriodBlocks = PAUSE_INTENT_VALIDITY_PERIOD_BLOCKS + 1 - await assertRevert( + await assert.reverts( depositSecurityModule.setPauseIntentValidityPeriodBlocks(newPauseIntentValidityPeriodBlocks, { from: stranger }) ) }) @@ -959,16 +993,14 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.notEqual(await depositSecurityModule.getMaxDeposits(), newMaxDeposits, 'invariant failed: maxDeposits') const tx = await depositSecurityModule.setMaxDeposits(newMaxDeposits, { from: owner }) assert.equal(await depositSecurityModule.getMaxDeposits(), newMaxDeposits, 'invalid result: setMaxDeposits') - assertEvent(tx, 'MaxDepositsChanged', { - expectedArgs: { newValue: newMaxDeposits }, - }) + assert.emits(tx, 'MaxDepositsChanged', { newValue: newMaxDeposits }) }) it('setMaxDeposits reverts if called not by owner', async () => { const newMaxDeposits = MAX_DEPOSITS_PER_BLOCK + 1 - await assertRevert(depositSecurityModule.setMaxDeposits(newMaxDeposits, { from: stranger })) + await assert.reverts(depositSecurityModule.setMaxDeposits(newMaxDeposits, { from: stranger })) }) it('minDepositBlockDistance should be gt 0', async () => { - await assertRevert( + await assert.reverts( depositSecurityModule.setMinDepositBlockDistance(0, { from: owner }), 'ZeroParameter("minDepositBlockDistance")' ) @@ -986,13 +1018,11 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { newMinDepositBlockDistance, 'invalid result: setMinDepositBlockDistance' ) - assertEvent(tx, 'MinDepositBlockDistanceChanged', { - expectedArgs: { newValue: newMinDepositBlockDistance }, - }) + assert.emits(tx, 'MinDepositBlockDistanceChanged', { newValue: newMinDepositBlockDistance }) }) it('setMinDepositBlockDistance reverts if called not by owner', async () => { const newMinDepositBlockDistance = MIN_DEPOSIT_BLOCK_DISTANCE + 1 - await assertRevert( + await assert.reverts( depositSecurityModule.setMinDepositBlockDistance(newMinDepositBlockDistance, { from: stranger }) ) }) @@ -1001,12 +1031,9 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { const DEPOSIT_NONCE = 12 const DEPOSIT_ROOT = '0xd151867719c94ad8458feaf491809f9bc8096c702a72747403ecaac30c179137' - let validAttestMessage - beforeEach(async () => { await depositContractMock.set_deposit_root(DEPOSIT_ROOT) await stakingRouterMock.setStakingModuleNonce(DEPOSIT_NONCE) - validAttestMessage = new DSMAttestMessage(block.number, block.hash, DEPOSIT_ROOT, STAKING_MODULE, DEPOSIT_NONCE) }) it('true if not paused and quorum > 0 and currentBlock - lastDepositBlock >= minDepositBlockDistance', async () => { @@ -1090,6 +1117,7 @@ contract('DepositSecurityModule', ([owner, stranger, guardian]) => { assert.isTrue(currentBlockNumber - lastDepositBlockNumber < minDepositBlockDistance) assert.isFalse(await depositSecurityModule.canDeposit(STAKING_MODULE)) }) + it('false if Lido cant deposit', async () => { await depositSecurityModule.addGuardian(GUARDIAN1, 1, { from: owner }) diff --git a/test/0.8.9/lido-exec-layer-rewards-vault.js b/test/0.8.9/lido-exec-layer-rewards-vault.test.js similarity index 61% rename from test/0.8.9/lido-exec-layer-rewards-vault.js rename to test/0.8.9/lido-exec-layer-rewards-vault.test.js index 3d258f5d8..d7070dd95 100644 --- a/test/0.8.9/lido-exec-layer-rewards-vault.js +++ b/test/0.8.9/lido-exec-layer-rewards-vault.test.js @@ -1,13 +1,12 @@ -const hre = require('hardhat') +const { ethers, contract, artifacts, web3 } = require('hardhat') -const { assertBn, assertEvent } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../helpers/assertThrow') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') +const { bn } = require('@aragon/contract-helpers-test') const { StETH, ETH } = require('../helpers/utils') const { assert } = require('../helpers/assert') const { deployProtocol } = require('../helpers/protocol') const { EvmSnapshot } = require('../helpers/blockchain') +const { ZERO_ADDRESS } = require('../helpers/constants') const ERC20OZMock = artifacts.require('ERC20OZMock.sol') const ERC721OZMock = artifacts.require('ERC721OZMock.sol') @@ -23,7 +22,7 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { treasury = deployed.treasury.address appManager = deployed.appManager.address - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() }) @@ -32,21 +31,21 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { }) it('Addresses which are not Lido contract cannot withdraw from execution layer rewards vault', async () => { - await assertRevert(elRewardsVault.withdrawRewards(12345, { from: anotherAccount }), 'ONLY_LIDO_CAN_WITHDRAW') - await assertRevert(elRewardsVault.withdrawRewards(12345, { from: deployer }), 'ONLY_LIDO_CAN_WITHDRAW') - await assertRevert(elRewardsVault.withdrawRewards(12345, { from: appManager }), 'ONLY_LIDO_CAN_WITHDRAW') + await assert.reverts(elRewardsVault.withdrawRewards(12345, { from: anotherAccount }), 'ONLY_LIDO_CAN_WITHDRAW') + await assert.reverts(elRewardsVault.withdrawRewards(12345, { from: deployer }), 'ONLY_LIDO_CAN_WITHDRAW') + await assert.reverts(elRewardsVault.withdrawRewards(12345, { from: appManager }), 'ONLY_LIDO_CAN_WITHDRAW') }) it('Execution layer rewards vault can receive Ether by plain transfers (no call data)', async () => { const before = +(await web3.eth.getBalance(elRewardsVault.address)).toString() const amount = 0.02 await web3.eth.sendTransaction({ to: elRewardsVault.address, from: anotherAccount, value: ETH(amount) }) - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(before + amount)) + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(before + amount)) }) it('Execution layer rewards vault refuses to receive Ether by transfers with call data', async () => { const amount = 0.02 - await assertRevert( + await assert.reverts( web3.eth.sendTransaction({ to: elRewardsVault.address, from: anotherAccount, @@ -72,8 +71,8 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { mockERC20Token = await ERC20OZMock.new(totalERC20Supply, { from: deployer }) - assertBn(await mockERC20Token.totalSupply(), totalERC20Supply) - assertBn(await mockERC20Token.balanceOf(deployer), totalERC20Supply) + assert.equals(await mockERC20Token.totalSupply(), totalERC20Supply) + assert.equals(await mockERC20Token.balanceOf(deployer), totalERC20Supply) await mockERC20Token.balanceOf(deployer) @@ -82,31 +81,31 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { await mockNFT.mintToken(nft1, { from: deployer }) await mockNFT.mintToken(nft2, { from: deployer }) - assertBn(await mockNFT.balanceOf(deployer), bn(2)) + assert.equals(await mockNFT.balanceOf(deployer), bn(2)) assert.equal(await mockNFT.ownerOf(nft1), deployer) assert.equal(await mockNFT.ownerOf(nft2), deployer) }) it(`can't recover zero ERC20 amount`, async () => { - await assertRevert(elRewardsVault.recoverERC20(mockERC20Token.address, bn(0)), `ZERO_RECOVERY_AMOUNT`) + await assert.reverts(elRewardsVault.recoverERC20(mockERC20Token.address, bn(0)), `ZERO_RECOVERY_AMOUNT`) }) it(`can't recover zero-address ERC20`, async () => { - await assertRevert(elRewardsVault.recoverERC20(ZERO_ADDRESS, bn(10))) + await assert.reverts(elRewardsVault.recoverERC20(ZERO_ADDRESS, bn(10))) }) it(`can't recover stETH by recoverERC20`, async () => { // initial stETH balance is zero - assertBn(await lido.balanceOf(anotherAccount), StETH(0)) + assert.equals(await lido.balanceOf(anotherAccount), StETH(0)) // submit 10 ETH to mint 10 stETH await web3.eth.sendTransaction({ from: anotherAccount, to: lido.address, value: ETH(10) }) // check 10 stETH minted on balance - assertBn(await lido.balanceOf(anotherAccount), StETH(10)) + assert.equals(await lido.balanceOf(anotherAccount), StETH(10)) // transfer 5 stETH to the elRewardsVault account await lido.transfer(elRewardsVault.address, StETH(5), { from: anotherAccount }) - assertBn(await lido.balanceOf(anotherAccount), StETH(5)) - assertBn(await lido.balanceOf(elRewardsVault.address), StETH(5)) + assert.equals(await lido.balanceOf(anotherAccount), StETH(5)) + assert.equals(await lido.balanceOf(elRewardsVault.address), StETH(5)) }) it(`recover some accidentally sent ERC20`, async () => { @@ -115,46 +114,52 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { await mockERC20Token.transfer(elRewardsVault.address, bn(600000), { from: deployer }) // check the resulted state - assertBn(await mockERC20Token.balanceOf(deployer), bn(0)) - assertBn(await mockERC20Token.balanceOf(anotherAccount), bn(400000)) - assertBn(await mockERC20Token.balanceOf(elRewardsVault.address), bn(600000)) + assert.equals(await mockERC20Token.balanceOf(deployer), bn(0)) + assert.equals(await mockERC20Token.balanceOf(anotherAccount), bn(400000)) + assert.equals(await mockERC20Token.balanceOf(elRewardsVault.address), bn(600000)) // recover ERC20 const firstReceipt = await elRewardsVault.recoverERC20(mockERC20Token.address, bn(100000), { from: deployer }) - assertEvent(firstReceipt, `ERC20Recovered`, { - expectedArgs: { requestedBy: deployer, token: mockERC20Token.address, amount: bn(100000) }, + assert.emits(firstReceipt, `ERC20Recovered`, { + requestedBy: deployer, + token: mockERC20Token.address, + amount: bn(100000), }) const secondReceipt = await elRewardsVault.recoverERC20(mockERC20Token.address, bn(400000), { from: anotherAccount, }) - assertEvent(secondReceipt, `ERC20Recovered`, { - expectedArgs: { requestedBy: anotherAccount, token: mockERC20Token.address, amount: bn(400000) }, + assert.emits(secondReceipt, `ERC20Recovered`, { + requestedBy: anotherAccount, + token: mockERC20Token.address, + amount: bn(400000), }) // check balances again - assertBn(await mockERC20Token.balanceOf(elRewardsVault.address), bn(100000)) - assertBn(await mockERC20Token.balanceOf(treasury), bn(500000)) - assertBn(await mockERC20Token.balanceOf(deployer), bn(0)) - assertBn(await mockERC20Token.balanceOf(anotherAccount), bn(400000)) + assert.equals(await mockERC20Token.balanceOf(elRewardsVault.address), bn(100000)) + assert.equals(await mockERC20Token.balanceOf(treasury), bn(500000)) + assert.equals(await mockERC20Token.balanceOf(deployer), bn(0)) + assert.equals(await mockERC20Token.balanceOf(anotherAccount), bn(400000)) // recover last portion const lastReceipt = await elRewardsVault.recoverERC20(mockERC20Token.address, bn(100000), { from: anotherAccount, }) - assertEvent(lastReceipt, `ERC20Recovered`, { - expectedArgs: { requestedBy: anotherAccount, token: mockERC20Token.address, amount: bn(100000) }, + assert.emits(lastReceipt, `ERC20Recovered`, { + requestedBy: anotherAccount, + token: mockERC20Token.address, + amount: bn(100000), }) // balance is zero already, have to be reverted - await assertRevert( + await assert.reverts( elRewardsVault.recoverERC20(mockERC20Token.address, bn(1), { from: deployer }), `ERC20: transfer amount exceeds balance` ) }) it(`can't recover zero-address ERC721(NFT)`, async () => { - await assertRevert(elRewardsVault.recoverERC721(ZERO_ADDRESS, 0)) + await assert.reverts(elRewardsVault.recoverERC721(ZERO_ADDRESS, 0)) }) it(`recover some accidentally sent NFTs`, async () => { @@ -163,18 +168,20 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { await mockNFT.transferFrom(deployer, elRewardsVault.address, nft2, { from: deployer }) // check the new holders' rights - assertBn(await mockNFT.balanceOf(deployer), bn(0)) - assertBn(await mockNFT.balanceOf(anotherAccount), bn(1)) - assertBn(await mockNFT.balanceOf(elRewardsVault.address), bn(1)) + assert.equals(await mockNFT.balanceOf(deployer), bn(0)) + assert.equals(await mockNFT.balanceOf(anotherAccount), bn(1)) + assert.equals(await mockNFT.balanceOf(elRewardsVault.address), bn(1)) // recover nft2 should work const receiptNfc2 = await elRewardsVault.recoverERC721(mockNFT.address, nft2, { from: anotherAccount }) - assertEvent(receiptNfc2, `ERC721Recovered`, { - expectedArgs: { requestedBy: anotherAccount, token: mockNFT.address, tokenId: nft2 }, + assert.emits(receiptNfc2, `ERC721Recovered`, { + requestedBy: anotherAccount, + token: mockNFT.address, + tokenId: nft2, }) // but nft1 recovery should revert - await assertRevert( + await assert.reverts( elRewardsVault.recoverERC721(mockNFT.address, nft1), `ERC721: transfer caller is not owner nor approved` ) @@ -183,14 +190,16 @@ contract('LidoExecutionLayerRewardsVault', ([deployer, anotherAccount]) => { await mockNFT.transferFrom(anotherAccount, elRewardsVault.address, nft1, { from: anotherAccount }) const receiptNft1 = await elRewardsVault.recoverERC721(mockNFT.address, nft1, { from: deployer }) - assertEvent(receiptNft1, `ERC721Recovered`, { - expectedArgs: { requestedBy: deployer, token: mockNFT.address, tokenId: nft1 }, + assert.emits(receiptNft1, `ERC721Recovered`, { + requestedBy: deployer, + token: mockNFT.address, + tokenId: nft1, }) // check final NFT ownership state - assertBn(await mockNFT.balanceOf(treasury), bn(2)) - assertBn(await mockNFT.ownerOf(nft1), treasury) - assertBn(await mockNFT.ownerOf(nft2), treasury) + assert.equals(await mockNFT.balanceOf(treasury), bn(2)) + assert.equals(await mockNFT.ownerOf(nft1), treasury) + assert.equals(await mockNFT.ownerOf(nft2), treasury) }) }) }) diff --git a/test/0.8.9/lido-locator.test.js b/test/0.8.9/lido-locator.test.js index bfc16fd53..9eb70095d 100644 --- a/test/0.8.9/lido-locator.test.js +++ b/test/0.8.9/lido-locator.test.js @@ -1,7 +1,9 @@ -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') -const hre = require('hardhat') +const { ethers, contract, artifacts } = require('hardhat') + +const { ZERO_ADDRESS } = require('../helpers/constants') const { assert } = require('../helpers/assert') const { locatorServices, getRandomLocatorConfig } = require('../helpers/locator') + const Proxy = artifacts.require('OssifiableProxy.sol') const LidoLocator = artifacts.require('LidoLocator.sol') @@ -16,12 +18,12 @@ contract('LidoLocator', ([deployer, agent]) => { proxy = await Proxy.new(implementation.address, agent, '0x', { from: deployer }) lidoLocatorProxy = await LidoLocator.at(proxy.address) - evmSnapshotId = await hre.ethers.provider.send('evm_snapshot', []) + evmSnapshotId = await ethers.provider.send('evm_snapshot', []) }) afterEach(async () => { - await hre.ethers.provider.send('evm_revert', [evmSnapshotId]) - evmSnapshotId = await hre.ethers.provider.send('evm_snapshot', []) + await ethers.provider.send('evm_revert', [evmSnapshotId]) + evmSnapshotId = await ethers.provider.send('evm_snapshot', []) }) describe('checking initial implementation', () => { diff --git a/test/0.8.9/oracle-daemon-config.test.js b/test/0.8.9/oracle-daemon-config.test.js index 81f186b65..bae27a78c 100644 --- a/test/0.8.9/oracle-daemon-config.test.js +++ b/test/0.8.9/oracle-daemon-config.test.js @@ -1,10 +1,10 @@ -const hre = require('hardhat') -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { ethers, artifacts, contract } = require('hardhat') +const { ZERO_ADDRESS } = require('../helpers/constants') const { assert } = require('../helpers/assert') const { EvmSnapshot } = require('../helpers/blockchain') -const OracleDaemonConfig = hre.artifacts.require('OracleDaemonConfig.sol') +const OracleDaemonConfig = artifacts.require('OracleDaemonConfig.sol') contract('OracleDaemonConfig', async ([deployer, manager, stranger]) => { let config, snapshot @@ -14,7 +14,7 @@ contract('OracleDaemonConfig', async ([deployer, manager, stranger]) => { before(async () => { config = await OracleDaemonConfig.new(deployer, [manager], { from: deployer }) - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() }) diff --git a/test/0.8.9/oracle-report-sanity-checker.test.js b/test/0.8.9/oracle-report-sanity-checker.test.js index 6f3ed1ab4..15ed998ff 100644 --- a/test/0.8.9/oracle-report-sanity-checker.test.js +++ b/test/0.8.9/oracle-report-sanity-checker.test.js @@ -1,13 +1,13 @@ -const hre = require('hardhat') +const { artifacts, contract, ethers } = require('hardhat') const { ETH } = require('../helpers/utils') const { assert } = require('../helpers/assert') const { getCurrentBlockTimestamp } = require('../helpers/blockchain') const mocksFilePath = 'contracts/0.8.9/test_helpers/OracleReportSanityCheckerMocks.sol' -const LidoStub = hre.artifacts.require(`${mocksFilePath}:LidoStub`) -const OracleReportSanityChecker = hre.artifacts.require('OracleReportSanityChecker') -const LidoLocatorStub = hre.artifacts.require(`${mocksFilePath}:LidoLocatorStub`) -const WithdrawalQueueStub = hre.artifacts.require(`${mocksFilePath}:WithdrawalQueueStub`) +const LidoStub = artifacts.require(`${mocksFilePath}:LidoStub`) +const OracleReportSanityChecker = artifacts.require('OracleReportSanityChecker') +const LidoLocatorStub = artifacts.require(`${mocksFilePath}:LidoLocatorStub`) +const WithdrawalQueueStub = artifacts.require(`${mocksFilePath}:WithdrawalQueueStub`) function wei(number, units = 'wei') { switch (units.toLowerCase()) { @@ -57,7 +57,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa before(async () => { // mine 1024 blocks with block duration 12 seconds - await hre.ethers.provider.send('hardhat_mine', ['0x' + Number(1024).toString(16), '0x' + Number(12).toString(16)]) + await ethers.provider.send('hardhat_mine', ['0x' + Number(1024).toString(16), '0x' + Number(12).toString(16)]) lidoMock = await LidoStub.new({ from: deployer }) withdrawalQueueMock = await WithdrawalQueueStub.new({ from: deployer }) lidoLocatorMock = await LidoLocatorStub.new( @@ -143,7 +143,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa }) it('reverts with error IncorrectWithdrawalsVaultBalance() when actual withdrawal vault balance is less than passed', async () => { - const currentWithdrawalVaultBalance = await hre.ethers.provider.getBalance(withdrawalVault) + const currentWithdrawalVaultBalance = await ethers.provider.getBalance(withdrawalVault) await assert.revertsWithCustomError( oracleReportSanityChecker.checkAccountingOracleReport( ...Object.values({ ...correctLidoOracleReport, withdrawalVaultBalance: currentWithdrawalVaultBalance.add(1) }) @@ -153,7 +153,7 @@ contract('OracleReportSanityChecker', ([deployer, admin, withdrawalVault, elRewa }) it('reverts with error IncorrectELRewardsVaultBalance() when actual el rewards vault balance is less than passed', async () => { - const currentELRewardsVaultBalance = await hre.ethers.provider.getBalance(elRewardsVault) + const currentELRewardsVaultBalance = await ethers.provider.getBalance(elRewardsVault) await assert.revertsWithCustomError( oracleReportSanityChecker.checkAccountingOracleReport( ...Object.values({ ...correctLidoOracleReport, elRewardsVaultBalance: currentELRewardsVaultBalance.add(1) }) diff --git a/test/0.8.9/oracle/accounting-oracle-access-control.test.js b/test/0.8.9/oracle/accounting-oracle-access-control.test.js index e126a3ccc..4c3eff0da 100644 --- a/test/0.8.9/oracle/accounting-oracle-access-control.test.js +++ b/test/0.8.9/oracle/accounting-oracle-access-control.test.js @@ -1,3 +1,4 @@ +const { contract, web3 } = require('hardhat') const { assert } = require('../../helpers/assert') const { e9, e18, e27 } = require('../../helpers/utils') diff --git a/test/0.8.9/oracle/accounting-oracle-deploy.test.js b/test/0.8.9/oracle/accounting-oracle-deploy.test.js index 3fbff1b2c..7775ac1b7 100644 --- a/test/0.8.9/oracle/accounting-oracle-deploy.test.js +++ b/test/0.8.9/oracle/accounting-oracle-deploy.test.js @@ -1,4 +1,5 @@ -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { artifacts, contract, web3 } = require('hardhat') +const { ZERO_ADDRESS } = require('../../helpers/constants') const { assert } = require('../../helpers/assert') const { hex } = require('../../helpers/utils') const { @@ -31,7 +32,6 @@ const { } = require('./hash-consensus-deploy.test') const AccountingOracle = artifacts.require('AccountingOracleTimeTravellable') -const LidoLocator = artifacts.require('LidoLocator') const MockLido = artifacts.require('MockLidoForAccountingOracle') const MockStakingRouter = artifacts.require('MockStakingRouterForAccountingOracle') const MockWithdrawalQueue = artifacts.require('MockWithdrawalQueueForAccountingOracle') @@ -256,10 +256,10 @@ async function initAccountingOracle({ await oracle.grantRole(await oracle.SUBMIT_DATA_ROLE(), dataSubmitter, { from: admin }) } - assert.equal(+(await oracle.EXTRA_DATA_FORMAT_EMPTY()), EXTRA_DATA_FORMAT_EMPTY) - assert.equal(+(await oracle.EXTRA_DATA_FORMAT_LIST()), EXTRA_DATA_FORMAT_LIST) - assert.equal(+(await oracle.EXTRA_DATA_TYPE_STUCK_VALIDATORS()), EXTRA_DATA_TYPE_STUCK_VALIDATORS) - assert.equal(+(await oracle.EXTRA_DATA_TYPE_EXITED_VALIDATORS()), EXTRA_DATA_TYPE_EXITED_VALIDATORS) + assert.equals((await oracle.EXTRA_DATA_FORMAT_EMPTY()), EXTRA_DATA_FORMAT_EMPTY) + assert.equals((await oracle.EXTRA_DATA_FORMAT_LIST()), EXTRA_DATA_FORMAT_LIST) + assert.equals((await oracle.EXTRA_DATA_TYPE_STUCK_VALIDATORS()), EXTRA_DATA_TYPE_STUCK_VALIDATORS) + assert.equals((await oracle.EXTRA_DATA_TYPE_EXITED_VALIDATORS()), EXTRA_DATA_TYPE_EXITED_VALIDATORS) return initTx } @@ -338,25 +338,25 @@ contract('AccountingOracle', ([admin, member1]) => { it('mock setup is correct', async () => { // check the mock time-travellable setup const time1 = +(await consensus.getTime()) - assert.equal(+(await oracle.getTime()), time1) + assert.equals((await oracle.getTime()), time1) await consensus.advanceTimeBy(SECONDS_PER_SLOT) const time2 = +(await consensus.getTime()) assert.equal(time2, time1 + SECONDS_PER_SLOT) - assert.equal(+(await oracle.getTime()), time2) + assert.equals((await oracle.getTime()), time2) const handleOracleReportCallData = await mockLido.getLastCall_handleOracleReport() - assert.equal(+handleOracleReportCallData.callCount, 0) + assert.equals(handleOracleReportCallData.callCount, 0) const updateExitedKeysByModuleCallData = await mockStakingRouter.lastCall_updateExitedKeysByModule() - assert.equal(+updateExitedKeysByModuleCallData.callCount, 0) + assert.equals(updateExitedKeysByModuleCallData.callCount, 0) - assert.equal(+(await mockStakingRouter.totalCalls_reportExitedKeysByNodeOperator()), 0) - assert.equal(+(await mockStakingRouter.totalCalls_reportStuckKeysByNodeOperator()), 0) + assert.equals((await mockStakingRouter.totalCalls_reportExitedKeysByNodeOperator()), 0) + assert.equals((await mockStakingRouter.totalCalls_reportStuckKeysByNodeOperator()), 0) const updateBunkerModeLastCall = await mockWithdrawalQueue.lastCall__updateBunkerMode() - assert.equal(+updateBunkerModeLastCall.callCount, 0) + assert.equals(updateBunkerModeLastCall.callCount, 0) }) it('the initial reference slot is greater than the last one of the legacy oracle', async () => { @@ -366,9 +366,9 @@ contract('AccountingOracle', ([admin, member1]) => { it('initial configuration is correct', async () => { assert.equal(await oracle.getConsensusContract(), consensus.address) - assert.equal(+(await oracle.getConsensusVersion()), CONSENSUS_VERSION) + assert.equals((await oracle.getConsensusVersion()), CONSENSUS_VERSION) assert.equal(await oracle.LIDO(), mockLido.address) - assert.equal(+(await oracle.SECONDS_PER_SLOT()), SECONDS_PER_SLOT) + assert.equals((await oracle.SECONDS_PER_SLOT()), SECONDS_PER_SLOT) }) it('reverts if lido locator address is zero', async () => { diff --git a/test/0.8.9/oracle/accounting-oracle-happy-path.test.js b/test/0.8.9/oracle/accounting-oracle-happy-path.test.js index b2a5dae85..539033bac 100644 --- a/test/0.8.9/oracle/accounting-oracle-happy-path.test.js +++ b/test/0.8.9/oracle/accounting-oracle-happy-path.test.js @@ -1,5 +1,5 @@ +const { contract } = require('hardhat') const { assert } = require('../../helpers/assert') -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') const { e9, e18, e27, hex } = require('../../helpers/utils') const { @@ -69,31 +69,27 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const report = await oracle.getConsensusReport() assert.equal(report.hash, ZERO_HASH) // see the next test for refSlot - assert.equal(+report.processingDeadlineTime, 0) + assert.equals(report.processingDeadlineTime, 0) assert.isFalse(report.processingStarted) const frame = await consensus.getCurrentFrame() const procState = await oracle.getProcessingState() - assert.equal(+procState.currentFrameRefSlot, +frame.refSlot) - assert.equal(+procState.processingDeadlineTime, 0) + assert.equals(procState.currentFrameRefSlot, +frame.refSlot) + assert.equals(procState.processingDeadlineTime, 0) assert.equal(procState.mainDataHash, ZERO_HASH) assert.isFalse(procState.mainDataSubmitted) assert.equal(procState.extraDataHash, ZERO_HASH) - assert.equal(+procState.extraDataFormat, 0) + assert.equals(procState.extraDataFormat, 0) assert.isFalse(procState.extraDataSubmitted) - assert.equal(+procState.extraDataItemsCount, 0) - assert.equal(+procState.extraDataItemsSubmitted, 0) + assert.equals(procState.extraDataItemsCount, 0) + assert.equals(procState.extraDataItemsSubmitted, 0) }) - it( - `reference slot of the empty initial consensus report is set to the last processed slot ` + - `of the legacy oracle`, - async () => { - const report = await oracle.getConsensusReport() - assert.equal(+report.refSlot, V1_ORACLE_LAST_REPORT_SLOT) - } - ) + it(`reference slot of the empty initial consensus report is set to the last processed slot of the legacy oracle`, async () => { + const report = await oracle.getConsensusReport() + assert.equals(report.refSlot, V1_ORACLE_LAST_REPORT_SLOT) + }) it('committee reaches consensus on a report hash', async () => { const { refSlot } = await consensus.getCurrentFrame() @@ -140,22 +136,22 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { it('oracle gets the report hash', async () => { const report = await oracle.getConsensusReport() assert.equal(report.hash, reportHash) - assert.equal(+report.refSlot, +reportFields.refSlot) - assert.equal(+report.processingDeadlineTime, computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME)) + assert.equals(report.refSlot, +reportFields.refSlot) + assert.equals(report.processingDeadlineTime, computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME)) assert.isFalse(report.processingStarted) const frame = await consensus.getCurrentFrame() const procState = await oracle.getProcessingState() - assert.equal(+procState.currentFrameRefSlot, +frame.refSlot) - assert.equal(+procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) + assert.equals(procState.currentFrameRefSlot, +frame.refSlot) + assert.equals(procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.equal(procState.mainDataHash, reportHash) assert.isFalse(procState.mainDataSubmitted) assert.equal(procState.extraDataHash, ZERO_HASH) - assert.equal(+procState.extraDataFormat, 0) + assert.equals(procState.extraDataFormat, 0) assert.isFalse(procState.extraDataSubmitted) - assert.equal(+procState.extraDataItemsCount, 0) - assert.equal(+procState.extraDataItemsSubmitted, 0) + assert.equals(procState.extraDataItemsCount, 0) + assert.equals(procState.extraDataItemsSubmitted, 0) }) it('some time passes', async () => { @@ -200,15 +196,15 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const frame = await consensus.getCurrentFrame() const procState = await oracle.getProcessingState() - assert.equal(+procState.currentFrameRefSlot, +frame.refSlot) - assert.equal(+procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) + assert.equals(procState.currentFrameRefSlot, +frame.refSlot) + assert.equals(procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.equal(procState.mainDataHash, reportHash) assert.isTrue(procState.mainDataSubmitted) assert.equal(procState.extraDataHash, reportFields.extraDataHash) - assert.equal(+procState.extraDataFormat, reportFields.extraDataFormat) + assert.equals(procState.extraDataFormat, reportFields.extraDataFormat) assert.isFalse(procState.extraDataSubmitted) - assert.equal(+procState.extraDataItemsCount, reportFields.extraDataItemsCount) - assert.equal(+procState.extraDataItemsSubmitted, 0) + assert.equals(procState.extraDataItemsCount, reportFields.extraDataItemsCount) + assert.equals(procState.extraDataItemsSubmitted, 0) }) it(`Lido got the oracle report`, async () => { @@ -218,18 +214,21 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { +lastOracleReportCall.secondsElapsedSinceLastReport, (reportFields.refSlot - V1_ORACLE_LAST_REPORT_SLOT) * SECONDS_PER_SLOT ) - assert.equal(+lastOracleReportCall.numValidators, reportFields.numValidators) - assertBn(lastOracleReportCall.clBalance, e9(reportFields.clBalanceGwei)) - assertBn(lastOracleReportCall.withdrawalVaultBalance, reportFields.withdrawalVaultBalance) - assertBn(lastOracleReportCall.elRewardsVaultBalance, reportFields.elRewardsVaultBalance) - assertBn(lastOracleReportCall.lastWithdrawalRequestIdToFinalize, reportFields.lastWithdrawalRequestIdToFinalize) - assertBn(lastOracleReportCall.finalizationShareRate, reportFields.finalizationShareRate) + assert.equals(lastOracleReportCall.numValidators, reportFields.numValidators) + assert.equals(lastOracleReportCall.clBalance, e9(reportFields.clBalanceGwei)) + assert.equals(lastOracleReportCall.withdrawalVaultBalance, reportFields.withdrawalVaultBalance) + assert.equals(lastOracleReportCall.elRewardsVaultBalance, reportFields.elRewardsVaultBalance) + assert.equals( + lastOracleReportCall.lastWithdrawalRequestIdToFinalize, + reportFields.lastWithdrawalRequestIdToFinalize + ) + assert.equals(lastOracleReportCall.finalizationShareRate, reportFields.finalizationShareRate) }) it(`withdrawal queue got bunker mode report`, async () => { const updateBunkerModeLastCall = await mockWithdrawalQueue.lastCall__updateBunkerMode() - assert.equal(+updateBunkerModeLastCall.callCount, 1) - assert.equal(+updateBunkerModeLastCall.isBunkerMode, reportFields.isBunkerMode) + assert.equals(updateBunkerModeLastCall.callCount, 1) + assert.equals(updateBunkerModeLastCall.isBunkerMode, reportFields.isBunkerMode) assert.equal( +updateBunkerModeLastCall.prevReportTimestamp, GENESIS_TIME + prevProcessingRefSlot * SECONDS_PER_SLOT @@ -251,10 +250,10 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { it(`legacy oracle got CL data report`, async () => { const lastLegacyOracleCall = await mockLegacyOracle.lastCall__handleConsensusLayerReport() - assert.equal(+lastLegacyOracleCall.totalCalls, 1) - assert.equal(+lastLegacyOracleCall.refSlot, reportFields.refSlot) - assert.equal(+lastLegacyOracleCall.clBalance, e9(reportFields.clBalanceGwei)) - assert.equal(+lastLegacyOracleCall.clValidators, reportFields.numValidators) + assert.equals(lastLegacyOracleCall.totalCalls, 1) + assert.equals(lastLegacyOracleCall.refSlot, reportFields.refSlot) + assert.equals(lastLegacyOracleCall.clBalance, e9(reportFields.clBalanceGwei)) + assert.equals(lastLegacyOracleCall.clValidators, reportFields.numValidators) }) it(`no data can be submitted for the same reference slot again`, async () => { @@ -308,15 +307,15 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const frame = await consensus.getCurrentFrame() const procState = await oracle.getProcessingState() - assert.equal(+procState.currentFrameRefSlot, +frame.refSlot) - assert.equal(+procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) + assert.equals(procState.currentFrameRefSlot, +frame.refSlot) + assert.equals(procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.equal(procState.mainDataHash, reportHash) assert.isTrue(procState.mainDataSubmitted) assert.equal(procState.extraDataHash, reportFields.extraDataHash) - assert.equal(+procState.extraDataFormat, reportFields.extraDataFormat) + assert.equals(procState.extraDataFormat, reportFields.extraDataFormat) assert.isTrue(procState.extraDataSubmitted) - assert.equal(+procState.extraDataItemsCount, reportFields.extraDataItemsCount) - assert.equal(+procState.extraDataItemsSubmitted, extraDataItems.length) + assert.equals(procState.extraDataItemsCount, reportFields.extraDataItemsCount) + assert.equals(procState.extraDataItemsSubmitted, extraDataItems.length) }) it('Staking router got the exited keys by node op report', async () => { @@ -324,12 +323,12 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { assert.equal(totalReportCalls, 2) const call1 = await mockStakingRouter.calls_reportExitedKeysByNodeOperator(0) - assert.equal(+call1.stakingModuleId, 2) + assert.equals(call1.stakingModuleId, 2) assert.equal(call1.nodeOperatorIds, '0x' + [1, 2].map((i) => hex(i, 8)).join('')) assert.equal(call1.keysCounts, '0x' + [1, 3].map((i) => hex(i, 16)).join('')) const call2 = await mockStakingRouter.calls_reportExitedKeysByNodeOperator(1) - assert.equal(+call2.stakingModuleId, 3) + assert.equals(call2.stakingModuleId, 3) assert.equal(call2.nodeOperatorIds, '0x' + [1].map((i) => hex(i, 8)).join('')) assert.equal(call2.keysCounts, '0x' + [2].map((i) => hex(i, 16)).join('')) }) @@ -339,17 +338,17 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { assert.equal(totalReportCalls, 3) const call1 = await mockStakingRouter.calls_reportStuckKeysByNodeOperator(0) - assert.equal(+call1.stakingModuleId, 1) + assert.equals(call1.stakingModuleId, 1) assert.equal(call1.nodeOperatorIds, '0x' + [0].map((i) => hex(i, 8)).join('')) assert.equal(call1.keysCounts, '0x' + [1].map((i) => hex(i, 16)).join('')) const call2 = await mockStakingRouter.calls_reportStuckKeysByNodeOperator(1) - assert.equal(+call2.stakingModuleId, 2) + assert.equals(call2.stakingModuleId, 2) assert.equal(call2.nodeOperatorIds, '0x' + [0].map((i) => hex(i, 8)).join('')) assert.equal(call2.keysCounts, '0x' + [2].map((i) => hex(i, 16)).join('')) const call3 = await mockStakingRouter.calls_reportStuckKeysByNodeOperator(2) - assert.equal(+call3.stakingModuleId, 3) + assert.equals(call3.stakingModuleId, 3) assert.equal(call3.nodeOperatorIds, '0x' + [2].map((i) => hex(i, 8)).join('')) assert.equal(call3.keysCounts, '0x' + [3].map((i) => hex(i, 16)).join('')) }) @@ -373,15 +372,15 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const frame = await consensus.getCurrentFrame() const procState = await oracle.getProcessingState() - assert.equal(+procState.currentFrameRefSlot, +frame.refSlot) - assert.equal(+procState.processingDeadlineTime, 0) + assert.equals(procState.currentFrameRefSlot, +frame.refSlot) + assert.equals(procState.processingDeadlineTime, 0) assert.equal(procState.mainDataHash, ZERO_HASH) assert.isFalse(procState.mainDataSubmitted) assert.equal(procState.extraDataHash, ZERO_HASH) - assert.equal(+procState.extraDataFormat, 0) + assert.equals(procState.extraDataFormat, 0) assert.isFalse(procState.extraDataSubmitted) - assert.equal(+procState.extraDataItemsCount, 0) - assert.equal(+procState.extraDataItemsSubmitted, 0) + assert.equals(procState.extraDataItemsCount, 0) + assert.equals(procState.extraDataItemsSubmitted, 0) }) it('new data report with empty extra data is agreed upon and submitted', async () => { @@ -410,7 +409,7 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { it(`withdrawal queue got bunker mode report`, async () => { const updateBunkerModeLastCall = await mockWithdrawalQueue.lastCall__updateBunkerMode() - assert.equal(+updateBunkerModeLastCall.callCount, 2) + assert.equals(updateBunkerModeLastCall.callCount, 2) }) it(`Staking router got the exited keys report`, async () => { @@ -437,15 +436,15 @@ contract('AccountingOracle', ([admin, member1, member2, member3, stranger]) => { const frame = await consensus.getCurrentFrame() const procState = await oracle.getProcessingState() - assert.equal(+procState.currentFrameRefSlot, +frame.refSlot) - assert.equal(+procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) + assert.equals(procState.currentFrameRefSlot, +frame.refSlot) + assert.equals(procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.equal(procState.mainDataHash, reportHash) assert.isTrue(procState.mainDataSubmitted) assert.equal(procState.extraDataHash, ZERO_HASH) - assert.equal(+procState.extraDataFormat, EXTRA_DATA_FORMAT_EMPTY) + assert.equals(procState.extraDataFormat, EXTRA_DATA_FORMAT_EMPTY) assert.isTrue(procState.extraDataSubmitted) - assert.equal(+procState.extraDataItemsCount, 0) - assert.equal(+procState.extraDataItemsSubmitted, 0) + assert.equals(procState.extraDataItemsCount, 0) + assert.equals(procState.extraDataItemsSubmitted, 0) }) it(`Staking router didn't get the exited keys by node op report`, async () => { diff --git a/test/0.8.9/oracle/accounting-oracle-submit-report-data.test.js b/test/0.8.9/oracle/accounting-oracle-submit-report-data.test.js index 4f5aee01a..3818656a4 100644 --- a/test/0.8.9/oracle/accounting-oracle-submit-report-data.test.js +++ b/test/0.8.9/oracle/accounting-oracle-submit-report-data.test.js @@ -1,3 +1,4 @@ +const { contract, web3 } = require('hardhat') const { assert } = require('../../helpers/assert') const { e9, e18, e27 } = require('../../helpers/utils') @@ -20,7 +21,7 @@ const { HASH_1, } = require('./accounting-oracle-deploy.test') -contract('AccountingOracle', ([admin, account1, account2, member1, member2, stranger]) => { +contract('AccountingOracle', ([admin, member1]) => { let consensus = null let oracle = null let reportItems = null @@ -472,19 +473,19 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra it('should call handleConsensusLayerReport on legacyOracle', async () => { await oracle.submitReportData(reportItems, oracleVersion, { from: member1 }) const lastCall = await mockLegacyOracle.lastCall__handleConsensusLayerReport() - assert.equal(+lastCall.totalCalls, 1) - assert.equal(+lastCall.refSlot, reportFields.refSlot) - assert.equal(+lastCall.clBalance, e9(reportFields.clBalanceGwei)) - assert.equal(+lastCall.clValidators, reportFields.numValidators) + assert.equals(lastCall.totalCalls, 1) + assert.equals(lastCall.refSlot, reportFields.refSlot) + assert.equals(lastCall.clBalance, e9(reportFields.clBalanceGwei)) + assert.equals(lastCall.clValidators, reportFields.numValidators) }) it('should call updateBunkerMode on WithdrawalQueue', async () => { const prevProcessingRefSlot = +(await oracle.getLastProcessingRefSlot()) await oracle.submitReportData(reportItems, oracleVersion, { from: member1 }) const lastCall = await mockWithdrawalQueue.lastCall__updateBunkerMode() - assert.equal(+lastCall.callCount, 1) - assert.equal(+lastCall.isBunkerMode, reportFields.isBunkerMode) - assert.equal(+lastCall.prevReportTimestamp, GENESIS_TIME + prevProcessingRefSlot * SECONDS_PER_SLOT) + assert.equals(lastCall.callCount, 1) + assert.equals(lastCall.isBunkerMode, reportFields.isBunkerMode) + assert.equals(lastCall.prevReportTimestamp, GENESIS_TIME + prevProcessingRefSlot * SECONDS_PER_SLOT) }) }) diff --git a/test/0.8.9/oracle/accounting-oracle-submit-report-extra-data.test.js b/test/0.8.9/oracle/accounting-oracle-submit-report-extra-data.test.js index b187dedf9..abe68f109 100644 --- a/test/0.8.9/oracle/accounting-oracle-submit-report-extra-data.test.js +++ b/test/0.8.9/oracle/accounting-oracle-submit-report-extra-data.test.js @@ -1,3 +1,4 @@ +const { contract } = require('hardhat') const { assert } = require('../../helpers/assert') const { e9, e18, e27, hex } = require('../../helpers/utils') @@ -558,7 +559,7 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra for (let i = 0; i < callsCount; i++) { const call = await stakingRouter.calls_reportStuckKeysByNodeOperator(i) const item = extraData.stuckKeys[i] - assert.equals(+call.stakingModuleId, item.moduleId) + assert.equals(call.stakingModuleId, item.moduleId) assert.equals(call.nodeOperatorIds, '0x' + item.nodeOpIds.map((id) => hex(id, 8)).join('')) assert.equals(call.keysCounts, '0x' + item.keysCounts.map((count) => hex(count, 16)).join('')) } @@ -574,14 +575,14 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra for (let i = 0; i < callsCount; i++) { const call = await stakingRouter.calls_reportExitedKeysByNodeOperator(i) const item = extraData.exitedKeys[i] - assert.equals(+call.stakingModuleId, item.moduleId) + assert.equals(call.stakingModuleId, item.moduleId) assert.equals(call.nodeOperatorIds, '0x' + item.nodeOpIds.map((id) => hex(id, 8)).join('')) assert.equals(call.keysCounts, '0x' + item.keysCounts.map((count) => hex(count, 16)).join('')) } }) it('calls onValidatorsCountsByNodeOperatorReportingFinished on StakingRouter', async () => { - const { extraData, extraDataList } = await prepareNextReportInNextFrame() + const { extraDataList } = await prepareNextReportInNextFrame() await oracle.submitReportExtraDataList(extraDataList, { from: member1 }) const callsCount = await stakingRouter.totalCalls_onValidatorsCountsByNodeOperatorReportingFinished() assert.equals(callsCount, 1) @@ -592,8 +593,8 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const { extraDataItems, extraDataList } = await prepareNextReportInNextFrame() await oracle.submitReportExtraDataList(extraDataList, { from: member1 }) const state = await oracle.getExtraDataProcessingState() - assert.equals(+state.itemsCount, extraDataItems.length) - assert.equals(+state.itemsCount, state.itemsProcessed) + assert.equals(state.itemsCount, extraDataItems.length) + assert.equals(state.itemsCount, state.itemsProcessed) await assert.revertsWithCustomError( oracle.submitReportExtraDataList(extraDataList, { from: member1 }), `ExtraDataAlreadyProcessed()` @@ -616,22 +617,22 @@ contract('AccountingOracle', ([admin, account1, account2, member1, member2, stra const stateBefore = await oracle.getExtraDataProcessingState() - assert.equals(+stateBefore.refSlot, reportFields.refSlot) - assert.equals(+stateBefore.dataFormat, EXTRA_DATA_FORMAT_LIST) + assert.equals(stateBefore.refSlot, reportFields.refSlot) + assert.equals(stateBefore.dataFormat, EXTRA_DATA_FORMAT_LIST) assert.isFalse(stateBefore.submitted) - assert.equals(+stateBefore.itemsCount, extraDataItems.length) - assert.equals(+stateBefore.itemsProcessed, 0) - assert.equals(+stateBefore.lastSortingKey, '0') + assert.equals(stateBefore.itemsCount, extraDataItems.length) + assert.equals(stateBefore.itemsProcessed, 0) + assert.equals(stateBefore.lastSortingKey, '0') assert.equals(stateBefore.dataHash, extraDataHash) await oracle.submitReportExtraDataList(extraDataList, { from: member1 }) const stateAfter = await oracle.getExtraDataProcessingState() - assert.equals(+stateAfter.refSlot, reportFields.refSlot) - assert.equals(+stateAfter.dataFormat, EXTRA_DATA_FORMAT_LIST) + assert.equals(stateAfter.refSlot, reportFields.refSlot) + assert.equals(stateAfter.dataFormat, EXTRA_DATA_FORMAT_LIST) assert.isTrue(stateAfter.submitted) - assert.equals(+stateAfter.itemsCount, extraDataItems.length) + assert.equals(stateAfter.itemsCount, extraDataItems.length) assert.equals(stateAfter.itemsProcessed, extraDataItems.length) // TODO: figure out how to build this value and test it properly assert.equals( diff --git a/test/0.8.9/oracle/base-oracle-access-control.test.js b/test/0.8.9/oracle/base-oracle-access-control.test.js index d66a5be4b..eb6a4ff73 100644 --- a/test/0.8.9/oracle/base-oracle-access-control.test.js +++ b/test/0.8.9/oracle/base-oracle-access-control.test.js @@ -1,3 +1,4 @@ +const { contract, web3, artifacts } = require('hardhat') const { assert } = require('../../helpers/assert') const { @@ -105,13 +106,13 @@ contract('BaseOracle', ([admin, account1, account2, member1, member2]) => { 'OnlyConsensusContractCanSubmitReport()' ) - assert.equal(+(await oracle.getConsensusReportLastCall()).callCount, 0) + assert.equals((await oracle.getConsensusReportLastCall()).callCount, 0) }) it('should allow calling from a consensus contract', async () => { await consensus.submitReportAsConsensus(HASH_1, initialRefSlot, initialRefSlot + SLOTS_PER_FRAME) - assert.equal(+(await oracle.getConsensusReportLastCall()).callCount, 1) + assert.equals((await oracle.getConsensusReportLastCall()).callCount, 1) }) }) }) diff --git a/test/0.8.9/oracle/base-oracle-deploy.test.js b/test/0.8.9/oracle/base-oracle-deploy.test.js index 60774f9fc..92e307651 100644 --- a/test/0.8.9/oracle/base-oracle-deploy.test.js +++ b/test/0.8.9/oracle/base-oracle-deploy.test.js @@ -1,3 +1,4 @@ +const { contract, artifacts } = require('hardhat') const { bn } = require('@aragon/contract-helpers-test') const BaseOracle = artifacts.require('BaseOracleTimeTravellable') @@ -95,7 +96,7 @@ module.exports = { deployBaseOracle, } -contract('BaseOracle', ([admin, member1]) => { +contract('BaseOracle', ([admin]) => { context('Deployment and initial configuration', () => { let oracle diff --git a/test/0.8.9/oracle/base-oracle-set-consensus.test.js b/test/0.8.9/oracle/base-oracle-set-consensus.test.js index df42be8f1..28e857dee 100644 --- a/test/0.8.9/oracle/base-oracle-set-consensus.test.js +++ b/test/0.8.9/oracle/base-oracle-set-consensus.test.js @@ -1,5 +1,7 @@ +const { contract, artifacts, web3 } = require('hardhat') const { assert } = require('../../helpers/assert') -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { ZERO_ADDRESS } = require('../../helpers/constants') + const MockConsensusContract = artifacts.require('MockConsensusContract') const { diff --git a/test/0.8.9/oracle/base-oracle-submit-report.test.js b/test/0.8.9/oracle/base-oracle-submit-report.test.js index 25f0b6be0..82ce4ba84 100644 --- a/test/0.8.9/oracle/base-oracle-submit-report.test.js +++ b/test/0.8.9/oracle/base-oracle-submit-report.test.js @@ -1,3 +1,4 @@ +const { contract } = require('hardhat') const { assert } = require('../../helpers/assert') const baseOracleAbi = require('../../../lib/abi/BaseOracle.json') @@ -28,7 +29,7 @@ contract('BaseOracle', ([admin]) => { }) it('initial report is submitted and _handleConsensusReport is called', async () => { - assert.equal(+(await baseOracle.getConsensusReportLastCall()).callCount, 0) + assert.equals((await baseOracle.getConsensusReportLastCall()).callCount, 0) const tx = await consensus.submitReportAsConsensus(HASH_1, initialRefSlot, initialRefSlot + SLOTS_PER_FRAME) assert.emits( tx, @@ -41,10 +42,10 @@ contract('BaseOracle', ([admin]) => { { abi: baseOracleAbi } ) const { report, callCount } = await baseOracle.getConsensusReportLastCall() - assert.equal(+callCount, 1) + assert.equals(callCount, 1) assert.equal(report.hash, HASH_1) - assert.equal(+report.refSlot, initialRefSlot) - assert.equal(+report.processingDeadlineTime, initialRefSlot + SLOTS_PER_FRAME) + assert.equals(report.refSlot, initialRefSlot) + assert.equals(report.processingDeadlineTime, initialRefSlot + SLOTS_PER_FRAME) }) it('older report cannot be submitted', async () => { @@ -71,7 +72,7 @@ contract('BaseOracle', ([admin]) => { initialRefSlot + 10, initialRefSlot + SLOTS_PER_FRAME ) - assert.equal(+(await baseOracle.getConsensusReportLastCall()).callCount, 2) + assert.equals((await baseOracle.getConsensusReportLastCall()).callCount, 2) assert.emits(tx1, 'ReportSubmitted', {}, { abi: baseOracleAbi }) const tx2 = await consensus.submitReportAsConsensus( @@ -87,7 +88,7 @@ contract('BaseOracle', ([admin]) => { abi: baseOracleAbi, } ) - assert.equal(+(await baseOracle.getConsensusReportLastCall()).callCount, 3) + assert.equals((await baseOracle.getConsensusReportLastCall()).callCount, 3) assert.emits(tx2, 'ReportSubmitted', {}, { abi: baseOracleAbi }) }) }) diff --git a/test/0.8.9/oracle/hash-consensus-access-control.test.js b/test/0.8.9/oracle/hash-consensus-access-control.test.js index 6ebea9717..a79cb7741 100644 --- a/test/0.8.9/oracle/hash-consensus-access-control.test.js +++ b/test/0.8.9/oracle/hash-consensus-access-control.test.js @@ -1,4 +1,4 @@ -const hre = require('hardhat') +const { ethers, contract, web3, artifacts } = require('hardhat') const { MaxUint256 } = require('@ethersproject/constants') const { assert } = require('../../helpers/assert') @@ -27,7 +27,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { reportProcessor2 = await MockReportProcessor.new(CONSENSUS_VERSION, { from: admin }) - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() } @@ -53,7 +53,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { 'MANAGE_MEMBERS_AND_QUORUM_ROLE' ) assert.equal(await consensus.getIsMember(member1), false) - assert.equal(+(await consensus.getQuorum()), 0) + assert.equals((await consensus.getQuorum()), 0) }) it('should allow calling from a possessor of MANAGE_MEMBERS_AND_QUORUM_ROLE role', async () => { @@ -61,7 +61,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { await consensus.addMember(member2, 1, { from: account2 }) assert.equal(await consensus.getIsMember(member2), true) - assert.equal(+(await consensus.getQuorum()), 1) + assert.equals((await consensus.getQuorum()), 1) }) }) @@ -73,7 +73,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { 'MANAGE_MEMBERS_AND_QUORUM_ROLE' ) assert.equal(await consensus.getIsMember(member1), false) - assert.equal(+(await consensus.getQuorum()), 0) + assert.equals((await consensus.getQuorum()), 0) }) it('should allow calling from a possessor of MANAGE_MEMBERS_AND_QUORUM_ROLE role', async () => { @@ -84,7 +84,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { await consensus.removeMember(member2, 1, { from: account2 }) assert.equal(await consensus.getIsMember(member2), false) - assert.equal(+(await consensus.getQuorum()), 1) + assert.equals((await consensus.getQuorum()), 1) }) }) @@ -95,14 +95,14 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { account1, 'MANAGE_MEMBERS_AND_QUORUM_ROLE' ) - assert.equal(+(await consensus.getQuorum()), 0) + assert.equals((await consensus.getQuorum()), 0) }) it('should allow calling from a possessor of MANAGE_MEMBERS_AND_QUORUM_ROLE role', async () => { await consensus.grantRole(manageMembersAndQuorumRoleKeccak156, account2) await consensus.setQuorum(1, { from: account2 }) - assert.equal(+(await consensus.getQuorum()), 1) + assert.equals((await consensus.getQuorum()), 1) }) }) @@ -113,7 +113,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { account1, 'DISABLE_CONSENSUS_ROLE' ) - assert.equal(+(await consensus.getQuorum()), 0) + assert.equals((await consensus.getQuorum()), 0) }) }) }) @@ -126,14 +126,14 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { account1, 'DISABLE_CONSENSUS_ROLE' ) - assert.equal(+(await consensus.getQuorum()), 0) + assert.equals((await consensus.getQuorum()), 0) }) it('should allow calling from a possessor of DISABLE_CONSENSUS_ROLE role', async () => { await consensus.grantRole(disableConsensusRoleKeccak156, account2) await consensus.setQuorum(MaxUint256, { from: account2 }) - assert.equal(+(await consensus.getQuorum()), MaxUint256) + assert.equals((await consensus.getQuorum()), MaxUint256) }) }) @@ -144,14 +144,14 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { account1, 'DISABLE_CONSENSUS_ROLE' ) - assert.equal(+(await consensus.getQuorum()), 0) + assert.equals((await consensus.getQuorum()), 0) }) it('should allow calling from a possessor of DISABLE_CONSENSUS_ROLE role', async () => { await consensus.grantRole(disableConsensusRoleKeccak156, account2) await consensus.disableConsensus({ from: account2 }) - assert.equal(+(await consensus.getQuorum()), MaxUint256) + assert.equals((await consensus.getQuorum()), MaxUint256) }) }) }) @@ -164,14 +164,14 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { account1, 'MANAGE_FRAME_CONFIG_ROLE' ) - assert.equal(+(await consensus.getFrameConfig()).epochsPerFrame, EPOCHS_PER_FRAME) + assert.equals((await consensus.getFrameConfig()).epochsPerFrame, EPOCHS_PER_FRAME) }) it('should allow calling from a possessor of MANAGE_FRAME_CONFIG_ROLE role', async () => { await consensus.grantRole(manageFrameConfigRoleKeccak156, account2) await consensus.setFrameConfig(5, 0, { from: account2 }) - assert.equal(+(await consensus.getFrameConfig()).epochsPerFrame, 5) + assert.equals((await consensus.getFrameConfig()).epochsPerFrame, 5) }) }) }) @@ -190,7 +190,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { await consensus.grantRole(manageReportProcessorRoleKeccak156, account2) await consensus.setReportProcessor(reportProcessor2.address, { from: account2 }) - assert.equal(+(await consensus.getReportProcessor()), reportProcessor2.address) + assert.equals((await consensus.getReportProcessor()), reportProcessor2.address) }) }) }) @@ -209,7 +209,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { await consensus.grantRole(manageFastLineConfigRoleKeccak156, account2) await consensus.setFastLaneLengthSlots(64, { from: account2 }) - assert.equal(+(await consensus.getFrameConfig()).fastLaneLengthSlots, 64) + assert.equals((await consensus.getFrameConfig()).fastLaneLengthSlots, 64) }) }) }) diff --git a/test/0.8.9/oracle/hash-consensus-deploy.test.js b/test/0.8.9/oracle/hash-consensus-deploy.test.js index 8d8b258ee..36885b604 100644 --- a/test/0.8.9/oracle/hash-consensus-deploy.test.js +++ b/test/0.8.9/oracle/hash-consensus-deploy.test.js @@ -1,3 +1,4 @@ +const { contract, artifacts } = require('hardhat') const { assert } = require('../../helpers/assert') const { bn, ZERO_ADDRESS } = require('@aragon/contract-helpers-test') @@ -105,25 +106,23 @@ contract('HashConsensus', ([admin, member1]) => { const INITIAL_EPOCH = 3 let consensus - let reportProcessor it('deploying hash consensus', async () => { const deployed = await deployHashConsensus(admin, { initialEpoch: INITIAL_EPOCH }) consensus = deployed.consensus - reportProcessor = deployed.reportProcessor }) it('chain config is correct', async () => { const config = await consensus.getChainConfig() - assert.equal(+config.slotsPerEpoch, SLOTS_PER_EPOCH) - assert.equal(+config.secondsPerSlot, SECONDS_PER_SLOT) - assert.equal(+config.genesisTime, GENESIS_TIME) + assert.equals(config.slotsPerEpoch, SLOTS_PER_EPOCH) + assert.equals(config.secondsPerSlot, SECONDS_PER_SLOT) + assert.equals(config.genesisTime, GENESIS_TIME) }) it('frame config is correct', async () => { const config = await consensus.getFrameConfig() - assert.equal(+config.initialEpoch, INITIAL_EPOCH) - assert.equal(+config.epochsPerFrame, EPOCHS_PER_FRAME) + assert.equals(config.initialEpoch, INITIAL_EPOCH) + assert.equals(config.epochsPerFrame, EPOCHS_PER_FRAME) }) it('reverts if report processor address is zero', async () => { diff --git a/test/0.8.9/oracle/hash-consensus-fast-lane-length.test.js b/test/0.8.9/oracle/hash-consensus-fast-lane-length.test.js index cfb6ff3bb..7c7d99101 100644 --- a/test/0.8.9/oracle/hash-consensus-fast-lane-length.test.js +++ b/test/0.8.9/oracle/hash-consensus-fast-lane-length.test.js @@ -1,10 +1,8 @@ +const { contract } = require('hardhat') const { assert } = require('../../helpers/assert') const { deployHashConsensus } = require('./hash-consensus-deploy.test') -const HashConsensus = artifacts.require('HashConsensusTimeTravellable') -const MockReportProcessor = artifacts.require('MockReportProcessor') - contract('HashConsensus', ([admin, member1, member2, stranger]) => { context('Fast Lane Length', () => { let consensus @@ -17,9 +15,9 @@ contract('HashConsensus', ([admin, member1, member2, stranger]) => { context('initial data', () => { it('sets properly', async () => { await deploy({ fastLaneLengthSlots: 0 }) - assert.equal(+(await consensus.getFrameConfig()).fastLaneLengthSlots, 0) + assert.equals((await consensus.getFrameConfig()).fastLaneLengthSlots, 0) await deploy({ fastLaneLengthSlots: 4 }) - assert.equal(+(await consensus.getFrameConfig()).fastLaneLengthSlots, 4) + assert.equals((await consensus.getFrameConfig()).fastLaneLengthSlots, 4) }) }) @@ -43,7 +41,7 @@ contract('HashConsensus', ([admin, member1, member2, stranger]) => { it('sets new value properly', async () => { const fastLaneLengthSlots = await getFastLaneLengthSlotsLimit() await consensus.setFastLaneLengthSlots(fastLaneLengthSlots, { from: admin }) - assert.equal(+(await consensus.getFrameConfig()).fastLaneLengthSlots, fastLaneLengthSlots) + assert.equals((await consensus.getFrameConfig()).fastLaneLengthSlots, fastLaneLengthSlots) }) it('emits FastLaneConfigSet event', async () => { diff --git a/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js b/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js index 581cdd886..a3546e8c0 100644 --- a/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js +++ b/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js @@ -1,30 +1,8 @@ +const { contract } = require('hardhat') const { assert } = require('../../helpers/assert') const { toNum } = require('../../helpers/utils') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') - -const { - SLOTS_PER_EPOCH, - SECONDS_PER_SLOT, - GENESIS_TIME, - EPOCHS_PER_FRAME, - SECONDS_PER_EPOCH, - SECONDS_PER_FRAME, - SLOTS_PER_FRAME, - computeSlotAt, - computeEpochAt, - computeEpochFirstSlot, - computeEpochFirstSlotAt, - computeTimestampAtSlot, - computeTimestampAtEpoch, - ZERO_HASH, - HASH_1, - HASH_2, - HASH_3, - HASH_4, - HASH_5, - CONSENSUS_VERSION, - deployHashConsensus, -} = require('./hash-consensus-deploy.test') + +const { HASH_1, CONSENSUS_VERSION, deployHashConsensus } = require('./hash-consensus-deploy.test') contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, stranger]) => { context('Fast-lane members', async () => { @@ -37,7 +15,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, const setTimeToFrame0 = async () => { await consensus.setTimeInEpochs((await consensus.getFrameConfig()).initialEpoch) - assert.equal(+(await consensus.getTimeInSlots()), +(await consensus.getCurrentFrame()).refSlot + 1) + assert.equals((await consensus.getTimeInSlots()), +(await consensus.getCurrentFrame()).refSlot + 1) } context('State after initialization', () => { diff --git a/test/0.8.9/oracle/hash-consensus-frames.js b/test/0.8.9/oracle/hash-consensus-frames.test.js similarity index 66% rename from test/0.8.9/oracle/hash-consensus-frames.js rename to test/0.8.9/oracle/hash-consensus-frames.test.js index 4fc6fdf80..8be4232da 100644 --- a/test/0.8.9/oracle/hash-consensus-frames.js +++ b/test/0.8.9/oracle/hash-consensus-frames.test.js @@ -1,6 +1,5 @@ +const { contract } = require('hardhat') const { assert } = require('../../helpers/assert') -const { assertEvent } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../../helpers/assertThrow') const { INITIAL_FAST_LANE_LENGTH_SLOTS, @@ -9,9 +8,7 @@ const { SLOTS_PER_EPOCH, SECONDS_PER_SLOT, SLOTS_PER_FRAME, - computeEpochAt, computeEpochFirstSlot, - computeTimestampAtSlot, computeTimestampAtEpoch, ZERO_HASH, HASH_1, @@ -19,18 +16,6 @@ const { deployHashConsensus, } = require('./hash-consensus-deploy.test') -const getFrameIndex = (time, epochsPerFrame, initialEpoch) => - Math.floor((computeEpochAt(time) - initialEpoch) / epochsPerFrame) - -const computeIthFrameStartSlot = (frameIndex, epochsPerFrame, initialEpoch) => - (initialEpoch + frameIndex * epochsPerFrame) * SLOTS_PER_EPOCH - -const computeIthFrameStartTime = (frameIndex, epochsPerFrame, initialEpoch) => - computeTimestampAtSlot(computeIthFrameStartSlot(frameIndex, epochsPerFrame, initialEpoch)) - -const computeNextFrameStartSlot = (time, epochsPerFrame, initialEpoch) => - computeIthFrameStartSlot(getFrameIndex(time, epochsPerFrame, initialEpoch), epochsPerFrame, initialEpoch) - contract('HashConsensus', ([admin, member1, member2]) => { const TEST_INITIAL_EPOCH = 3 @@ -44,17 +29,17 @@ contract('HashConsensus', ([admin, member1, member2]) => { context('getFrameConfig', () => { before(deploy) it('should return initial data', async () => { - assert.equal(+(await consensus.getFrameConfig()).epochsPerFrame, EPOCHS_PER_FRAME) - assert.equal(+(await consensus.getFrameConfig()).initialEpoch, INITIAL_EPOCH) - assert.equal(+(await consensus.getFrameConfig()).fastLaneLengthSlots, INITIAL_FAST_LANE_LENGTH_SLOTS) + assert.equals((await consensus.getFrameConfig()).epochsPerFrame, EPOCHS_PER_FRAME) + assert.equals((await consensus.getFrameConfig()).initialEpoch, INITIAL_EPOCH) + assert.equals((await consensus.getFrameConfig()).fastLaneLengthSlots, INITIAL_FAST_LANE_LENGTH_SLOTS) }) it('should return new data', async () => { await consensus.setFrameConfig(100, 50) - assert.equal(+(await consensus.getFrameConfig()).epochsPerFrame, 100) - assert.equal(+(await consensus.getFrameConfig()).fastLaneLengthSlots, 50) - assert.equal(+(await consensus.getFrameConfig()).initialEpoch, INITIAL_EPOCH) + assert.equals((await consensus.getFrameConfig()).epochsPerFrame, 100) + assert.equals((await consensus.getFrameConfig()).fastLaneLengthSlots, 50) + assert.equals((await consensus.getFrameConfig()).initialEpoch, INITIAL_EPOCH) }) }) context('setFrameConfig', () => { @@ -63,18 +48,18 @@ contract('HashConsensus', ([admin, member1, member2]) => { it('should set data', async () => { await consensus.setFrameConfig(100, 50) - assert.equal(+(await consensus.getFrameConfig()).epochsPerFrame, 100) - assert.equal(+(await consensus.getFrameConfig()).fastLaneLengthSlots, 50) - assert.equal(+(await consensus.getFrameConfig()).initialEpoch, INITIAL_EPOCH) + assert.equals((await consensus.getFrameConfig()).epochsPerFrame, 100) + assert.equals((await consensus.getFrameConfig()).fastLaneLengthSlots, 50) + assert.equals((await consensus.getFrameConfig()).initialEpoch, INITIAL_EPOCH) }) it('should set first epoch in next frame', async () => { await consensus.setTimeInEpochs(INITIAL_EPOCH + EPOCHS_PER_FRAME) await consensus.setFrameConfig(100, 50) - assert.equal(+(await consensus.getFrameConfig()).epochsPerFrame, 100) - assert.equal(+(await consensus.getFrameConfig()).fastLaneLengthSlots, 50) - assert.equal(+(await consensus.getFrameConfig()).initialEpoch, EPOCHS_PER_FRAME + 1) + assert.equals((await consensus.getFrameConfig()).epochsPerFrame, 100) + assert.equals((await consensus.getFrameConfig()).fastLaneLengthSlots, 50) + assert.equals((await consensus.getFrameConfig()).initialEpoch, EPOCHS_PER_FRAME + 1) }) it('should revert if epochsPerFrame == 0', async () => { @@ -94,8 +79,8 @@ contract('HashConsensus', ([admin, member1, member2]) => { it('should emit FrameConfigSet & FastLaneConfigSet event', async () => { const tx = await consensus.setFrameConfig(100, 50) - assertEvent(tx, 'FrameConfigSet', { expectedArgs: { newInitialEpoch: 1, newEpochsPerFrame: 100 } }) - assertEvent(tx, 'FastLaneConfigSet', { expectedArgs: { fastLaneLengthSlots: 50 } }) + assert.emits(tx, 'FrameConfigSet', { newInitialEpoch: 1, newEpochsPerFrame: 100 }) + assert.emits(tx, 'FastLaneConfigSet', { fastLaneLengthSlots: 50 }) }) it('should not emit FrameConfigSet & FastLaneConfigSet event', async () => { @@ -122,7 +107,7 @@ contract('HashConsensus', ([admin, member1, member2]) => { await consensus.addMember(member2, 2, { from: admin }) await consensus.setQuorum(3, { from: admin }) - assert.equal(+(await consensus.getQuorum()), 3) + assert.equals(await consensus.getQuorum(), 3) assert.isTrue(await consensus.getIsMember(member1)) assert.isTrue(await consensus.getIsMember(member2)) @@ -137,16 +122,16 @@ contract('HashConsensus', ([admin, member1, member2]) => { }) it('but otherwise, the contract is dysfunctional', async () => { - await assertRevert(consensus.removeMember(member2, 2), 'InitialEpochIsYetToArrive()') - await assertRevert(consensus.removeMember(member2, 1), 'InitialEpochIsYetToArrive()') - await assertRevert(consensus.setQuorum(2), 'InitialEpochIsYetToArrive()') + await assert.reverts(consensus.removeMember(member2, 2), 'InitialEpochIsYetToArrive()') + await assert.reverts(consensus.removeMember(member2, 1), 'InitialEpochIsYetToArrive()') + await assert.reverts(consensus.setQuorum(2), 'InitialEpochIsYetToArrive()') - await assertRevert(consensus.getCurrentFrame(), 'InitialEpochIsYetToArrive()') - await assertRevert(consensus.getConsensusState(), 'InitialEpochIsYetToArrive()') - await assertRevert(consensus.getConsensusStateForMember(member1), 'InitialEpochIsYetToArrive()') + await assert.reverts(consensus.getCurrentFrame(), 'InitialEpochIsYetToArrive()') + await assert.reverts(consensus.getConsensusState(), 'InitialEpochIsYetToArrive()') + await assert.reverts(consensus.getConsensusStateForMember(member1), 'InitialEpochIsYetToArrive()') const firstRefSlot = TEST_INITIAL_EPOCH * SLOTS_PER_EPOCH - 1 - await assertRevert( + await assert.reverts( consensus.submitReport(firstRefSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }), 'InitialEpochIsYetToArrive()' ) @@ -156,22 +141,22 @@ contract('HashConsensus', ([admin, member1, member2]) => { await consensus.setTimeInEpochs(TEST_INITIAL_EPOCH) await consensus.setQuorum(2, { from: admin }) - assert.equal(+(await consensus.getQuorum()), 2) + assert.equals(await consensus.getQuorum(), 2) const frame = await consensus.getCurrentFrame() - assert.equal(+frame.refSlot, computeEpochFirstSlot(TEST_INITIAL_EPOCH) - 1) - assert.equal(+frame.reportProcessingDeadlineSlot, computeEpochFirstSlot(TEST_INITIAL_EPOCH) + SLOTS_PER_FRAME - 1) + assert.equals(frame.refSlot, computeEpochFirstSlot(TEST_INITIAL_EPOCH) - 1) + assert.equals(frame.reportProcessingDeadlineSlot, computeEpochFirstSlot(TEST_INITIAL_EPOCH) + SLOTS_PER_FRAME - 1) const consensusState = await consensus.getConsensusState() assert.equal(consensusState.consensusReport, ZERO_HASH) const memberInfo = await consensus.getConsensusStateForMember(member1) assert.isTrue(memberInfo.isMember) - assert.equal(+memberInfo.currentFrameRefSlot, +frame.refSlot) - assert.equal(+memberInfo.lastMemberReportRefSlot, 0) + assert.equals(memberInfo.currentFrameRefSlot, +frame.refSlot) + assert.equals(memberInfo.lastMemberReportRefSlot, 0) const tx = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ReportReceived', { expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 } }) + assert.emits(tx, 'ReportReceived', { refSlot: frame.refSlot, member: member1, report: HASH_1 }) }) }) @@ -185,10 +170,10 @@ contract('HashConsensus', ([admin, member1, member2]) => { }) it(`crossing frame boundary time advances reference and deadline slots by the frame size`, async () => { - assert.equal(+(await consensus.getTime()), computeTimestampAtEpoch(1)) + assert.equals(await consensus.getTime(), computeTimestampAtEpoch(1)) await consensus.setFrameConfig(5, 0) - assert.equal(+(await consensus.getFrameConfig()).initialEpoch, 1) + assert.equals((await consensus.getFrameConfig()).initialEpoch, 1) /// epochs 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 /// before |-------------r|-------------^|--------------|--------------| @@ -199,21 +184,21 @@ contract('HashConsensus', ([admin, member1, member2]) => { await consensus.setTime(computeTimestampAtEpoch(11) - 1) const frame = await consensus.getCurrentFrame() - assert.equal(+frame.refSlot, computeEpochFirstSlot(6) - 1) - assert.equal(+frame.reportProcessingDeadlineSlot, computeEpochFirstSlot(11) - 1) + assert.equals(frame.refSlot, computeEpochFirstSlot(6) - 1) + assert.equals(frame.reportProcessingDeadlineSlot, computeEpochFirstSlot(11) - 1) await consensus.setTime(computeTimestampAtEpoch(11)) const newFrame = await consensus.getCurrentFrame() - assert.equal(+newFrame.refSlot, computeEpochFirstSlot(11) - 1) - assert.equal(+newFrame.reportProcessingDeadlineSlot, computeEpochFirstSlot(16) - 1) + assert.equals(newFrame.refSlot, computeEpochFirstSlot(11) - 1) + assert.equals(newFrame.reportProcessingDeadlineSlot, computeEpochFirstSlot(16) - 1) }) it('increasing frame size always keeps the current start slot', async () => { - assert.equal(+(await consensus.getTime()), computeTimestampAtEpoch(1)) + assert.equals(await consensus.getTime(), computeTimestampAtEpoch(1)) await consensus.setFrameConfig(5, 0) - assert.equal(+(await consensus.getFrameConfig()).initialEpoch, 1) + assert.equals((await consensus.getFrameConfig()).initialEpoch, 1) /// we're at the last slot of the frame 1 spanning epochs 6-10 /// @@ -226,21 +211,21 @@ contract('HashConsensus', ([admin, member1, member2]) => { await consensus.setTime(computeTimestampAtEpoch(11) - SECONDS_PER_SLOT) const frame = await consensus.getCurrentFrame() - assert.equal(+frame.refSlot, computeEpochFirstSlot(6) - 1) - assert.equal(+frame.reportProcessingDeadlineSlot, computeEpochFirstSlot(11) - 1) + assert.equals(frame.refSlot, computeEpochFirstSlot(6) - 1) + assert.equals(frame.reportProcessingDeadlineSlot, computeEpochFirstSlot(11) - 1) await consensus.setFrameConfig(7, 0) const newFrame = await consensus.getCurrentFrame() - assert.equal(+newFrame.refSlot, computeEpochFirstSlot(6) - 1) - assert.equal(+newFrame.reportProcessingDeadlineSlot, computeEpochFirstSlot(13) - 1) + assert.equals(newFrame.refSlot, computeEpochFirstSlot(6) - 1) + assert.equals(newFrame.reportProcessingDeadlineSlot, computeEpochFirstSlot(13) - 1) }) it(`decreasing the frame size cannot decrease the current reference slot`, async () => { - assert.equal(+(await consensus.getTime()), computeTimestampAtEpoch(1)) + assert.equals(await consensus.getTime(), computeTimestampAtEpoch(1)) await consensus.setFrameConfig(5, 0) - assert.equal(+(await consensus.getFrameConfig()).initialEpoch, 1) + assert.equals((await consensus.getFrameConfig()).initialEpoch, 1) /// we're in the first half of the frame 1 spanning epochs 6-10 /// @@ -253,21 +238,21 @@ contract('HashConsensus', ([admin, member1, member2]) => { await consensus.setTime(computeTimestampAtEpoch(7)) const frame = await consensus.getCurrentFrame() - assert.equal(+frame.refSlot, computeEpochFirstSlot(6) - 1) - assert.equal(+frame.reportProcessingDeadlineSlot, computeEpochFirstSlot(11) - 1) + assert.equals(frame.refSlot, computeEpochFirstSlot(6) - 1) + assert.equals(frame.reportProcessingDeadlineSlot, computeEpochFirstSlot(11) - 1) await consensus.setFrameConfig(4, 0) const newFrame = await consensus.getCurrentFrame() - assert.equal(+newFrame.refSlot, computeEpochFirstSlot(6) - 1) - assert.equal(+newFrame.reportProcessingDeadlineSlot, computeEpochFirstSlot(10) - 1) + assert.equals(newFrame.refSlot, computeEpochFirstSlot(6) - 1) + assert.equals(newFrame.reportProcessingDeadlineSlot, computeEpochFirstSlot(10) - 1) }) it('decreasing the frame size may advance the current reference slot, but at least by the new frame size', async () => { - assert.equal(+(await consensus.getTime()), computeTimestampAtEpoch(1)) + assert.equals(await consensus.getTime(), computeTimestampAtEpoch(1)) await consensus.setFrameConfig(5, 0) - assert.equal(+(await consensus.getFrameConfig()).initialEpoch, 1) + assert.equals((await consensus.getFrameConfig()).initialEpoch, 1) /// we're at the end of the frame 1 spanning epochs 6-10 /// @@ -280,14 +265,14 @@ contract('HashConsensus', ([admin, member1, member2]) => { await consensus.setTime(computeTimestampAtEpoch(10)) const frame = await consensus.getCurrentFrame() - assert.equal(+frame.refSlot, computeEpochFirstSlot(6) - 1) - assert.equal(+frame.reportProcessingDeadlineSlot, computeEpochFirstSlot(11) - 1) + assert.equals(frame.refSlot, computeEpochFirstSlot(6) - 1) + assert.equals(frame.reportProcessingDeadlineSlot, computeEpochFirstSlot(11) - 1) await consensus.setFrameConfig(4, 0) const newFrame = await consensus.getCurrentFrame() - assert.equal(+newFrame.refSlot, computeEpochFirstSlot(10) - 1) - assert.equal(+newFrame.reportProcessingDeadlineSlot, computeEpochFirstSlot(14) - 1) + assert.equals(newFrame.refSlot, computeEpochFirstSlot(10) - 1) + assert.equals(newFrame.reportProcessingDeadlineSlot, computeEpochFirstSlot(14) - 1) }) }) }) diff --git a/test/0.8.9/oracle/hash-consensus-happy-path.test.js b/test/0.8.9/oracle/hash-consensus-happy-path.test.js index d65afe5b0..afa3995e2 100644 --- a/test/0.8.9/oracle/hash-consensus-happy-path.test.js +++ b/test/0.8.9/oracle/hash-consensus-happy-path.test.js @@ -1,18 +1,13 @@ -const { assert } = require('chai') -const { assertBn, assertEvent, assertAmountOfEvents } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../../helpers/assertThrow') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') +const { contract } = require('hardhat') +const { assert } = require('../../helpers/assert') const { SLOTS_PER_EPOCH, SECONDS_PER_SLOT, - GENESIS_TIME, EPOCHS_PER_FRAME, SECONDS_PER_EPOCH, SECONDS_PER_FRAME, SLOTS_PER_FRAME, - computeSlotAt, - computeEpochAt, computeEpochFirstSlotAt, computeTimestampAtEpoch, computeTimestampAtSlot, @@ -20,15 +15,10 @@ const { HASH_1, HASH_2, HASH_3, - HASH_4, - HASH_5, CONSENSUS_VERSION, deployHashConsensus, } = require('./hash-consensus-deploy.test') -const HashConsensus = artifacts.require('HashConsensusTimeTravellable') -const MockReportProcessor = artifacts.require('MockReportProcessor') - contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { let consensus let reportProcessor @@ -45,21 +35,21 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { it('adding members', async () => { await consensus.addMember(member1, 1, { from: admin }) assert.equal(await consensus.getIsMember(member1), true) - assert.equal(+(await consensus.getQuorum()), 1) + assert.equals(await consensus.getQuorum(), 1) await consensus.addMember(member2, 2, { from: admin }) assert.equal(await consensus.getIsMember(member2), true) - assert.equal(+(await consensus.getQuorum()), 2) + assert.equals(await consensus.getQuorum(), 2) await consensus.addMember(member3, 2, { from: admin }) assert.equal(await consensus.getIsMember(member3), true) - assert.equal(+(await consensus.getQuorum()), 2) + assert.equals(await consensus.getQuorum(), 2) }) it('some fraction of the reporting frame passes', async () => { - assert.equal(+(await consensus.getTime()), computeTimestampAtEpoch(INITIAL_EPOCH)) + assert.equals(await consensus.getTime(), computeTimestampAtEpoch(INITIAL_EPOCH)) await consensus.advanceTimeBySlots(3) - assert.equal(+(await consensus.getTime()), computeTimestampAtEpoch(INITIAL_EPOCH) + 3 * SECONDS_PER_SLOT) + assert.equals(await consensus.getTime(), computeTimestampAtEpoch(INITIAL_EPOCH) + 3 * SECONDS_PER_SLOT) }) let frame @@ -70,14 +60,14 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { const expectedRefSlot = computeEpochFirstSlotAt(time) - 1 const expectedDeadlineSlot = expectedRefSlot + EPOCHS_PER_FRAME * SLOTS_PER_EPOCH - assert.equal(+frame1.refSlot, expectedRefSlot) - assert.equal(+frame1.reportProcessingDeadlineSlot, expectedDeadlineSlot) + assert.equals(frame1.refSlot, expectedRefSlot) + assert.equals(frame1.reportProcessingDeadlineSlot, expectedDeadlineSlot) await consensus.advanceTimeBy(SECONDS_PER_FRAME) const frame2 = await consensus.getCurrentFrame() - assert.equal(+frame2.refSlot, expectedRefSlot + SLOTS_PER_FRAME) - assert.equal(+frame2.reportProcessingDeadlineSlot, expectedDeadlineSlot + SLOTS_PER_FRAME) + assert.equals(frame2.refSlot, expectedRefSlot + SLOTS_PER_FRAME) + assert.equals(frame2.reportProcessingDeadlineSlot, expectedDeadlineSlot + SLOTS_PER_FRAME) frame = frame2 }) @@ -87,13 +77,13 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { const tx = await consensus.submitReport(frame.refSlot, HASH_3, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ReportReceived', { expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_3 } }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.emits(tx, 'ReportReceived', { refSlot: frame.refSlot, member: member1, report: HASH_3 }) + assert.notEmits(tx, 'ConsensusReached') const memberInfo = await consensus.getConsensusStateForMember(member1) assert.isTrue(memberInfo.isMember) - assert.equal(+memberInfo.lastMemberReportRefSlot, +frame.refSlot) - assert.equal(+memberInfo.currentFrameRefSlot, +frame.refSlot) + assert.equals(memberInfo.lastMemberReportRefSlot, +frame.refSlot) + assert.equals(memberInfo.currentFrameRefSlot, +frame.refSlot) assert.equal(memberInfo.currentFrameMemberReport, HASH_3) assert.isTrue(memberInfo.canReport) }) @@ -102,7 +92,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { const consensusState = await consensus.getConsensusState() assert.equal(consensusState.consensusReport, ZERO_HASH) assert.isFalse(consensusState.isReportProcessing) - assert.equal(+(await reportProcessor.getLastCall_submitReport()).callCount, 0) + assert.equals((await reportProcessor.getLastCall_submitReport()).callCount, 0) const memberInfo = await consensus.getConsensusStateForMember(member1) assert.equal(memberInfo.currentFrameConsensusReport, ZERO_HASH) @@ -115,13 +105,13 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { const tx = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) - assertEvent(tx, 'ReportReceived', { expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 } }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.emits(tx, 'ReportReceived', { refSlot: frame.refSlot, member: member2, report: HASH_1 }) + assert.notEmits(tx, 'ConsensusReached') const memberInfo = await consensus.getConsensusStateForMember(member2) assert.isTrue(memberInfo.isMember) - assert.equal(+memberInfo.lastMemberReportRefSlot, +frame.refSlot) - assert.equal(+memberInfo.currentFrameRefSlot, +frame.refSlot) + assert.equals(memberInfo.lastMemberReportRefSlot, +frame.refSlot) + assert.equals(memberInfo.currentFrameRefSlot, +frame.refSlot) assert.equal(memberInfo.currentFrameMemberReport, HASH_1) assert.isTrue(memberInfo.canReport) }) @@ -130,7 +120,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { const consensusState = await consensus.getConsensusState() assert.equal(consensusState.consensusReport, ZERO_HASH) assert.isFalse(consensusState.isReportProcessing) - assert.equal(+(await reportProcessor.getLastCall_submitReport()).callCount, 0) + assert.equals((await reportProcessor.getLastCall_submitReport()).callCount, 0) const memberInfo = await consensus.getConsensusStateForMember(member1) assert.equal(memberInfo.currentFrameConsensusReport, ZERO_HASH) @@ -143,13 +133,13 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { const tx = await consensus.submitReport(frame.refSlot, HASH_3, CONSENSUS_VERSION, { from: member3 }) - assertEvent(tx, 'ReportReceived', { expectedArgs: { refSlot: frame.refSlot, member: member3, report: HASH_3 } }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot: frame.refSlot, report: HASH_3, support: 2 } }) + assert.emits(tx, 'ReportReceived', { refSlot: frame.refSlot, member: member3, report: HASH_3 }) + assert.emits(tx, 'ConsensusReached', { refSlot: frame.refSlot, report: HASH_3, support: 2 }) const memberInfo = await consensus.getConsensusStateForMember(member3) assert.isTrue(memberInfo.isMember) - assert.equal(+memberInfo.lastMemberReportRefSlot, +frame.refSlot) - assert.equal(+memberInfo.currentFrameRefSlot, +frame.refSlot) + assert.equals(memberInfo.lastMemberReportRefSlot, +frame.refSlot) + assert.equals(memberInfo.currentFrameRefSlot, +frame.refSlot) assert.equal(memberInfo.currentFrameMemberReport, HASH_3) assert.isTrue(memberInfo.canReport) }) @@ -163,10 +153,10 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { assert.equal(memberInfo.currentFrameConsensusReport, HASH_3) const submitReportLastCall = await reportProcessor.getLastCall_submitReport() - assert.equal(+submitReportLastCall.callCount, 1) + assert.equals(submitReportLastCall.callCount, 1) assert.equal(submitReportLastCall.report, HASH_3) - assert.equal(+submitReportLastCall.refSlot, +frame.refSlot) - assert.equal(+submitReportLastCall.deadline, computeTimestampAtSlot(frame.reportProcessingDeadlineSlot)) + assert.equals(submitReportLastCall.refSlot, +frame.refSlot) + assert.equals(submitReportLastCall.deadline, computeTimestampAtSlot(frame.reportProcessingDeadlineSlot)) }) it('first member votes for hash 1', async () => { @@ -176,13 +166,13 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { const tx = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ReportReceived', { expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 } }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot: frame.refSlot, report: HASH_1, support: 2 } }) + assert.emits(tx, 'ReportReceived', { refSlot: frame.refSlot, member: member1, report: HASH_1 }) + assert.emits(tx, 'ConsensusReached', { refSlot: frame.refSlot, report: HASH_1, support: 2 }) const memberInfo = await consensus.getConsensusStateForMember(member1) assert.isTrue(memberInfo.isMember) - assert.equal(+memberInfo.lastMemberReportRefSlot, +frame.refSlot) - assert.equal(+memberInfo.currentFrameRefSlot, +frame.refSlot) + assert.equals(memberInfo.lastMemberReportRefSlot, +frame.refSlot) + assert.equals(memberInfo.currentFrameRefSlot, +frame.refSlot) assert.equal(memberInfo.currentFrameMemberReport, HASH_1) assert.isTrue(memberInfo.canReport) }) @@ -196,10 +186,10 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { assert.equal(memberInfo.currentFrameConsensusReport, HASH_1) const submitReportLastCall = await reportProcessor.getLastCall_submitReport() - assert.equal(+submitReportLastCall.callCount, 2) + assert.equals(submitReportLastCall.callCount, 2) assert.equal(submitReportLastCall.report, HASH_1) - assert.equal(+submitReportLastCall.refSlot, +frame.refSlot) - assert.equal(+submitReportLastCall.deadline, computeTimestampAtSlot(frame.reportProcessingDeadlineSlot)) + assert.equals(submitReportLastCall.refSlot, +frame.refSlot) + assert.equals(submitReportLastCall.deadline, computeTimestampAtSlot(frame.reportProcessingDeadlineSlot)) }) it('report processor starts processing the report', async () => { @@ -217,7 +207,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { assert.isFalse((await consensus.getConsensusStateForMember(member2)).canReport) - await assertRevert( + await assert.reverts( consensus.submitReport(frame.refSlot, HASH_3, CONSENSUS_VERSION, { from: member2 }), 'ConsensusReportAlreadyProcessing()' ) @@ -231,7 +221,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { prevFrame = frame newFrame = await consensus.getCurrentFrame() - assert.equal(+newFrame.refSlot, +prevFrame.refSlot + SLOTS_PER_FRAME) + assert.equals(newFrame.refSlot, +prevFrame.refSlot + SLOTS_PER_FRAME) const consensusState = await consensus.getConsensusState() assert.equal(consensusState.consensusReport, ZERO_HASH) @@ -239,10 +229,10 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { const checkMember = async (member) => { const memberInfo = await consensus.getConsensusStateForMember(member) - assert.equal(+memberInfo.currentFrameRefSlot, +newFrame.refSlot) + assert.equals(memberInfo.currentFrameRefSlot, +newFrame.refSlot) assert.equal(memberInfo.currentFrameConsensusReport, ZERO_HASH) assert.isTrue(memberInfo.isMember) - assert.equal(+memberInfo.lastMemberReportRefSlot, +prevFrame.refSlot) + assert.equals(memberInfo.lastMemberReportRefSlot, +prevFrame.refSlot) assert.equal(memberInfo.currentFrameMemberReport, ZERO_HASH) assert.isTrue(memberInfo.canReport) } @@ -251,22 +241,22 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { await checkMember(member2) await checkMember(member3) - assert.equal(+(await reportProcessor.getLastCall_submitReport()).callCount, 2) + assert.equals((await reportProcessor.getLastCall_submitReport()).callCount, 2) }) it('a member cannot submit report for the previous ref slot', async () => { - await assertRevert( + await assert.reverts( consensus.submitReport(prevFrame.refSlot, HASH_2, CONSENSUS_VERSION, { from: member1 }), 'InvalidSlot()' ) }) it('a member cannot submit report for a non-reference slot', async () => { - await assertRevert( + await assert.reverts( consensus.submitReport(newFrame.refSlot - 1, HASH_2, CONSENSUS_VERSION, { from: member1 }), 'InvalidSlot()' ) - await assertRevert( + await assert.reverts( consensus.submitReport(newFrame.refSlot + 1, HASH_2, CONSENSUS_VERSION, { from: member1 }), 'InvalidSlot()' ) @@ -275,15 +265,17 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { it('first member votes for hash 2', async () => { const tx = await consensus.submitReport(newFrame.refSlot, HASH_2, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ReportReceived', { - expectedArgs: { refSlot: newFrame.refSlot, member: member1, report: HASH_2 }, + assert.emits(tx, 'ReportReceived', { + refSlot: newFrame.refSlot, + member: member1, + report: HASH_2, }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') const memberInfo = await consensus.getConsensusStateForMember(member1) assert.isTrue(memberInfo.isMember) - assert.equal(+memberInfo.lastMemberReportRefSlot, +newFrame.refSlot) - assert.equal(+memberInfo.currentFrameRefSlot, +newFrame.refSlot) + assert.equals(memberInfo.lastMemberReportRefSlot, +newFrame.refSlot) + assert.equals(memberInfo.currentFrameRefSlot, +newFrame.refSlot) assert.equal(memberInfo.currentFrameMemberReport, HASH_2) assert.isTrue(memberInfo.canReport) }) @@ -292,7 +284,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, stranger]) => { const consensusState = await consensus.getConsensusState() assert.equal(consensusState.consensusReport, ZERO_HASH) assert.isFalse(consensusState.isReportProcessing) - assert.equal(+(await reportProcessor.getLastCall_submitReport()).callCount, 2) + assert.equals((await reportProcessor.getLastCall_submitReport()).callCount, 2) const memberInfo = await consensus.getConsensusStateForMember(member1) assert.equal(memberInfo.currentFrameConsensusReport, ZERO_HASH) diff --git a/test/0.8.9/oracle/hash-consensus-members.test.js b/test/0.8.9/oracle/hash-consensus-members.test.js index 7008755ef..e19372d73 100644 --- a/test/0.8.9/oracle/hash-consensus-members.test.js +++ b/test/0.8.9/oracle/hash-consensus-members.test.js @@ -1,48 +1,18 @@ +const { contract } = require('hardhat') const { assert } = require('../../helpers/assert') const { toNum } = require('../../helpers/utils') -const { assertBn, assertEvent, assertAmountOfEvents } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../../helpers/assertThrow') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') - -const { - SLOTS_PER_EPOCH, - SECONDS_PER_SLOT, - GENESIS_TIME, - EPOCHS_PER_FRAME, - SECONDS_PER_EPOCH, - SECONDS_PER_FRAME, - SLOTS_PER_FRAME, - computeSlotAt, - computeEpochAt, - computeEpochFirstSlot, - computeEpochFirstSlotAt, - computeTimestampAtSlot, - computeTimestampAtEpoch, - ZERO_HASH, - HASH_1, - HASH_2, - HASH_3, - HASH_4, - HASH_5, - CONSENSUS_VERSION, - deployHashConsensus, -} = require('./hash-consensus-deploy.test') - -const HashConsensus = artifacts.require('HashConsensusTimeTravellable') -const MockReportProcessor = artifacts.require('MockReportProcessor') +const { assertAmountOfEvents } = require('@aragon/contract-helpers-test/src/asserts') +const { ZERO_ADDRESS } = require('../../helpers/constants') -contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, stranger]) => { - let consensus - let reportProcessor +const { HASH_1, HASH_2, CONSENSUS_VERSION, deployHashConsensus, ZERO_HASH } = require('./hash-consensus-deploy.test') +contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, stranger]) => { context('Managing members and quorum', () => { let consensus - let reportProcessor const deploy = async (options = undefined) => { const deployed = await deployHashConsensus(admin, options) consensus = deployed.consensus - reportProcessor = deployed.reportProcessor } context('initial state', () => { @@ -58,12 +28,12 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, const member1Info = await consensus.getConsensusStateForMember(member1) assert.isFalse(member1Info.isMember) assert.isFalse(member1Info.canReport) - assert.equal(+member1Info.lastMemberReportRefSlot, 0) + assert.equals(member1Info.lastMemberReportRefSlot, 0) assert.equal(member1Info.currentFrameMemberReport, ZERO_HASH) }) it('quorum is zero', async () => { - assert.equal(+(await consensus.getQuorum()), 0) + assert.equals(await consensus.getQuorum(), 0) }) }) @@ -81,7 +51,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, const newQuorum = 1 const tx = await consensus.addMember(member1, newQuorum, { from: admin }) - assertEvent(tx, 'MemberAdded', { expectedArgs: { addr: member1, newTotalMembers: 1, newQuorum: 1 } }) + assert.emits(tx, 'MemberAdded', { addr: member1, newTotalMembers: 1, newQuorum: 1 }) assert.isTrue(await consensus.getIsMember(member1)) const membersInfo = await consensus.getMembers() @@ -91,25 +61,25 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, const member1Info = await consensus.getConsensusStateForMember(member1) assert.isTrue(member1Info.isMember) assert.isTrue(member1Info.canReport) - assert.equal(+member1Info.lastMemberReportRefSlot, 0) + assert.equals(member1Info.lastMemberReportRefSlot, 0) assert.equal(member1Info.currentFrameMemberReport, ZERO_HASH) - assert.equal(+(await consensus.getQuorum()), 1) + assert.equals(await consensus.getQuorum(), 1) }) it(`doesn't allow to add the same member twice`, async () => { - await assertRevert(consensus.addMember(member1, 2, { from: admin }), 'DuplicateMember()') + await assert.reverts(consensus.addMember(member1, 2, { from: admin }), 'DuplicateMember()') }) it(`requires quorum to be more than half of the total members count`, async () => { - await assertRevert(consensus.addMember(member2, 1, { from: admin }), 'QuorumTooSmall(2, 1)') + await assert.reverts(consensus.addMember(member2, 1, { from: admin }), 'QuorumTooSmall(2, 1)') }) it(`allows setting the quorum more than total members count`, async () => { const tx = await consensus.addMember(member2, 3, { from: admin }) - assertEvent(tx, 'MemberAdded', { expectedArgs: { addr: member2, newTotalMembers: 2, newQuorum: 3 } }) + assert.emits(tx, 'MemberAdded', { addr: member2, newTotalMembers: 2, newQuorum: 3 }) assert.isTrue(await consensus.getIsMember(member2)) - assert.equal(+(await consensus.getQuorum()), 3) + assert.equals(await consensus.getQuorum(), 3) }) it(`lowering the quorum while adding a member may trigger consensus`, async () => { @@ -124,8 +94,8 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) const tx = await consensus.addMember(member5, 3, { from: admin }) - assertEvent(tx, 'MemberAdded', { expectedArgs: { addr: member5, newTotalMembers: 5, newQuorum: 3 } }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 3 } }) + assert.emits(tx, 'MemberAdded', { addr: member5, newTotalMembers: 5, newQuorum: 3 }) + assert.emits(tx, 'ConsensusReached', { refSlot, report: HASH_1, support: 3 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) }) }) @@ -146,47 +116,47 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, }) it('removes a member, setting the new quorum', async () => { - tx = await consensus.removeMember(member1, 3, { from: admin }) + const tx = await consensus.removeMember(member1, 3, { from: admin }) - assertEvent(tx, 'MemberRemoved', { expectedArgs: { addr: member1, newTotalMembers: 4, newQuorum: 3 } }) + assert.emits(tx, 'MemberRemoved', { addr: member1, newTotalMembers: 4, newQuorum: 3 }) assert.isFalse(await consensus.getIsMember(member1)) - assert.equal(+(await consensus.getQuorum()), 3) + assert.equals(await consensus.getQuorum(), 3) const member1Info = await consensus.getConsensusStateForMember(member1) assert.isFalse(member1Info.isMember) - assert.equal(+member1Info.lastMemberReportRefSlot, 0) + assert.equals(member1Info.lastMemberReportRefSlot, 0) assert.equal(member1Info.currentFrameMemberReport, ZERO_HASH) }) it(`doesn't allow removing a non-member`, async () => { - await assertRevert(consensus.removeMember(stranger, 4, { from: admin }), 'NonMember()') + await assert.reverts(consensus.removeMember(stranger, 4, { from: admin }), 'NonMember()') }) it(`doesn't allow removing an already removed member`, async () => { await consensus.removeMember(member1, 4, { from: admin }) - await assertRevert(consensus.removeMember(member1, 4, { from: admin }), 'NonMember()') + await assert.reverts(consensus.removeMember(member1, 4, { from: admin }), 'NonMember()') }) it('allows removing all members', async () => { await consensus.removeMember(member1, 3, { from: admin }) assert.sameMembers((await consensus.getMembers()).addresses, [member2, member3, member4, member5]) - assert.equal(+(await consensus.getQuorum()), 3) + assert.equals(await consensus.getQuorum(), 3) await consensus.removeMember(member3, 2, { from: admin }) assert.sameMembers((await consensus.getMembers()).addresses, [member2, member4, member5]) - assert.equal(+(await consensus.getQuorum()), 2) + assert.equals(await consensus.getQuorum(), 2) await consensus.removeMember(member4, 2, { from: admin }) assert.sameMembers((await consensus.getMembers()).addresses, [member2, member5]) - assert.equal(+(await consensus.getQuorum()), 2) + assert.equals(await consensus.getQuorum(), 2) await consensus.removeMember(member5, 1, { from: admin }) assert.sameMembers((await consensus.getMembers()).addresses, [member2]) - assert.equal(+(await consensus.getQuorum()), 1) + assert.equals(await consensus.getQuorum(), 1) await consensus.removeMember(member2, 1, { from: admin }) assert.isEmpty((await consensus.getMembers()).addresses) - assert.equal(+(await consensus.getQuorum()), 1) + assert.equals(await consensus.getQuorum(), 1) }) it(`removing a member who didn't vote doesn't decrease any report variant's support`, async () => { @@ -215,9 +185,9 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, assert.sameOrderedMembers(reportVariants.variants, [HASH_2]) assert.sameOrderedMembers(reportVariants.support.map(toNum), [3]) - tx = await consensus.removeMember(member2, 3, { from: admin }) + const tx = await consensus.removeMember(member2, 3, { from: admin }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_2, support: 3 } }) + assert.emits(tx, 'ConsensusReached', { refSlot, report: HASH_2, support: 3 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_2) }) @@ -247,7 +217,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, await consensus.removeMember(member1, 3, { from: admin }) - reportVariants = await consensus.getReportVariants() + const reportVariants = await consensus.getReportVariants() assert.sameOrderedMembers(reportVariants.variants, [HASH_1]) assert.sameOrderedMembers(reportVariants.support.map(toNum), [0]) }) @@ -264,7 +234,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 2 } }) + assert.emits(tx, 'ConsensusReached', { refSlot, report: HASH_1, support: 2 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.addMember(member3, 3, { from: admin }) @@ -284,7 +254,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 2 } }) + assert.emits(tx, 'ConsensusReached', { refSlot, report: HASH_1, support: 2 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.addMember(member3, 2, { from: admin }) @@ -304,7 +274,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 2 } }) + assert.emits(tx, 'ConsensusReached', { refSlot, report: HASH_1, support: 2 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.addMember(member3, 3, { from: admin }) @@ -331,7 +301,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 2 } }) + assert.emits(tx, 'ConsensusReached', { refSlot, report: HASH_1, support: 2 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member3 }) @@ -348,7 +318,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member5 }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_2, support: 3 } }) + assert.emits(tx, 'ConsensusReached', { refSlot, report: HASH_2, support: 3 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_2) }) @@ -362,7 +332,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) let tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_1, support: 2 } }) + assert.emits(tx, 'ConsensusReached', { refSlot, report: HASH_1, support: 2 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member3 }) @@ -382,7 +352,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) tx = await consensus.removeMember(member2, 3, { from: admin }) - assertEvent(tx, 'ConsensusReached', { expectedArgs: { refSlot, report: HASH_2, support: 3 } }) + assert.emits(tx, 'ConsensusReached', { refSlot, report: HASH_2, support: 3 }) assert.equal((await consensus.getConsensusState()).consensusReport, HASH_2) }) }) diff --git a/test/0.8.9/oracle/hash-consensus-report-processor.test.js b/test/0.8.9/oracle/hash-consensus-report-processor.test.js index 89fd55353..f9a7387e1 100644 --- a/test/0.8.9/oracle/hash-consensus-report-processor.test.js +++ b/test/0.8.9/oracle/hash-consensus-report-processor.test.js @@ -1,10 +1,10 @@ +const { contract, artifacts } = require('hardhat') const { assert } = require('../../helpers/assert') -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { ZERO_ADDRESS } = require('../../helpers/constants') const { HASH_1, CONSENSUS_VERSION, deployHashConsensus } = require('./hash-consensus-deploy.test') const { toNum } = require('../../helpers/utils') -const HashConsensus = artifacts.require('HashConsensusTimeTravellable') const MockReportProcessor = artifacts.require('MockReportProcessor') contract('HashConsensus', ([admin, member1, member2, stranger]) => { @@ -65,7 +65,7 @@ contract('HashConsensus', ([admin, member1, member2, stranger]) => { // to simulate situation when processing still in progress await consensus.setReportProcessor(reportProcessor2.address, { from: admin }) - assert.equal(+(await reportProcessor2.getLastCall_submitReport()).callCount, 1) + assert.equals((await reportProcessor2.getLastCall_submitReport()).callCount, 1) }) it('prev did processed current frame report — do not submit report to next', async () => { @@ -77,7 +77,7 @@ contract('HashConsensus', ([admin, member1, member2, stranger]) => { await reportProcessor1.startReportProcessing() await consensus.setReportProcessor(reportProcessor2.address, { from: admin }) - assert.equal(+(await reportProcessor2.getLastCall_submitReport()).callCount, 0) + assert.equals((await reportProcessor2.getLastCall_submitReport()).callCount, 0) }) it('next processor already have processed report for current frame', async () => { @@ -92,7 +92,7 @@ contract('HashConsensus', ([admin, member1, member2, stranger]) => { // 3 — Check call count of report submits await consensus.setReportProcessor(reportProcessor2.address, { from: admin }) - assert.equal(+(await reportProcessor2.getLastCall_submitReport()).callCount, 0) + assert.equals((await reportProcessor2.getLastCall_submitReport()).callCount, 0) }) it('do not submit report to next processor if there was no conensus', async () => { diff --git a/test/0.8.9/oracle/hash-consensus-set-quorum.js b/test/0.8.9/oracle/hash-consensus-set-quorum.test.js similarity index 62% rename from test/0.8.9/oracle/hash-consensus-set-quorum.js rename to test/0.8.9/oracle/hash-consensus-set-quorum.test.js index f49459cd9..283f09480 100644 --- a/test/0.8.9/oracle/hash-consensus-set-quorum.js +++ b/test/0.8.9/oracle/hash-consensus-set-quorum.test.js @@ -1,18 +1,10 @@ -const { assert } = require('chai') -const { assertEvent, assertAmountOfEvents, assertBn } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../../helpers/assertThrow') +const { contract } = require('hardhat') +const { assert } = require('../../helpers/assert') const { - SLOTS_PER_EPOCH, - SECONDS_PER_SLOT, - SECONDS_PER_EPOCH, - SECONDS_PER_FRAME, - computeEpochFirstSlot, - computeTimestampAtEpoch, ZERO_HASH, UNREACHABLE_QUORUM, HASH_1, - HASH_3, CONSENSUS_VERSION, deployHashConsensus, } = require('./hash-consensus-deploy.test') @@ -30,29 +22,29 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { before(deployContract) it('quorum is zero at deploy', async () => { - assert.equal(+(await consensus.getQuorum()), 0) + assert.equals(await consensus.getQuorum(), 0) }) it('quorum is changed, event is fired and getter returns new value', async () => { const tx1 = await consensus.setQuorum(1) - assert.equal(+(await consensus.getQuorum()), 1) - assertEvent(tx1, 'QuorumSet', { expectedArgs: { newQuorum: 1, totalMembers: 0, prevQuorum: 0 } }) + assert.equals(await consensus.getQuorum(), 1) + assert.emits(tx1, 'QuorumSet', { newQuorum: 1, totalMembers: 0, prevQuorum: 0 }) }) it('change to same value does not emit event and value is the same', async () => { const tx2 = await consensus.setQuorum(1) - assert.equal(+(await consensus.getQuorum()), 1) - assertAmountOfEvents(tx2, 'QuorumSet', { expectedAmount: 0 }) + assert.equals(await consensus.getQuorum(), 1) + assert.notEmits(tx2, 'QuorumSet') }) it('quorum value changes up and down', async () => { const tx3 = await consensus.setQuorum(10) - assert.equal(+(await consensus.getQuorum()), 10) - assertEvent(tx3, 'QuorumSet', { expectedArgs: { newQuorum: 10, totalMembers: 0, prevQuorum: 1 } }) + assert.equals(await consensus.getQuorum(), 10) + assert.emits(tx3, 'QuorumSet', { newQuorum: 10, totalMembers: 0, prevQuorum: 1 }) const tx4 = await consensus.setQuorum(5) - assert.equal(+(await consensus.getQuorum()), 5) - assertEvent(tx4, 'QuorumSet', { expectedArgs: { newQuorum: 5, totalMembers: 0, prevQuorum: 10 } }) + assert.equals(await consensus.getQuorum(), 5) + assert.emits(tx4, 'QuorumSet', { newQuorum: 5, totalMembers: 0, prevQuorum: 10 }) }) }) @@ -60,33 +52,33 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { before(deployContract) it('addMember adds member and updates quorum', async () => { - assert.equal(+(await consensus.getQuorum()), 0) + assert.equals(await consensus.getQuorum(), 0) const tx1 = await consensus.addMember(member1, 1, { from: admin }) - assert.equal(+(await consensus.getQuorum()), 1) - assertEvent(tx1, 'QuorumSet', { expectedArgs: { newQuorum: 1, totalMembers: 1, prevQuorum: 0 } }) + assert.equals(await consensus.getQuorum(), 1) + assert.emits(tx1, 'QuorumSet', { newQuorum: 1, totalMembers: 1, prevQuorum: 0 }) }) it('setQuorum reverts on value less than members/2', async () => { - await assertRevert(consensus.setQuorum(0), 'QuorumTooSmall(1, 0)') + await assert.reverts(consensus.setQuorum(0), 'QuorumTooSmall(1, 0)') await consensus.addMember(member2, 2, { from: admin }) - assert.equal(+(await consensus.getQuorum()), 2) + assert.equals(await consensus.getQuorum(), 2) - await assertRevert(consensus.setQuorum(1), 'QuorumTooSmall(2, 1)') + await assert.reverts(consensus.setQuorum(1), 'QuorumTooSmall(2, 1)') }) it('addMember sets any valid quorum value', async () => { await consensus.addMember(member3, 2, { from: admin }) - assert.equal(+(await consensus.getQuorum()), 2) + assert.equals(await consensus.getQuorum(), 2) await consensus.setQuorum(3) - assert.equal(+(await consensus.getQuorum()), 3) + assert.equals(await consensus.getQuorum(), 3) - await assertRevert(consensus.setQuorum(1), 'QuorumTooSmall(2, 1)') + await assert.reverts(consensus.setQuorum(1), 'QuorumTooSmall(2, 1)') await consensus.setQuorum(2) - assert.equal(+(await consensus.getQuorum()), 2) + assert.equals(await consensus.getQuorum(), 2) }) }) @@ -95,10 +87,12 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { it('disableConsensus updated quorum value and emits events', async () => { const tx = await consensus.disableConsensus() - assertEvent(tx, 'QuorumSet', { - expectedArgs: { newQuorum: UNREACHABLE_QUORUM.toString(10), totalMembers: 0, prevQuorum: 0 }, + assert.emits(tx, 'QuorumSet', { + newQuorum: UNREACHABLE_QUORUM.toString(10), + totalMembers: 0, + prevQuorum: 0, }) - assertBn(await consensus.getQuorum(), UNREACHABLE_QUORUM) + assert.equals(await consensus.getQuorum(), UNREACHABLE_QUORUM) }) }) }) @@ -125,21 +119,25 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { it('consensus is reached at 2/3 for quorum of 2', async () => { await consensus.setQuorum(2) const tx1 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx1, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 }, + assert.emits(tx1, 'ReportReceived', { + refSlot: frame.refSlot, + member: member1, + report: HASH_1, }) - assertAmountOfEvents(tx1, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx1, 'ConsensusReached') const tx2 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) - assertEvent(tx2, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 }, + assert.emits(tx2, 'ReportReceived', { + refSlot: frame.refSlot, + member: member2, + report: HASH_1, }) - assertAmountOfEvents(tx2, 'ConsensusReached', { expectedAmount: 1 }) - assert.equal(+(await reportProcessor.getLastCall_submitReport()).callCount, 1) + assert.emitsNumberOfEvents(tx2, 'ConsensusReached', 1) + assert.equals((await reportProcessor.getLastCall_submitReport()).callCount, 1) }) it('quorum increases and effective consensus is changed to none', async () => { const tx3 = await consensus.setQuorum(3) - assertAmountOfEvents(tx3, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx3, 'ConsensusReached') const consensusState = await consensus.getConsensusState() assert.equal(consensusState.consensusReport, ZERO_HASH) assert.isFalse(consensusState.isReportProcessing) @@ -158,21 +156,25 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { it('2/3 reports come in', async () => { const tx1 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx1, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 }, + assert.emits(tx1, 'ReportReceived', { + refSlot: frame.refSlot, + member: member1, + report: HASH_1, }) - assertAmountOfEvents(tx1, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx1, 'ConsensusReached') const tx2 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) - assertEvent(tx2, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 }, + assert.emits(tx2, 'ReportReceived', { + refSlot: frame.refSlot, + member: member2, + report: HASH_1, }) - assertAmountOfEvents(tx2, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx2, 'ConsensusReached') }) it('quorum decreases and consensus is reached', async () => { const tx3 = await consensus.setQuorum(2) - assertAmountOfEvents(tx3, 'ConsensusReached', { expectedAmount: 1 }) + assert.emitsNumberOfEvents(tx3, 'ConsensusReached', 1) const consensusState = await consensus.getConsensusState() assert.equal(consensusState.consensusReport, HASH_1) }) @@ -184,17 +186,21 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { it('2/3 members reach consensus with quorum of 2', async () => { await consensus.setQuorum(2) const tx1 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx1, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 }, + assert.emits(tx1, 'ReportReceived', { + refSlot: frame.refSlot, + member: member1, + report: HASH_1, }) - assertAmountOfEvents(tx1, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx1, 'ConsensusReached') const tx2 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) - assertEvent(tx2, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 }, + assert.emits(tx2, 'ReportReceived', { + refSlot: frame.refSlot, + member: member2, + report: HASH_1, }) - assertAmountOfEvents(tx2, 'ConsensusReached', { expectedAmount: 1 }) - assert.equal(+(await reportProcessor.getLastCall_submitReport()).callCount, 1) + assert.emitsNumberOfEvents(tx2, 'ConsensusReached', 1) + assert.equals((await reportProcessor.getLastCall_submitReport()).callCount, 1) }) it('quorum goes up and effective consensus changes to none', async () => { @@ -206,13 +212,13 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { it('quorum goes down but same consensus is not triggered and report is not submitted', async () => { const tx = await consensus.setQuorum(2) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') const consensusState = await consensus.getConsensusState() assert.equal(consensusState.consensusReport, HASH_1) assert.isFalse(consensusState.isReportProcessing) - assert.equal(+(await reportProcessor.getLastCall_submitReport()).callCount, 1) + assert.equals((await reportProcessor.getLastCall_submitReport()).callCount, 1) }) }) @@ -222,16 +228,20 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { it('2/3 members reach consensus with Quorum of 2', async () => { await consensus.setQuorum(2) const tx1 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member1 }) - assertEvent(tx1, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member1, report: HASH_1 }, + assert.emits(tx1, 'ReportReceived', { + refSlot: frame.refSlot, + member: member1, + report: HASH_1, }) - assertAmountOfEvents(tx1, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx1, 'ConsensusReached') const tx2 = await consensus.submitReport(frame.refSlot, HASH_1, CONSENSUS_VERSION, { from: member2 }) - assertEvent(tx2, 'ReportReceived', { - expectedArgs: { refSlot: frame.refSlot, member: member2, report: HASH_1 }, + assert.emits(tx2, 'ReportReceived', { + refSlot: frame.refSlot, + member: member2, + report: HASH_1, }) - assertAmountOfEvents(tx2, 'ConsensusReached', { expectedAmount: 1 }) + assert.emitsNumberOfEvents(tx2, 'ConsensusReached', 1) }) it('reportProcessor starts processing', async () => { @@ -249,8 +259,8 @@ contract('HashConsensus', ([admin, member1, member2, member3]) => { it('quorum decreases but no consensus is triggered', async () => { const tx = await consensus.setQuorum(2) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) - assert.equal(+(await reportProcessor.getLastCall_submitReport()).callCount, 1) + assert.notEmits(tx, 'ConsensusReached') + assert.equals((await reportProcessor.getLastCall_submitReport()).callCount, 1) }) }) }) diff --git a/test/0.8.9/oracle/hash-consensus-submit-report.test.js b/test/0.8.9/oracle/hash-consensus-submit-report.test.js index e54e08164..7aedf07a9 100644 --- a/test/0.8.9/oracle/hash-consensus-submit-report.test.js +++ b/test/0.8.9/oracle/hash-consensus-submit-report.test.js @@ -1,16 +1,15 @@ +const { contract } = require('hardhat') const { assert } = require('../../helpers/assert') const { deployHashConsensus, CONSENSUS_VERSION, ZERO_HASH, HASH_1 } = require('./hash-consensus-deploy.test') -const HashConsensus = artifacts.require('HashConsensusTimeTravellable') -const MockReportProcessor = artifacts.require('MockReportProcessor') - const CONSENSUS_VERSION_2 = 2 contract('HashConsensus', ([admin, member1, member2, stranger]) => { context('Report Submitting', () => { let consensus let frame + let reportProcessor const deploy = async (options = { epochsPerFrame: 200 }) => { const deployed = await deployHashConsensus(admin, options) diff --git a/test/0.8.9/oracle/validators-exit-bus-oracle-access-control.test.js b/test/0.8.9/oracle/validators-exit-bus-oracle-access-control.test.js index ba7e0a1f4..dca98c7f8 100644 --- a/test/0.8.9/oracle/validators-exit-bus-oracle-access-control.test.js +++ b/test/0.8.9/oracle/validators-exit-bus-oracle-access-control.test.js @@ -1,5 +1,6 @@ -const { assert } = require('chai') -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { contract, web3 } = require('hardhat') +const { assert } = require('../../helpers/assert') +const { ZERO_ADDRESS } = require('../../helpers/constants') const { CONSENSUS_VERSION, diff --git a/test/0.8.9/oracle/validators-exit-bus-oracle-deploy.test.js b/test/0.8.9/oracle/validators-exit-bus-oracle-deploy.test.js index d8a2f3050..69066b197 100644 --- a/test/0.8.9/oracle/validators-exit-bus-oracle-deploy.test.js +++ b/test/0.8.9/oracle/validators-exit-bus-oracle-deploy.test.js @@ -1,6 +1,7 @@ +const { contract, artifacts, web3 } = require('hardhat') const { assert } = require('../../helpers/assert') const { hex, strip0x } = require('../../helpers/utils') -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { ZERO_ADDRESS } = require('../../helpers/constants') const { updateLocatorImplementation, deployLocatorWithDummyAddressesImplementation, @@ -156,7 +157,7 @@ async function deployExitBusOracle( await oracle.grantRole(await oracle.SUBMIT_DATA_ROLE(), dataSubmitter, { from: admin }) } - assert.equal(+(await oracle.DATA_FORMAT_LIST()), DATA_FORMAT_LIST) + assert.equals(await oracle.DATA_FORMAT_LIST(), DATA_FORMAT_LIST) if (resumeAfterDeploy) { await oracle.resume({ from: admin }) @@ -178,18 +179,18 @@ contract('ValidatorsExitBusOracle', ([admin, member1]) => { it('mock time-travellable setup is correct', async () => { const time1 = +(await consensus.getTime()) - assert.equal(+(await oracle.getTime()), time1) + assert.equals(await oracle.getTime(), time1) await consensus.advanceTimeBy(SECONDS_PER_SLOT) const time2 = +(await consensus.getTime()) assert.equal(time2, time1 + SECONDS_PER_SLOT) - assert.equal(+(await oracle.getTime()), time2) + assert.equals(await oracle.getTime(), time2) }) it('initial configuration is correct', async () => { assert.equal(await oracle.getConsensusContract(), consensus.address) - assert.equal(+(await oracle.getConsensusVersion()), CONSENSUS_VERSION) - assert.equal(+(await oracle.SECONDS_PER_SLOT()), SECONDS_PER_SLOT) + assert.equals(await oracle.getConsensusVersion(), CONSENSUS_VERSION) + assert.equals(await oracle.SECONDS_PER_SLOT(), SECONDS_PER_SLOT) assert.equal(await oracle.isPaused(), true) }) diff --git a/test/0.8.9/oracle/validators-exit-bus-oracle-gas.test.js b/test/0.8.9/oracle/validators-exit-bus-oracle-gas.test.js index 83f850e15..ddc91d4ef 100644 --- a/test/0.8.9/oracle/validators-exit-bus-oracle-gas.test.js +++ b/test/0.8.9/oracle/validators-exit-bus-oracle-gas.test.js @@ -1,38 +1,17 @@ -const { BN } = require('bn.js') -const { assert } = require('chai') -const { assertBn, assertEvent, assertAmountOfEvents } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../../helpers/assertThrow') -const { toNum, processNamedTuple } = require('../../helpers/utils') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') +const { contract } = require('hardhat') +const { assert } = require('../../helpers/assert') const { - SLOTS_PER_EPOCH, - SECONDS_PER_SLOT, - GENESIS_TIME, - SECONDS_PER_EPOCH, - EPOCHS_PER_FRAME, SLOTS_PER_FRAME, SECONDS_PER_FRAME, - MAX_REQUESTS_PER_REPORT, - MAX_REQUESTS_LIST_LENGTH, - MAX_REQUESTS_PER_DAY, - RATE_LIMIT_WINDOW_SLOTS, - RATE_LIMIT_THROUGHPUT, - computeSlotAt, - computeEpochAt, - computeEpochFirstSlotAt, - computeEpochFirstSlot, computeTimestampAtSlot, - computeTimestampAtEpoch, ZERO_HASH, CONSENSUS_VERSION, DATA_FORMAT_LIST, getReportDataItems, calcReportDataHash, - encodeExitRequestHex, encodeExitRequestsDataList, deployExitBusOracle, - deployOracleReportSanityCheckerForExitBus, } = require('./validators-exit-bus-oracle-deploy.test') const PUBKEYS = [ @@ -146,16 +125,16 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it('oracle gets the report hash', async () => { const report = await oracle.getConsensusReport() assert.equal(report.hash, reportHash) - assert.equal(+report.refSlot, +reportFields.refSlot) - assert.equal(+report.processingDeadlineTime, computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME)) + assert.equals(report.refSlot, +reportFields.refSlot) + assert.equals(report.processingDeadlineTime, computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME)) assert.isFalse(report.processingStarted) const procState = await oracle.getProcessingState() assert.equal(procState.dataHash, reportHash) assert.isFalse(procState.dataSubmitted) - assert.equal(+procState.dataFormat, 0) - assert.equal(+procState.requestsCount, 0) - assert.equal(+procState.requestsSubmitted, 0) + assert.equals(procState.dataFormat, 0) + assert.equals(procState.requestsCount, 0) + assert.equals(procState.requestsSubmitted, 0) }) it('some time passes', async () => { @@ -164,22 +143,19 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it(`a committee member submits the report data, exit requests are emitted`, async () => { const tx = await oracle.submitReportData(reportItems, oracleVersion, { from: member1 }) - assertEvent(tx, 'ProcessingStarted', { expectedArgs: { refSlot: reportFields.refSlot } }) + assert.emits(tx, 'ProcessingStarted', { refSlot: reportFields.refSlot }) assert.isTrue((await oracle.getConsensusReport()).processingStarted) const timestamp = await oracle.getTime() const { requests, requestsPerModule, requestsPerNodeOp } = exitRequests for (let i = 0; i < requests.length; ++i) { - assertEvent(tx, 'ValidatorExitRequest', { - index: i, - expectedArgs: { - stakingModuleId: requests[i].moduleId, - nodeOperatorId: requests[i].nodeOpId, - validatorIndex: requests[i].valIndex, - validatorPubkey: requests[i].valPubkey, - timestamp, - }, + assert.emitsAt(tx, 'ValidatorExitRequest', i, { + stakingModuleId: requests[i].moduleId, + nodeOperatorId: requests[i].nodeOpId, + validatorIndex: requests[i].valIndex, + validatorPubkey: requests[i].valPubkey, + timestamp, }) } @@ -191,9 +167,9 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const procState = await oracle.getProcessingState() assert.equal(procState.dataHash, reportHash) assert.isTrue(procState.dataSubmitted) - assert.equal(+procState.dataFormat, DATA_FORMAT_LIST) - assert.equal(+procState.requestsCount, exitRequests.requests.length) - assert.equal(+procState.requestsSubmitted, exitRequests.requests.length) + assert.equals(procState.dataFormat, DATA_FORMAT_LIST) + assert.equals(procState.requestsCount, exitRequests.requests.length) + assert.equals(procState.requestsSubmitted, exitRequests.requests.length) }) it('some time passes', async () => { diff --git a/test/0.8.9/oracle/validators-exit-bus-oracle-happy-path.test.js b/test/0.8.9/oracle/validators-exit-bus-oracle-happy-path.test.js index 9eeb4228d..ae553285d 100644 --- a/test/0.8.9/oracle/validators-exit-bus-oracle-happy-path.test.js +++ b/test/0.8.9/oracle/validators-exit-bus-oracle-happy-path.test.js @@ -1,35 +1,16 @@ -const { BN } = require('bn.js') -const { assert } = require('chai') -const { assertBn, assertEvent, assertAmountOfEvents } = require('@aragon/contract-helpers-test/src/asserts') -const { assertRevert } = require('../../helpers/assertThrow') +const { contract } = require('hardhat') +const { assert } = require('../../helpers/assert') const { toNum } = require('../../helpers/utils') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') const { - SLOTS_PER_EPOCH, - SECONDS_PER_SLOT, - GENESIS_TIME, - SECONDS_PER_EPOCH, - EPOCHS_PER_FRAME, SLOTS_PER_FRAME, SECONDS_PER_FRAME, - MAX_REQUESTS_PER_REPORT, - MAX_REQUESTS_LIST_LENGTH, - MAX_REQUESTS_PER_DAY, - RATE_LIMIT_WINDOW_SLOTS, - RATE_LIMIT_THROUGHPUT, - computeSlotAt, - computeEpochAt, - computeEpochFirstSlotAt, - computeEpochFirstSlot, computeTimestampAtSlot, - computeTimestampAtEpoch, ZERO_HASH, CONSENSUS_VERSION, DATA_FORMAT_LIST, getReportDataItems, calcReportDataHash, - encodeExitRequestHex, encodeExitRequestsDataList, deployExitBusOracle, } = require('./validators-exit-bus-oracle-deploy.test') @@ -82,7 +63,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const report = await oracle.getConsensusReport() assert.equal(report.hash, ZERO_HASH) // see the next test for refSlot - assert.equal(+report.processingDeadlineTime, 0) + assert.equals(report.processingDeadlineTime, 0) assert.isFalse(report.processingStarted) const frame = await consensus.getCurrentFrame() @@ -92,19 +73,15 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger assert.equal(procState.dataHash, ZERO_HASH) assert.equal(procState.processingDeadlineTime, 0) assert.isFalse(procState.dataSubmitted) - assert.equal(+procState.dataFormat, 0) - assert.equal(+procState.requestsCount, 0) - assert.equal(+procState.requestsSubmitted, 0) + assert.equals(procState.dataFormat, 0) + assert.equals(procState.requestsCount, 0) + assert.equals(procState.requestsSubmitted, 0) }) - it( - `reference slot of the empty initial consensus report is set to the last processing slot ` + - `passed to the initialize function`, - async () => { - const report = await oracle.getConsensusReport() - assert.equal(+report.refSlot, LAST_PROCESSING_REF_SLOT) - } - ) + it(`reference slot of the empty initial consensus report is set to the last processing slot passed to the initialize function`, async () => { + const report = await oracle.getConsensusReport() + assert.equals(report.refSlot, LAST_PROCESSING_REF_SLOT) + }) it('committee reaches consensus on a report hash', async () => { const { refSlot } = await consensus.getCurrentFrame() @@ -132,8 +109,8 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it('oracle gets the report hash', async () => { const report = await oracle.getConsensusReport() assert.equal(report.hash, reportHash) - assert.equal(+report.refSlot, +reportFields.refSlot) - assert.equal(+report.processingDeadlineTime, computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME)) + assert.equals(report.refSlot, +reportFields.refSlot) + assert.equals(report.processingDeadlineTime, computeTimestampAtSlot(+report.refSlot + SLOTS_PER_FRAME)) assert.isFalse(report.processingStarted) const frame = await consensus.getCurrentFrame() @@ -143,9 +120,9 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger assert.equal(procState.dataHash, reportHash) assert.equal(procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.isFalse(procState.dataSubmitted) - assert.equal(+procState.dataFormat, 0) - assert.equal(+procState.requestsCount, 0) - assert.equal(+procState.requestsSubmitted, 0) + assert.equals(procState.dataFormat, 0) + assert.equals(procState.requestsCount, 0) + assert.equals(procState.requestsSubmitted, 0) }) it('some time passes', async () => { @@ -153,11 +130,14 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger }) it('non-member cannot submit the data', async () => { - await assertRevert(oracle.submitReportData(reportItems, oracleVersion, { from: stranger }), 'SenderNotAllowed()') + await assert.reverts( + oracle.submitReportData(reportItems, oracleVersion, { from: stranger }), + 'SenderNotAllowed()' + ) }) it('the data cannot be submitted passing a different contract version', async () => { - await assertRevert( + await assert.reverts( oracle.submitReportData(reportItems, oracleVersion - 1, { from: member1 }), `UnexpectedContractVersion(${oracleVersion}, ${oracleVersion - 1})` ) @@ -165,8 +145,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it('the data cannot be submitted passing a different consensus version', async () => { const invalidReport = { ...reportFields, consensusVersion: CONSENSUS_VERSION + 1 } - const invalidReportItems = getReportDataItems(invalidReport) - await assertRevert( + await assert.reverts( oracle.submitReportData(invalidReport, oracleVersion, { from: member1 }), `UnexpectedConsensusVersion(${CONSENSUS_VERSION}, ${CONSENSUS_VERSION + 1})` ) @@ -176,7 +155,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger const invalidReport = { ...reportFields, requestsCount: reportFields.requestsCount + 1 } const invalidReportItems = getReportDataItems(invalidReport) const invalidReportHash = calcReportDataHash(invalidReportItems) - await assertRevert( + await assert.reverts( oracle.submitReportData(invalidReportItems, oracleVersion, { from: member1 }), `UnexpectedDataHash("${reportHash}", "${invalidReportHash}")` ) @@ -184,21 +163,18 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it(`a committee member submits the report data, exit requests are emitted`, async () => { const tx = await oracle.submitReportData(reportItems, oracleVersion, { from: member1 }) - assertEvent(tx, 'ProcessingStarted', { expectedArgs: { refSlot: reportFields.refSlot } }) + assert.emits(tx, 'ProcessingStarted', { refSlot: reportFields.refSlot }) assert.isTrue((await oracle.getConsensusReport()).processingStarted) const timestamp = await oracle.getTime() for (let i = 0; i < exitRequests.length; ++i) { - assertEvent(tx, 'ValidatorExitRequest', { - index: i, - expectedArgs: { - stakingModuleId: exitRequests[i].moduleId, - nodeOperatorId: exitRequests[i].nodeOpId, - validatorIndex: exitRequests[i].valIndex, - validatorPubkey: exitRequests[i].valPubkey, - timestamp, - }, + assert.emitsAt(tx, 'ValidatorExitRequest', i, { + stakingModuleId: exitRequests[i].moduleId, + nodeOperatorId: exitRequests[i].nodeOpId, + validatorIndex: exitRequests[i].valIndex, + validatorPubkey: exitRequests[i].valPubkey, + timestamp, }) } }) @@ -211,9 +187,9 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger assert.equal(procState.dataHash, reportHash) assert.equal(procState.processingDeadlineTime, computeTimestampAtSlot(+frame.reportProcessingDeadlineSlot)) assert.isTrue(procState.dataSubmitted) - assert.equal(+procState.dataFormat, DATA_FORMAT_LIST) - assert.equal(+procState.requestsCount, exitRequests.length) - assert.equal(+procState.requestsSubmitted, exitRequests.length) + assert.equals(procState.dataFormat, DATA_FORMAT_LIST) + assert.equals(procState.requestsCount, exitRequests.length) + assert.equals(procState.requestsSubmitted, exitRequests.length) }) it('last requested validator indices are updated', async () => { diff --git a/test/0.8.9/oracle/validators-exit-bus-oracle-submit-report-data.test.js b/test/0.8.9/oracle/validators-exit-bus-oracle-submit-report-data.test.js index e8d581405..f7140cb26 100644 --- a/test/0.8.9/oracle/validators-exit-bus-oracle-submit-report-data.test.js +++ b/test/0.8.9/oracle/validators-exit-bus-oracle-submit-report-data.test.js @@ -1,3 +1,4 @@ +const { contract } = require('hardhat') const { assert } = require('../../helpers/assert') const { @@ -255,10 +256,10 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger it('updates processing state', async () => { const storageBefore = await oracle.getDataProcessingState() - assert.equals(+storageBefore.refSlot, 0) - assert.equals(+storageBefore.requestsCount, 0) - assert.equals(+storageBefore.requestsProcessed, 0) - assert.equals(+storageBefore.dataFormat, 0) + assert.equals(storageBefore.refSlot, 0) + assert.equals(storageBefore.requestsCount, 0) + assert.equals(storageBefore.requestsProcessed, 0) + assert.equals(storageBefore.dataFormat, 0) const { refSlot } = await consensus.getCurrentFrame() const requests = [ @@ -269,16 +270,16 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger await oracle.submitReportData(report, oracleVersion, { from: member1 }) const storageAfter = await oracle.getDataProcessingState() - assert.equals(+storageAfter.refSlot, +refSlot) - assert.equals(+storageAfter.requestsCount, requests.length) - assert.equals(+storageAfter.requestsProcessed, requests.length) - assert.equals(+storageAfter.dataFormat, DATA_FORMAT_LIST) + assert.equals(storageAfter.refSlot, +refSlot) + assert.equals(storageAfter.requestsCount, requests.length) + assert.equals(storageAfter.requestsProcessed, requests.length) + assert.equals(storageAfter.dataFormat, DATA_FORMAT_LIST) }) it('updates total requests processed count', async () => { let currentCount = 0 const countStep0 = await oracle.getTotalRequestsProcessed() - assert.equals(+countStep0, currentCount) + assert.equals(countStep0, currentCount) // Step 1 — process 1 item const requestsStep1 = [{ moduleId: 3, nodeOpId: 1, valIndex: 2, valPubkey: PUBKEYS[1] }] @@ -286,7 +287,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger await oracle.submitReportData(reportStep1, oracleVersion, { from: member1 }) const countStep1 = await oracle.getTotalRequestsProcessed() currentCount += requestsStep1.length - assert.equals(+countStep1, currentCount) + assert.equals(countStep1, currentCount) // Step 2 — process 2 items await consensus.advanceTimeToNextFrameStart() @@ -298,7 +299,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger await oracle.submitReportData(reportStep2, oracleVersion, { from: member1 }) const countStep2 = await oracle.getTotalRequestsProcessed() currentCount += requestsStep2.length - assert.equals(+countStep2, currentCount) + assert.equals(countStep2, currentCount) // Step 3 — process no items await consensus.advanceTimeToNextFrameStart() @@ -307,7 +308,7 @@ contract('ValidatorsExitBusOracle', ([admin, member1, member2, member3, stranger await oracle.submitReportData(reportStep3, oracleVersion, { from: member1 }) const countStep3 = await oracle.getTotalRequestsProcessed() currentCount += requestsStep3.length - assert.equals(+countStep3, currentCount) + assert.equals(countStep3, currentCount) }) }) diff --git a/test/0.8.9/pausable-until.test.js b/test/0.8.9/pausable-until.test.js index c6d98d169..136dab74d 100644 --- a/test/0.8.9/pausable-until.test.js +++ b/test/0.8.9/pausable-until.test.js @@ -1,21 +1,21 @@ -const hre = require('hardhat') +const { artifacts, contract, ethers } = require('hardhat') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') +const { bn } = require('@aragon/contract-helpers-test') const { EvmSnapshot, advanceChainTime, getCurrentBlockTimestamp } = require('../helpers/blockchain') -const { ETH, StETH } = require('../helpers/utils') const { assert } = require('../helpers/assert') const PausableUntil = artifacts.require('PausableUntilPrivateExposed') -contract('PausableUntil', ([deployer, _, anotherAccount]) => { +contract('PausableUntil', ([deployer]) => { let pausable let PAUSE_INFINITELY + let snapshot before('deploy lido with dao', async () => { pausable = await PausableUntil.new({ from: deployer }) PAUSE_INFINITELY = await pausable.PAUSE_INFINITELY() - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() }) diff --git a/test/0.8.9/positive-token-rebase-limiter.test.js b/test/0.8.9/positive-token-rebase-limiter.test.js index 49df2664d..a7bebe038 100644 --- a/test/0.8.9/positive-token-rebase-limiter.test.js +++ b/test/0.8.9/positive-token-rebase-limiter.test.js @@ -1,6 +1,6 @@ -const hre = require('hardhat') +const { artifacts, contract, ethers } = require('hardhat') -const { bn, MAX_UINT64, ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { bn, MAX_UINT64 } = require('@aragon/contract-helpers-test') const { EvmSnapshot } = require('../helpers/blockchain') const { ETH } = require('../helpers/utils') const { assert } = require('../helpers/assert') @@ -8,13 +8,13 @@ const { assert } = require('../helpers/assert') const PositiveTokenRebaseLimiter = artifacts.require('PositiveTokenRebaseLimiterMock.sol') const UNLIMITED_REBASE = bn(MAX_UINT64) -contract('PositiveTokenRebaseLimiter', ([account1]) => { +contract('PositiveTokenRebaseLimiter', () => { let limiter, snapshot before('deploy mock', async () => { limiter = await PositiveTokenRebaseLimiter.new() - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() }) diff --git a/test/0.8.9/staking-router-allocation-combinations.test.js b/test/0.8.9/staking-router-allocation-combinations.test.js index c455a9213..5913aa52b 100644 --- a/test/0.8.9/staking-router-allocation-combinations.test.js +++ b/test/0.8.9/staking-router-allocation-combinations.test.js @@ -1,6 +1,5 @@ -const hre = require('hardhat') -const { assert } = require('chai') -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') +const { artifacts, contract, ethers } = require('hardhat') +const { assert } = require('../helpers/assert') const { BigNumber } = require('ethers') const StakingRouter = artifacts.require('StakingRouterMock.sol') const StakingModuleMock = artifacts.require('StakingModuleMock.sol') @@ -40,12 +39,12 @@ contract('StakingRouter', (accounts) => { await stakingRouter.grantRole(STAKING_MODULE_PAUSE_ROLE, admin, { from: admin }) await stakingRouter.grantRole(STAKING_MODULE_MANAGE_ROLE, admin, { from: admin }) - evmSnapshotId = await hre.ethers.provider.send('evm_snapshot', []) + evmSnapshotId = await ethers.provider.send('evm_snapshot', []) }) afterEach(async () => { - await hre.ethers.provider.send('evm_revert', [evmSnapshotId]) - evmSnapshotId = await hre.ethers.provider.send('evm_snapshot', []) + await ethers.provider.send('evm_revert', [evmSnapshotId]) + evmSnapshotId = await ethers.provider.send('evm_snapshot', []) }) const TWO_MODULES_TARGET_SHARES_CASES = [ @@ -75,18 +74,18 @@ contract('StakingRouter', (accounts) => { for (const availableKeys of MODULE_AVAILABLE_KEYS_CASES) { for (const activeKeys of MODULE_ACTIVE_KEYS_CASES) { await StakingModule1.setAvailableKeysCount(availableKeys) - assertBn(await StakingModule1.getAvailableValidatorsCount(), availableKeys) + assert.equals(await StakingModule1.getAvailableValidatorsCount(), availableKeys) await StakingModule1.setActiveValidatorsCount(activeKeys) - assertBn(await StakingModule1.getActiveValidatorsCount(), activeKeys) + assert.equals(await StakingModule1.getActiveValidatorsCount(), activeKeys) const { allocated, allocations } = await stakingRouter.getDepositsAllocation(depositableKeys) const expectedAllocated = Math.min(depositableKeys, availableKeys) - assertBn(allocated, expectedAllocated) + assert.equals(allocated, expectedAllocated) assert.equal(allocations.length, 1) - assertBn(allocations[0], activeKeys + expectedAllocated) + assert.equals(allocations[0], activeKeys + expectedAllocated) } } } @@ -121,20 +120,20 @@ contract('StakingRouter', (accounts) => { for (const module2AvailableKeys of module2AvailableKeyCases) { for (const module1ActiveKeys of module1ActiveKeyCases) { for (const module2ActiveKeys of module2ActiveKeyCases) { - assertBn((await stakingRouter.getStakingModuleByIndex(0)).targetShare, module1TargetShare) - assertBn((await stakingRouter.getStakingModuleByIndex(1)).targetShare, module2TargetShare) + assert.equals((await stakingRouter.getStakingModuleByIndex(0)).targetShare, module1TargetShare) + assert.equals((await stakingRouter.getStakingModuleByIndex(1)).targetShare, module2TargetShare) await StakingModule1.setAvailableKeysCount(module1AvailableKeys) - assertBn(await StakingModule1.getAvailableValidatorsCount(), module1AvailableKeys) + assert.equals(await StakingModule1.getAvailableValidatorsCount(), module1AvailableKeys) await StakingModule2.setAvailableKeysCount(module2AvailableKeys) - assertBn(await StakingModule2.getAvailableValidatorsCount(), module2AvailableKeys) + assert.equals(await StakingModule2.getAvailableValidatorsCount(), module2AvailableKeys) await StakingModule1.setActiveValidatorsCount(module1ActiveKeys) - assertBn(await StakingModule1.getActiveValidatorsCount(), module1ActiveKeys) + assert.equals(await StakingModule1.getActiveValidatorsCount(), module1ActiveKeys) await StakingModule2.setActiveValidatorsCount(module2ActiveKeys) - assertBn(await StakingModule2.getActiveValidatorsCount(), module2ActiveKeys) + assert.equals(await StakingModule2.getActiveValidatorsCount(), module2ActiveKeys) const { allocated, allocations } = await stakingRouter.getDepositsAllocation(depositableKeys) @@ -157,13 +156,13 @@ contract('StakingRouter', (accounts) => { ) const expectedAllocated = Math.min(depositableKeys, module1DepositableKeys + module2DepositableKeys) - assertBn(allocated, expectedAllocated) + assert.equals(allocated, expectedAllocated) assert.equal(allocations.length, 2) - assertBn( + assert.equals( allocations[0], module1ActiveKeys + Math.max(0, expectedAllocated - module2DepositableKeys) ) - assertBn( + assert.equals( allocations[1], module2ActiveKeys + Math.max(0, expectedAllocated - module1DepositableKeys) ) diff --git a/test/0.8.9/staking-router-deposits-allocation.test.js b/test/0.8.9/staking-router-deposits-allocation.test.js index 729bdf608..8cffae23a 100644 --- a/test/0.8.9/staking-router-deposits-allocation.test.js +++ b/test/0.8.9/staking-router-deposits-allocation.test.js @@ -1,6 +1,6 @@ -const hre = require('hardhat') -const { assert } = require('chai') -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') +const { artifacts, contract, ethers } = require('hardhat') +const { assert } = require('../helpers/assert') + const StakingRouter = artifacts.require('StakingRouterMock.sol') const StakingModuleMock = artifacts.require('StakingModuleMock.sol') const DepositContractMock = artifacts.require('DepositContractMock.sol') @@ -35,12 +35,12 @@ contract('StakingRouter', (accounts) => { await stakingRouter.grantRole(STAKING_MODULE_PAUSE_ROLE, admin, { from: admin }) await stakingRouter.grantRole(STAKING_MODULE_MANAGE_ROLE, admin, { from: admin }) - evmSnapshotId = await hre.ethers.provider.send('evm_snapshot', []) + evmSnapshotId = await ethers.provider.send('evm_snapshot', []) }) afterEach(async () => { - await hre.ethers.provider.send('evm_revert', [evmSnapshotId]) - evmSnapshotId = await hre.ethers.provider.send('evm_snapshot', []) + await ethers.provider.send('evm_revert', [evmSnapshotId]) + evmSnapshotId = await ethers.provider.send('evm_snapshot', []) }) describe('One staking module', () => { @@ -58,34 +58,34 @@ contract('StakingRouter', (accounts) => { it('getDepositsAllocation :: staking module without keys', async () => { const { allocated, allocations } = await stakingRouter.getDepositsAllocation(0) - assertBn(allocated, 0) - assert.equal(allocations.length, 1) - assertBn(allocations[0], 0) + assert.equals(allocated, 0) + assert.equals(allocations.length, 1) + assert.equals(allocations[0], 0) }) it('getDepositsAllocation :: staking module with zero used keys', async () => { await curatedStakingModuleMock.setAvailableKeysCount(500) - assertBn(await curatedStakingModuleMock.getAvailableValidatorsCount(), 500) + assert.equals(await curatedStakingModuleMock.getAvailableValidatorsCount(), 500) const { allocated, allocations } = await stakingRouter.getDepositsAllocation(1000) - assertBn(allocated, 500) + assert.equals(allocated, 500) assert.equal(allocations.length, 1) - assertBn(allocations[0], 500) + assert.equals(allocations[0], 500) }) it('getDepositsAllocation :: staking module with non zero used keys', async () => { await curatedStakingModuleMock.setActiveValidatorsCount(250) - assertBn(await curatedStakingModuleMock.getActiveValidatorsCount(), 250) + assert.equals(await curatedStakingModuleMock.getActiveValidatorsCount(), 250) await curatedStakingModuleMock.setAvailableKeysCount(250) - assertBn(await curatedStakingModuleMock.getAvailableValidatorsCount(), 250) + assert.equals(await curatedStakingModuleMock.getAvailableValidatorsCount(), 250) const { allocated, allocations } = await stakingRouter.getDepositsAllocation(250) - assertBn(allocated, 250) + assert.equals(allocated, 250) assert.equal(allocations.length, 1) - assertBn(allocations[0], 500) + assert.equals(allocations[0], 500) }) }) @@ -111,25 +111,25 @@ contract('StakingRouter', (accounts) => { it('getDepositsAllocation :: equal available keys', async () => { await curatedStakingModuleMock.setActiveValidatorsCount(4500) - assertBn(await curatedStakingModuleMock.getActiveValidatorsCount(), 4500) + assert.equals(await curatedStakingModuleMock.getActiveValidatorsCount(), 4500) await curatedStakingModuleMock.setAvailableKeysCount(500) - assertBn(await curatedStakingModuleMock.getAvailableValidatorsCount(), 500) + assert.equals(await curatedStakingModuleMock.getAvailableValidatorsCount(), 500) await soloStakingModuleMock.setActiveValidatorsCount(50) - assertBn(await soloStakingModuleMock.getActiveValidatorsCount(), 50) + assert.equals(await soloStakingModuleMock.getActiveValidatorsCount(), 50) await soloStakingModuleMock.setAvailableKeysCount(250) - assertBn(await soloStakingModuleMock.getAvailableValidatorsCount(), 250) + assert.equals(await soloStakingModuleMock.getAvailableValidatorsCount(), 250) const { allocated, allocations } = await stakingRouter.getDepositsAllocation(333) - assertBn(allocated, 333) + assert.equals(allocated, 333) assert.equal(allocations.length, 2) - assertBn(allocations[0], 4786) + assert.equals(allocations[0], 4786) // newTotalKeysCount: 4883 -> 0.02 * 4883 = 97 - assertBn(allocations[1], 97) + assert.equals(allocations[1], 97) }) }) diff --git a/test/0.8.9/staking-router-deposits.test.js b/test/0.8.9/staking-router-deposits.test.js index 42a9499a8..51b7c3811 100644 --- a/test/0.8.9/staking-router-deposits.test.js +++ b/test/0.8.9/staking-router-deposits.test.js @@ -1,5 +1,4 @@ -const hre = require('hardhat') -const { assertEvent } = require('@aragon/contract-helpers-test/src/asserts') +const { contract, ethers, web3 } = require('hardhat') const { EvmSnapshot } = require('../helpers/blockchain') const { setupNodeOperatorsRegistry } = require('../helpers/staking-modules') @@ -28,7 +27,7 @@ contract('StakingRouter', ([depositor, stranger]) => { operators = await setupNodeOperatorsRegistry(deployed, true) voting = deployed.voting.address depositContract = deployed.depositContract - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() }) @@ -59,7 +58,7 @@ contract('StakingRouter', ([depositor, stranger]) => { await assert.reverts(lido.deposit(maxDepositsCount, curated.id, '0x', { from: stranger }), 'APP_AUTH_DSM_FAILED') await assert.reverts(lido.deposit(maxDepositsCount, curated.id, '0x', { from: voting }), 'APP_AUTH_DSM_FAILED') - await assert.revertsWithCustomError( + await assert.reverts( stakingRouter.deposit(maxDepositsCount, curated.id, '0x', { from: voting }), 'AppAuthLidoFailed()' ) @@ -109,7 +108,7 @@ contract('StakingRouter', ([depositor, stranger]) => { assert.equals(await lido.getBufferedEther(), ETH(32), 'invalid total buffer') - assertEvent(receipt, 'Unbuffered', { expectedArgs: { amount: ETH(maxDepositsCount * 32) } }) + assert.emits(receipt, 'Unbuffered', { amount: ETH(maxDepositsCount * 32) }) }) it('Lido.deposit() :: revert if stakingModuleId more than uint24', async () => { diff --git a/test/0.8.9/staking-router-keys-reporting.test.js b/test/0.8.9/staking-router-keys-reporting.test.js index da54cda06..c2ee02f16 100644 --- a/test/0.8.9/staking-router-keys-reporting.test.js +++ b/test/0.8.9/staking-router-keys-reporting.test.js @@ -1,4 +1,4 @@ -const hre = require('hardhat') +const { artifacts, contract, ethers } = require('hardhat') const { EvmSnapshot } = require('../helpers/blockchain') const { assert } = require('../helpers/assert') const { hex, hexConcat, toNum } = require('../helpers/utils') @@ -8,7 +8,7 @@ const StakingModuleMock = artifacts.require('StakingModuleMock.sol') const DepositContractMock = artifacts.require('DepositContractMock.sol') contract('StakingRouter', ([deployer, lido, admin]) => { - const evmSnapshot = new EvmSnapshot(hre.ethers.provider) + const evmSnapshot = new EvmSnapshot(ethers.provider) let depositContract, router let module1, module2 @@ -44,7 +44,7 @@ contract('StakingRouter', ([deployer, lido, admin]) => { } before(async () => { - for await (moduleI of [module1, module2]) { + for (const moduleI of [module1, module2]) { const callInfo = await getCallInfo(moduleI) assert.equal(callInfo.updateStuckValidatorsCount.callCount, 0) assert.equal(callInfo.updateExitedValidatorsCount.callCount, 0) @@ -76,10 +76,10 @@ contract('StakingRouter', ([deployer, lido, admin]) => { it('initially, router assumes no staking modules have exited validators', async () => { const info = await router.getStakingModule(module1Id) - assert.equal(+info.exitedValidatorsCount, 0) + assert.equals(info.exitedValidatorsCount, 0) const totalExited = await router.getExitedValidatorsCountAcrossAllModules() - assert.equal(+totalExited, 0) + assert.equals(totalExited, 0) }) it('reporting total exited validators of a non-existent module reverts', async () => { @@ -99,12 +99,12 @@ contract('StakingRouter', ([deployer, lido, admin]) => { it('staking module info gets updated', async () => { const info = await router.getStakingModule(module1Id) - assert.equal(+info.exitedValidatorsCount, 3) + assert.equals(info.exitedValidatorsCount, 3) }) it('exited validators count accross all modules gets updated', async () => { const totalExited = await router.getExitedValidatorsCountAcrossAllModules() - assert.equal(+totalExited, 3) + assert.equals(totalExited, 3) }) it('no functions were called on the module', async () => { @@ -114,17 +114,14 @@ contract('StakingRouter', ([deployer, lido, admin]) => { assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) }) - it( - `calling onValidatorsCountsByNodeOperatorReportingFinished doesn't call ` + `anything on the module`, - async () => { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it(`calling onValidatorsCountsByNodeOperatorReportingFinished doesn't call anything on the module`, async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo = await getCallInfo(module1) - assert.equal(callInfo.updateStuckValidatorsCount.callCount, 0) - assert.equal(callInfo.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - } - ) + const callInfo = await getCallInfo(module1) + assert.equal(callInfo.updateStuckValidatorsCount.callCount, 0) + assert.equal(callInfo.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + }) it('reporting stuck validators by node op of a non-existent module reverts', async () => { const nonExistentModuleId = module1Id + 1 @@ -167,24 +164,21 @@ contract('StakingRouter', ([deployer, lido, admin]) => { }, ] - it( - 'passing data with mismatched length while reporting stuck validators by node operator ' + 'reverts', - async () => { - await Promise.all( - mismatchedLengthData.map((data) => - assert.reverts( - router.reportStakingModuleStuckValidatorsCountByNodeOperator( - module1Id, - data.nodeOpIds, - data.validatorsCounts, - { from: admin } - ), - 'InvalidReportData(2)' - ) + it('passing data with mismatched length while reporting stuck validators by node operator reverts', async () => { + await Promise.all( + mismatchedLengthData.map((data) => + assert.reverts( + router.reportStakingModuleStuckValidatorsCountByNodeOperator( + module1Id, + data.nodeOpIds, + data.validatorsCounts, + { from: admin } + ), + 'InvalidReportData(2)' ) ) - } - ) + ) + }) const invalidLengthData = [ { @@ -229,24 +223,21 @@ contract('StakingRouter', ([deployer, lido, admin]) => { }, ] - it( - 'passing data with invalid length while reporting stuck validators by node operator ' + 'reverts', - async () => { - await Promise.all( - invalidLengthData.map((data) => - assert.reverts( - router.reportStakingModuleStuckValidatorsCountByNodeOperator( - module1Id, - data.nodeOpIds, - data.validatorsCounts, - { from: admin } - ), - 'InvalidReportData(3)' - ) + it('passing data with invalid length while reporting stuck validators by node operator reverts', async () => { + await Promise.all( + invalidLengthData.map((data) => + assert.reverts( + router.reportStakingModuleStuckValidatorsCountByNodeOperator( + module1Id, + data.nodeOpIds, + data.validatorsCounts, + { from: admin } + ), + 'InvalidReportData(3)' ) ) - } - ) + ) + }) it('reporting stuck validators by node operator passes the info to the module', async () => { const nodeOpIds = [3, 5] @@ -271,18 +262,15 @@ contract('StakingRouter', ([deployer, lido, admin]) => { assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) }) - it( - `calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + `anything on the module`, - async () => { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it(`calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call anything on the module`, async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo = await getCallInfo(module1) - assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + const callInfo = await getCallInfo(module1) + assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo.updateExitedValidatorsCount.callCount, 0) - } - ) + assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo.updateExitedValidatorsCount.callCount, 0) + }) it('reporting exited validators by node op of a non-existent module reverts', async () => { const nonExistentModuleId = module1Id + 1 @@ -306,43 +294,37 @@ contract('StakingRouter', ([deployer, lido, admin]) => { ) }) - it( - 'passing data with mismatched length while reporting exited validators by node operator ' + 'reverts', - async () => { - await Promise.all( - mismatchedLengthData.map((data) => - assert.reverts( - router.reportStakingModuleExitedValidatorsCountByNodeOperator( - module1Id, - data.nodeOpIds, - data.validatorsCounts, - { from: admin } - ), - 'InvalidReportData(2)' - ) + it('passing data with mismatched length while reporting exited validators by node operator reverts', async () => { + await Promise.all( + mismatchedLengthData.map((data) => + assert.reverts( + router.reportStakingModuleExitedValidatorsCountByNodeOperator( + module1Id, + data.nodeOpIds, + data.validatorsCounts, + { from: admin } + ), + 'InvalidReportData(2)' ) ) - } - ) + ) + }) - it( - 'passing data with invalid length while reporting exited validators by node operator ' + 'reverts', - async () => { - await Promise.all( - invalidLengthData.map((data) => - assert.reverts( - router.reportStakingModuleExitedValidatorsCountByNodeOperator( - module1Id, - data.nodeOpIds, - data.validatorsCounts, - { from: admin } - ), - 'InvalidReportData(3)' - ) + it('passing data with invalid length while reporting exited validators by node operator reverts', async () => { + await Promise.all( + invalidLengthData.map((data) => + assert.reverts( + router.reportStakingModuleExitedValidatorsCountByNodeOperator( + module1Id, + data.nodeOpIds, + data.validatorsCounts, + { from: admin } + ), + 'InvalidReportData(3)' ) ) - } - ) + ) + }) it('reporting exited validators by node operator (total 2) passes the info to the module', async () => { const nodeOpIds = [1, 2] @@ -374,21 +356,18 @@ contract('StakingRouter', ([deployer, lido, admin]) => { it(`router's view on exited validators count accross all modules stays the same`, async () => { const totalExited = await router.getExitedValidatorsCountAcrossAllModules() - assert.equal(+totalExited, 3) + assert.equals(totalExited, 3) }) - it( - `calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + `anything on the module`, - async () => { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it(`calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call anything on the module`, async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo = await getCallInfo(module1) - assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + const callInfo = await getCallInfo(module1) + assert.equal(callInfo.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo.updateExitedValidatorsCount.callCount, 1) - } - ) + assert.equal(callInfo.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo.updateExitedValidatorsCount.callCount, 1) + }) it('reporting one more exited validator by node operator passes the info to the module', async () => { const nodeOpIds = [3] @@ -418,8 +397,8 @@ contract('StakingRouter', ([deployer, lido, admin]) => { await module1.setTotalExitedValidatorsCount(3) }) - it( - `now that exited validators totals in the router and in the module match, calling` + + // eslint-disable-next-line prettier/prettier + it(`now that exited validators totals in the router and in the module match, calling` + `onValidatorsCountsByNodeOperatorReportingFinished calls ` + `onExitedAndStuckValidatorsCountsUpdated on the module`, async () => { @@ -433,8 +412,8 @@ contract('StakingRouter', ([deployer, lido, admin]) => { } ) - it( - `calling onValidatorsCountsByNodeOperatorReportingFinished one more time calls ` + + // eslint-disable-next-line prettier/prettier + it(`calling onValidatorsCountsByNodeOperatorReportingFinished one more time calls ` + `onExitedAndStuckValidatorsCountsUpdated on the module again`, async () => { await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) @@ -476,13 +455,13 @@ contract('StakingRouter', ([deployer, lido, admin]) => { it('initially, router assumes no staking modules have exited validators', async () => { const info1 = await router.getStakingModule(moduleIds[0]) - assert.equal(+info1.exitedValidatorsCount, 0) + assert.equals(info1.exitedValidatorsCount, 0) const info2 = await router.getStakingModule(moduleIds[1]) - assert.equal(+info2.exitedValidatorsCount, 0) + assert.equals(info2.exitedValidatorsCount, 0) const totalExited = await router.getExitedValidatorsCountAcrossAllModules() - assert.equal(+totalExited, 0) + assert.equals(totalExited, 0) }) it('reporting 3 exited keys total for module 1 and 2 exited keys total for module 2', async () => { @@ -491,15 +470,15 @@ contract('StakingRouter', ([deployer, lido, admin]) => { it('staking modules info gets updated', async () => { const info1 = await router.getStakingModule(moduleIds[0]) - assert.equal(+info1.exitedValidatorsCount, 3) + assert.equals(info1.exitedValidatorsCount, 3) const info2 = await router.getStakingModule(moduleIds[1]) - assert.equal(+info2.exitedValidatorsCount, 2) + assert.equals(info2.exitedValidatorsCount, 2) }) it('exited validators count accross all modules gets updated', async () => { const totalExited = await router.getExitedValidatorsCountAcrossAllModules() - assert.equal(+totalExited, 5) + assert.equals(totalExited, 5) }) it('no functions were called on any module', async () => { @@ -514,22 +493,19 @@ contract('StakingRouter', ([deployer, lido, admin]) => { assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) }) - it( - `calling onValidatorsCountsByNodeOperatorReportingFinished doesn't call ` + `anything on any module`, - async () => { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it(`calling onValidatorsCountsByNodeOperatorReportingFinished doesn't call anything on any module`, async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo1 = await getCallInfo(module1) - assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 0) - assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + const callInfo1 = await getCallInfo(module1) + assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 0) + assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - const callInfo2 = await getCallInfo(module2) - assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 0) - assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - } - ) + const callInfo2 = await getCallInfo(module2) + assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 0) + assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + }) it('reporting stuck validators by node operator passes the info to the module 1', async () => { const nodeOpIds = [1] @@ -587,22 +563,19 @@ contract('StakingRouter', ([deployer, lido, admin]) => { assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) }) - it( - `calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + `anything on any module`, - async () => { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it(`calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call anything on any module`, async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo1 = await getCallInfo(module1) - assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + const callInfo1 = await getCallInfo(module1) + assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - const callInfo2 = await getCallInfo(module2) - assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - } - ) + const callInfo2 = await getCallInfo(module2) + assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + }) it('reporting exited validators by node operator passes the info to the module 1', async () => { const nodeOpIds = [3, 4] @@ -636,22 +609,19 @@ contract('StakingRouter', ([deployer, lido, admin]) => { await module1.setTotalExitedValidatorsCount(2) }) - it( - `calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call ` + `anything on any module`, - async () => { - await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) + it(`calling onValidatorsCountsByNodeOperatorReportingFinished still doesn't call anything on any module`, async () => { + await router.onValidatorsCountsByNodeOperatorReportingFinished({ from: admin }) - const callInfo1 = await getCallInfo(module1) - assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 1) - assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + const callInfo1 = await getCallInfo(module1) + assert.equal(callInfo1.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo1.updateExitedValidatorsCount.callCount, 1) + assert.equal(callInfo1.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - const callInfo2 = await getCallInfo(module2) - assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) - assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) - assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) - } - ) + const callInfo2 = await getCallInfo(module2) + assert.equal(callInfo2.updateStuckValidatorsCount.callCount, 1) + assert.equal(callInfo2.updateExitedValidatorsCount.callCount, 0) + assert.equal(callInfo2.onExitedAndStuckValidatorsCountsUpdated.callCount, 0) + }) it('reporting exited validators by node operator passes the info to the module 2', async () => { const nodeOpIds = [20] @@ -685,8 +655,8 @@ contract('StakingRouter', ([deployer, lido, admin]) => { await module2.setTotalExitedValidatorsCount(2) }) - it( - `now that router's view on exited validators total match the module 2's view,` + + // eslint-disable-next-line prettier/prettier + it(`now that router's view on exited validators total match the module 2's view,` + `calling onValidatorsCountsByNodeOperatorReportingFinished calls ` + `onExitedAndStuckValidatorsCountsUpdated on the module 2`, async () => { @@ -738,8 +708,8 @@ contract('StakingRouter', ([deployer, lido, admin]) => { await module1.setTotalExitedValidatorsCount(3) }) - it( - `now that router's view on exited validators total match the both modules' view,` + + // eslint-disable-next-line prettier/prettier + it(`now that router's view on exited validators total match the both modules' view,` + `calling onValidatorsCountsByNodeOperatorReportingFinished calls ` + `onExitedAndStuckValidatorsCountsUpdated on both modules`, async () => { diff --git a/test/0.8.9/staking-router.test.js b/test/0.8.9/staking-router.test.js index d050c8fe9..fd7e1fe3f 100644 --- a/test/0.8.9/staking-router.test.js +++ b/test/0.8.9/staking-router.test.js @@ -1,15 +1,13 @@ -const hre = require('hardhat') +const { artifacts, contract, ethers } = require('hardhat') const { MaxUint256 } = require('@ethersproject/constants') const { utils } = require('web3') const { BN } = require('bn.js') const { assert } = require('../helpers/assert') const { EvmSnapshot } = require('../helpers/blockchain') const { newDao, newApp } = require('../helpers/dao') -const { artifacts } = require('hardhat') const { ETH } = require('../helpers/utils') const DepositContractMock = artifacts.require('DepositContractMock') -const StakingRouterMock = artifacts.require('StakingRouterMock.sol') const StakingRouter = artifacts.require('StakingRouter.sol') const StakingModuleMock = artifacts.require('StakingModuleMock.sol') @@ -32,7 +30,7 @@ const StakingModuleStatus = { contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { let depositContract, app const wc = '0x'.padEnd(66, '1234') - const snapshot = new EvmSnapshot(hre.ethers.provider) + const snapshot = new EvmSnapshot(ethers.provider) describe('setup env', async () => { before(async () => { @@ -288,7 +286,7 @@ contract('StakingRouter', ([deployer, lido, admin, appManager, stranger]) => { it('staking modules limit is 32', async () => { for (let i = 0; i < 32; i++) { const stakingModule = await StakingModuleMock.new({ from: deployer }) - const tx = await app.addStakingModule('Test module', stakingModule.address, 100, 100, 100, { from: appManager }) + await app.addStakingModule('Test module', stakingModule.address, 100, 100, 100, { from: appManager }) } const oneMoreStakingModule = await StakingModuleMock.new({ from: deployer }) diff --git a/test/0.8.9/withdrawal-queue.test.js b/test/0.8.9/withdrawal-queue.test.js index d0fa4c54e..d0e3bd04d 100644 --- a/test/0.8.9/withdrawal-queue.test.js +++ b/test/0.8.9/withdrawal-queue.test.js @@ -1,13 +1,12 @@ -const hre = require('hardhat') -const { artifacts, contract, ethers } = require('hardhat') +const { artifacts, contract, ethers, web3 } = require('hardhat') const { bn, getEventArgument, ZERO_ADDRESS } = require('@aragon/contract-helpers-test') -const { ETH, StETH, shareRate, shares, setBalance } = require('../helpers/utils') +const { ETH, StETH, shareRate, shares } = require('../helpers/utils') const { assert } = require('../helpers/assert') const withdrawals = require('../helpers/withdrawals') const { signPermit, makeDomainSeparator } = require('../0.6.12/helpers/permit_helpers') const { MAX_UINT256, ACCOUNTS_AND_KEYS } = require('../0.6.12/helpers/constants') -const { impersonate, EvmSnapshot } = require('../helpers/blockchain') +const { impersonate, EvmSnapshot, setBalance } = require('../helpers/blockchain') const StETHMock = artifacts.require('StETHMock.sol') const WstETH = artifacts.require('WstETHMock.sol') @@ -603,7 +602,7 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { }) it('sequential search', async () => { - for ([idToFind, searchLength] of [ + for (const [idToFind, searchLength] of [ [1, 3], [1, 10], [10, 2], @@ -737,12 +736,10 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { }) context('claimWithdrawals()', () => { - let requestId const amount = ETH(20) beforeEach('Enqueue a request', async () => { await withdrawalQueue.requestWithdrawals([amount], owner, { from: user }) - requestId = await withdrawalQueue.getLastRequestId() }) it('claims correct requests', async () => { @@ -802,7 +799,7 @@ contract('WithdrawalQueue', ([owner, stranger, daoAgent, user]) => { await steth.mintShares(wsteth.address, shares(100)) await steth.mintShares(user, shares(100)) await wsteth.approve(withdrawalQueue.address, ETH(300), { from: user }) - await impersonate(hre.ethers.provider, alice.address) + await impersonate(ethers.provider, alice.address) await web3.eth.sendTransaction({ to: alice.address, from: user, value: ETH(1) }) await wsteth.transfer(alice.address, ETH(100), { from: user }) diff --git a/test/0.8.9/withdrawal-request-nft.test.js b/test/0.8.9/withdrawal-request-nft.test.js index d45a4d596..44538619f 100644 --- a/test/0.8.9/withdrawal-request-nft.test.js +++ b/test/0.8.9/withdrawal-request-nft.test.js @@ -1,333 +1,327 @@ -const hre = require('hardhat') +const { contract, artifacts, ethers } = require('hardhat') const { assert } = require('../helpers/assert') -const { EvmSnapshot } = require('../helpers/blockchain') -const { shares, ETH, shareRate, setBalance } = require('../helpers/utils') -const withdrawals = require('../helpers/withdrawals') -const StETH = hre.artifacts.require('StETHMock') -const WstETH = hre.artifacts.require('WstETHMock') -const ERC721ReceiverMock = hre.artifacts.require('ERC721ReceiverMock') - -hre.contract( - 'WithdrawalNFT', - ([deployer, stEthHolder, wstEthHolder, nftHolderStETH, nftHolderWstETH, recipient, stranger]) => { - let withdrawalQueueERC721, stETH, wstETH, erc721ReceiverMock - let nftHolderStETHTokenIds, nftHolderWstETHTokenIds, nonExistedTokenId - const snapshot = new EvmSnapshot(hre.ethers.provider) - - before(async () => { - stETH = await StETH.new({ value: ETH(1), from: deployer }) - await setBalance(stETH.address, ETH(100)) - - wstETH = await WstETH.new(stETH.address, { from: deployer }) - erc721ReceiverMock = await ERC721ReceiverMock.new({ from: deployer }) - withdrawalQueueERC721 = (await withdrawals.deploy(deployer, wstETH.address, 'Lido TEST Request', 'unstEsT')).queue - await withdrawalQueueERC721.initialize( - deployer, // owner - deployer, // pauser - deployer, // resumer - deployer, // finalizer - deployer - ) - await withdrawalQueueERC721.resume({ from: deployer }) +const { EvmSnapshot, setBalance } = require('../helpers/blockchain') +const { shares, ETH, shareRate } = require('../helpers/utils') +const withdrawals = require('../helpers/withdrawals') - await stETH.setTotalPooledEther(ETH(101)) - await stETH.mintShares(stEthHolder, shares(50)) - await stETH.mintShares(wstETH.address, shares(50)) - await wstETH.mint(wstEthHolder, ETH(25)) +const StETH = artifacts.require('StETHMock') +const WstETH = artifacts.require('WstETHMock') +const ERC721ReceiverMock = artifacts.require('ERC721ReceiverMock') + +contract('WithdrawalNFT', (addresses) => { + const [deployer, stEthHolder, wstEthHolder, nftHolderStETH, nftHolderWstETH, recipient, stranger] = addresses + let withdrawalQueueERC721, stETH, wstETH, erc721ReceiverMock + let nftHolderStETHTokenIds, nftHolderWstETHTokenIds, nonExistedTokenId + const snapshot = new EvmSnapshot(ethers.provider) + + before(async () => { + stETH = await StETH.new({ value: ETH(1), from: deployer }) + await setBalance(stETH.address, ETH(100)) + + wstETH = await WstETH.new(stETH.address, { from: deployer }) + erc721ReceiverMock = await ERC721ReceiverMock.new({ from: deployer }) + withdrawalQueueERC721 = (await withdrawals.deploy(deployer, wstETH.address, 'Lido TEST Request', 'unstEsT')).queue + await withdrawalQueueERC721.initialize( + deployer, // owner + deployer, // pauser + deployer, // resumer + deployer, // finalizer + deployer + ) + await withdrawalQueueERC721.resume({ from: deployer }) + + await stETH.setTotalPooledEther(ETH(101)) + await stETH.mintShares(stEthHolder, shares(50)) + await stETH.mintShares(wstETH.address, shares(50)) + await wstETH.mint(wstEthHolder, ETH(25)) + + await stETH.approve(withdrawalQueueERC721.address, ETH(50), { from: stEthHolder }) + await wstETH.approve(withdrawalQueueERC721.address, ETH(25), { from: wstEthHolder }) + await withdrawalQueueERC721.requestWithdrawals([ETH(25), ETH(25)], nftHolderStETH, { from: stEthHolder }) + nftHolderStETHTokenIds = [1, 2] + await withdrawalQueueERC721.requestWithdrawalsWstETH([ETH(25)], nftHolderWstETH, { from: wstEthHolder }) + nftHolderWstETHTokenIds = [3] + nonExistedTokenId = 4 + await snapshot.make() + }) + + afterEach(async () => { + await snapshot.rollback() + }) + + describe('ERC721Metadata', () => { + it('Initial properties', async () => { + assert.equals(await withdrawalQueueERC721.symbol(), 'unstEsT') + assert.equals(await withdrawalQueueERC721.name(), 'Lido TEST Request') + }) + }) - await stETH.approve(withdrawalQueueERC721.address, ETH(50), { from: stEthHolder }) - await wstETH.approve(withdrawalQueueERC721.address, ETH(25), { from: wstEthHolder }) - await withdrawalQueueERC721.requestWithdrawals([ETH(25), ETH(25)], nftHolderStETH, { from: stEthHolder }) - nftHolderStETHTokenIds = [1, 2] - await withdrawalQueueERC721.requestWithdrawalsWstETH([ETH(25)], nftHolderWstETH, { from: wstEthHolder }) - nftHolderWstETHTokenIds = [3] - nonExistedTokenId = 4 - await snapshot.make() + describe('supportsInterface()', () => { + it('returns true for IERC165 interfaceiId (0x01ffc9a7)', async () => { + assert.isTrue(await withdrawalQueueERC721.supportsInterface('0x01ffc9a7')) + }) + it('returns true for IERC721 interface id (0x80ac58cd)', async () => { + assert.isTrue(await withdrawalQueueERC721.supportsInterface('0x80ac58cd')) }) + it('returns true for AccessControlEnumerable interface id (0x5a05180f)', async () => { + assert.isTrue(await withdrawalQueueERC721.supportsInterface('0x5a05180f')) + }) + it('returns false for unsupported e interface id (0xffffffff)', async () => { + assert.isFalse(await withdrawalQueueERC721.supportsInterface('0xffffffff')) + }) + it('returns false for unsupported e interface id (0xdeadbeaf)', async () => { + assert.isFalse(await withdrawalQueueERC721.supportsInterface('0xdeadbeaf')) + }) + }) - afterEach(async () => { - await snapshot.rollback() + describe('balanceOf()', () => { + it('return 0 when user has not withdrawal requests', async () => { + assert.equals(await withdrawalQueueERC721.balanceOf(recipient), 0) }) - describe('ERC721Metadata', () => { - it('Initial properties', async () => { - assert.equals(await withdrawalQueueERC721.symbol(), 'unstEsT') - assert.equals(await withdrawalQueueERC721.name(), 'Lido TEST Request') - }) + it('return correct withdrawal requests count', async () => { + assert.equals(await withdrawalQueueERC721.balanceOf(nftHolderStETH), 2) + assert.equals(await withdrawalQueueERC721.balanceOf(nftHolderWstETH), 1) }) + }) - describe('supportsInterface()', () => { - it('returns true for IERC165 interfaceiId (0x01ffc9a7)', async () => { - assert.isTrue(await withdrawalQueueERC721.supportsInterface('0x01ffc9a7')) - }) - it('returns true for IERC721 interface id (0x80ac58cd)', async () => { - assert.isTrue(await withdrawalQueueERC721.supportsInterface('0x80ac58cd')) - }) - it('returns true for AccessControlEnumerable interface id (0x5a05180f)', async () => { - assert.isTrue(await withdrawalQueueERC721.supportsInterface('0x5a05180f')) - }) - it('returns false for unsupported e interface id (0xffffffff)', async () => { - assert.isFalse(await withdrawalQueueERC721.supportsInterface('0xffffffff')) - }) - it('returns false for unsupported e interface id (0xdeadbeaf)', async () => { - assert.isFalse(await withdrawalQueueERC721.supportsInterface('0xdeadbeaf')) - }) + describe('ownerOf()', () => { + it('reverts with error InvalidRequestId() when token id is 0', async () => { + await assert.reverts(withdrawalQueueERC721.ownerOf(0), `InvalidRequestId(0)`) }) - describe('balanceOf()', () => { - it('return 0 when user has not withdrawal requests', async () => { - assert.equals(await withdrawalQueueERC721.balanceOf(recipient), 0) - }) + it('reverts with error InvalidRequestId() when called with non existed token id', async () => { + await assert.reverts(withdrawalQueueERC721.ownerOf(nonExistedTokenId), `InvalidRequestId(${nonExistedTokenId})`) + }) - it('return correct withdrawal requests count', async () => { - assert.equals(await withdrawalQueueERC721.balanceOf(nftHolderStETH), 2) - assert.equals(await withdrawalQueueERC721.balanceOf(nftHolderWstETH), 1) - }) + it('reverts correct owner', async () => { + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), nftHolderStETH) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), nftHolderStETH) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), nftHolderWstETH) }) + }) - describe('ownerOf()', () => { - it('reverts with error InvalidRequestId() when token id is 0', async () => { - await assert.reverts(withdrawalQueueERC721.ownerOf(0), `InvalidRequestId(0)`) - }) + describe('approve()', async () => { + it('reverts with message "ApprovalToOwner()" when approval for owner address', async () => { + await assert.reverts( + withdrawalQueueERC721.approve(nftHolderStETH, nftHolderStETHTokenIds[0], { from: nftHolderStETH }), + 'ApprovalToOwner()' + ) + }) - it('reverts with error InvalidRequestId() when called with non existed token id', async () => { - await assert.reverts(withdrawalQueueERC721.ownerOf(nonExistedTokenId), `InvalidRequestId(${nonExistedTokenId})`) - }) + it('reverts with message "NotOwnerOrApprovedForAll()" when called noy by owner', async () => { + await assert.reverts( + withdrawalQueueERC721.approve(recipient, nftHolderStETHTokenIds[0], { from: stranger }), + `NotOwnerOrApprovedForAll("${stranger}")` + ) + }) - it('reverts correct owner', async () => { - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), nftHolderStETH) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), nftHolderStETH) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), nftHolderWstETH) - }) + it('sets approval for address', async () => { + await withdrawalQueueERC721.approve(recipient, nftHolderStETHTokenIds[0], { from: nftHolderStETH }) + assert.equal(await withdrawalQueueERC721.getApproved(nftHolderStETHTokenIds[0]), recipient) }) + }) - describe('approve()', async () => { - it('reverts with message "ApprovalToOwner()" when approval for owner address', async () => { - await assert.reverts( - withdrawalQueueERC721.approve(nftHolderStETH, nftHolderStETHTokenIds[0], { from: nftHolderStETH }), - 'ApprovalToOwner()' - ) - }) + describe('getApproved()', async () => { + it('reverts with message "InvalidRequestId()" when called with non existed token id', async () => { + await assert.reverts( + withdrawalQueueERC721.getApproved(nonExistedTokenId), + `InvalidRequestId(${nonExistedTokenId})` + ) + }) + }) - it('reverts with message "NotOwnerOrApprovedForAll()" when called noy by owner', async () => { - await assert.reverts( - withdrawalQueueERC721.approve(recipient, nftHolderStETHTokenIds[0], { from: stranger }), - `NotOwnerOrApprovedForAll("${stranger}")` - ) - }) + describe('setApprovalForAll()', async () => { + it('reverts with message "ApproveToCaller()" when owner equal to operator', async () => { + await assert.reverts( + withdrawalQueueERC721.setApprovalForAll(nftHolderStETH, true, { from: nftHolderStETH }), + 'ApproveToCaller()' + ) + }) + }) + + describe('safeTransferFrom(address,address,uint256)', async () => { + it('reverts with message "NotOwnerOrApproved()" when approvalNotSet and not owner', async () => { + await assert.reverts( + withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { + from: stranger, + }), + `NotOwnerOrApproved("${stranger}")` + ) + }) - it('sets approval for address', async () => { - await withdrawalQueueERC721.approve(recipient, nftHolderStETHTokenIds[0], { from: nftHolderStETH }) - assert.equal(await withdrawalQueueERC721.getApproved(nftHolderStETHTokenIds[0]), recipient) + it('transfers if called by owner', async () => { + assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) + await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { + from: nftHolderStETH, }) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) }) - describe('getApproved()', async () => { - it('reverts with message "InvalidRequestId()" when called with non existed token id', async () => { - await assert.reverts( - withdrawalQueueERC721.getApproved(nonExistedTokenId), - `InvalidRequestId(${nonExistedTokenId})` - ) + it('transfers if token approval set', async () => { + await withdrawalQueueERC721.approve(recipient, nftHolderStETHTokenIds[0], { from: nftHolderStETH }) + assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) + await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { + from: recipient, }) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) }) - describe('setApprovalForAll()', async () => { - it('reverts with message "ApproveToCaller()" when owner equal to operator', async () => { - await assert.reverts( - withdrawalQueueERC721.setApprovalForAll(nftHolderStETH, true, { from: nftHolderStETH }), - 'ApproveToCaller()' - ) + it('transfers if operator approval set', async () => { + await withdrawalQueueERC721.setApprovalForAll(recipient, true, { from: nftHolderStETH }) + assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) + assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) + await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { + from: recipient, }) + await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[1], { + from: recipient, + }) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) }) - describe('safeTransferFrom(address,address,uint256)', async () => { - it('reverts with message "NotOwnerOrApproved()" when approvalNotSet and not owner', async () => { - await assert.reverts( - withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: stranger, - }), - `NotOwnerOrApproved("${stranger}")` - ) - }) + it('reverts with message "TransferToNonIERC721Receiver()" when transfer to contract that not implements IERC721Receiver interface', async () => { + await assert.reverts( + withdrawalQueueERC721.safeTransferFrom(nftHolderWstETH, stETH.address, nftHolderWstETHTokenIds[0], { + from: nftHolderWstETH, + }), + `TransferToNonIERC721Receiver("${stETH.address}")` + ) + }) - it('transfers if called by owner', async () => { - assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { + it('reverts with propagated error message when recipient contract implements ERC721Receiver and reverts on onERC721Received call', async () => { + await erc721ReceiverMock.setDoesAcceptTokens(false, { from: deployer }) + await assert.reverts( + withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, erc721ReceiverMock.address, nftHolderStETHTokenIds[0], { from: nftHolderStETH, - }) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - }) + }), + 'ERC721_NOT_ACCEPT_TOKENS' + ) + }) - it('transfers if token approval set', async () => { - await withdrawalQueueERC721.approve(recipient, nftHolderStETHTokenIds[0], { from: nftHolderStETH }) - assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: recipient, - }) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - }) + it("doesn't revert when recipient contract implements ERC721Receiver interface and accepts tokens", async () => { + await erc721ReceiverMock.setDoesAcceptTokens(true, { from: deployer }) + assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), erc721ReceiverMock.address) + await withdrawalQueueERC721.safeTransferFrom( + nftHolderStETH, + erc721ReceiverMock.address, + nftHolderStETHTokenIds[0], + { + from: nftHolderStETH, + } + ) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), erc721ReceiverMock.address) + }) + }) - it('transfers if operator approval set', async () => { - await withdrawalQueueERC721.setApprovalForAll(recipient, true, { from: nftHolderStETH }) - assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) - await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: recipient, - }) - await withdrawalQueueERC721.safeTransferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[1], { - from: recipient, - }) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) - }) + describe('transferFrom()', async () => { + it('reverts with message "NotOwnerOrApproved()" when approvalNotSet and not owner', async () => { + await assert.reverts( + withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { from: stranger }), + `NotOwnerOrApproved("${stranger}")` + ) + }) - it('reverts with message "TransferToNonIERC721Receiver()" when transfer to contract that not implements IERC721Receiver interface', async () => { - await assert.reverts( - withdrawalQueueERC721.safeTransferFrom(nftHolderWstETH, stETH.address, nftHolderWstETHTokenIds[0], { - from: nftHolderWstETH, - }), - `TransferToNonIERC721Receiver("${stETH.address}")` - ) - }) + it('reverts when transfer to the same address', async () => { + await assert.reverts( + withdrawalQueueERC721.transferFrom(nftHolderWstETH, nftHolderWstETH, nftHolderWstETHTokenIds[0], { + from: nftHolderWstETH, + }), + 'TransferToThemselves()' + ) + }) - it('reverts with propagated error message when recipient contract implements ERC721Receiver and reverts on onERC721Received call', async () => { - await erc721ReceiverMock.setDoesAcceptTokens(false, { from: deployer }) - await assert.reverts( - withdrawalQueueERC721.safeTransferFrom( - nftHolderStETH, - erc721ReceiverMock.address, - nftHolderStETHTokenIds[0], - { - from: nftHolderStETH, - } - ), - 'ERC721_NOT_ACCEPT_TOKENS' - ) + it('reverts with error "RequestAlreadyClaimed()" when called on claimed request', async () => { + const batch = await withdrawalQueueERC721.finalizationBatch(3, shareRate(1)) + await withdrawalQueueERC721.finalize(3, { from: deployer, value: batch.ethToLock }) + const ownerETHBefore = await ethers.provider.getBalance(nftHolderStETH) + const tx = await withdrawalQueueERC721.methods['claimWithdrawal(uint256)'](nftHolderStETHTokenIds[0], { + from: nftHolderStETH, }) + const ownerETHAfter = await ethers.provider.getBalance(nftHolderStETH) + // adhoc fix for solidity-coverage that ignores gasPrice = 0 + assert.almostEqual(ownerETHAfter, ownerETHBefore.add(ETH(25)), tx.receipt.gasUsed) - it("doesn't revert when recipient contract implements ERC721Receiver interface and accepts tokens", async () => { - await erc721ReceiverMock.setDoesAcceptTokens(true, { from: deployer }) - assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), erc721ReceiverMock.address) - await withdrawalQueueERC721.safeTransferFrom( - nftHolderStETH, - erc721ReceiverMock.address, - nftHolderStETHTokenIds[0], - { - from: nftHolderStETH, - } - ) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), erc721ReceiverMock.address) - }) + await assert.reverts( + withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { + from: nftHolderStETH, + }), + `RequestAlreadyClaimed(${nftHolderStETHTokenIds[0]})` + ) }) - describe('transferFrom()', async () => { - it('reverts with message "NotOwnerOrApproved()" when approvalNotSet and not owner', async () => { - await assert.reverts( - withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { from: stranger }), - `NotOwnerOrApproved("${stranger}")` - ) + it('transfers if called by owner', async () => { + assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), recipient) + await withdrawalQueueERC721.transferFrom(nftHolderWstETH, recipient, nftHolderWstETHTokenIds[0], { + from: nftHolderWstETH, }) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), recipient) + }) - it('reverts when transfer to the same address', async () => { - await assert.reverts( - withdrawalQueueERC721.transferFrom(nftHolderWstETH, nftHolderWstETH, nftHolderWstETHTokenIds[0], { - from: nftHolderWstETH, - }), - 'TransferToThemselves()' - ) + it('transfers if token approval set', async () => { + await withdrawalQueueERC721.approve(recipient, nftHolderStETHTokenIds[0], { from: nftHolderStETH }) + assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) + await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { + from: recipient, }) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) + }) - it('reverts with error "RequestAlreadyClaimed()" when called on claimed request', async () => { - const batch = await withdrawalQueueERC721.finalizationBatch(3, shareRate(1)) - await withdrawalQueueERC721.finalize(3, { from: deployer, value: batch.ethToLock }) - const ownerETHBefore = await hre.ethers.provider.getBalance(nftHolderStETH) - const tx = await withdrawalQueueERC721.methods['claimWithdrawal(uint256)'](nftHolderStETHTokenIds[0], { - from: nftHolderStETH, - }) - const ownerETHAfter = await hre.ethers.provider.getBalance(nftHolderStETH) - // adhoc fix for solidity-coverage that ignores gasPrice = 0 - assert.almostEqual(ownerETHAfter, ownerETHBefore.add(ETH(25)), tx.receipt.gasUsed) - - await assert.reverts( - withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: nftHolderStETH, - }), - `RequestAlreadyClaimed(${nftHolderStETHTokenIds[0]})` - ) + it('transfers if operator approval set', async () => { + await withdrawalQueueERC721.setApprovalForAll(recipient, true, { from: nftHolderStETH }) + assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) + assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) + await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { + from: recipient, }) - - it('transfers if called by owner', async () => { - assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), recipient) - await withdrawalQueueERC721.transferFrom(nftHolderWstETH, recipient, nftHolderWstETHTokenIds[0], { - from: nftHolderWstETH, - }) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), recipient) + await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[1], { + from: recipient, }) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) + }) - it('transfers if token approval set', async () => { - await withdrawalQueueERC721.approve(recipient, nftHolderStETHTokenIds[0], { from: nftHolderStETH }) - assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: recipient, - }) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) + it('can claim request after transfer', async () => { + await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { + from: nftHolderStETH, }) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - it('transfers if operator approval set', async () => { - await withdrawalQueueERC721.setApprovalForAll(recipient, true, { from: nftHolderStETH }) - assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - assert.notEqual(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) - await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: recipient, - }) - await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[1], { - from: recipient, - }) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[1]), recipient) - }) + const batch = await withdrawalQueueERC721.finalizationBatch(3, shareRate(1)) + await withdrawalQueueERC721.finalize(3, { from: deployer, value: batch.ethToLock }) - it('can claim request after transfer', async () => { - await withdrawalQueueERC721.transferFrom(nftHolderStETH, recipient, nftHolderStETHTokenIds[0], { - from: nftHolderStETH, - }) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderStETHTokenIds[0]), recipient) - - const batch = await withdrawalQueueERC721.finalizationBatch(3, shareRate(1)) - await withdrawalQueueERC721.finalize(3, { from: deployer, value: batch.ethToLock }) - - const recipientETHBefore = await hre.ethers.provider.getBalance(recipient) - const tx = await withdrawalQueueERC721.methods['claimWithdrawal(uint256)'](nftHolderStETHTokenIds[0], { - from: recipient, - }) - const recipientETHAfter = await hre.ethers.provider.getBalance(recipient) - // adhoc fix for solidity-coverage that ignores gasPrice = 0 - assert.almostEqual(recipientETHAfter, recipientETHBefore.add(ETH(25)), tx.receipt.gasUsed) + const recipientETHBefore = await ethers.provider.getBalance(recipient) + const tx = await withdrawalQueueERC721.methods['claimWithdrawal(uint256)'](nftHolderStETHTokenIds[0], { + from: recipient, }) + const recipientETHAfter = await ethers.provider.getBalance(recipient) + // adhoc fix for solidity-coverage that ignores gasPrice = 0 + assert.almostEqual(recipientETHAfter, recipientETHBefore.add(ETH(25)), tx.receipt.gasUsed) + }) - it("doesn't reverts when transfer to contract that not implements IERC721Receiver interface", async () => { - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), nftHolderWstETH) - await withdrawalQueueERC721.transferFrom(nftHolderWstETH, stETH.address, nftHolderWstETHTokenIds[0], { - from: nftHolderWstETH, - }) - assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), stETH.address) + it("doesn't reverts when transfer to contract that not implements IERC721Receiver interface", async () => { + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), nftHolderWstETH) + await withdrawalQueueERC721.transferFrom(nftHolderWstETH, stETH.address, nftHolderWstETHTokenIds[0], { + from: nftHolderWstETH, }) + assert.equal(await withdrawalQueueERC721.ownerOf(nftHolderWstETHTokenIds[0]), stETH.address) }) + }) - describe('Burn', () => { - it('balanceOf decreases after claim', async () => { - const balanceBefore = await withdrawalQueueERC721.balanceOf(nftHolderStETH) - - const batch = await withdrawalQueueERC721.finalizationBatch(3, shareRate(1)) - await withdrawalQueueERC721.finalize(3, { from: deployer, value: batch.ethToLock }) + describe('Burn', () => { + it('balanceOf decreases after claim', async () => { + const balanceBefore = await withdrawalQueueERC721.balanceOf(nftHolderStETH) - await withdrawalQueueERC721.methods['claimWithdrawal(uint256)'](nftHolderStETHTokenIds[0], { - from: nftHolderStETH, - }) + const batch = await withdrawalQueueERC721.finalizationBatch(3, shareRate(1)) + await withdrawalQueueERC721.finalize(3, { from: deployer, value: batch.ethToLock }) - assert.equals(balanceBefore - (await withdrawalQueueERC721.balanceOf(nftHolderStETH)), 1) + await withdrawalQueueERC721.methods['claimWithdrawal(uint256)'](nftHolderStETHTokenIds[0], { + from: nftHolderStETH, }) + + assert.equals(balanceBefore - (await withdrawalQueueERC721.balanceOf(nftHolderStETH)), 1) }) - } -) + }) +}) diff --git a/test/common/lib/min-first-allocation-strategy.test.js b/test/common/lib/min-first-allocation-strategy.test.js index 4d18a0616..97c592306 100644 --- a/test/common/lib/min-first-allocation-strategy.test.js +++ b/test/common/lib/min-first-allocation-strategy.test.js @@ -1,9 +1,8 @@ -const hre = require('hardhat') -const { assert } = require('chai') -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') +const { artifacts, contract, ethers } = require('hardhat') +const { assert } = require('../../helpers/assert') -const MinFirstAlgorithmLegacyConsumer = hre.artifacts.require('MinFirstAllocationStrategyConsumerMockLegacyVersion') -const MinFirstAlgorithmModernConsumer = hre.artifacts.require('MinFirstAllocationStrategyConsumerMockModernVersion') +const MinFirstAlgorithmLegacyConsumer = artifacts.require('MinFirstAllocationStrategyConsumerMockLegacyVersion') +const MinFirstAlgorithmModernConsumer = artifacts.require('MinFirstAllocationStrategyConsumerMockModernVersion') contract('MinFirstAllocationStrategy', (accounts) => { for (const [consumerVersion, consumerFactory] of [ @@ -18,12 +17,12 @@ contract('MinFirstAllocationStrategy', (accounts) => { before(async () => { minFirstAllocationStrategy = await consumerFactory.new({ from: deployer }) - evmSnapshotId = await hre.ethers.provider.send('evm_snapshot', []) + evmSnapshotId = await ethers.provider.send('evm_snapshot', []) }) afterEach(async () => { - await hre.ethers.provider.send('evm_revert', [evmSnapshotId]) - evmSnapshotId = await hre.ethers.provider.send('evm_snapshot', []) + await ethers.provider.send('evm_revert', [evmSnapshotId]) + evmSnapshotId = await ethers.provider.send('evm_snapshot', []) }) describe('allocateToBestCandidate()', () => { @@ -35,7 +34,7 @@ contract('MinFirstAllocationStrategy', (accounts) => { [], maxAllocationSize ) - assertBn(allocated, 0) + assert.equals(allocated, 0) assert.equal(newAllocations.length, 0) } }) @@ -58,9 +57,9 @@ contract('MinFirstAllocationStrategy', (accounts) => { maxAllocationSize ) const expectedAllocated = Math.min(Math.max(0, capacity - allocation), maxAllocationSize) - assertBn(allocated, expectedAllocated) + assert.equals(allocated, expectedAllocated) assert.equal(newAllocations.length, 1) - assertBn(newAllocations[0], allocation + expectedAllocated) + assert.equals(newAllocations[0], allocation + expectedAllocated) } } } @@ -100,9 +99,9 @@ contract('MinFirstAllocationStrategy', (accounts) => { newAllocations ) assert.equal(expectedNewAllocations.length, newAllocations.length, assertMessage) - assertBn(allocated, expectedAllocated, assertMessage) + assert.equals(allocated, expectedAllocated, assertMessage) for (let i = 0; i < newAllocations.length; ++i) { - assertBn(newAllocations[i], expectedNewAllocations[i], assertMessage) + assert.equals(newAllocations[i], expectedNewAllocations[i], assertMessage) } } } @@ -149,9 +148,9 @@ contract('MinFirstAllocationStrategy', (accounts) => { newAllocations ) assert.equal(expectedNewAllocations.length, newAllocations.length, assertMessage) - assertBn(allocated, expectedAllocated, assertMessage) + assert.equals(allocated, expectedAllocated, assertMessage) for (let i = 0; i < newAllocations.length; ++i) { - assertBn(newAllocations[i], expectedNewAllocations[i], assertMessage) + assert.equals(newAllocations[i], expectedNewAllocations[i], assertMessage) } } }) @@ -165,7 +164,7 @@ contract('MinFirstAllocationStrategy', (accounts) => { it('should not allocate for various allocation sizes', async () => { for (const maxAllocationSize of [0, 4, 8, 15, 16, 23, 42]) { const { allocated, newAllocations } = await minFirstAllocationStrategy.allocate([], [], maxAllocationSize) - assertBn(allocated, 0) + assert.equals(allocated, 0) assert.equal(newAllocations.length, 0) } }) @@ -190,9 +189,9 @@ contract('MinFirstAllocationStrategy', (accounts) => { assertAllocationAssumptions([allocation], [capacity], maxAllocationSize, allocated, newAllocations) const expectedAllocated = Math.min(Math.max(0, capacity - allocation), maxAllocationSize) - assertBn(allocated, expectedAllocated) + assert.equals(allocated, expectedAllocated) assert.equal(newAllocations.length, 1) - assertBn(newAllocations[0], allocation + expectedAllocated) + assert.equals(newAllocations[0], allocation + expectedAllocated) } } } @@ -235,9 +234,9 @@ contract('MinFirstAllocationStrategy', (accounts) => { newAllocations ) assert.equal(expectedNewAllocations.length, newAllocations.length, assertMessage) - assertBn(allocated, expectedAllocated, assertMessage) + assert.equals(allocated, expectedAllocated, assertMessage) for (let i = 0; i < newAllocations.length; ++i) { - assertBn(newAllocations[i], expectedNewAllocations[i], assertMessage) + assert.equals(newAllocations[i], expectedNewAllocations[i], assertMessage) } } } @@ -289,9 +288,9 @@ contract('MinFirstAllocationStrategy', (accounts) => { newAllocations ) assert.equal(expectedNewAllocations.length, newAllocations.length, assertMessage) - assertBn(allocated, expectedAllocated, assertMessage) + assert.equals(allocated, expectedAllocated, assertMessage) for (let i = 0; i < newAllocations.length; ++i) { - assertBn(newAllocations[i], expectedNewAllocations[i], assertMessage) + assert.equals(newAllocations[i], expectedNewAllocations[i], assertMessage) } } }) @@ -345,7 +344,7 @@ function assertAllocationAssumptions(allocations, capacities, maxAllocationSize, // assumption 4: if new allocation item exceeds capacity it must be equal to value in prev allocation for (let i = 0; i < newAllocations.length; ++i) { if (allocations[i] >= capacities[i]) { - assertBn(newAllocations[i], allocations[i], assertMessage) + assert.equals(newAllocations[i], allocations[i], assertMessage) } } diff --git a/test/helpers/assert.js b/test/helpers/assert.js index a1304ca1d..37d27791e 100644 --- a/test/helpers/assert.js +++ b/test/helpers/assert.js @@ -1,4 +1,5 @@ const chai = require('chai') +const { web3 } = require('hardhat') const { getEvents, isBn } = require('@aragon/contract-helpers-test') const { assertRevert } = require('./assertThrow') const { toChecksumAddress } = require('ethereumjs-util') @@ -10,6 +11,11 @@ chai.util.addMethod(chai.assert, 'emits', function (receipt, eventName, args = { this.isTrue(event !== undefined, `Event ${eventName} with args ${JSON.stringify(args)} wasn't found`) }) +chai.util.addMethod(chai.assert, 'emitsAt', function (receipt, eventName, index, args = {}, options = {}) { + const event = getEventAt(receipt, eventName, index, args, options.abi) + this.isTrue(event !== undefined, `Event ${eventName} at ${index} with args ${JSON.stringify(args)} wasn't found`) +}) + chai.util.addMethod( chai.assert, 'emitsNumberOfEvents', @@ -80,7 +86,7 @@ chai.util.addMethod(chai.assert, 'notEquals', function (actual, expected, errorM }) chai.util.addMethod(chai.assert, 'addressEqual', function (actual, expected, errorMsg) { - assert.equal(toChecksumAddress(actual), toChecksumAddress(expected), errorMsg) + chai.assert.equal(toChecksumAddress(actual), toChecksumAddress(expected), errorMsg) }) chai.util.addMethod(chai.assert, 'revertsWithCustomError', async function (receipt, reason) { @@ -112,6 +118,18 @@ chai.util.addMethod(chai.assert, 'almostEqual', function (actual, expected, epsi } }) +function getEventAt(receipt, eventName, index, args, abi) { + const e = getEvents(receipt, eventName, { decodeForAbi: abi })[index] + + if ( + Object.entries(args).every( + ([argName, argValue]) => e.args[argName] !== undefined && normalizeArg(e.args[argName]) === normalizeArg(argValue) + ) + ) + return e + else return undefined +} + function getEvent(receipt, eventName, args, abi) { return getEvents(receipt, eventName, { decodeForAbi: abi }).find((e) => // find the first index where every event argument matches the expected one diff --git a/test/helpers/blockchain.js b/test/helpers/blockchain.js index 9a6284490..c1bf3efbd 100644 --- a/test/helpers/blockchain.js +++ b/test/helpers/blockchain.js @@ -1,23 +1,23 @@ -const hre = require('hardhat') +const { network, web3, ethers } = require('hardhat') const { wei } = require('./wei') async function waitBlocks(numBlocksToMine) { let block for (let i = 0; i < numBlocksToMine; ++i) { - await hre.network.provider.send('evm_mine') + await network.provider.send('evm_mine') block = await web3.eth.getBlock('latest') } return block } async function advanceChainTime(seconds) { - await hre.network.provider.send('evm_increaseTime', [seconds]) - await hre.network.provider.send('evm_mine') + await network.provider.send('evm_increaseTime', [seconds]) + await network.provider.send('evm_mine') } async function getCurrentBlockTimestamp() { - const blockNum = await hre.ethers.provider.getBlockNumber() - const block = await hre.ethers.provider.getBlock(blockNum) + const blockNum = await ethers.provider.getBlockNumber() + const block = await ethers.provider.getBlock(blockNum) return block.timestamp } @@ -54,13 +54,13 @@ function impersonate(provider, address) { async function getBalance(addressOrContract) { const address = addressOrContract.address || addressOrContract - return wei.int(await hre.ethers.provider.getBalance(address)) + return wei.int(await ethers.provider.getBalance(address)) } async function setBalance(addressOrContract, value) { const address = addressOrContract.address || addressOrContract - const hexValue = hre.web3.utils.numberToHex(wei.str(value)) - await hre.network.provider.send('hardhat_setBalance', [address, hexValue]) + const hexValue = web3.utils.numberToHex(wei.str(value)) + await network.provider.send('hardhat_setBalance', [address, hexValue]) } module.exports = { diff --git a/test/helpers/dao.js b/test/helpers/dao.js index 144743a74..580f6fc44 100644 --- a/test/helpers/dao.js +++ b/test/helpers/dao.js @@ -1,5 +1,7 @@ +const { artifacts } = require('hardhat') const { hash } = require('eth-ens-namehash') const { getEventArgument } = require('@aragon/contract-helpers-test') + const Kernel = artifacts.require('@aragon/os/build/contracts/kernel/Kernel') const ACL = artifacts.require('@aragon/os/build/contracts/acl/ACL') const EVMScriptRegistryFactory = artifacts.require('@aragon/os/build/contracts/factory/EVMScriptRegistryFactory') diff --git a/test/helpers/factories.js b/test/helpers/factories.js index f1974ae0a..c93c7d2ca 100644 --- a/test/helpers/factories.js +++ b/test/helpers/factories.js @@ -1,3 +1,4 @@ +const { web3 } = require('hardhat') const withdrawals = require('./withdrawals') const { newApp } = require('./dao') const { artifacts } = require('hardhat') @@ -8,8 +9,6 @@ const { SLOTS_PER_EPOCH, SECONDS_PER_SLOT, EPOCHS_PER_FRAME, CONSENSUS_VERSION } const OssifiableProxy = artifacts.require('OssifiableProxy') const LidoMock = artifacts.require('LidoMock') -const Lido = artifacts.require('Lido') -const WstETHMock = artifacts.require('WstETHMock') const WstETH = artifacts.require('WstETH') const LegacyOracle = artifacts.require('LegacyOracle') const MockLegacyOracle = artifacts.require('MockLegacyOracle') diff --git a/test/helpers/locator-deploy.js b/test/helpers/locator-deploy.js index cd030663f..d905b6f96 100644 --- a/test/helpers/locator-deploy.js +++ b/test/helpers/locator-deploy.js @@ -1,3 +1,5 @@ +const { artifacts } = require('hardhat') + const LidoLocator = artifacts.require('LidoLocator') const DUMMY_ADDRESS = '0x' + 'f'.repeat(40) diff --git a/test/helpers/node-operators.js b/test/helpers/node-operators.js index f99ffa861..9e4e94e1e 100644 --- a/test/helpers/node-operators.js +++ b/test/helpers/node-operators.js @@ -1,5 +1,5 @@ -const hre = require('hardhat') -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') +const { artifacts } = require('hardhat') +const { assert } = require('./assert') const { FakeValidatorKeys } = require('./signing-keys') const { prepIdsCountsPayload } = require('./utils') @@ -28,7 +28,6 @@ async function addNodeOperator(registry, config, txOptions) { const exitedSigningKeysCount = config.exitedSigningKeysCount || 0 const depositedSigningKeysCount = config.depositedSigningKeysCount || 0 const vettedSigningKeysCount = config.vettedSigningKeysCount || 0 - const refundedValidatorsKeysCount = config.refundedValidatorsKeysCount || 0 const stuckValidatorsCount = config.stuckValidatorsCount || 0 const isActive = config.isActive === undefined ? true : config.isActive @@ -75,7 +74,7 @@ async function addNodeOperator(registry, config, txOptions) { await registry.deactivateNodeOperator(newOperatorId, txOptions) } - const stakingModule = await hre.artifacts + const stakingModule = await artifacts .require('contracts/0.8.9/interfaces/IStakingModule.sol:IStakingModule') .at(registry.address) @@ -84,15 +83,15 @@ async function addNodeOperator(registry, config, txOptions) { const nodeOperator = await registry.getNodeOperator(newOperatorId, true) if (isActive) { - assertBn(nodeOperator.stakingLimit, vettedSigningKeysCount) - assertBn(nodeOperator.totalSigningKeys, totalSigningKeysCount) - assertBn(nodeOperatorsSummary.totalExitedValidators, exitedSigningKeysCount) - assertBn(nodeOperatorsSummary.totalDepositedValidators, depositedSigningKeysCount) - assertBn(nodeOperatorsSummary.depositableValidatorsCount, vettedSigningKeysCount - depositedSigningKeysCount) + assert.equals(nodeOperator.stakingLimit, vettedSigningKeysCount) + assert.equals(nodeOperator.totalSigningKeys, totalSigningKeysCount) + assert.equals(nodeOperatorsSummary.totalExitedValidators, exitedSigningKeysCount) + assert.equals(nodeOperatorsSummary.totalDepositedValidators, depositedSigningKeysCount) + assert.equals(nodeOperatorsSummary.depositableValidatorsCount, vettedSigningKeysCount - depositedSigningKeysCount) } else { - assertBn(nodeOperatorsSummary.totalExitedValidators, exitedSigningKeysCount) - assertBn(nodeOperatorsSummary.totalDepositedValidators, depositedSigningKeysCount) - assertBn(nodeOperatorsSummary.depositableValidatorsCount, 0) + assert.equals(nodeOperatorsSummary.totalExitedValidators, exitedSigningKeysCount) + assert.equals(nodeOperatorsSummary.totalDepositedValidators, depositedSigningKeysCount) + assert.equals(nodeOperatorsSummary.depositableValidatorsCount, 0) } return { validatorKeys, id: newOperatorId.toNumber() } } diff --git a/test/helpers/oracle.js b/test/helpers/oracle.js index 6f9b9f89a..8e291fc97 100644 --- a/test/helpers/oracle.js +++ b/test/helpers/oracle.js @@ -1,3 +1,5 @@ +const { web3 } = require('hardhat') + const { CONSENSUS_VERSION, ZERO_BYTES32 } = require('./constants') const { assert } = require('./assert') diff --git a/test/helpers/signatures.js b/test/helpers/signatures.js index 1a4ee3564..200964dab 100644 --- a/test/helpers/signatures.js +++ b/test/helpers/signatures.js @@ -82,7 +82,6 @@ function signPauseData(pauseMessagePrefix, pauseMessage, guardianPrivateKey) { } function encodePauseData(pauseMessagePrefix, pauseMessage) { - const uint256Size = 64 return hexToBytes( strip0x(pauseMessagePrefix) + encodeBN(pauseMessage.blockNumber) + encodeBN(pauseMessage.stakingModule) ) @@ -91,9 +90,6 @@ function encodePauseData(pauseMessagePrefix, pauseMessage) { function encodeBN(value) { return new BN(value).toString('hex', UINT256_SIZE) // 32bytes } -function encodeBNuint24(value) { - return new BN(value).toString('hex', 6) // 3bytes -} function signDepositData( attestMessagePrefix, @@ -113,7 +109,6 @@ function signDepositData( function encodeAttestMessage(attestMessagePrefix, blockNumber, blockHash, depositRoot, StakingModuleId, keysOpIndex) { const uint256Size = 64 - const uint24Size = 6 return hexToBytes( strip0x(attestMessagePrefix) + @@ -126,7 +121,8 @@ function encodeAttestMessage(attestMessagePrefix, blockNumber, blockHash, deposi } function hexToBytes(hex) { - for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)) + const bytes = [] + for (let c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)) return bytes } diff --git a/test/helpers/staking-modules.js b/test/helpers/staking-modules.js index 636f88354..bc946515d 100644 --- a/test/helpers/staking-modules.js +++ b/test/helpers/staking-modules.js @@ -1,4 +1,6 @@ +const { artifacts } = require('hardhat') const { newApp } = require('./dao') + const NodeOperatorsRegistry = artifacts.require('NodeOperatorsRegistry') const NodeOperatorsRegistryMock = artifacts.require('NodeOperatorsRegistryMock') diff --git a/test/helpers/utils.js b/test/helpers/utils.js index 9c2f5acb2..aaaede6c9 100644 --- a/test/helpers/utils.js +++ b/test/helpers/utils.js @@ -1,6 +1,6 @@ -const hre = require('hardhat') +const { web3 } = require('hardhat') +const assert = require('node:assert') const { BN } = require('bn.js') -const { getEventAt } = require('@aragon/contract-helpers-test') const ZERO_HASH = '0x0000000000000000000000000000000000000000000000000000000000000000' @@ -68,24 +68,6 @@ function strip0x(s) { return s.substr(0, 2) === '0x' ? s.substr(2) : s } -// transforms all object entries -const transformEntries = (obj, tr) => - Object.fromEntries( - Object.entries(obj) - .map(tr) - .filter((x) => x !== undefined) - ) - -// converts all object BN keys to strings, drops numeric keys and the __length__ key -const processNamedTuple = (obj) => - transformEntries(obj, ([k, v]) => { - return /^(\d+|__length__)$/.test(k) ? undefined : [k, BN.isBN(v) ? v.toString() : v] - }) - -const printEvents = (tx) => { - console.log(tx.receipt.logs.map(({ event, args }) => ({ event, args: processNamedTuple(args) }))) -} - // Divides a BN by 1e15 const div15 = (bn) => bn.div(new BN(1000000)).div(new BN(1000000)).div(new BN(1000)) @@ -101,36 +83,6 @@ const shareRate = e27 const bnE9 = new BN(10).pow(new BN(9)) const ethToGwei = (valueEth) => toBN(valueEth).div(bnE9).toString() -function formatWei(weiString) { - return ethers.utils.formatEther(ethers.utils.parseUnits(weiString, 'wei'), { commify: true }) + ' ETH' -} - -function formatBN(bn) { - return formatWei(bn.toString()) -} - -async function getEthBalance(address) { - return formatWei(await web3.eth.getBalance(address)) -} - -function formatStEth(bn) { - return ethers.utils.formatEther(ethers.utils.parseUnits(bn.toString(), 'wei'), { commify: true }) + ' stETH' -} - -const assertNoEvent = (receipt, eventName, msg) => { - const event = getEventAt(receipt, eventName) - assert.equal(event, undefined, msg) -} - -function assertBnClose(x, y, maxDiff, msg = undefined) { - const diff = new BN(x).sub(new BN(y)).abs() - assert( - diff.lte(new BN(maxDiff)), - () => `Expected ${x} to be close to ${y} with max diff ${maxDiff}, actual diff ${diff}`, - () => `Expected ${x} not to be close to ${y} with min diff ${maxDiff}, actual diff ${diff}` - ) -} - const changeEndianness = (string) => { string = string.replace('0x', '') const result = [] @@ -145,10 +97,6 @@ const changeEndianness = (string) => { const toNum = (x) => (Array.isArray(x) ? x.map(toNum) : +x) const toStr = (x) => (Array.isArray(x) ? x.map(toStr) : `${x}`) -const setBalance = async (address, value) => { - await hre.network.provider.send('hardhat_setBalance', [address, web3.utils.numberToHex(value)]) -} - const prepIdsCountsPayload = (ids, counts) => { if (!Array.isArray(ids)) ids = [ids] if (!Array.isArray(counts)) counts = [counts] @@ -177,9 +125,6 @@ module.exports = { toBN, hex, strip0x, - transformEntries, - processNamedTuple, - printEvents, div15, e9, e18, @@ -189,12 +134,6 @@ module.exports = { ethToGwei, StETH: ETH, tokens, - getEthBalance, - formatWei, - formatBN, - formatStEth, - assertNoEvent, - assertBnClose, changeEndianness, genKeys, shareRate, @@ -202,7 +141,6 @@ module.exports = { padRight, toNum, toStr, - setBalance, prepIdsCountsPayload, calcSharesMintedAsFees, } diff --git a/test/helpers/withdrawals.js b/test/helpers/withdrawals.js index af1065517..1a40270bb 100644 --- a/test/helpers/withdrawals.js +++ b/test/helpers/withdrawals.js @@ -1,4 +1,4 @@ -const { utils } = require('ethers') +const { artifacts } = require('hardhat') const OssifiableProxy = artifacts.require('OssifiableProxy.sol') const WithdrawalQueueERC721 = artifacts.require('WithdrawalQueueERC721.sol') diff --git a/test/scenario/changing_oracles_during_epoch.js b/test/scenario/changing_oracles_during_epoch.test.js similarity index 75% rename from test/scenario/changing_oracles_during_epoch.js rename to test/scenario/changing_oracles_during_epoch.test.js index 67f658e8d..8f65086bd 100644 --- a/test/scenario/changing_oracles_during_epoch.js +++ b/test/scenario/changing_oracles_during_epoch.test.js @@ -1,7 +1,6 @@ -const { newDao, newApp } = require('../0.4.24/helpers/dao') -const { assertBn, assertEvent } = require('@aragon/contract-helpers-test/src/asserts') -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') -const { assertRevert } = require('../helpers/assertThrow') +const { contract } = require('hardhat') + +const { assert } = require('../helpers/assert') const { e9 } = require('../helpers/utils') const { @@ -23,9 +22,7 @@ const EPOCHS_PER_FRAME = 225 const SLOTS_PER_FRAME = EPOCHS_PER_FRAME * SLOTS_PER_EPOCH const SECONDS_PER_FRAME = SLOTS_PER_FRAME * SECONDS_PER_SLOT -// const EPOCH_LENGTH = 32 * 12 - -contract('AccountingOracle', ([appManager, voting, malicious1, malicious2, member1, member2, member3]) => { +contract('AccountingOracle', ([voting, malicious1, malicious2, member1, member2, member3]) => { let lido, consensus, oracle const GOOD_DATA = { @@ -69,15 +66,15 @@ contract('AccountingOracle', ([appManager, voting, malicious1, malicious2, membe await initAccountingOracle({ ...deployed, admin: voting }) - assert.equal(+(await oracle.getTime()), GENESIS_TIME + SECONDS_PER_FRAME) + assert.equals((await oracle.getTime()), GENESIS_TIME + SECONDS_PER_FRAME) await consensus.addMember(member1, 4, { from: voting }) await consensus.addMember(member2, 4, { from: voting }) }) it('reverts with zero ref. slot', async () => { - assertBn((await consensus.getCurrentFrame()).refSlot, 1 * SLOTS_PER_FRAME - 1) - await assertRevert(consensus.submitReport(0, HASH_1, CONSENSUS_VERSION, { from: member1 }), 'InvalidSlot()') + assert.equals((await consensus.getCurrentFrame()).refSlot, 1 * SLOTS_PER_FRAME - 1) + await assert.reverts(consensus.submitReport(0, HASH_1, CONSENSUS_VERSION, { from: member1 }), 'InvalidSlot()') }) it('oracle conract handles changing the oracles during epoch', async () => { @@ -100,16 +97,18 @@ contract('AccountingOracle', ([appManager, voting, malicious1, malicious2, membe let tx = await consensus.submitReport(SLOTS_PER_FRAME - 1, goodDataHash, CONSENSUS_VERSION, { from: member3 }) - assertEvent(tx, 'ConsensusReached', { - expectedArgs: { refSlot: SLOTS_PER_FRAME - 1, report: goodDataHash, support: 3 }, + assert.emits(tx, 'ConsensusReached', { + refSlot: SLOTS_PER_FRAME - 1, + report: goodDataHash, + support: 3, }) tx = await oracle.submitReportData(goodDataItems, await oracle.getContractVersion(), { from: member3 }) - assertEvent(tx, 'ProcessingStarted', { expectedArgs: { refSlot: SLOTS_PER_FRAME - 1 } }) + assert.emits(tx, 'ProcessingStarted', { refSlot: SLOTS_PER_FRAME - 1 }) const lastHandleOracleReportCall = await lido.getLastCall_handleOracleReport() - assertBn(lastHandleOracleReportCall.clBalance, e9(GOOD_DATA.clBalanceGwei)) - assertBn(lastHandleOracleReportCall.numValidators, GOOD_DATA.numValidators) + assert.equals(lastHandleOracleReportCall.clBalance, e9(GOOD_DATA.clBalanceGwei)) + assert.equals(lastHandleOracleReportCall.numValidators, GOOD_DATA.numValidators) }) }) diff --git a/test/deposit.test.js b/test/scenario/deposit.test.js similarity index 58% rename from test/deposit.test.js rename to test/scenario/deposit.test.js index 2e630d307..eb4e6e702 100644 --- a/test/deposit.test.js +++ b/test/scenario/deposit.test.js @@ -1,15 +1,15 @@ -const hre = require('hardhat') +const { contract, ethers, web3 } = require('hardhat') +const { assert } = require('../helpers/assert') -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') -const { ZERO_ADDRESS, bn } = require('@aragon/contract-helpers-test') +const { bn } = require('@aragon/contract-helpers-test') -const { EvmSnapshot } = require('./helpers/blockchain') -const { setupNodeOperatorsRegistry } = require('./helpers/staking-modules') -const { deployProtocol } = require('./helpers/protocol') -const { ETH, pad, hexConcat, changeEndianness, prepIdsCountsPayload } = require('./helpers/utils') -const nodeOperators = require('./helpers/node-operators') -const { assert } = require('./helpers/assert') -const { depositContractFactory } = require('./helpers/factories') +const { EvmSnapshot } = require('../helpers/blockchain') +const { setupNodeOperatorsRegistry } = require('../helpers/staking-modules') +const { deployProtocol } = require('../helpers/protocol') +const { ETH, pad, hexConcat, changeEndianness, prepIdsCountsPayload, tokens } = require('../helpers/utils') +const nodeOperators = require('../helpers/node-operators') +const { depositContractFactory } = require('../helpers/factories') +const { ZERO_ADDRESS } = require('../helpers/constants') const ADDRESS_1 = '0x0000000000000000000000000000000000000001' const ADDRESS_2 = '0x0000000000000000000000000000000000000002' @@ -21,8 +21,6 @@ const MAX_DEPOSITS = 150 const CURATED_MODULE_ID = 1 const CALLDATA = '0x0' -const tokens = ETH - contract('Lido with official deposit contract', ([user1, user2, user3, nobody, depositor]) => { let app, token, depositContract, operators, stakingRouter let voting, snapshot @@ -66,7 +64,7 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d voting = deployed.voting.address depositContract = deployed.depositContract - snapshot = new EvmSnapshot(hre.ethers.provider) + snapshot = new EvmSnapshot(ethers.provider) await snapshot.make() }) @@ -76,8 +74,8 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d const checkStat = async ({ depositedValidators, beaconBalance }) => { const stat = await app.getBeaconStat() - assertBn(stat.depositedValidators, depositedValidators, 'deposited ether check') - assertBn(stat.beaconBalance, beaconBalance, 'remote ether check') + assert.equals(stat.depositedValidators, depositedValidators, 'deposited ether check') + assert.equals(stat.beaconBalance, beaconBalance, 'remote ether check') } it('deposit works', async () => { @@ -102,47 +100,47 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 0, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(2)) - assertBn(await app.getBufferedEther(), ETH(2)) - assertBn(await token.balanceOf(user1), tokens(1)) - assertBn(await token.totalSupply(), tokens(2)) + assert.equals(await app.getTotalPooledEther(), ETH(2)) + assert.equals(await app.getBufferedEther(), ETH(2)) + assert.equals(await token.balanceOf(user1), tokens(1)) + assert.equals(await token.totalSupply(), tokens(2)) // +2 ETH await app.submit(ZERO_ADDRESS, { from: user2, value: ETH(2) }) // another form of a deposit call await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 0, beaconBalance: 0 }) - assertBn(bn(await depositContract.get_deposit_count()), 0) - assertBn(await app.getTotalPooledEther(), ETH(4)) - assertBn(await app.getBufferedEther(), ETH(4)) - assertBn(await token.balanceOf(user2), tokens(2)) - assertBn(await token.totalSupply(), tokens(4)) + assert.equals(bn(await depositContract.get_deposit_count()), 0) + assert.equals(await app.getTotalPooledEther(), ETH(4)) + assert.equals(await app.getBufferedEther(), ETH(4)) + assert.equals(await token.balanceOf(user2), tokens(2)) + assert.equals(await token.totalSupply(), tokens(4)) // +30 ETH await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(30) }) await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 1, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(34)) - assertBn(await app.getBufferedEther(), ETH(2)) - assertBn(await token.balanceOf(user1), tokens(1)) - assertBn(await token.balanceOf(user2), tokens(2)) - assertBn(await token.balanceOf(user3), tokens(30)) - assertBn(await token.totalSupply(), tokens(34)) + assert.equals(await app.getTotalPooledEther(), ETH(34)) + assert.equals(await app.getBufferedEther(), ETH(2)) + assert.equals(await token.balanceOf(user1), tokens(1)) + assert.equals(await token.balanceOf(user2), tokens(2)) + assert.equals(await token.balanceOf(user3), tokens(30)) + assert.equals(await token.totalSupply(), tokens(34)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 1) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 1) // +100 ETH await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(100) }) await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 4, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(134)) - assertBn(await app.getBufferedEther(), ETH(6)) - assertBn(await token.balanceOf(user1), tokens(101)) - assertBn(await token.balanceOf(user2), tokens(2)) - assertBn(await token.balanceOf(user3), tokens(30)) - assertBn(await token.totalSupply(), tokens(134)) - - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 4) + assert.equals(await app.getTotalPooledEther(), ETH(134)) + assert.equals(await app.getBufferedEther(), ETH(6)) + assert.equals(await token.balanceOf(user1), tokens(101)) + assert.equals(await token.balanceOf(user2), tokens(2)) + assert.equals(await token.balanceOf(user3), tokens(30)) + assert.equals(await token.totalSupply(), tokens(134)) + + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 4) }) it('key removal is taken into account during deposit', async () => { @@ -173,7 +171,7 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await web3.eth.sendTransaction({ to: app.address, from: user3, value: ETH(32) }) await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 1) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 1) await assert.reverts(operators.removeSigningKey(0, 0, { from: voting }), 'OUT_OF_RANGE') await operators.removeSigningKey(0, 1, { from: voting }) @@ -184,9 +182,9 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d // deposit should go to second operator, as the first one got their key limits set to 1 await assert.reverts(operators.removeSigningKey(1, 0, { from: voting }), 'OUT_OF_RANGE') await assert.reverts(operators.removeSigningKey(1, 1, { from: voting }), 'OUT_OF_RANGE') - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 4) - assertBn(await app.getTotalPooledEther(), ETH(133)) - assertBn(await app.getBufferedEther(), ETH(5)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 4) + assert.equals(await app.getTotalPooledEther(), ETH(133)) + assert.equals(await app.getBufferedEther(), ETH(5)) }) it('Node Operators filtering during deposit works when doing a huge deposit', async () => { @@ -228,48 +226,48 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d // Deposit huge chunk await web3.eth.sendTransaction({ to: app.address, from: user1, value: ETH(32 * 3 + 50 - 1 /* initial */) }) - tx = await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { + await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor, }) // assertEvent(tx, 'StakingRouterTransferReceived') await checkStat({ depositedValidators: 3, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(146)) - assertBn(await app.getBufferedEther(), ETH(50)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 3) + assert.equals(await app.getTotalPooledEther(), ETH(146)) + assert.equals(await app.getBufferedEther(), ETH(50)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 3) - assertBn(await web3.eth.getBalance(app.address), ETH(50), 'Lido balance') - assertBn(await web3.eth.getBalance(stakingRouter.address), 0, 'StakingRouter balance') + assert.equals(await web3.eth.getBalance(app.address), ETH(50), 'Lido balance') + assert.equals(await web3.eth.getBalance(stakingRouter.address), 0, 'StakingRouter balance') - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Next deposit changes nothing await web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(32) }) await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(178)) - assertBn(await app.getBufferedEther(), ETH(82)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 3) + assert.equals(await app.getTotalPooledEther(), ETH(178)) + assert.equals(await app.getBufferedEther(), ETH(82)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // #1 goes below the limit (nothing changed cause staking limit decreases) const { operatorIds, keysCounts } = prepIdsCountsPayload(1, 1) @@ -278,19 +276,19 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(179)) - assertBn(await app.getBufferedEther(), ETH(83)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 3) + assert.equals(await app.getTotalPooledEther(), ETH(179)) + assert.equals(await app.getBufferedEther(), ETH(83)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Adding a key & setting staking limit will help await operators.addSigningKeys(0, 1, pad('0x0003', 48), pad('0x01', 96), { from: voting }) @@ -300,19 +298,19 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 4, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(180)) - assertBn(await app.getBufferedEther(), ETH(52)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 4) + assert.equals(await app.getTotalPooledEther(), ETH(180)) + assert.equals(await app.getBufferedEther(), ETH(52)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 4) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Reactivation of #2 (doesn't change anything cause staking limit was trimmed on deactivation) await operators.activateNodeOperator(2, { from: voting }) @@ -320,19 +318,19 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 4, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(192)) - assertBn(await app.getBufferedEther(), ETH(64)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 4) - - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await app.getTotalPooledEther(), ETH(192)) + assert.equals(await app.getBufferedEther(), ETH(64)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 4) + + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) }) it('Node Operators filtering during deposit works when doing small deposits', async () => { @@ -380,38 +378,38 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(146)) - assertBn(await app.getBufferedEther(), ETH(50)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 3) + assert.equals(await app.getTotalPooledEther(), ETH(146)) + assert.equals(await app.getBufferedEther(), ETH(50)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Next deposit changes nothing await web3.eth.sendTransaction({ to: app.address, from: user2, value: ETH(32) }) await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(178)) - assertBn(await app.getBufferedEther(), ETH(82)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 3) + assert.equals(await app.getTotalPooledEther(), ETH(178)) + assert.equals(await app.getBufferedEther(), ETH(82)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // #1 goes below the limit (nothing changed cause staking limit decreases) const { operatorIds, keysCounts } = prepIdsCountsPayload(1, 1) @@ -420,19 +418,19 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(179)) - assertBn(await app.getBufferedEther(), ETH(83)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 3) + assert.equals(await app.getTotalPooledEther(), ETH(179)) + assert.equals(await app.getBufferedEther(), ETH(83)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 3) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Adding a key & setting staking limit will help await operators.addSigningKeys(0, 1, pad('0x0003', 48), pad('0x01', 96), { from: voting }) @@ -442,19 +440,19 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 4, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(180)) - assertBn(await app.getBufferedEther(), ETH(52)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 4) + assert.equals(await app.getTotalPooledEther(), ETH(180)) + assert.equals(await app.getBufferedEther(), ETH(52)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 4) - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Reactivation of #2 (doesn't change anything cause staking limit was trimmed on deactivation) await operators.activateNodeOperator(2, { from: voting }) @@ -462,19 +460,19 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 4, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(192)) - assertBn(await app.getBufferedEther(), ETH(64)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 4) - - assertBn(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) - assertBn(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) - - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await app.getTotalPooledEther(), ETH(192)) + assert.equals(await app.getBufferedEther(), ETH(64)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 4) + + assert.equals(await operators.getTotalSigningKeyCount(0, { from: nobody }), 3) + assert.equals(await operators.getTotalSigningKeyCount(1, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getTotalSigningKeyCount(3, { from: nobody }), 0) + + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) }) it('Deposit finds the right operator', async () => { @@ -525,14 +523,14 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 2, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(64)) - assertBn(await app.getBufferedEther(), ETH(0)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 2) + assert.equals(await app.getTotalPooledEther(), ETH(64)) + assert.equals(await app.getBufferedEther(), ETH(0)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 2) - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 2) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) // Reactivation of #2 - has the smallest stake await operators.activateNodeOperator(2, { from: voting }) @@ -551,14 +549,14 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d await app.methods[`deposit(uint256,uint256,bytes)`](MAX_DEPOSITS, CURATED_MODULE_ID, CALLDATA, { from: depositor }) await checkStat({ depositedValidators: 3, beaconBalance: 0 }) - assertBn(await app.getTotalPooledEther(), ETH(100)) - assertBn(await app.getBufferedEther(), ETH(4)) - assertBn(bn(changeEndianness(await depositContract.get_deposit_count())), 3) - - assertBn(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) - assertBn(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 3) - assertBn(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) + assert.equals(await app.getTotalPooledEther(), ETH(100)) + assert.equals(await app.getBufferedEther(), ETH(4)) + assert.equals(bn(changeEndianness(await depositContract.get_deposit_count())), 3) + + assert.equals(await operators.getUnusedSigningKeyCount(0, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(1, { from: nobody }), 1) + assert.equals(await operators.getUnusedSigningKeyCount(2, { from: nobody }), 3) + assert.equals(await operators.getUnusedSigningKeyCount(3, { from: nobody }), 0) }) it('depositBufferedEther() deposits less then DEFAULT_MAX_DEPOSITS_PER_CALL', async () => { @@ -592,8 +590,8 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d gas: 20000000, }) - assertBn(await app.getTotalPooledEther(), ETH(amountToDeposit)) - assertBn(await app.getBufferedEther(), ETH(31)) + assert.equals(await app.getTotalPooledEther(), ETH(amountToDeposit)) + assert.equals(await app.getBufferedEther(), ETH(31)) }) it('depositBufferedEther() deposits equal to DEFAULT_MAX_DEPOSITS_PER_CALL', async () => { @@ -629,7 +627,7 @@ contract('Lido with official deposit contract', ([user1, user2, user3, nobody, d gas: 20000000, }) - assertBn(await app.getTotalPooledEther(), ETH(amountToDeposit)) - assertBn(await app.getBufferedEther(), ETH(33)) + assert.equals(await app.getTotalPooledEther(), ETH(amountToDeposit)) + assert.equals(await app.getBufferedEther(), ETH(33)) }) }) diff --git a/test/scenario/deposit_distribution.js b/test/scenario/deposit_distribution.test.js similarity index 97% rename from test/scenario/deposit_distribution.js rename to test/scenario/deposit_distribution.test.js index ddbbace42..d768a641b 100644 --- a/test/scenario/deposit_distribution.js +++ b/test/scenario/deposit_distribution.test.js @@ -1,12 +1,13 @@ -const hre = require('hardhat') -const { ETH, genKeys } = require('../helpers/utils') +const { contract, ethers, web3 } = require('hardhat') const { assert } = require('../helpers/assert') + +const { ETH, genKeys } = require('../helpers/utils') const { EvmSnapshot } = require('../helpers/blockchain') const { deployProtocol } = require('../helpers/protocol') const { setupNodeOperatorsRegistry } = require('../helpers/staking-modules') contract('StakingRouter', ([depositor, stranger1, address1, address2]) => { - const snapshot = new EvmSnapshot(hre.ethers.provider) + const snapshot = new EvmSnapshot(ethers.provider) let depositContract, stakingRouter let lido, curated, anotherCurated, voting diff --git a/test/scenario/execution_layer_rewards_after_the_merge.js b/test/scenario/execution_layer_rewards_after_the_merge.test.js similarity index 68% rename from test/scenario/execution_layer_rewards_after_the_merge.js rename to test/scenario/execution_layer_rewards_after_the_merge.test.js index 701809e9d..951372ef2 100644 --- a/test/scenario/execution_layer_rewards_after_the_merge.js +++ b/test/scenario/execution_layer_rewards_after_the_merge.test.js @@ -1,12 +1,11 @@ +const { contract, artifacts, web3 } = require('hardhat') const { assert } = require('../helpers/assert') + const { BN } = require('bn.js') -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') const { getEventArgument } = require('@aragon/contract-helpers-test') -const { gwei, ZERO_HASH } = require('../helpers/utils') - -const { pad, toBN, ETH, tokens, setBalance } = require('../helpers/utils') +const { gwei, ZERO_HASH, ethToGwei, pad, toBN, ETH, tokens } = require('../helpers/utils') const { DSMAttestMessage, DSMPauseMessage } = require('../helpers/signatures') -const { waitBlocks } = require('../helpers/blockchain') +const { waitBlocks, setBalance } = require('../helpers/blockchain') const { deployProtocol } = require('../helpers/protocol') const { setupNodeOperatorsRegistry } = require('../helpers/staking-modules') const { SLOTS_PER_FRAME } = require('../helpers/constants') @@ -45,8 +44,6 @@ contract.skip('Lido: merge acceptance', (addresses) => { user3, // unrelated address nobody, - // Execution layer rewards source - userELRewards, ] = addresses let pool, nodeOperatorsRegistry, token @@ -127,7 +124,7 @@ contract.skip('Lido: merge acceptance', (addresses) => { depositRoot = await depositContractMock.get_deposit_root() - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') await stakingRouter.setWithdrawalCredentials(withdrawalCredentials, { from: voting }) // Withdrawal credentials were set @@ -145,9 +142,9 @@ contract.skip('Lido: merge acceptance', (addresses) => { nodeOperator1.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi, }) - assertBn(nodeOperator1.id, 0, 'operator id') + assert.equals(nodeOperator1.id, 0, 'operator id') - assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') + assert.equals(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') const numKeys = 1 @@ -166,12 +163,12 @@ contract.skip('Lido: merge acceptance', (addresses) => { // The key was added let totalKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator1.id, { from: nobody }) - assertBn(totalKeys, 1, 'total signing keys') + assert.equals(totalKeys, 1, 'total signing keys') // The key was not used yet let unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator1.id, { from: nobody }) - assertBn(unusedKeys, 1, 'unused signing keys') + assert.equals(unusedKeys, 1, 'unused signing keys') txn = await nodeOperatorsRegistry.addNodeOperator(nodeOperator2.name, nodeOperator2.address, { from: voting }) @@ -179,9 +176,9 @@ contract.skip('Lido: merge acceptance', (addresses) => { nodeOperator2.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi, }) - assertBn(nodeOperator2.id, 1, 'operator id') + assert.equals(nodeOperator2.id, 1, 'operator id') - assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators') + assert.equals(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators') await nodeOperatorsRegistry.addSigningKeysOperatorBH( nodeOperator2.id, @@ -198,11 +195,11 @@ contract.skip('Lido: merge acceptance', (addresses) => { // The key was added totalKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator2.id, { from: nobody }) - assertBn(totalKeys, 1, 'total signing keys') + assert.equals(totalKeys, 1, 'total signing keys') // The key was not used yet unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator2.id, { from: nobody }) - assertBn(unusedKeys, 1, 'unused signing keys') + assert.equals(unusedKeys, 1, 'unused signing keys') }) it('the first user deposits 3 ETH to the pool', async () => { @@ -236,22 +233,22 @@ contract.skip('Lido: merge acceptance', (addresses) => { // No Ether was deposited yet to the validator contract - assertBn(await depositContractMock.totalCalls(), 0) + assert.equals(await depositContractMock.totalCalls(), 0) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 0, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, 0, 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 0, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, 0, 'remote ether2') // All Ether was buffered within the pool contract atm - assertBn(await pool.getBufferedEther(), ETH(3), 'buffered ether') - assertBn(await pool.getTotalPooledEther(), ETH(3), 'total pooled ether') + assert.equals(await pool.getBufferedEther(), ETH(3), 'buffered ether') + assert.equals(await pool.getTotalPooledEther(), ETH(3), 'total pooled ether') // The amount of tokens corresponding to the deposited ETH value was minted to the user - assertBn(await token.balanceOf(user1), tokens(3), 'user1 tokens') + assert.equals(await token.balanceOf(user1), tokens(3), 'user1 tokens') - assertBn(await token.totalSupply(), tokens(3), 'token total supply') + assert.equals(await token.totalSupply(), tokens(3), 'token total supply') }) it('the second user deposits 30 ETH to the pool', async () => { @@ -286,29 +283,29 @@ contract.skip('Lido: merge acceptance', (addresses) => { // The first 32 ETH chunk was deposited to the deposit contract, // using public key and signature of the only validator of the first operator - assertBn(await depositContractMock.totalCalls(), 1) + assert.equals(await depositContractMock.totalCalls(), 1) const regCall = await depositContractMock.calls.call(0) assert.equal(regCall.pubkey, nodeOperator1.validators[0].key) assert.equal(regCall.withdrawal_credentials, withdrawalCredentials) assert.equal(regCall.signature, nodeOperator1.validators[0].sig) - assertBn(regCall.value, ETH(32)) + assert.equals(regCall.value, ETH(32)) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 1, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, 0, 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 1, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, 0, 'remote ether2') // Some Ether remained buffered within the pool contract - assertBn(await pool.getBufferedEther(), ETH(1), 'buffered ether') - assertBn(await pool.getTotalPooledEther(), ETH(1 + 32), 'total pooled ether') + assert.equals(await pool.getBufferedEther(), ETH(1), 'buffered ether') + assert.equals(await pool.getTotalPooledEther(), ETH(1 + 32), 'total pooled ether') // The amount of tokens corresponding to the deposited ETH value was minted to the users - assertBn(await token.balanceOf(user1), tokens(3), 'user1 tokens') - assertBn(await token.balanceOf(user2), tokens(30), 'user2 tokens') + assert.equals(await token.balanceOf(user1), tokens(3), 'user1 tokens') + assert.equals(await token.balanceOf(user2), tokens(30), 'user2 tokens') - assertBn(await token.totalSupply(), tokens(3 + 30), 'token total supply') + assert.equals(await token.totalSupply(), tokens(3 + 30), 'token total supply') }) it('the third user deposits 64 ETH to the pool', async () => { @@ -332,7 +329,7 @@ contract.skip('Lido: merge acceptance', (addresses) => { validAttestMessage.sign(guardians.privateKeys[guardians.addresses[1]]), ] - assertBn(await depositContractMock.totalCalls(), 1) + assert.equals(await depositContractMock.totalCalls(), 1) await depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -346,36 +343,36 @@ contract.skip('Lido: merge acceptance', (addresses) => { // The first 32 ETH chunk was deposited to the deposit contract, // using public key and signature of the only validator of the second operator - assertBn(await depositContractMock.totalCalls(), 2) + assert.equals(await depositContractMock.totalCalls(), 2) const regCall = await depositContractMock.calls.call(1) assert.equal(regCall.pubkey, nodeOperator2.validators[0].key) assert.equal(regCall.withdrawal_credentials, withdrawalCredentials) assert.equal(regCall.signature, nodeOperator2.validators[0].sig) - assertBn(regCall.value, ETH(32)) + assert.equals(regCall.value, ETH(32)) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, 0, 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 2, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, 0, 'remote ether2') // The pool ran out of validator keys, so the remaining 32 ETH were added to the // pool buffer - assertBn(await pool.getBufferedEther(), ETH(1 + 32), 'buffered ether') - assertBn(await pool.getTotalPooledEther(), ETH(33 + 64), 'total pooled ether') + assert.equals(await pool.getBufferedEther(), ETH(1 + 32), 'buffered ether') + assert.equals(await pool.getTotalPooledEther(), ETH(33 + 64), 'total pooled ether') // The amount of tokens corresponding to the deposited ETH value was minted to the users - assertBn(await token.balanceOf(user1), tokens(3), 'user1 tokens') - assertBn(await token.balanceOf(user2), tokens(30), 'user2 tokens') - assertBn(await token.balanceOf(user3), tokens(64), 'user3 tokens') + assert.equals(await token.balanceOf(user1), tokens(3), 'user1 tokens') + assert.equals(await token.balanceOf(user2), tokens(30), 'user2 tokens') + assert.equals(await token.balanceOf(user3), tokens(64), 'user3 tokens') - assertBn(await token.totalSupply(), tokens(3 + 30 + 64), 'token total supply') + assert.equals(await token.totalSupply(), tokens(3 + 30 + 64), 'token total supply') }) it('collect 9 ETH execution layer rewards to the vault', async () => { await setBalance(elRewardsVault.address, ETH(9)) - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(9), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(9), 'Execution layer rewards vault balance') }) it('the oracle reports balance increase on Ethereum2 side (+32 ETH) and claims collected execution layer rewards (+9 ETH)', async () => { @@ -384,12 +381,12 @@ contract.skip('Lido: merge acceptance', (addresses) => { // Total shares are equal to deposited eth before ratio change and fee mint const oldTotalShares = await token.getTotalShares() - assertBn(oldTotalShares, ETH(97), 'total shares') + assert.equals(oldTotalShares, ETH(97), 'total shares') // Old total pooled Ether const oldTotalPooledEther = await pool.getTotalPooledEther() - assertBn(oldTotalPooledEther, ETH(33 + 64), 'total pooled ether') + assert.equals(oldTotalPooledEther, ETH(33 + 64), 'total pooled ether') // Reporting 1.5-fold balance increase (64 => 96) @@ -404,7 +401,7 @@ contract.skip('Lido: merge acceptance', (addresses) => { ) // Execution layer rewards just claimed - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') // Total shares increased because fee minted (fee shares added) // shares ~= oldTotalShares + reward * oldTotalShares / (newTotalPooledEther - reward) @@ -418,43 +415,43 @@ contract.skip('Lido: merge acceptance', (addresses) => { const newTotalShares = await token.getTotalShares() - assertBn(newTotalShares, new BN('99970126960418222554'), 'total shares') + assert.equals(newTotalShares, new BN('99970126960418222554'), 'total shares') const elRewards = 9 // Total pooled Ether increased const newTotalPooledEther = await pool.getTotalPooledEther() - assertBn(newTotalPooledEther, ETH(33 + 96 + elRewards), 'total pooled ether') + assert.equals(newTotalPooledEther, ETH(33 + 96 + elRewards), 'total pooled ether') // Ether2 stat reported by the pool changed correspondingly const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, ETH(96), 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 2, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, ETH(96), 'remote ether2') // Buffered Ether amount changed on execution layer rewards - assertBn(await pool.getBufferedEther(), ETH(33 + elRewards), 'buffered ether') + assert.equals(await pool.getBufferedEther(), ETH(33 + elRewards), 'buffered ether') // New tokens was minted to distribute fee - assertBn(await token.totalSupply(), tokens(129 + elRewards), 'token total supply') + assert.equals(await token.totalSupply(), tokens(129 + elRewards), 'token total supply') const reward = toBN(ETH(96 - 64 + elRewards)) const mintedAmount = new BN(totalFeePoints).mul(reward).divn(TOTAL_BASIS_POINTS) // Token user balances increased - assertBn(await token.balanceOf(user1), new BN('4141237113402061855'), 'user1 tokens') - assertBn(await token.balanceOf(user2), new BN('41412371134020618556'), 'user2 tokens') - assertBn(await token.balanceOf(user3), new BN('88346391752577319587'), 'user3 tokens') + assert.equals(await token.balanceOf(user1), new BN('4141237113402061855'), 'user1 tokens') + assert.equals(await token.balanceOf(user2), new BN('41412371134020618556'), 'user2 tokens') + assert.equals(await token.balanceOf(user3), new BN('88346391752577319587'), 'user3 tokens') // Fee, in the form of minted tokens, was distributed between treasury, insurance fund // and node operators // treasuryTokenBalance ~= mintedAmount * treasuryFeePoints / 10000 // insuranceTokenBalance ~= mintedAmount * insuranceFeePoints / 10000 - assertBn(await token.balanceOf(treasuryAddr), new BN('2049999999999999999'), 'treasury tokens') + assert.equals(await token.balanceOf(treasuryAddr), new BN('2049999999999999999'), 'treasury tokens') // Module fee, rewards distribution between modules should be make by module - assertBn(await token.balanceOf(nodeOperatorsRegistry.address), new BN('2049999999999999999'), 'module1 tokens') + assert.equals(await token.balanceOf(nodeOperatorsRegistry.address), new BN('2049999999999999999'), 'module1 tokens') // Real minted amount should be a bit less than calculated caused by round errors on mint and transfer operations assert( @@ -469,14 +466,14 @@ contract.skip('Lido: merge acceptance', (addresses) => { it('collect another 7 ETH execution layer rewards to the vault', async () => { const balanceBefore = await web3.eth.getBalance(elRewardsVault.address) await setBalance(elRewardsVault.address, ETH(2)) - assertBn( + assert.equals( await web3.eth.getBalance(elRewardsVault.address), ETH(2) + balanceBefore, 'Execution layer rewards vault balance' ) await setBalance(elRewardsVault.address, ETH(5)) - assertBn( + assert.equals( await web3.eth.getBalance(elRewardsVault.address), ETH(7) + balanceBefore, 'Execution layer rewards vault balance' @@ -488,12 +485,12 @@ contract.skip('Lido: merge acceptance', (addresses) => { // Total shares are equal to deposited eth before ratio change and fee mint const oldTotalShares = await token.getTotalShares() - assertBn(oldTotalShares, new BN('99970126960418222554'), 'total shares') + assert.equals(oldTotalShares, new BN('99970126960418222554'), 'total shares') // Old total pooled Ether const oldTotalPooledEther = await pool.getTotalPooledEther() - assertBn(oldTotalPooledEther, ETH(138), 'total pooled ether') + assert.equals(oldTotalPooledEther, ETH(138), 'total pooled ether') // Reporting the same balance as it was before (96ETH => 96ETH) await oracleMock.submitReportData( @@ -507,51 +504,48 @@ contract.skip('Lido: merge acceptance', (addresses) => { ) // Execution layer rewards just claimed - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') // Total shares preserved because fee shares NOT minted // shares ~= oldTotalShares + reward * oldTotalShares / (newTotalPooledEther - reward) const newTotalShares = await token.getTotalShares() - assertBn(newTotalShares, oldTotalShares, 'total shares') + assert.equals(newTotalShares, oldTotalShares, 'total shares') // Total pooled Ether increased const newTotalPooledEther = await pool.getTotalPooledEther() - assertBn(newTotalPooledEther, ETH(138 + 7), 'total pooled ether') + assert.equals(newTotalPooledEther, ETH(138 + 7), 'total pooled ether') // Ether2 stat reported by the pool changed correspondingly const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, ETH(96), 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 2, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, ETH(96), 'remote ether2') // Buffered Ether amount changed on execution layer rewards - assertBn(await pool.getBufferedEther(), ETH(42 + 7), 'buffered ether') - - assertBn(await token.totalSupply(), tokens(145), 'token total supply') + assert.equals(await pool.getBufferedEther(), ETH(42 + 7), 'buffered ether') - const reward = toBN(0) - const mintedAmount = new BN(0) + assert.equals(await token.totalSupply(), tokens(145), 'token total supply') // All of the balances should be increased with proportion of newTotalPooledEther/oldTotalPooledEther (which is >1) // cause shares per user and overall shares number are preserved - assertBn(await token.balanceOf(user1), new BN('4351299865531151949'), 'user1 tokens') - assertBn(await token.balanceOf(user2), new BN('43512998655311519498'), 'user2 tokens') - assertBn(await token.balanceOf(user3), new BN('92827730464664574929'), 'user3 tokens') + assert.equals(await token.balanceOf(user1), new BN('4351299865531151949'), 'user1 tokens') + assert.equals(await token.balanceOf(user2), new BN('43512998655311519498'), 'user2 tokens') + assert.equals(await token.balanceOf(user3), new BN('92827730464664574929'), 'user3 tokens') - assertBn(await token.balanceOf(treasuryAddr), new BN('2153985507246376811'), 'treasury tokens') - assertBn(await token.balanceOf(nodeOperatorsRegistry.address), new BN('2153985507246376811'), 'module1 tokens') + assert.equals(await token.balanceOf(treasuryAddr), new BN('2153985507246376811'), 'treasury tokens') + assert.equals(await token.balanceOf(nodeOperatorsRegistry.address), new BN('2153985507246376811'), 'module1 tokens') // operators do not claim rewards from module - assertBn(await token.balanceOf(nodeOperator1.address), 0, 'operator_1 tokens') - assertBn(await token.balanceOf(nodeOperator2.address), 0, 'operator_2 tokens') + assert.equals(await token.balanceOf(nodeOperator1.address), 0, 'operator_1 tokens') + assert.equals(await token.balanceOf(nodeOperator2.address), 0, 'operator_2 tokens') }) it('collect another 5 ETH execution layer rewards to the vault', async () => { await setBalance(elRewardsVault.address, ETH(5)) - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(5), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(5), 'Execution layer rewards vault balance') }) it('the oracle reports loss on Ethereum2 side (-2 ETH) and claims collected execution layer rewards (+5 ETH)', async () => { @@ -559,12 +553,12 @@ contract.skip('Lido: merge acceptance', (addresses) => { // Total shares are equal to deposited eth before ratio change and fee mint const oldTotalShares = await token.getTotalShares() - assertBn(oldTotalShares, new BN('99970126960418222554'), 'total shares') + assert.equals(oldTotalShares, new BN('99970126960418222554'), 'total shares') // Old total pooled Ether const oldTotalPooledEther = await pool.getTotalPooledEther() - assertBn(oldTotalPooledEther, ETH(145), 'total pooled ether') + assert.equals(oldTotalPooledEther, ETH(145), 'total pooled ether') // Reporting balance decrease (96ETH => 94ETH) await oracleMock.submitReportData( @@ -578,44 +572,41 @@ contract.skip('Lido: merge acceptance', (addresses) => { ) // Execution layer rewards just claimed - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') // Total shares preserved because fee shares NOT minted // shares ~= oldTotalShares + reward * oldTotalShares / (newTotalPooledEther - reward) const newTotalShares = await token.getTotalShares() - assertBn(newTotalShares, oldTotalShares, 'total shares') + assert.equals(newTotalShares, oldTotalShares, 'total shares') // Total pooled Ether increased by 5ETH - 2ETH const newTotalPooledEther = await pool.getTotalPooledEther() - assertBn(newTotalPooledEther, ETH(145 + 3), 'total pooled ether') + assert.equals(newTotalPooledEther, ETH(145 + 3), 'total pooled ether') // Ether2 stat reported by the pool changed correspondingly const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, ETH(94), 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 2, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, ETH(94), 'remote ether2') // Buffered Ether amount changed on execution layer rewards - assertBn(await pool.getBufferedEther(), ETH(49 + 5), 'buffered ether') + assert.equals(await pool.getBufferedEther(), ETH(49 + 5), 'buffered ether') - assertBn(await token.totalSupply(), tokens(145 + 3), 'token total supply') - - const reward = toBN(0) - const mintedAmount = new BN(0) + assert.equals(await token.totalSupply(), tokens(145 + 3), 'token total supply') // All of the balances should be increased with proportion of newTotalPooledEther/oldTotalPooledEther (which is >1) // cause shares per user and overall shares number are preserved - assertBn(await token.balanceOf(user1), new BN('4441326759300761990'), 'user1 tokens') - assertBn(await token.balanceOf(user2), new BN('44413267593007619901'), 'user2 tokens') - assertBn(await token.balanceOf(user3), new BN('94748304198416255789'), 'user3 tokens') + assert.equals(await token.balanceOf(user1), new BN('4441326759300761990'), 'user1 tokens') + assert.equals(await token.balanceOf(user2), new BN('44413267593007619901'), 'user2 tokens') + assert.equals(await token.balanceOf(user3), new BN('94748304198416255789'), 'user3 tokens') - assertBn(await token.balanceOf(treasuryAddr), new BN('2198550724637681159'), 'treasury tokens') - assertBn(await token.balanceOf(nodeOperatorsRegistry.address), new BN('2198550724637681159'), 'module1 tokens') + assert.equals(await token.balanceOf(treasuryAddr), new BN('2198550724637681159'), 'treasury tokens') + assert.equals(await token.balanceOf(nodeOperatorsRegistry.address), new BN('2198550724637681159'), 'module1 tokens') }) it('collect another 3 ETH execution layer rewards to the vault', async () => { await setBalance(elRewardsVault.address, ETH(3)) - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(3), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(3), 'Execution layer rewards vault balance') }) it('the oracle reports loss on Ethereum2 side (-3 ETH) and claims collected execution layer rewards (+3 ETH)', async () => { @@ -623,12 +614,12 @@ contract.skip('Lido: merge acceptance', (addresses) => { // Total shares are equal to deposited eth before ratio change and fee mint const oldTotalShares = await token.getTotalShares() - assertBn(oldTotalShares, new BN('99970126960418222554'), 'total shares') + assert.equals(oldTotalShares, new BN('99970126960418222554'), 'total shares') // Old total pooled Ether const oldTotalPooledEther = await pool.getTotalPooledEther() - assertBn(oldTotalPooledEther, ETH(148), 'total pooled ether') + assert.equals(oldTotalPooledEther, ETH(148), 'total pooled ether') // Reporting balance decrease (94ETH => 91ETH) await oracleMock.submitReportData( @@ -642,42 +633,39 @@ contract.skip('Lido: merge acceptance', (addresses) => { ) // Execution layer rewards just claimed - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') // Total shares preserved because fee shares NOT minted // shares ~= oldTotalShares + reward * oldTotalShares / (newTotalPooledEther - reward) const newTotalShares = await token.getTotalShares() - assertBn(newTotalShares, oldTotalShares, 'total shares') + assert.equals(newTotalShares, oldTotalShares, 'total shares') // Total pooled Ether increased by 5ETH - 2ETH const newTotalPooledEther = await pool.getTotalPooledEther() - assertBn(newTotalPooledEther, oldTotalPooledEther, 'total pooled ether') + assert.equals(newTotalPooledEther, oldTotalPooledEther, 'total pooled ether') // Ether2 stat reported by the pool changed correspondingly const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, ETH(91), 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 2, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, ETH(91), 'remote ether2') // Buffered Ether amount changed on execution layer rewards - assertBn(await pool.getBufferedEther(), ETH(54 + 3), 'buffered ether') - - assertBn(await token.totalSupply(), tokens(148), 'token total supply') + assert.equals(await pool.getBufferedEther(), ETH(54 + 3), 'buffered ether') - const reward = toBN(0) - const mintedAmount = new BN(0) + assert.equals(await token.totalSupply(), tokens(148), 'token total supply') // All of the balances should be the same as before cause overall changes sums to zero - assertBn(await token.balanceOf(user1), new BN('4441326759300761990'), 'user1 tokens') - assertBn(await token.balanceOf(user2), new BN('44413267593007619901'), 'user2 tokens') - assertBn(await token.balanceOf(user3), new BN('94748304198416255789'), 'user3 tokens') + assert.equals(await token.balanceOf(user1), new BN('4441326759300761990'), 'user1 tokens') + assert.equals(await token.balanceOf(user2), new BN('44413267593007619901'), 'user2 tokens') + assert.equals(await token.balanceOf(user3), new BN('94748304198416255789'), 'user3 tokens') - assertBn(await token.balanceOf(treasuryAddr), new BN('2198550724637681159'), 'treasury tokens') - assertBn(await token.balanceOf(nodeOperatorsRegistry.address), new BN('2198550724637681159'), 'module1 tokens') + assert.equals(await token.balanceOf(treasuryAddr), new BN('2198550724637681159'), 'treasury tokens') + assert.equals(await token.balanceOf(nodeOperatorsRegistry.address), new BN('2198550724637681159'), 'module1 tokens') }) it('collect another 2 ETH execution layer rewards to the vault', async () => { await setBalance(elRewardsVault.address, ETH(2)) - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(2), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(2), 'Execution layer rewards vault balance') }) it('the oracle reports loss on Ethereum2 side (-8 ETH) and claims collected execution layer rewards (+2 ETH)', async () => { @@ -685,12 +673,12 @@ contract.skip('Lido: merge acceptance', (addresses) => { // Total shares are equal to deposited eth before ratio change and fee mint const oldTotalShares = await token.getTotalShares() - assertBn(oldTotalShares, new BN('99970126960418222554'), 'total shares') + assert.equals(oldTotalShares, new BN('99970126960418222554'), 'total shares') // Old total pooled Ether const oldTotalPooledEther = await pool.getTotalPooledEther() - assertBn(oldTotalPooledEther, ETH(148), 'total pooled ether') + assert.equals(oldTotalPooledEther, ETH(148), 'total pooled ether') // Reporting balance decrease (91ETH => 83ETH) await oracleMock.submitReportData( @@ -704,42 +692,42 @@ contract.skip('Lido: merge acceptance', (addresses) => { ) // Execution layer rewards just claimed - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') // Total shares preserved because fee shares NOT minted // shares ~= oldTotalShares + reward * oldTotalShares / (newTotalPooledEther - reward) const newTotalShares = await token.getTotalShares() - assertBn(newTotalShares, oldTotalShares, 'total shares') + assert.equals(newTotalShares, oldTotalShares, 'total shares') // Total pooled Ether decreased by 8ETH-2ETH const newTotalPooledEther = await pool.getTotalPooledEther() - assertBn(newTotalPooledEther, ETH(142), 'total pooled ether') + assert.equals(newTotalPooledEther, ETH(142), 'total pooled ether') // Ether2 stat reported by the pool changed correspondingly const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, ETH(83), 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 2, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, ETH(83), 'remote ether2') // Buffered Ether amount changed on execution layer rewards - assertBn(await pool.getBufferedEther(), ETH(57 + 2), 'buffered ether') + assert.equals(await pool.getBufferedEther(), ETH(57 + 2), 'buffered ether') - assertBn(await token.totalSupply(), tokens(142), 'token total supply') + assert.equals(await token.totalSupply(), tokens(142), 'token total supply') // All of the balances should be decreased with proportion of newTotalPooledEther/oldTotalPooledEther (which is <1) // cause shares per user and overall shares number are preserved - assertBn(await token.balanceOf(user1), new BN('4261272971761541909'), 'user1 tokens') - assertBn(await token.balanceOf(user2), new BN('42612729717615419094'), 'user2 tokens') - assertBn(await token.balanceOf(user3), new BN('90907156730912894068'), 'user3 tokens') - - assertBn(await token.balanceOf(treasuryAddr), new BN('2109420289855072463'), 'treasury tokens') - assertBn(await token.balanceOf(nodeOperatorsRegistry.address), new BN('2109420289855072463'), 'module1 tokens') - assertBn(await token.balanceOf(nodeOperator1.address), 0, 'operator_1 tokens') - assertBn(await token.balanceOf(nodeOperator2.address), 0, 'operator_2 tokens') + assert.equals(await token.balanceOf(user1), new BN('4261272971761541909'), 'user1 tokens') + assert.equals(await token.balanceOf(user2), new BN('42612729717615419094'), 'user2 tokens') + assert.equals(await token.balanceOf(user3), new BN('90907156730912894068'), 'user3 tokens') + + assert.equals(await token.balanceOf(treasuryAddr), new BN('2109420289855072463'), 'treasury tokens') + assert.equals(await token.balanceOf(nodeOperatorsRegistry.address), new BN('2109420289855072463'), 'module1 tokens') + assert.equals(await token.balanceOf(nodeOperator1.address), 0, 'operator_1 tokens') + assert.equals(await token.balanceOf(nodeOperator2.address), 0, 'operator_2 tokens') }) it('collect another 3 ETH execution layer rewards to the vault', async () => { await setBalance(elRewardsVault.address, ETH(3)) - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(3), 'Execution layer vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(3), 'Execution layer vault balance') }) it('the oracle reports balance increase on Ethereum2 side (+2 ETH) and claims collected execution layer rewards (+3 ETH)', async () => { @@ -747,12 +735,12 @@ contract.skip('Lido: merge acceptance', (addresses) => { // Total shares are equal to deposited eth before ratio change and fee mint const oldTotalShares = await token.getTotalShares() - assertBn(oldTotalShares, new BN('99970126960418222554'), 'total shares') + assert.equals(oldTotalShares, new BN('99970126960418222554'), 'total shares') // Old total pooled Ether const oldTotalPooledEther = await pool.getTotalPooledEther() - assertBn(oldTotalPooledEther, ETH(142), 'total pooled ether') + assert.equals(oldTotalPooledEther, ETH(142), 'total pooled ether') // Reporting balance increase (83ETH => 85ETH) await oracleMock.submitReportData( @@ -766,38 +754,38 @@ contract.skip('Lido: merge acceptance', (addresses) => { ) // Execution layer rewards just claimed - assertBn(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), ETH(0), 'Execution layer rewards vault balance') // Total shares increased because fee minted (fee shares added) // shares ~= oldTotalShares + reward * oldTotalShares / (newTotalPooledEther - reward) const newTotalShares = await token.getTotalShares() - assertBn(newTotalShares, new BN('100311321932979376897'), 'total shares') + assert.equals(newTotalShares, new BN('100311321932979376897'), 'total shares') // Total pooled Ether increased by 2ETH+3ETH const newTotalPooledEther = await pool.getTotalPooledEther() - assertBn(newTotalPooledEther, ETH(142 + 5), 'total pooled ether') + assert.equals(newTotalPooledEther, ETH(142 + 5), 'total pooled ether') // Ether2 stat reported by the pool changed correspondingly const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, ETH(85), 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 2, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, ETH(85), 'remote ether2') // Buffered Ether amount changed on execution layer rewards - assertBn(await pool.getBufferedEther(), ETH(59 + 3), 'buffered ether') + assert.equals(await pool.getBufferedEther(), ETH(59 + 3), 'buffered ether') - assertBn(await token.totalSupply(), tokens(142 + 5), 'token total supply') + assert.equals(await token.totalSupply(), tokens(142 + 5), 'token total supply') // Token user balances increased - assertBn(await token.balanceOf(user1), new BN('4396313312415956969'), 'user1 tokens') - assertBn(await token.balanceOf(user2), new BN('43963133124159569699'), 'user2 tokens') - assertBn(await token.balanceOf(user3), new BN('93788017331540415359'), 'user3 tokens') + assert.equals(await token.balanceOf(user1), new BN('4396313312415956969'), 'user1 tokens') + assert.equals(await token.balanceOf(user2), new BN('43963133124159569699'), 'user2 tokens') + assert.equals(await token.balanceOf(user3), new BN('93788017331540415359'), 'user3 tokens') // Fee, in the form of minted tokens, was distributed between treasury, insurance fund // and node operators // treasuryTokenBalance = (oldTreasuryShares + mintedRewardShares * treasuryFeePoints / 10000) * sharePrice - assertBn((await token.balanceOf(treasuryAddr)).divn(10), new BN('242626811594202898'), 'treasury tokens') - assertBn( + assert.equals((await token.balanceOf(treasuryAddr)).divn(10), new BN('242626811594202898'), 'treasury tokens') + assert.equals( (await token.balanceOf(nodeOperatorsRegistry.address)).divn(10), new BN('242626811594202898'), 'module1 tokens' @@ -823,7 +811,7 @@ contract.skip('Lido: merge acceptance', (addresses) => { const elRewards = ETH(0.1) await setBalance(elRewardsVault.address, elRewards) - assertBn(await web3.eth.getBalance(elRewardsVault.address), elRewards, 'Execution layer rewards vault balance') + assert.equals(await web3.eth.getBalance(elRewardsVault.address), elRewards, 'Execution layer rewards vault balance') let frame = 7 let lastBeaconBalance = toBN(ETH(85)) @@ -861,23 +849,23 @@ contract.skip('Lido: merge acceptance', (addresses) => { 1 ) - assertBn( + assert.equals( await web3.eth.getBalance(elRewardsVault.address), elRewardsVaultBalance.sub(elRewardsToWithdraw), 'Execution layer rewards vault balance' ) - assertBn( + assert.equals( await pool.getTotalPooledEther(), totalPooledEther.add(beaconBalanceInc).add(elRewardsToWithdraw), 'total pooled ether' ) - assertBn( + assert.equals( await pool.totalSupply(), totalSupply.add(beaconBalanceInc).add(elRewardsToWithdraw), 'token total supply' ) - assertBn(await pool.getBufferedEther(), bufferedEther.add(elRewardsToWithdraw), 'buffered ether') + assert.equals(await pool.getBufferedEther(), bufferedEther.add(elRewardsToWithdraw), 'buffered ether') elRewardsVaultBalance = toBN(await web3.eth.getBalance(elRewardsVault.address)) totalPooledEther = await pool.getTotalPooledEther() @@ -890,6 +878,6 @@ contract.skip('Lido: merge acceptance', (addresses) => { frame += 1 } - assertBn(elRewardsWithdrawn, elRewards) + assert.equals(elRewardsWithdrawn, elRewards) }) }) diff --git a/test/scenario/helpers/deploy.js b/test/scenario/helpers/deploy.js index febfd0f92..633bd0c27 100644 --- a/test/scenario/helpers/deploy.js +++ b/test/scenario/helpers/deploy.js @@ -1,4 +1,4 @@ -const { artifacts } = require('hardhat') +const { artifacts, web3 } = require('hardhat') const withdrawals = require('../../helpers/withdrawals') const { newDao, newApp } = require('../../0.4.24/helpers/dao') diff --git a/test/scenario/lido_deposit_iteration_limit.js b/test/scenario/lido_deposit_iteration_limit.test.js similarity index 81% rename from test/scenario/lido_deposit_iteration_limit.js rename to test/scenario/lido_deposit_iteration_limit.test.js index bc694116a..418b69592 100644 --- a/test/scenario/lido_deposit_iteration_limit.js +++ b/test/scenario/lido_deposit_iteration_limit.test.js @@ -1,11 +1,13 @@ -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') -const { getEventArgument, ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { contract, artifacts, web3 } = require('hardhat') +const { getEventArgument } = require('@aragon/contract-helpers-test') +const { assert } = require('../helpers/assert') const { pad, ETH, hexConcat } = require('../helpers/utils') const { waitBlocks } = require('../helpers/blockchain') const { DSMAttestMessage, DSMPauseMessage } = require('../helpers/signatures') const { deployProtocol } = require('../helpers/protocol') const { setupNodeOperatorsRegistry } = require('../helpers/staking-modules') +const { ZERO_ADDRESS } = require('../helpers/constants') const NodeOperatorsRegistry = artifacts.require('NodeOperatorsRegistry') const CURATED_MODULE_ID = 1 @@ -45,7 +47,7 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = voting = deployed.voting.address await depositSecurityModule.setMaxDeposits(10, { from: appManager }) - assertBn(await depositSecurityModule.getMaxDeposits(), 10, 'invariant failed: max deposits') + assert.equals(await depositSecurityModule.getMaxDeposits(), 10, 'invariant failed: max deposits') }) it('voting adds a node operator with 26 signing keys', async () => { @@ -59,7 +61,7 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = decodeForAbi: NodeOperatorsRegistry._json.abi, }) - assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') + assert.equals(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') const data = Array.from({ length: numKeys }, (_, i) => { const n = 1 + 10 * i @@ -77,20 +79,20 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = await nodeOperatorsRegistry.setNodeOperatorStakingLimit(0, validatorsLimit, { from: voting }) const totalKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperatorId, { from: nobody }) - assertBn(totalKeys, numKeys, 'total signing keys') + assert.equals(totalKeys, numKeys, 'total signing keys') }) it('a user submits 25 * 32 ETH', async () => { const depositAmount = 25 * 32 const referral = ZERO_ADDRESS await pool.submit(referral, { from: user1, value: ETH(depositAmount - 1) }) - assertBn(await pool.getTotalPooledEther(), ETH(depositAmount), 'total controlled ether') + assert.equals(await pool.getTotalPooledEther(), ETH(depositAmount), 'total controlled ether') // at this point, no deposit assignments were made and all ether is buffered - assertBn(await pool.getBufferedEther(), ETH(depositAmount), 'buffered ether') + assert.equals(await pool.getBufferedEther(), ETH(depositAmount), 'buffered ether') const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 0, 'deposited validators') + assert.equals(ether2Stat.depositedValidators, 0, 'deposited validators') }) it('guardians can assign the buffered ether to validators by calling depositBufferedEther()', async () => { @@ -122,13 +124,13 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = ) // no more than depositIterationLimit validators are assigned in a single transaction - assertBn(await depositContractMock.totalCalls(), 10, 'total validators assigned') + assert.equals(await depositContractMock.totalCalls(), 10, 'total validators assigned') const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 10, 'deposited validators') + assert.equals(ether2Stat.depositedValidators, 10, 'deposited validators') // the rest of the received Ether is still buffered in the pool - assertBn(await pool.getBufferedEther(), ETH(15 * 32), 'buffered ether') + assert.equals(await pool.getBufferedEther(), ETH(15 * 32), 'buffered ether') }) it('guardians can advance the deposit loop further by calling depositBufferedEther() once again', async () => { @@ -159,11 +161,11 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = signatures ) - assertBn(await depositContractMock.totalCalls(), 20, 'total validators assigned') + assert.equals(await depositContractMock.totalCalls(), 20, 'total validators assigned') const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 20, 'deposited validators') - assertBn(await pool.getBufferedEther(), ETH(5 * 32), 'buffered ether') + assert.equals(ether2Stat.depositedValidators, 20, 'deposited validators') + assert.equals(await pool.getBufferedEther(), ETH(5 * 32), 'buffered ether') }) it('the number of assigned validators is limited by the remaining ether', async () => { @@ -194,21 +196,21 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = signatures ) - assertBn(await depositContractMock.totalCalls(), 25) + assert.equals(await depositContractMock.totalCalls(), 25) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 25, 'deposited validators') + assert.equals(ether2Stat.depositedValidators, 25, 'deposited validators') // the is no ether left buffered in the pool - assertBn(await pool.getBufferedEther(), ETH(0), 'buffered ether') + assert.equals(await pool.getBufferedEther(), ETH(0), 'buffered ether') }) it('a user submits 2 * 32 ETH', async () => { const referral = ZERO_ADDRESS await pool.submit(referral, { from: user1, value: ETH(2 * 32) }) - assertBn(await pool.getTotalPooledEther(), ETH(27 * 32), 'total controlled ether') - assertBn(await pool.getBufferedEther(), ETH(2 * 32), 'buffered ether') + assert.equals(await pool.getTotalPooledEther(), ETH(27 * 32), 'total controlled ether') + assert.equals(await pool.getBufferedEther(), ETH(2 * 32), 'buffered ether') }) it('the number of assigned validators is still limited by the number of available validator keys', async () => { @@ -239,13 +241,13 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = signatures ) - assertBn(await depositContractMock.totalCalls(), 26) + assert.equals(await depositContractMock.totalCalls(), 26) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 26, 'deposited validators') + assert.equals(ether2Stat.depositedValidators, 26, 'deposited validators') // the rest of the received Ether is still buffered in the pool - assertBn(await pool.getBufferedEther(), ETH(1 * 32), 'buffered ether') + assert.equals(await pool.getBufferedEther(), ETH(1 * 32), 'buffered ether') }) it('depositBufferedEther is a nop if there are no signing keys available', async () => { @@ -276,9 +278,9 @@ contract('Lido: deposit loop iteration limit', ([user1, nobody, nodeOperator]) = signatures ) - assertBn(await depositContractMock.totalCalls(), 26, 'total validators assigned') + assert.equals(await depositContractMock.totalCalls(), 26, 'total validators assigned') // the rest of the received Ether is still buffered in the pool - assertBn(await pool.getBufferedEther(), ETH(1 * 32), 'buffered ether') + assert.equals(await pool.getBufferedEther(), ETH(1 * 32), 'buffered ether') }) }) diff --git a/test/scenario/lido_happy_path.js b/test/scenario/lido_happy_path.test.js similarity index 80% rename from test/scenario/lido_happy_path.js rename to test/scenario/lido_happy_path.test.js index e8eb6d5a2..54a764802 100644 --- a/test/scenario/lido_happy_path.js +++ b/test/scenario/lido_happy_path.test.js @@ -1,6 +1,6 @@ -const { assert } = require('chai') +const { contract, artifacts, web3 } = require('hardhat') +const { assert } = require('../helpers/assert') const { BN } = require('bn.js') -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') const { getEventArgument } = require('@aragon/contract-helpers-test') const { pad, toBN, ETH, tokens, hexConcat } = require('../helpers/utils') @@ -91,11 +91,11 @@ contract('Lido: happy path', (addresses) => { it('voting sets fee and its distribution', async () => { // Fee and distribution were set - // assertBn(await pool.getFee({ from: nobody }), totalFeePoints, 'total fee') + // assert.equals(await pool.getFee({ from: nobody }), totalFeePoints, 'total fee') // const distribution = await pool.getFeeDistribution({ from: nobody }) // console.log('distribution', distribution) - // assertBn(distribution.treasuryFeeBasisPoints, treasuryFeePoints, 'treasury fee') - // assertBn(distribution.operatorsFeeBasisPoints, nodeOperatorsFeePoints, 'node operators fee') + // assert.equals(distribution.treasuryFeeBasisPoints, treasuryFeePoints, 'treasury fee') + // assert.equals(distribution.operatorsFeeBasisPoints, nodeOperatorsFeePoints, 'node operators fee') }) it('voting sets withdrawal credentials', async () => { @@ -134,9 +134,9 @@ contract('Lido: happy path', (addresses) => { nodeOperator1.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi, }) - assertBn(nodeOperator1.id, 0, 'operator id') + assert.equals(nodeOperator1.id, 0, 'operator id') - assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') + assert.equals(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') }) it('the first node operator registers one validator', async () => { @@ -159,12 +159,12 @@ contract('Lido: happy path', (addresses) => { // The key was added const totalKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator1.id, { from: nobody }) - assertBn(totalKeys, 1, 'total signing keys') + assert.equals(totalKeys, 1, 'total signing keys') // The key was not used yet const unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator1.id, { from: nobody }) - assertBn(unusedKeys, 1, 'unused signing keys') + assert.equals(unusedKeys, 1, 'unused signing keys') }) it('the first user deposits 3 ETH to the pool', async () => { @@ -198,22 +198,22 @@ contract('Lido: happy path', (addresses) => { // No Ether was deposited yet to the validator contract - assertBn(await depositContractMock.totalCalls(), 0) + assert.equals(await depositContractMock.totalCalls(), 0) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 0, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, 0, 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 0, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, 0, 'remote ether2') // All Ether was buffered within the pool contract atm - assertBn(await pool.getBufferedEther(), ETH(3), 'buffered ether') - assertBn(await pool.getTotalPooledEther(), ETH(3), 'total pooled ether') + assert.equals(await pool.getBufferedEther(), ETH(3), 'buffered ether') + assert.equals(await pool.getTotalPooledEther(), ETH(3), 'total pooled ether') // The amount of tokens corresponding to the deposited ETH value was minted to the user - assertBn(await token.balanceOf(user1), tokens(2), 'user1 tokens') + assert.equals(await token.balanceOf(user1), tokens(2), 'user1 tokens') - assertBn(await token.totalSupply(), tokens(3), 'token total supply') + assert.equals(await token.totalSupply(), tokens(3), 'token total supply') }) it('the second user deposits 30 ETH to the pool', async () => { @@ -248,34 +248,34 @@ contract('Lido: happy path', (addresses) => { // The first 32 ETH chunk was deposited to the deposit contract, // using public key and signature of the only validator of the first operator - assertBn(await depositContractMock.totalCalls(), 1) + assert.equals(await depositContractMock.totalCalls(), 1) const regCall = await depositContractMock.calls.call(0) assert.equal(regCall.pubkey, nodeOperator1.validators[0].key) assert.equal(regCall.withdrawal_credentials, withdrawalCredentials) assert.equal(regCall.signature, nodeOperator1.validators[0].sig) - assertBn(regCall.value, ETH(32)) + assert.equals(regCall.value, ETH(32)) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 1, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, 0, 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 1, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, 0, 'remote ether2') // Some Ether remained buffered within the pool contract - assertBn(await pool.getBufferedEther(), ETH(1), 'buffered ether') - assertBn(await pool.getTotalPooledEther(), ETH(1 + 32), 'total pooled ether') + assert.equals(await pool.getBufferedEther(), ETH(1), 'buffered ether') + assert.equals(await pool.getTotalPooledEther(), ETH(1 + 32), 'total pooled ether') // The amount of tokens corresponding to the deposited ETH value was minted to the users - assertBn(await token.balanceOf(user1), tokens(2), 'user1 tokens') - assertBn(await token.balanceOf(user2), tokens(30), 'user2 tokens') + assert.equals(await token.balanceOf(user1), tokens(2), 'user1 tokens') + assert.equals(await token.balanceOf(user2), tokens(30), 'user2 tokens') - assertBn(await token.totalSupply(), tokens(3 + 30), 'token total supply') + assert.equals(await token.totalSupply(), tokens(3 + 30), 'token total supply') }) it('at this point, the pool has ran out of signing keys', async () => { const unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator1.id, { from: nobody }) - assertBn(unusedKeys, 0, 'unused signing keys') + assert.equals(unusedKeys, 0, 'unused signing keys') }) const nodeOperator2 = { @@ -299,9 +299,9 @@ contract('Lido: happy path', (addresses) => { nodeOperator2.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi, }) - assertBn(nodeOperator2.id, 1, 'operator id') + assert.equals(nodeOperator2.id, 1, 'operator id') - assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators') + assert.equals(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators') const numKeys = 1 @@ -320,12 +320,12 @@ contract('Lido: happy path', (addresses) => { await nodeOperatorsRegistry.setNodeOperatorStakingLimit(1, validatorsLimit, { from: voting }) const totalKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator2.id, { from: nobody }) - assertBn(totalKeys, 1, 'total signing keys') + assert.equals(totalKeys, 1, 'total signing keys') // The key was not used yet const unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator2.id, { from: nobody }) - assertBn(unusedKeys, 1, 'unused signing keys') + assert.equals(unusedKeys, 1, 'unused signing keys') }) it('the third user deposits 64 ETH to the pool', async () => { @@ -361,43 +361,43 @@ contract('Lido: happy path', (addresses) => { // The first 32 ETH chunk was deposited to the deposit contract, // using public key and signature of the only validator of the second operator - assertBn(await depositContractMock.totalCalls(), 2) + assert.equals(await depositContractMock.totalCalls(), 2) const regCall = await depositContractMock.calls.call(1) assert.equal(regCall.pubkey, nodeOperator2.validators[0].key) assert.equal(regCall.withdrawal_credentials, withdrawalCredentials) assert.equal(regCall.signature, nodeOperator2.validators[0].sig) - assertBn(regCall.value, ETH(32)) + assert.equals(regCall.value, ETH(32)) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, 0, 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 2, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, 0, 'remote ether2') // The pool ran out of validator keys, so the remaining 32 ETH were added to the // pool buffer - assertBn(await pool.getBufferedEther(), ETH(1 + 32), 'buffered ether') - assertBn(await pool.getTotalPooledEther(), ETH(33 + 64), 'total pooled ether') + assert.equals(await pool.getBufferedEther(), ETH(1 + 32), 'buffered ether') + assert.equals(await pool.getTotalPooledEther(), ETH(33 + 64), 'total pooled ether') // The amount of tokens corresponding to the deposited ETH value was minted to the users - assertBn(await token.balanceOf(user1), tokens(2), 'user1 tokens') - assertBn(await token.balanceOf(user2), tokens(30), 'user2 tokens') - assertBn(await token.balanceOf(user3), tokens(64), 'user3 tokens') + assert.equals(await token.balanceOf(user1), tokens(2), 'user1 tokens') + assert.equals(await token.balanceOf(user2), tokens(30), 'user2 tokens') + assert.equals(await token.balanceOf(user3), tokens(64), 'user3 tokens') - assertBn(await token.totalSupply(), tokens(3 + 30 + 64), 'token total supply') + assert.equals(await token.totalSupply(), tokens(3 + 30 + 64), 'token total supply') }) it('the oracle reports balance increase on Ethereum2 side', async () => { // Total shares are equal to deposited eth before ratio change and fee mint const oldTotalShares = await token.getTotalShares() - assertBn(oldTotalShares, ETH(97), 'total shares') + assert.equals(oldTotalShares, ETH(97), 'total shares') // Old total pooled Ether const oldTotalPooledEther = await pool.getTotalPooledEther() - assertBn(oldTotalPooledEther, ETH(33 + 64), 'total pooled ether') + assert.equals(oldTotalPooledEther, ETH(33 + 64), 'total pooled ether') // Reporting 1.005-fold balance increase (64 => 64.32) to stay in limits @@ -407,35 +407,35 @@ contract('Lido: happy path', (addresses) => { // shares = oldTotalShares + reward * totalFee * oldTotalShares / (newTotalPooledEther - reward * totalFee) const newTotalShares = await token.getTotalShares() - assertBn(newTotalShares, '97031905270948112819', 'total shares') + assert.equals(newTotalShares, '97031905270948112819', 'total shares') // Total pooled Ether increased const newTotalPooledEther = await pool.getTotalPooledEther() - assertBn(newTotalPooledEther, ETH(33 + 64.32), 'total pooled ether') + assert.equals(newTotalPooledEther, ETH(33 + 64.32), 'total pooled ether') // Ether2 stat reported by the pool changed correspondingly const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, ETH(64.32), 'remote ether2') + assert.equals(ether2Stat.depositedValidators, 2, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, ETH(64.32), 'remote ether2') // Buffered Ether amount didn't change - assertBn(await pool.getBufferedEther(), ETH(33), 'buffered ether') + assert.equals(await pool.getBufferedEther(), ETH(33), 'buffered ether') // New tokens was minted to distribute fee - assertBn(await token.totalSupply(), tokens(97.32), 'token total supply') + assert.equals(await token.totalSupply(), tokens(97.32), 'token total supply') const reward = toBN(ETH(64.32 - 64)) const mintedAmount = new BN(totalFeePoints).mul(reward).divn(10000) // Token user balances increased - assertBn(await token.balanceOf(INITIAL_HOLDER), '1002969072164948453', 'initial holder tokens') - assertBn(await token.balanceOf(user1), '2005938144329896907', 'user1 tokens') - assertBn(await token.balanceOf(user2), '30089072164948453608', 'user2 tokens') - assertBn(await token.balanceOf(user3), '64190020618556701031', 'user3 tokens') + assert.equals(await token.balanceOf(INITIAL_HOLDER), '1002969072164948453', 'initial holder tokens') + assert.equals(await token.balanceOf(user1), '2005938144329896907', 'user1 tokens') + assert.equals(await token.balanceOf(user2), '30089072164948453608', 'user2 tokens') + assert.equals(await token.balanceOf(user3), '64190020618556701031', 'user3 tokens') // Fee, in the form of minted tokens, was distributed between treasury, insurance fund // and node operators @@ -498,7 +498,7 @@ contract('Lido: happy path', (addresses) => { from: nodeOperator3.address, }) const nodeOperatorInfo = await nodeOperatorsRegistry.getNodeOperator(nodeOperator3.id, false) - assertBn(nodeOperatorInfo.stakingLimit, 5) + assert.equals(nodeOperatorInfo.stakingLimit, 5) }) it('deposit to nodeOperator3 validators', async () => { @@ -535,13 +535,13 @@ contract('Lido: happy path', (addresses) => { let nodeOperatorInfo = await nodeOperatorsRegistry.getNodeOperator(nodeOperator3.id, false) // validate that only 5 signing keys used after key removing - assertBn(nodeOperatorInfo.stakingLimit, nodeOperatorInfo.usedSigningKeys) - assertBn(nodeOperatorInfo.totalSigningKeys, 9) + assert.equals(nodeOperatorInfo.stakingLimit, nodeOperatorInfo.usedSigningKeys) + assert.equals(nodeOperatorInfo.totalSigningKeys, 9) // validate that all other validators used and pool still has buffered ether nodeOperatorInfo = await nodeOperatorsRegistry.getNodeOperator(nodeOperator1.id, false) - assertBn(nodeOperatorInfo.totalSigningKeys, nodeOperatorInfo.usedSigningKeys) + assert.equals(nodeOperatorInfo.totalSigningKeys, nodeOperatorInfo.usedSigningKeys) nodeOperatorInfo = await nodeOperatorsRegistry.getNodeOperator(nodeOperator2.id, false) - assertBn(nodeOperatorInfo.totalSigningKeys, nodeOperatorInfo.usedSigningKeys) + assert.equals(nodeOperatorInfo.totalSigningKeys, nodeOperatorInfo.usedSigningKeys) }) }) diff --git a/test/scenario/lido_penalties_slashing.js b/test/scenario/lido_penalties_slashing.test.js similarity index 69% rename from test/scenario/lido_penalties_slashing.js rename to test/scenario/lido_penalties_slashing.test.js index d5d6721d5..dfc27b072 100644 --- a/test/scenario/lido_penalties_slashing.js +++ b/test/scenario/lido_penalties_slashing.test.js @@ -1,8 +1,8 @@ -const hre = require('hardhat') -const { assertBn } = require('@aragon/contract-helpers-test/src/asserts') +const { contract, artifacts, ethers, network, web3 } = require('hardhat') +const { assert } = require('../helpers/assert') + const { getEventArgument, bn } = require('@aragon/contract-helpers-test') -const { assert } = require('../helpers/assert') const { pad, ETH, StETH, shares, prepIdsCountsPayload } = require('../helpers/utils') const { waitBlocks } = require('../helpers/blockchain') const { deployProtocol } = require('../helpers/protocol') @@ -90,7 +90,6 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { } // storing incremental calculated values that changes all across the test suite - const expectedTotalShares = shares(0) let expectedUser1Balance = StETH(0) let expectedUser1Shares = shares(0) @@ -118,9 +117,9 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { nodeOperator1.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi, }) - assertBn(nodeOperator1.id, 0, 'operator id') + assert.equals(nodeOperator1.id, 0, 'operator id') - assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') + assert.equals(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') }) it('the first node operator registers one validator', async () => { @@ -139,12 +138,12 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { // The key was added const totalKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator1.id, { from: nobody }) - assertBn(totalKeys, 1, 'total signing keys') + assert.equals(totalKeys, 1, 'total signing keys') // The key was not used yet const unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator1.id, { from: nobody }) - assertBn(unusedKeys, 1, 'unused signing keys') + assert.equals(unusedKeys, 1, 'unused signing keys') }) it('the user deposits 32 ETH to the pool', async () => { @@ -187,27 +186,27 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { // No Ether was deposited yet to the validator contract - assertBn(await depositContractMock.totalCalls(), 0, 'no validators registered yet') + assert.equals(await depositContractMock.totalCalls(), 0, 'no validators registered yet') const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 0, 'no validators have received the ether2') - assertBn(ether2Stat.beaconBalance, 0, 'remote ether2 not reported yet') + assert.equals(ether2Stat.depositedValidators, 0, 'no validators have received the ether2') + assert.equals(ether2Stat.beaconBalance, 0, 'remote ether2 not reported yet') - assertBn(await pool.getBufferedEther(), ETH(33), `All Ether was buffered within the pool contract atm`) - assertBn(await pool.getTotalPooledEther(), ETH(33), 'total pooled ether') + assert.equals(await pool.getBufferedEther(), ETH(33), `All Ether was buffered within the pool contract atm`) + assert.equals(await pool.getTotalPooledEther(), ETH(33), 'total pooled ether') expectedUser1Balance = StETH(32) expectedUser1Shares = shares(32) - assertBn(await token.sharesOf(user1), shares(32), 'User1 holds 32 shares') - assertBn( + assert.equals(await token.sharesOf(user1), shares(32), 'User1 holds 32 shares') + assert.equals( await token.balanceOf(user1), expectedUser1Balance, 'The amount of tokens corresponding to the deposited ETH value was minted to the user' ) - assertBn(await token.totalSupply(), StETH(33), 'token total supply') + assert.equals(await token.totalSupply(), StETH(33), 'token total supply') - assertBn( + assert.equals( await token.getTotalShares(), shares(33), 'Total shares are equal to deposited eth before ratio change and fee mint' @@ -219,9 +218,17 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { }) it(`new validator doesn't get buffered ether even if there's 32 ETH deposit in the pool`, async () => { - assertBn(await pool.getBufferedEther(), ETH(33), `all ether is buffered until there's a validator to deposit it`) - assertBn(await pool.getTotalPooledEther(), ETH(33), 'total pooled ether') - assertBn(await nodeOperatorsRegistry.getUnusedSigningKeyCount(0), 1, 'one key available for the first validator') + assert.equals( + await pool.getBufferedEther(), + ETH(33), + `all ether is buffered until there's a validator to deposit it` + ) + assert.equals(await pool.getTotalPooledEther(), ETH(33), 'total pooled ether') + assert.equals( + await nodeOperatorsRegistry.getUnusedSigningKeyCount(0), + 1, + 'one key available for the first validator' + ) }) it(`pushes pooled eth to the available validator`, async () => { @@ -261,9 +268,9 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { }) it('new validator gets the 32 ETH deposit from the pool', async () => { - assertBn(await pool.getBufferedEther(), ETH(1), `only initial eth is left`) - assertBn(await pool.getTotalPooledEther(), ETH(33), 'total pooled ether') - assertBn( + assert.equals(await pool.getBufferedEther(), ETH(1), `only initial eth is left`) + assert.equals(await pool.getTotalPooledEther(), ETH(33), 'total pooled ether') + assert.equals( await nodeOperatorsRegistry.getUnusedSigningKeyCount(0), 0, 'no more available keys for the first validator' @@ -271,37 +278,41 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { }) it('first oracle report is taken as-is for Lido', async () => { - assertBn(await pool.getTotalPooledEther(), ETH(33), '32 ETH deposit + 1 ETH initial') + assert.equals(await pool.getTotalPooledEther(), ETH(33), '32 ETH deposit + 1 ETH initial') // Reporting 1 ETH balance loss (32 => 31) await pushReport(1, ETH(31)) - assertBn(await token.getTotalShares(), shares(33), 'Total shares stay the same because no fee shares are added') + assert.equals( + await token.getTotalShares(), + shares(33), + 'Total shares stay the same because no fee shares are added' + ) - assertBn(await pool.getTotalPooledEther(), ETH(32), 'Total pooled Ether decreased') + assert.equals(await pool.getTotalPooledEther(), ETH(32), 'Total pooled Ether decreased') const clStat = await pool.getBeaconStat() - assertBn(clStat.depositedValidators, 1, 'validators count') - assertBn(clStat.beaconBalance, ETH(31), 'Ether2 stat reported by the pool changed correspondingly') + assert.equals(clStat.depositedValidators, 1, 'validators count') + assert.equals(clStat.beaconBalance, ETH(31), 'Ether2 stat reported by the pool changed correspondingly') - assertBn(await pool.getBufferedEther(), ETH(1), 'Initial stake remains in the buffer') - assertBn(await token.totalSupply(), StETH(32), 'Token total supply penalized') + assert.equals(await pool.getBufferedEther(), ETH(1), 'Initial stake remains in the buffer') + assert.equals(await token.totalSupply(), StETH(32), 'Token total supply penalized') - assertBn(await token.sharesOf(user1), shares(32), 'User1 still holds 32 shares') + assert.equals(await token.sharesOf(user1), shares(32), 'User1 still holds 32 shares') expectedUser1Balance = bn(shares(32)).muln(32).divn(33) // 32/33 ETH/share is a new price - assertBn(await token.balanceOf(user1), expectedUser1Balance, `Token user balances decreased`) + assert.equals(await token.balanceOf(user1), expectedUser1Balance, `Token user balances decreased`) - assertBn(await token.balanceOf(treasuryAddr), 0, 'No fees distributed yet: treasury') - assertBn(await token.balanceOf(nodeOperator1.address), 0, 'No fees distributed yet: operator_1') + assert.equals(await token.balanceOf(treasuryAddr), 0, 'No fees distributed yet: treasury') + assert.equals(await token.balanceOf(nodeOperator1.address), 0, 'No fees distributed yet: operator_1') }) it('the oracle reports balance loss on CL side', async () => { - assertBn( + assert.equals( await token.getTotalShares(), shares(33), 'Total shares are equal to deposited eth before ratio change and fee mint' ) - assertBn( + assert.equals( await pool.getTotalPooledEther(), ETH(32), 'Old total pooled Ether 31 ETH od previous report + 1 ETH initial' @@ -310,21 +321,25 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { // Reporting 2 ETH balance loss (31 => 29) await pushReport(1, ETH(29)) - assertBn(await token.getTotalShares(), shares(33), `Total shares stay the same because no fee shares are added`) - assertBn(await pool.getTotalPooledEther(), ETH(30), 'Total pooled Ether decreased') + assert.equals( + await token.getTotalShares(), + shares(33), + `Total shares stay the same because no fee shares are added` + ) + assert.equals(await pool.getTotalPooledEther(), ETH(30), 'Total pooled Ether decreased') const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 1, 'deposited validators') - assertBn(ether2Stat.beaconBalance, ETH(29), 'Ether2 stat reported by the pool changed correspondingly') + assert.equals(ether2Stat.depositedValidators, 1, 'deposited validators') + assert.equals(ether2Stat.beaconBalance, ETH(29), 'Ether2 stat reported by the pool changed correspondingly') - assertBn(await pool.getBufferedEther(), ETH(1), 'Buffered Ether amount didnt change') - assertBn(await token.totalSupply(), StETH(30), 'Total supply accounts for penalties taken by the validator') + assert.equals(await pool.getBufferedEther(), ETH(1), 'Buffered Ether amount didnt change') + assert.equals(await token.totalSupply(), StETH(30), 'Total supply accounts for penalties taken by the validator') expectedUser1Balance = bn(shares(32)).muln(30).divn(33) // New share price is 30/33 ETH/share - assertBn(await token.balanceOf(user1), expectedUser1Balance, 'Token user1 balances decreased') + assert.equals(await token.balanceOf(user1), expectedUser1Balance, 'Token user1 balances decreased') - assertBn(await token.balanceOf(treasuryAddr), 0, 'No fees distributed yet: treasury') - assertBn(await token.balanceOf(nodeOperator1.address), 0, 'No fees distributed yet: operator_1') + assert.equals(await token.balanceOf(treasuryAddr), 0, 'No fees distributed yet: treasury') + assert.equals(await token.balanceOf(nodeOperator1.address), 0, 'No fees distributed yet: operator_1') }) const nodeOperator2 = { @@ -347,9 +362,9 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { nodeOperator2.id = getEventArgument(txn, 'NodeOperatorAdded', 'nodeOperatorId', { decodeForAbi: NodeOperatorsRegistry._json.abi, }) - assertBn(nodeOperator2.id, 1, 'correct operator id added') + assert.equals(nodeOperator2.id, 1, 'correct operator id added') - assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators updated') + assert.equals(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators updated') const numKeys = 1 @@ -368,17 +383,17 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { await nodeOperatorsRegistry.setNodeOperatorStakingLimit(1, validatorsLimit, { from: voting }) const totalKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator2.id, { from: nobody }) - assertBn(totalKeys, 1, 'second operator added one key') + assert.equals(totalKeys, 1, 'second operator added one key') // The key was not used yet const unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator2.id, { from: nobody }) - assertBn(unusedKeys, 1, 'unused signing keys') + assert.equals(unusedKeys, 1, 'unused signing keys') }) it('the user deposits another 32 ETH to the pool', async () => { - assertBn(await token.totalSupply(), StETH(30), 'token total supply before') - assertBn(await token.getTotalShares(), shares(33), 'token total supply before') + assert.equals(await token.totalSupply(), StETH(30), 'token total supply before') + assert.equals(await token.getTotalShares(), shares(33), 'token total supply before') await web3.eth.sendTransaction({ to: pool.address, from: user1, value: ETH(32) }) const block = await waitBlocks(await depositSecurityModule.getMinDepositBlockDistance()) @@ -415,64 +430,64 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { signatures ) - assertBn(await depositContractMock.totalCalls(), 2) + assert.equals(await depositContractMock.totalCalls(), 2) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'deposited ether2') - assertBn(ether2Stat.beaconBalance, ETH(29), 'remote ether2 as reported last time') + assert.equals(ether2Stat.depositedValidators, 2, 'deposited ether2') + assert.equals(ether2Stat.beaconBalance, ETH(29), 'remote ether2 as reported last time') - assertBn(await pool.getBufferedEther(), ETH(1), 'Only initial ether is in the buffer') - assertBn(await pool.getTotalPooledEther(), ETH(62), 'total pooled ether') - assertBn(await token.totalSupply(), StETH(62), 'token total supply') + assert.equals(await pool.getBufferedEther(), ETH(1), 'Only initial ether is in the buffer') + assert.equals(await pool.getTotalPooledEther(), ETH(62), 'total pooled ether') + assert.equals(await token.totalSupply(), StETH(62), 'token total supply') // 32 ETH deposit to shares if price is 30/33 ETH/shares const sharesAdded = bn(ETH(32)) .mul(bn(ETH(33))) .div(bn(shares(30))) expectedUser1Shares = bn(expectedUser1Shares).add(sharesAdded) - assertBn(await token.sharesOf(user1), expectedUser1Shares, 'User1 acquires new shares by new share price') - assertBn( + assert.equals(await token.sharesOf(user1), expectedUser1Shares, 'User1 acquires new shares by new share price') + assert.equals( await token.getTotalShares(), bn(shares(1)).add(expectedUser1Shares), 'total shares are changed proportionally' ) expectedUser1Balance = bn(expectedUser1Balance).add(bn(StETH(32))) - assertBn(await token.balanceOf(user1), expectedUser1Balance, 'user1 tokens') + assert.equals(await token.balanceOf(user1), expectedUser1Balance, 'user1 tokens') }) it('the oracle reports balance loss for the third time', async () => { - assertBn(await pool.getTotalPooledEther(), ETH(62), 'Old total pooled Ether') + assert.equals(await pool.getTotalPooledEther(), ETH(62), 'Old total pooled Ether') const expectedTotalShares = bn(shares(1)).add(bn(expectedUser1Shares)) - assertBn(await token.getTotalShares(), expectedTotalShares, 'Old total shares') + assert.equals(await token.getTotalShares(), expectedTotalShares, 'Old total shares') // Reporting 1 ETH balance loss ( total pooled 61 => 60) await pushReport(1, ETH(28)) - assertBn( + assert.equals( await token.getTotalShares(), bn(shares(1)).add(expectedUser1Shares), 'Total shares stay the same because no fee shares are added' ) - assertBn(await pool.getTotalPooledEther(), ETH(61), 'Total pooled Ether decreased') + assert.equals(await pool.getTotalPooledEther(), ETH(61), 'Total pooled Ether decreased') const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'Another validator is deposited') - assertBn(ether2Stat.beaconBalance, ETH(28), 'Ether2 stat reported by the pool changed correspondingly') + assert.equals(ether2Stat.depositedValidators, 2, 'Another validator is deposited') + assert.equals(ether2Stat.beaconBalance, ETH(28), 'Ether2 stat reported by the pool changed correspondingly') - assertBn(await pool.getBufferedEther(), ETH(1), 'Only initial ETH in the buffer') - assertBn(await pool.getTotalPooledEther(), ETH(61), 'Total pooled Ether') - assertBn(await token.totalSupply(), StETH(61), 'token total supply shrunk by loss taken') - assertBn(await token.getTotalShares(), expectedTotalShares, 'total shares stays same') + assert.equals(await pool.getBufferedEther(), ETH(1), 'Only initial ETH in the buffer') + assert.equals(await pool.getTotalPooledEther(), ETH(61), 'Total pooled Ether') + assert.equals(await token.totalSupply(), StETH(61), 'token total supply shrunk by loss taken') + assert.equals(await token.getTotalShares(), expectedTotalShares, 'total shares stays same') - assertBn(await token.sharesOf(user1), expectedUser1Shares, 'User1 shares stays same') + assert.equals(await token.sharesOf(user1), expectedUser1Shares, 'User1 shares stays same') expectedUser1Balance = bn(expectedUser1Shares) // New price .mul(bn(StETH(61))) .div(expectedTotalShares) - assertBn(await token.balanceOf(user1), expectedUser1Balance, 'Token user balances decreased') + assert.equals(await token.balanceOf(user1), expectedUser1Balance, 'Token user balances decreased') - assertBn(await token.balanceOf(treasuryAddr), 0, 'No fees distributed yet: treasury') - assertBn(await token.balanceOf(nodeOperator1.address), 0, 'No fees distributed yet: operator_1') + assert.equals(await token.balanceOf(treasuryAddr), 0, 'No fees distributed yet: treasury') + assert.equals(await token.balanceOf(nodeOperator1.address), 0, 'No fees distributed yet: operator_1') }) it(`the oracle can't report less validators than previously`, async () => { @@ -480,13 +495,13 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { }) it(`user deposits another 32 ETH to the pool`, async () => { - assertBn(await pool.getTotalPooledEther(), ETH(61), 'Old total pooled Ether') + assert.equals(await pool.getTotalPooledEther(), ETH(61), 'Old total pooled Ether') const oldTotalShares = bn(shares(1)).add(bn(expectedUser1Shares)) - assertBn(await token.getTotalShares(), oldTotalShares, 'Old total shares') + assert.equals(await token.getTotalShares(), oldTotalShares, 'Old total shares') await web3.eth.sendTransaction({ to: pool.address, from: user1, value: ETH(32) }) - await hre.network.provider.send('hardhat_mine', ['0x100']) + await network.provider.send('hardhat_mine', ['0x100']) const block = await web3.eth.getBlock('latest') const keysOpIndex = await nodeOperatorsRegistry.getKeysOpIndex() @@ -512,25 +527,25 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { ) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 2, 'no validators have received the current deposit') + assert.equals(ether2Stat.depositedValidators, 2, 'no validators have received the current deposit') - assertBn(await pool.getBufferedEther(), ETH(33), '33 ETH is pooled') - assertBn(await pool.getTotalPooledEther(), ETH(93), 'Total pooled Ether') - assertBn(await token.totalSupply(), StETH(93), 'token total supply') + assert.equals(await pool.getBufferedEther(), ETH(33), '33 ETH is pooled') + assert.equals(await pool.getTotalPooledEther(), ETH(93), 'Total pooled Ether') + assert.equals(await token.totalSupply(), StETH(93), 'token total supply') const sharesAdded = bn(ETH(32)) .mul(oldTotalShares) .div(bn(ETH(61))) - assertBn( + assert.equals( await token.getTotalShares(), oldTotalShares.add(sharesAdded), 'Total shares are equal to deposited eth before ratio change and fee mint' ) expectedUser1Shares = bn(expectedUser1Shares).add(sharesAdded) - assertBn(await token.sharesOf(user1), expectedUser1Shares, 'User1 bought shares on 32 ETH') + assert.equals(await token.sharesOf(user1), expectedUser1Shares, 'User1 bought shares on 32 ETH') expectedUser1Balance = expectedUser1Balance.add(bn(StETH(32))) - assertBn( + assert.equals( await token.balanceOf(user1), expectedUser1Balance, 'The amount of tokens corresponding to the deposited ETH value was minted to the user' @@ -539,8 +554,8 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { it(`voting stops the staking module`, async () => { await stakingRouter.setStakingModuleStatus(1, 2, { from: voting }) - assertBn(await stakingRouter.getStakingModulesCount(), 1, 'only 1 module exists') - assertBn(await stakingRouter.getStakingModuleStatus(1), 2, 'no active staking modules') + assert.equals(await stakingRouter.getStakingModulesCount(), 1, 'only 1 module exists') + assert.equals(await stakingRouter.getStakingModuleStatus(1), 2, 'no active staking modules') }) it(`first operator adds a second validator`, async () => { @@ -560,25 +575,25 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { const totalFirstOperatorKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator1.id, { from: nobody, }) - assertBn(totalFirstOperatorKeys, 2, 'added one signing key to total') + assert.equals(totalFirstOperatorKeys, 2, 'added one signing key to total') const unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator1.id, { from: nobody }) - assertBn(unusedKeys, 1, 'one signing key is unused') + assert.equals(unusedKeys, 1, 'one signing key is unused') }) it(`voting stops the first operator`, async () => { const activeOperatorsBefore = await nodeOperatorsRegistry.getActiveNodeOperatorsCount() await nodeOperatorsRegistry.deactivateNodeOperator(0, { from: voting }) const activeOperatorsAfter = await nodeOperatorsRegistry.getActiveNodeOperatorsCount() - assertBn(activeOperatorsAfter, activeOperatorsBefore.subn(1), 'deactivated one operator') + assert.equals(activeOperatorsAfter, activeOperatorsBefore.subn(1), 'deactivated one operator') }) it(`voting stops the second operator`, async () => { const activeOperatorsBefore = await nodeOperatorsRegistry.getActiveNodeOperatorsCount() await nodeOperatorsRegistry.deactivateNodeOperator(1, { from: voting }) const activeOperatorsAfter = await nodeOperatorsRegistry.getActiveNodeOperatorsCount() - assertBn(activeOperatorsAfter, activeOperatorsBefore.subn(1), 'deactivated one operator') - assertBn(activeOperatorsAfter, 0, 'no active operators') + assert.equals(activeOperatorsAfter, activeOperatorsBefore.subn(1), 'deactivated one operator') + assert.equals(activeOperatorsAfter, 0, 'no active operators') }) it(`without active staking modules fee is sent to treasury`, async () => { @@ -604,9 +619,13 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { const nodeOperatorsRegistrySharesAfter = await token.sharesOf(nodeOperatorsRegistry.address) const treasurySharesAfter = await token.sharesOf(treasuryAddr) - assertBn(nodeOperator1TokenSharesAfter, nodeOperator1TokenSharesBefore, `first node operator hasn't got fees`) - assertBn(nodeOperator2TokenSharesAfter, nodeOperator2TokenSharesBefore, `second node operator hasn't got fees`) - assertBn(nodeOperatorsRegistrySharesAfter, nodeOperatorsRegistrySharesBefore, `NOR stakingModule hasn't got fees`) + assert.equals(nodeOperator1TokenSharesAfter, nodeOperator1TokenSharesBefore, `first node operator hasn't got fees`) + assert.equals(nodeOperator2TokenSharesAfter, nodeOperator2TokenSharesBefore, `second node operator hasn't got fees`) + assert.equals( + nodeOperatorsRegistrySharesAfter, + nodeOperatorsRegistrySharesBefore, + `NOR stakingModule hasn't got fees` + ) const tenKBN = bn(10000) const totalFeeToDistribute = bn(beaconBalanceIncrement.toString()).mul(bn(totalFeePoints)).div(tenKBN) @@ -614,13 +633,13 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { const totalPooledEther = await pool.getTotalPooledEther() const sharesToMint = totalFeeToDistribute.mul(prevTotalShares).div(totalPooledEther.sub(totalFeeToDistribute)) - assertBn(treasurySharesAfter.sub(treasurySharesBefore), sharesToMint, 'treasury got the total fee') + assert.equals(treasurySharesAfter.sub(treasurySharesBefore), sharesToMint, 'treasury got the total fee') }) it(`voting starts staking module`, async () => { await stakingRouter.setStakingModuleStatus(1, 0, { from: voting }) - assertBn(await stakingRouter.getStakingModulesCount(), 1, 'only 1 module exists') - assertBn(await stakingRouter.getStakingModuleStatus(1), 0, 'no active staking modules') + assert.equals(await stakingRouter.getStakingModulesCount(), 1, 'only 1 module exists') + assert.equals(await stakingRouter.getStakingModuleStatus(1), 0, 'no active staking modules') }) it(`oracle reports profit, previously stopped staking module gets the fee`, async () => { @@ -648,7 +667,7 @@ contract('Lido: penalties, slashing, operator stops', (addresses) => { const nodeOperator1TokenSharesAfter = await token.sharesOf(nodeOperator1.address) const nodeOperator2TokenSharesAfter = await token.sharesOf(nodeOperator2.address) - assertBn( + assert.equals( nodeOperator1TokenSharesAfter, nodeOperator1TokenSharesBefore, `first node operator balance hasn't changed` diff --git a/test/scenario/lido_rewards_distribution_math.js b/test/scenario/lido_rewards_distribution_math.test.js similarity index 85% rename from test/scenario/lido_rewards_distribution_math.js rename to test/scenario/lido_rewards_distribution_math.test.js index 819db2ce5..c4a73c3cb 100644 --- a/test/scenario/lido_rewards_distribution_math.js +++ b/test/scenario/lido_rewards_distribution_math.test.js @@ -1,15 +1,14 @@ -const { BN } = require('bn.js') -const { assertBn, assertEvent } = require('@aragon/contract-helpers-test/src/asserts') -const { ZERO_ADDRESS } = require('@aragon/contract-helpers-test') +const { contract, artifacts, ethers, web3 } = require('hardhat') +const { assert } = require('../helpers/assert') const { waitBlocks } = require('../helpers/blockchain') const { pad, ETH, hexConcat, toBN, calcSharesMintedAsFees } = require('../helpers/utils') const { deployProtocol } = require('../helpers/protocol') const { setupNodeOperatorsRegistry } = require('../helpers/staking-modules') -const { assert } = require('../helpers/assert') + const { DSMAttestMessage, DSMPauseMessage, signDepositData } = require('../helpers/signatures') const { pushOracleReport } = require('../helpers/oracle') -const { SECONDS_PER_FRAME } = require('../helpers/constants') +const { SECONDS_PER_FRAME, ZERO_ADDRESS } = require('../helpers/constants') const { oracleReportSanityCheckerStubFactory } = require('../helpers/factories') const Lido = artifacts.require('Lido') @@ -125,14 +124,14 @@ contract('Lido: rewards distribution math', (addresses) => { }) it(`initial treasury balance is zero`, async () => { - assertBn(await token.balanceOf(treasuryAddr), new BN(0), 'treasury balance is zero') + assert.equals(await token.balanceOf(treasuryAddr), 0, 'treasury balance is zero') }) it(`registers one node operator with one key`, async () => { await nodeOperatorsRegistry.addNodeOperator(nodeOperator1.name, nodeOperator1.address, { from: voting }) nodeOperator1.id = 0 - assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') + assert.equals(await nodeOperatorsRegistry.getNodeOperatorsCount(), 1, 'total node operators') await nodeOperatorsRegistry.addSigningKeysOperatorBH( nodeOperator1.id, 1, @@ -144,18 +143,18 @@ contract('Lido: rewards distribution math', (addresses) => { ) const totalKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator1.id, { from: nobody }) - assertBn(totalKeys, 1, 'total signing keys') + assert.equals(totalKeys, 1, 'total signing keys') const unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator1.id, { from: nobody }) - assertBn(unusedKeys, 1, 'unused signing keys') + assert.equals(unusedKeys, 1, 'unused signing keys') - assertBn(await token.balanceOf(nodeOperator1.address), new BN(0), 'nodeOperator1 balance is zero') + assert.equals(await token.balanceOf(nodeOperator1.address), 0, 'nodeOperator1 balance is zero') await nodeOperatorsRegistry.setNodeOperatorStakingLimit(nodeOperator1.id, 1, { from: voting }) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 0, 'no validators have received the ether2') - assertBn(ether2Stat.beaconBalance, 0, 'remote ether2 not reported yet') + assert.equals(ether2Stat.depositedValidators, 0, 'no validators have received the ether2') + assert.equals(ether2Stat.beaconBalance, 0, 'remote ether2 not reported yet') }) it(`registers submit correctly`, async () => { @@ -165,25 +164,25 @@ contract('Lido: rewards distribution math', (addresses) => { const receipt = await pool.submit(ZERO_ADDRESS, { value: depositAmount, from: user1 }) - assertEvent(receipt, 'Transfer', { expectedArgs: { from: 0, to: user1, value: depositAmount } }) + assert.emits(receipt, 'Transfer', { from: ZERO_ADDRESS, to: user1, value: depositAmount }) const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 0, 'one validator have received the ether2') - assertBn(ether2Stat.beaconBalance, 0, `no remote ether2 on validator's balance is reported yet`) + assert.equals(ether2Stat.depositedValidators, 0, 'one validator have received the ether2') + assert.equals(ether2Stat.beaconBalance, 0, `no remote ether2 on validator's balance is reported yet`) - assertBn(await pool.getBufferedEther(), expectedTotalEther, `all the ether is buffered until deposit`) - assertBn(await pool.getTotalPooledEther(), expectedTotalEther, 'total pooled ether') + assert.equals(await pool.getBufferedEther(), expectedTotalEther, `all the ether is buffered until deposit`) + assert.equals(await pool.getTotalPooledEther(), expectedTotalEther, 'total pooled ether') // The amount of tokens corresponding to the deposited ETH value was minted to the user - assertBn(await token.balanceOf(user1), depositAmount, 'user1 tokens') + assert.equals(await token.balanceOf(user1), depositAmount, 'user1 tokens') - assertBn(await token.totalSupply(), expectedTotalEther, 'token total supply') + assert.equals(await token.totalSupply(), expectedTotalEther, 'token total supply') // Total shares are equal to deposited eth before ratio change and fee mint - assertBn(await token.getTotalShares(), expectedTotalEther, 'total shares') + assert.equals(await token.getTotalShares(), expectedTotalEther, 'total shares') - assertBn(await token.balanceOf(treasuryAddr), new BN(0), 'treasury balance is zero') - assertBn(await token.balanceOf(nodeOperator1.address), new BN(0), 'nodeOperator1 balance is zero') + assert.equals(await token.balanceOf(treasuryAddr), 0, 'treasury balance is zero') + assert.equals(await token.balanceOf(nodeOperator1.address), 0, 'nodeOperator1 balance is zero') }) it(`the first deposit gets deployed`, async () => { @@ -214,21 +213,21 @@ contract('Lido: rewards distribution math', (addresses) => { '0x', signatures ) - assertBn( + assert.equals( await nodeOperatorsRegistry.getUnusedSigningKeyCount(0), 0, 'no more available keys for the first validator' ) - assertBn( + assert.equals( await token.balanceOf(user1), ETH(34), 'user1 balance is equal first reported value + their buffered deposit value' ) - assertBn(await token.sharesOf(user1), ETH(34), 'user1 shares are equal to the first deposit') - assertBn(await token.totalSupply(), ETH(34 + initialHolderBalanceETH), 'token total supply') + assert.equals(await token.sharesOf(user1), ETH(34), 'user1 shares are equal to the first deposit') + assert.equals(await token.totalSupply(), ETH(34 + initialHolderBalanceETH), 'token total supply') - assertBn(await token.balanceOf(treasuryAddr), ETH(0), 'treasury balance equals buffered value') - assertBn(await token.balanceOf(nodeOperator1.address), new BN(0), 'nodeOperator1 balance is zero') + assert.equals(await token.balanceOf(treasuryAddr), ETH(0), 'treasury balance equals buffered value') + assert.equals(await token.balanceOf(nodeOperator1.address), 0, 'nodeOperator1 balance is zero') }) it(`first report registers profit`, async () => { @@ -236,7 +235,6 @@ contract('Lido: rewards distribution math', (addresses) => { const profitAmount = ETH(profitAmountEth) const reportingValue = ETH(32 + profitAmountEth) const prevTotalShares = await pool.getTotalShares() - const nodeOperator1TokenBefore = await token.balanceOf(operator_1) // for some reason there's nothing in this receipt's log, so we're not going to use it const treasurySharesBefore = await pool.sharesOf(treasuryAddr) @@ -252,7 +250,6 @@ contract('Lido: rewards distribution math', (addresses) => { await pool.getTotalPooledEther() ) - const totalFeeToDistribute = await pool.getPooledEthByShares(sharesMintedAsFees) const nodeOperatorsSharesToMint = sharesMintedAsFees.div(toBN(2)) const treasurySharesToMint = sharesMintedAsFees.sub(nodeOperatorsSharesToMint) const nodeOperatorsFeeToMint = await pool.getPooledEthByShares(nodeOperatorsSharesToMint) @@ -345,9 +342,9 @@ contract('Lido: rewards distribution math', (addresses) => { 1, 'user1 balance is equal first reported value + their buffered deposit value' ) - assertBn(await token.sharesOf(user1), ETH(34), 'user1 shares are equal to the first deposit') + assert.equals(await token.sharesOf(user1), ETH(34), 'user1 shares are equal to the first deposit') - assertBn(await token.totalSupply(), ETH(36), 'token total supply') + assert.equals(await token.totalSupply(), ETH(36), 'token total supply') assert.equals(await pool.getTotalShares(), prevTotalShares.add(sharesMintedAsFees)) }) @@ -356,7 +353,7 @@ contract('Lido: rewards distribution math', (addresses) => { await nodeOperatorsRegistry.setNodeOperatorStakingLimit(1, 1, { from: voting }) nodeOperator2.id = 1 - assertBn(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators') + assert.equals(await nodeOperatorsRegistry.getNodeOperatorsCount(), 2, 'total node operators') await nodeOperatorsRegistry.addSigningKeysOperatorBH( nodeOperator2.id, 1, @@ -369,16 +366,16 @@ contract('Lido: rewards distribution math', (addresses) => { await nodeOperatorsRegistry.setNodeOperatorStakingLimit(nodeOperator2.id, 1, { from: voting }) const totalKeys = await nodeOperatorsRegistry.getTotalSigningKeyCount(nodeOperator2.id, { from: nobody }) - assertBn(totalKeys, 1, 'total signing keys') + assert.equals(totalKeys, 1, 'total signing keys') const unusedKeys = await nodeOperatorsRegistry.getUnusedSigningKeyCount(nodeOperator2.id, { from: nobody }) - assertBn(unusedKeys, 1, 'unused signing keys') + assert.equals(unusedKeys, 1, 'unused signing keys') - assertBn(await token.balanceOf(nodeOperator2.address), new BN(0), 'nodeOperator2 balance is zero') + assert.equals(await token.balanceOf(nodeOperator2.address), 0, 'nodeOperator2 balance is zero') const ether2Stat = await pool.getBeaconStat() - assertBn(ether2Stat.depositedValidators, 1, 'one validator have received the ether2') - assertBn(ether2Stat.beaconBalance, ETH(33), 'remote ether2 not reported yet') + assert.equals(ether2Stat.depositedValidators, 1, 'one validator have received the ether2') + assert.equals(ether2Stat.beaconBalance, ETH(33), 'remote ether2 not reported yet') }) it(`deposits another amount to second operator's validator`, async () => { @@ -392,22 +389,26 @@ contract('Lido: rewards distribution math', (addresses) => { const receipt = await pool.submit(ZERO_ADDRESS, { value: depositAmount, from: user2 }) // note: that number isn't equal to depositAmount - assertEvent(receipt, 'Transfer', { expectedArgs: { from: 0, to: user2, value: awaitedTokens } }) + assert.emits(receipt, 'Transfer', { from: ZERO_ADDRESS, to: user2, value: awaitedTokens }) // 2 from the previous deposit of the first user - assertBn( + assert.equals( await pool.getBufferedEther(), ETH(depositedEthValue + 2 + initialHolderBalanceETH), `all the ether is buffered until deposit` ) // The amount of tokens corresponding to the deposited ETH value was minted to the user - assertBn(await token.balanceOf(user2), awaitedTokens, 'user2 tokens') + assert.equals(await token.balanceOf(user2), awaitedTokens, 'user2 tokens') // current deposit + firstDeposit + first profit - assertBn(await token.totalSupply(), ETH(depositedEthValue + 34 + 1 + initialHolderBalanceETH), 'token total supply') + assert.equals( + await token.totalSupply(), + ETH(depositedEthValue + 34 + 1 + initialHolderBalanceETH), + 'token total supply' + ) // Total shares are equal to deposited eth before ratio change and fee mint - assertBn(await token.getTotalShares(), sharesBefore.add(awaitedShares), 'total shares') + assert.equals(await token.getTotalShares(), sharesBefore.add(awaitedShares), 'total shares') }) it(`the second deposit gets deployed`, async () => { @@ -448,7 +449,7 @@ contract('Lido: rewards distribution math', (addresses) => { ), ] - const [_, deltas] = await getSharesTokenDeltas( + const [, deltas] = await getSharesTokenDeltas( () => depositSecurityModule.depositBufferedEther( block.number, @@ -466,14 +467,13 @@ contract('Lido: rewards distribution math', (addresses) => { user2 ) - assertBn(await nodeOperatorsRegistry.getUnusedSigningKeyCount(0), 0, 'no more available keys') - const zeroBn = new BN(0) + assert.equals(await nodeOperatorsRegistry.getUnusedSigningKeyCount(0), 0, 'no more available keys') // deposit doesn't change any kind of balances - deltas.forEach((delta, i) => assertBn(delta, zeroBn, `delta ${i} is zero`)) + deltas.forEach((delta, i) => assert.equals(delta, 0, `delta ${i} is zero`)) }) it(`delta shares are zero on no profit reported after the deposit`, async () => { - const [_, deltas] = await getSharesTokenDeltas( + const [, deltas] = await getSharesTokenDeltas( () => reportBeacon(2, ETH(32 + 1 + 32)), treasuryAddr, nodeOperator1.address, @@ -482,10 +482,9 @@ contract('Lido: rewards distribution math', (addresses) => { user2 ) - assertBn(await nodeOperatorsRegistry.getUnusedSigningKeyCount(0), 0, 'no more available keys') - const zeroBn = new BN(0) + assert.equals(await nodeOperatorsRegistry.getUnusedSigningKeyCount(0), 0, 'no more available keys') // deposit doesn't change any kind of _shares_ balances - deltas.forEach((delta, i) => i % 2 && assertBn(delta, zeroBn, `delta ${i} is zero`)) + deltas.forEach((delta, i) => i % 2 && assert.equals(delta, 0, `delta ${i} is zero`)) }) it(`balances change correctly on second profit`, async () => { @@ -636,9 +635,9 @@ contract('Lido: rewards distribution math', (addresses) => { 1, 'user1 balance is equal first reported value + their buffered deposit value' ) - assertBn(await token.sharesOf(user1), ETH(34), 'user1 shares are equal to the first deposit') + assert.equals(await token.sharesOf(user1), ETH(34), 'user1 shares are equal to the first deposit') - assertBn(await token.totalSupply(), ETH(70), 'token total supply') + assert.equals(await token.totalSupply(), ETH(70), 'token total supply') assert.equals(await pool.getTotalShares(), prevTotalShares.add(sharesMintedAsFees)) }) @@ -669,7 +668,7 @@ contract('Lido: rewards distribution math', (addresses) => { } ) await anotherCuratedModule.setNodeOperatorStakingLimit(0, validatorsCount, { from: voting }) - assertBn( + assert.equals( await anotherCuratedModule.getUnusedSigningKeyCount(0), validatorsCount, 'operator of module has 10 unused keys' @@ -680,7 +679,7 @@ contract('Lido: rewards distribution math', (addresses) => { const depositAmount = ETH(32) await pool.submit(ZERO_ADDRESS, { value: depositAmount, from: user1 }) - const [_, newCurated] = await stakingRouter.getStakingModules() + const [, newCurated] = await stakingRouter.getStakingModules() await nodeOperatorsRegistry.setNodeOperatorStakingLimit(0, 0, { from: voting }) @@ -701,7 +700,7 @@ contract('Lido: rewards distribution math', (addresses) => { const user1SharesBefore = await token.sharesOf(user1) const totalSupplyBefore = await token.totalSupply() - assertBn(await anotherCuratedModule.getUnusedSigningKeyCount(0), 10, 'operator of module has 10 unused keys') + assert.equals(await anotherCuratedModule.getUnusedSigningKeyCount(0), 10, 'operator of module has 10 unused keys') await depositSecurityModule.depositBufferedEther( block.number, block.hash, @@ -711,16 +710,16 @@ contract('Lido: rewards distribution math', (addresses) => { '0x', signatures ) - assertBn(await anotherCuratedModule.getUnusedSigningKeyCount(0), 9, 'operator of module has 9 unused keys') + assert.equals(await anotherCuratedModule.getUnusedSigningKeyCount(0), 9, 'operator of module has 9 unused keys') - assertBn( + assert.equals( await token.balanceOf(user1), user1BalanceBefore, 'user1 balance is equal first reported value + their buffered deposit value' ) - assertBn(await token.sharesOf(user1), user1SharesBefore, 'user1 shares are equal to the first deposit') - assertBn(await token.totalSupply(), totalSupplyBefore, 'token total supply') - assertBn(await token.getBufferedEther(), ETH(3), '') + assert.equals(await token.sharesOf(user1), user1SharesBefore, 'user1 shares are equal to the first deposit') + assert.equals(await token.totalSupply(), totalSupplyBefore, 'token total supply') + assert.equals(await token.getBufferedEther(), ETH(3), '') }) it(`rewards distribution`, async () => { From 629d22a11aae72077a0ca6c47d5678e6505753db Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Wed, 22 Feb 2023 01:56:15 +0200 Subject: [PATCH 08/14] =?UTF-8?q?=F0=9F=92=85:=20last=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../oracle/accounting-oracle-deploy.test.js | 20 ++++++++-------- .../hash-consensus-access-control.test.js | 24 +++++++++---------- .../hash-consensus-fast-lane-members.test.js | 2 +- .../changing_oracles_during_epoch.test.js | 2 +- 4 files changed, 24 insertions(+), 24 deletions(-) diff --git a/test/0.8.9/oracle/accounting-oracle-deploy.test.js b/test/0.8.9/oracle/accounting-oracle-deploy.test.js index 7775ac1b7..380db9e49 100644 --- a/test/0.8.9/oracle/accounting-oracle-deploy.test.js +++ b/test/0.8.9/oracle/accounting-oracle-deploy.test.js @@ -256,10 +256,10 @@ async function initAccountingOracle({ await oracle.grantRole(await oracle.SUBMIT_DATA_ROLE(), dataSubmitter, { from: admin }) } - assert.equals((await oracle.EXTRA_DATA_FORMAT_EMPTY()), EXTRA_DATA_FORMAT_EMPTY) - assert.equals((await oracle.EXTRA_DATA_FORMAT_LIST()), EXTRA_DATA_FORMAT_LIST) - assert.equals((await oracle.EXTRA_DATA_TYPE_STUCK_VALIDATORS()), EXTRA_DATA_TYPE_STUCK_VALIDATORS) - assert.equals((await oracle.EXTRA_DATA_TYPE_EXITED_VALIDATORS()), EXTRA_DATA_TYPE_EXITED_VALIDATORS) + assert.equals(await oracle.EXTRA_DATA_FORMAT_EMPTY(), EXTRA_DATA_FORMAT_EMPTY) + assert.equals(await oracle.EXTRA_DATA_FORMAT_LIST(), EXTRA_DATA_FORMAT_LIST) + assert.equals(await oracle.EXTRA_DATA_TYPE_STUCK_VALIDATORS(), EXTRA_DATA_TYPE_STUCK_VALIDATORS) + assert.equals(await oracle.EXTRA_DATA_TYPE_EXITED_VALIDATORS(), EXTRA_DATA_TYPE_EXITED_VALIDATORS) return initTx } @@ -338,13 +338,13 @@ contract('AccountingOracle', ([admin, member1]) => { it('mock setup is correct', async () => { // check the mock time-travellable setup const time1 = +(await consensus.getTime()) - assert.equals((await oracle.getTime()), time1) + assert.equals(await oracle.getTime(), time1) await consensus.advanceTimeBy(SECONDS_PER_SLOT) const time2 = +(await consensus.getTime()) assert.equal(time2, time1 + SECONDS_PER_SLOT) - assert.equals((await oracle.getTime()), time2) + assert.equals(await oracle.getTime(), time2) const handleOracleReportCallData = await mockLido.getLastCall_handleOracleReport() assert.equals(handleOracleReportCallData.callCount, 0) @@ -352,8 +352,8 @@ contract('AccountingOracle', ([admin, member1]) => { const updateExitedKeysByModuleCallData = await mockStakingRouter.lastCall_updateExitedKeysByModule() assert.equals(updateExitedKeysByModuleCallData.callCount, 0) - assert.equals((await mockStakingRouter.totalCalls_reportExitedKeysByNodeOperator()), 0) - assert.equals((await mockStakingRouter.totalCalls_reportStuckKeysByNodeOperator()), 0) + assert.equals(await mockStakingRouter.totalCalls_reportExitedKeysByNodeOperator(), 0) + assert.equals(await mockStakingRouter.totalCalls_reportStuckKeysByNodeOperator(), 0) const updateBunkerModeLastCall = await mockWithdrawalQueue.lastCall__updateBunkerMode() assert.equals(updateBunkerModeLastCall.callCount, 0) @@ -366,9 +366,9 @@ contract('AccountingOracle', ([admin, member1]) => { it('initial configuration is correct', async () => { assert.equal(await oracle.getConsensusContract(), consensus.address) - assert.equals((await oracle.getConsensusVersion()), CONSENSUS_VERSION) + assert.equals(await oracle.getConsensusVersion(), CONSENSUS_VERSION) assert.equal(await oracle.LIDO(), mockLido.address) - assert.equals((await oracle.SECONDS_PER_SLOT()), SECONDS_PER_SLOT) + assert.equals(await oracle.SECONDS_PER_SLOT(), SECONDS_PER_SLOT) }) it('reverts if lido locator address is zero', async () => { diff --git a/test/0.8.9/oracle/hash-consensus-access-control.test.js b/test/0.8.9/oracle/hash-consensus-access-control.test.js index a79cb7741..5a6577a6c 100644 --- a/test/0.8.9/oracle/hash-consensus-access-control.test.js +++ b/test/0.8.9/oracle/hash-consensus-access-control.test.js @@ -53,7 +53,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { 'MANAGE_MEMBERS_AND_QUORUM_ROLE' ) assert.equal(await consensus.getIsMember(member1), false) - assert.equals((await consensus.getQuorum()), 0) + assert.equals(await consensus.getQuorum(), 0) }) it('should allow calling from a possessor of MANAGE_MEMBERS_AND_QUORUM_ROLE role', async () => { @@ -61,7 +61,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { await consensus.addMember(member2, 1, { from: account2 }) assert.equal(await consensus.getIsMember(member2), true) - assert.equals((await consensus.getQuorum()), 1) + assert.equals(await consensus.getQuorum(), 1) }) }) @@ -73,7 +73,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { 'MANAGE_MEMBERS_AND_QUORUM_ROLE' ) assert.equal(await consensus.getIsMember(member1), false) - assert.equals((await consensus.getQuorum()), 0) + assert.equals(await consensus.getQuorum(), 0) }) it('should allow calling from a possessor of MANAGE_MEMBERS_AND_QUORUM_ROLE role', async () => { @@ -84,7 +84,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { await consensus.removeMember(member2, 1, { from: account2 }) assert.equal(await consensus.getIsMember(member2), false) - assert.equals((await consensus.getQuorum()), 1) + assert.equals(await consensus.getQuorum(), 1) }) }) @@ -95,14 +95,14 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { account1, 'MANAGE_MEMBERS_AND_QUORUM_ROLE' ) - assert.equals((await consensus.getQuorum()), 0) + assert.equals(await consensus.getQuorum(), 0) }) it('should allow calling from a possessor of MANAGE_MEMBERS_AND_QUORUM_ROLE role', async () => { await consensus.grantRole(manageMembersAndQuorumRoleKeccak156, account2) await consensus.setQuorum(1, { from: account2 }) - assert.equals((await consensus.getQuorum()), 1) + assert.equals(await consensus.getQuorum(), 1) }) }) @@ -113,7 +113,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { account1, 'DISABLE_CONSENSUS_ROLE' ) - assert.equals((await consensus.getQuorum()), 0) + assert.equals(await consensus.getQuorum(), 0) }) }) }) @@ -126,14 +126,14 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { account1, 'DISABLE_CONSENSUS_ROLE' ) - assert.equals((await consensus.getQuorum()), 0) + assert.equals(await consensus.getQuorum(), 0) }) it('should allow calling from a possessor of DISABLE_CONSENSUS_ROLE role', async () => { await consensus.grantRole(disableConsensusRoleKeccak156, account2) await consensus.setQuorum(MaxUint256, { from: account2 }) - assert.equals((await consensus.getQuorum()), MaxUint256) + assert.equals(await consensus.getQuorum(), MaxUint256) }) }) @@ -144,14 +144,14 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { account1, 'DISABLE_CONSENSUS_ROLE' ) - assert.equals((await consensus.getQuorum()), 0) + assert.equals(await consensus.getQuorum(), 0) }) it('should allow calling from a possessor of DISABLE_CONSENSUS_ROLE role', async () => { await consensus.grantRole(disableConsensusRoleKeccak156, account2) await consensus.disableConsensus({ from: account2 }) - assert.equals((await consensus.getQuorum()), MaxUint256) + assert.equals(await consensus.getQuorum(), MaxUint256) }) }) }) @@ -190,7 +190,7 @@ contract('HashConsensus', ([admin, account1, account2, member1, member2]) => { await consensus.grantRole(manageReportProcessorRoleKeccak156, account2) await consensus.setReportProcessor(reportProcessor2.address, { from: account2 }) - assert.equals((await consensus.getReportProcessor()), reportProcessor2.address) + assert.equals(await consensus.getReportProcessor(), reportProcessor2.address) }) }) }) diff --git a/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js b/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js index a3546e8c0..7342f9bfe 100644 --- a/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js +++ b/test/0.8.9/oracle/hash-consensus-fast-lane-members.test.js @@ -15,7 +15,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, const setTimeToFrame0 = async () => { await consensus.setTimeInEpochs((await consensus.getFrameConfig()).initialEpoch) - assert.equals((await consensus.getTimeInSlots()), +(await consensus.getCurrentFrame()).refSlot + 1) + assert.equals(await consensus.getTimeInSlots(), +(await consensus.getCurrentFrame()).refSlot + 1) } context('State after initialization', () => { diff --git a/test/scenario/changing_oracles_during_epoch.test.js b/test/scenario/changing_oracles_during_epoch.test.js index 8f65086bd..2c0de7380 100644 --- a/test/scenario/changing_oracles_during_epoch.test.js +++ b/test/scenario/changing_oracles_during_epoch.test.js @@ -66,7 +66,7 @@ contract('AccountingOracle', ([voting, malicious1, malicious2, member1, member2, await initAccountingOracle({ ...deployed, admin: voting }) - assert.equals((await oracle.getTime()), GENESIS_TIME + SECONDS_PER_FRAME) + assert.equals(await oracle.getTime(), GENESIS_TIME + SECONDS_PER_FRAME) await consensus.addMember(member1, 4, { from: voting }) await consensus.addMember(member2, 4, { from: voting }) From 983bddfc93625e1c0db22dd0b4423e95e1aa46dd Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Wed, 22 Feb 2023 08:37:14 +0200 Subject: [PATCH 09/14] =?UTF-8?q?=F0=9F=A4=96:=20lint=20error=20on=20using?= =?UTF-8?q?=20aragon=20aserts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 6 +++++- .../oracle/hash-consensus-members.test.js | 19 +++++++++---------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/.eslintrc b/.eslintrc index c04d261bc..3f0be1576 100644 --- a/.eslintrc +++ b/.eslintrc @@ -26,7 +26,11 @@ "quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }], "jsx-quotes": ["error", "prefer-single"], "no-useless-escape": "off", - "linebreak-style": ["error", "unix"] + "linebreak-style": ["error", "unix"], + "no-restricted-modules": ["error", { + "name": "@aragon/contract-helpers-test/src/asserts", + "message": "Please use helpers/assert instead." + }] }, "overrides": [ { diff --git a/test/0.8.9/oracle/hash-consensus-members.test.js b/test/0.8.9/oracle/hash-consensus-members.test.js index e19372d73..6785bd9e9 100644 --- a/test/0.8.9/oracle/hash-consensus-members.test.js +++ b/test/0.8.9/oracle/hash-consensus-members.test.js @@ -1,7 +1,6 @@ const { contract } = require('hardhat') const { assert } = require('../../helpers/assert') const { toNum } = require('../../helpers/utils') -const { assertAmountOfEvents } = require('@aragon/contract-helpers-test/src/asserts') const { ZERO_ADDRESS } = require('../../helpers/constants') const { HASH_1, HASH_2, CONSENSUS_VERSION, deployHashConsensus, ZERO_HASH } = require('./hash-consensus-deploy.test') @@ -238,11 +237,11 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.addMember(member3, 3, { from: admin }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) tx = await consensus.removeMember(member3, 2, { from: admin }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) }) @@ -258,11 +257,11 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.addMember(member3, 2, { from: admin }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.removeMember(member3, 2, { from: admin }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) }) @@ -278,16 +277,16 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.addMember(member3, 3, { from: admin }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') // TODO: is this really ok? assert.equal((await consensus.getConsensusState()).consensusReport, ZERO_HASH) tx = await consensus.submitReport(refSlot, HASH_1, CONSENSUS_VERSION, { from: member3 }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.removeMember(member3, 2, { from: admin }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) }) @@ -305,7 +304,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member3 }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) await consensus.addMember(member4, 3, { from: admin }) @@ -336,7 +335,7 @@ contract('HashConsensus', ([admin, member1, member2, member3, member4, member5, assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) tx = await consensus.submitReport(refSlot, HASH_2, CONSENSUS_VERSION, { from: member3 }) - assertAmountOfEvents(tx, 'ConsensusReached', { expectedAmount: 0 }) + assert.notEmits(tx, 'ConsensusReached') assert.equal((await consensus.getConsensusState()).consensusReport, HASH_1) await consensus.addMember(member4, 3, { from: admin }) From 0ca43ea08fda46e7bf2b57152060dda173949257 Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Wed, 22 Feb 2023 11:02:32 +0200 Subject: [PATCH 10/14] =?UTF-8?q?=F0=9F=A4=96:=20eslint=20settings=20for?= =?UTF-8?q?=20node=2016=20js=20features?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.eslintrc b/.eslintrc index 3f0be1576..835071e9c 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,16 +1,14 @@ { "env": { "node": true, - "es2020": true + "es2022": true }, "extends": ["standard", "plugin:prettier/recommended"], - "parser": "@babel/eslint-parser", "parserOptions": { - "ecmaVersion": 8, + "ecmaVersion": 2022, "sourceType": "module", "ecmaFeatures": { - "jsx": true, - "modules": true + "jsx": true } }, "plugins": ["node", "prettier", "standard"], From d4d4c98fc98fc5a27ee5993ebd57731357beb24d Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Wed, 22 Feb 2023 11:06:18 +0200 Subject: [PATCH 11/14] =?UTF-8?q?=F0=9F=93=A6:=20remove=20babel=20eslint-p?= =?UTF-8?q?arser?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 1 - yarn.lock | 41 ----------------------------------------- 2 files changed, 42 deletions(-) diff --git a/package.json b/package.json index ecf2455e6..b8f65afb6 100644 --- a/package.json +++ b/package.json @@ -76,7 +76,6 @@ "@aragon/minime": "1.0.0", "@aragon/test-helpers": "^2.1.0", "@babel/core": "^7.21.0", - "@babel/eslint-parser": "^7.19.1", "@babel/node": "^7.12.1", "@babel/preset-env": "^7.11.5", "@babel/register": "^7.12.1", diff --git a/yarn.lock b/yarn.lock index 480ff498e..7aeb5088b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -321,20 +321,6 @@ __metadata: languageName: node linkType: hard -"@babel/eslint-parser@npm:^7.19.1": - version: 7.19.1 - resolution: "@babel/eslint-parser@npm:7.19.1" - dependencies: - "@nicolo-ribaudo/eslint-scope-5-internals": 5.1.1-v1 - eslint-visitor-keys: ^2.1.0 - semver: ^6.3.0 - peerDependencies: - "@babel/core": ">=7.11.0" - eslint: ^7.5.0 || ^8.0.0 - checksum: e7bbcdd8b61bc7040af63e8b1abf109224085ccf3e72ef08cc00647b9fae4a74df54cfc0860218ce38f7520938494cdeeb3b1824b989366a733551faf7048667 - languageName: node - linkType: hard - "@babel/generator@npm:^7.11.5, @babel/generator@npm:^7.11.6, @babel/generator@npm:^7.4.4": version: 7.11.6 resolution: "@babel/generator@npm:7.11.6" @@ -3724,7 +3710,6 @@ __metadata: "@aragon/os": ^4.4.0 "@aragon/test-helpers": ^2.1.0 "@babel/core": ^7.21.0 - "@babel/eslint-parser": ^7.19.1 "@babel/node": ^7.12.1 "@babel/preset-env": ^7.11.5 "@babel/register": ^7.12.1 @@ -3820,15 +3805,6 @@ __metadata: languageName: node linkType: hard -"@nicolo-ribaudo/eslint-scope-5-internals@npm:5.1.1-v1": - version: 5.1.1-v1 - resolution: "@nicolo-ribaudo/eslint-scope-5-internals@npm:5.1.1-v1" - dependencies: - eslint-scope: 5.1.1 - checksum: 0d166bdbda46fe9c4f42ad1df1ae6a943b118cda138590cec21db92e383c02136b9a20152bc6736dd84a315dc3459dcd9be20072c7d2c36a5648be1f21d115da - languageName: node - linkType: hard - "@noble/hashes@npm:1.1.2": version: 1.1.2 resolution: "@noble/hashes@npm:1.1.2" @@ -11688,16 +11664,6 @@ __metadata: languageName: node linkType: hard -"eslint-scope@npm:5.1.1": - version: 5.1.1 - resolution: "eslint-scope@npm:5.1.1" - dependencies: - esrecurse: ^4.3.0 - estraverse: ^4.1.1 - checksum: 79465cf5082f4216176f6d49c7d088de89ee890f912eb87b831f23ee9a5e17ed0f3f2ab6108fb8fefa0474ba5ebeaa9bdefbe49ba704bd879b73f2445e23ee10 - languageName: node - linkType: hard - "eslint-scope@npm:^4.0.3": version: 4.0.3 resolution: "eslint-scope@npm:4.0.3" @@ -11761,13 +11727,6 @@ __metadata: languageName: node linkType: hard -"eslint-visitor-keys@npm:^2.1.0": - version: 2.1.0 - resolution: "eslint-visitor-keys@npm:2.1.0" - checksum: 75eaae9006f5bcb9d1e09641719b840b83c4758f5f25bc06a0e94918d78658d0f19691bdc2e3b100604d0fe2d1eb94a2aab287ba24ad2f02f87cacdccb86c2e4 - languageName: node - linkType: hard - "eslint-visitor-keys@npm:^3.3.0": version: 3.3.0 resolution: "eslint-visitor-keys@npm:3.3.0" From 24b8755963eaeb33e927e4995640ba07f4a7760a Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Wed, 22 Feb 2023 11:58:06 +0200 Subject: [PATCH 12/14] =?UTF-8?q?=F0=9F=A4=96:=20more=20proper=20configs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .editorconfig | 6 +----- .eslintrc | 5 ++--- .gitignore | 2 +- ava.config.cjs | 6 +++--- package.json | 24 ++++++++++++------------ yarn.lock | 3 ++- 6 files changed, 21 insertions(+), 25 deletions(-) diff --git a/.editorconfig b/.editorconfig index abda0feff..e4e910d09 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,10 +8,6 @@ charset = utf-8 indent_style = space indent_size = 4 -[*.{js,yml}] -charset = utf-8 -insert_final_newline = true -end_of_line = lf -indent_style = space +[*.{js,yml,json,cjs}] indent_size = 2 max_line_length = 120 diff --git a/.eslintrc b/.eslintrc index 835071e9c..4e6676456 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,4 +1,5 @@ { + "plugins": ["prettier", "standard"], "env": { "node": true, "es2022": true @@ -6,13 +7,11 @@ "extends": ["standard", "plugin:prettier/recommended"], "parserOptions": { "ecmaVersion": 2022, - "sourceType": "module", + "sourceType": "script", "ecmaFeatures": { "jsx": true } }, - "plugins": ["node", "prettier", "standard"], - "rules": { "prettier/prettier": "error", "no-undef": "warn", diff --git a/.gitignore b/.gitignore index 239264963..6888423e7 100644 --- a/.gitignore +++ b/.gitignore @@ -46,4 +46,4 @@ cli/vendor # foundry artifacts foundry/cache -foundry/out \ No newline at end of file +foundry/out diff --git a/ava.config.cjs b/ava.config.cjs index f879b539b..d742ffab4 100644 --- a/ava.config.cjs +++ b/ava.config.cjs @@ -1,5 +1,5 @@ module.exports = { - require: ['@babel/register'], - files: ['e2e/test/**/*.test.js'], - concurrency: 5 + require: ['@babel/register'], + files: ['e2e/test/**/*.test.js'], + concurrency: 5, } diff --git a/package.json b/package.json index b8f65afb6..976ea1485 100644 --- a/package.json +++ b/package.json @@ -72,6 +72,7 @@ "@aragon/apps-lido": "lidofinance/aragon-apps#master", "@aragon/buidler-aragon": "^0.2.9", "@aragon/contract-helpers-test": "^0.1.0", + "@aragon/hardhat-aragon": "^1.0.0", "@aragon/id": "^2.0.3", "@aragon/minime": "1.0.0", "@aragon/test-helpers": "^2.1.0", @@ -85,10 +86,13 @@ "@nomiclabs/hardhat-truffle5": "^2.0.2", "@nomiclabs/hardhat-web3": "^2.0.0", "@openzeppelin/test-helpers": "^0.5.6", + "@truffle/contract": "^4.2.22", "ava": "^3.13.0", "ava-spec": "^1.1.1", "babel-plugin-istanbul": "^6.0.0", + "bn.js": "^5.2.1", "chai": "^4.2.0", + "concurrently": "^6.4.0", "dotenv": "^8.2.0", "electron": "^22.0.0", "eslint": "^8.34.0", @@ -98,17 +102,21 @@ "eslint-plugin-n": "^15.6.1", "eslint-plugin-prettier": "^4.2.1", "eslint-plugin-promise": "^6.1.1", - "eslint-plugin-standard": "^5.0.0", "eth-ens-namehash": "^2.0.8", "ethereumjs-testrpc-sc": "^6.5.1-sc.1", + "ethereumjs-util": "^7.0.8", + "ethers": "^5.1.4", "hardhat": "2.12.7", "hardhat-contract-sizer": "^2.5.0", "hardhat-gas-reporter": "^1.0.8", "hardhat-ignore-warnings": "skozin/hardhat-ignore-warnings#0ecf2ae85bddb83594193ee5c463cb4ae54cde7d", "husky": "^8.0.2", "ipfs-http-client": "^55.0.0", + "js-sha3": "^0.8.0", "lerna": "^3.22.1", "lint-staged": ">=10", + "minimatch": "^6.2.0", + "node-gyp": "^8.4.1", "prettier": "^2.8.4", "solhint": "^3.3.7", "solhint-plugin-lido": "^0.0.4", @@ -117,22 +125,14 @@ "truffle-extract": "^1.2.1", "truffle-flattener": "^1.5.0", "web3": "^1.3.0", - "winston": "^3.3.3" + "winston": "^3.3.3", + "yargs": "^16.0.3" }, "dependencies": { - "@aragon/hardhat-aragon": "^1.0.0", "@aragon/os": "^4.4.0", "@openzeppelin/contracts": "3.4.0", "@openzeppelin/contracts-v4.4": "npm:@openzeppelin/contracts@4.4.1", - "@truffle/contract": "^4.2.22", - "concurrently": "^6.4.0", - "ethereumjs-util": "^7.0.8", - "ethers": "^5.1.4", - "minimatch": "^6.2.0", - "node-gyp": "^8.4.1", - "openzeppelin-solidity": "2.0.0", - "solhint-plugin-lido": "^0.0.4", - "yargs": "^16.0.3" + "openzeppelin-solidity": "2.0.0" }, "overrides": { "hardhat-gas-reporter": { diff --git a/yarn.lock b/yarn.lock index 7aeb5088b..3101a03f7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3725,6 +3725,7 @@ __metadata: ava: ^3.13.0 ava-spec: ^1.1.1 babel-plugin-istanbul: ^6.0.0 + bn.js: ^5.2.1 chai: ^4.2.0 concurrently: ^6.4.0 dotenv: ^8.2.0 @@ -3736,7 +3737,6 @@ __metadata: eslint-plugin-n: ^15.6.1 eslint-plugin-prettier: ^4.2.1 eslint-plugin-promise: ^6.1.1 - eslint-plugin-standard: ^5.0.0 eth-ens-namehash: ^2.0.8 ethereumjs-testrpc-sc: ^6.5.1-sc.1 ethereumjs-util: ^7.0.8 @@ -3747,6 +3747,7 @@ __metadata: hardhat-ignore-warnings: "skozin/hardhat-ignore-warnings#0ecf2ae85bddb83594193ee5c463cb4ae54cde7d" husky: ^8.0.2 ipfs-http-client: ^55.0.0 + js-sha3: ^0.8.0 lerna: ^3.22.1 lint-staged: ">=10" minimatch: ^6.2.0 From 9c4a03814070fc53b2e991c2d881d2e000e7ac4c Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Wed, 22 Feb 2023 16:01:43 +0200 Subject: [PATCH 13/14] =?UTF-8?q?=F0=9F=A4=96:=20don't=20ignore=20js=20lin?= =?UTF-8?q?t=20on=20CI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/linters.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/linters.yml b/.github/workflows/linters.yml index 1358c47e1..6fbb43936 100644 --- a/.github/workflows/linters.yml +++ b/.github/workflows/linters.yml @@ -51,7 +51,6 @@ jobs: - name: Run JS linters run: yarn lint:js - continue-on-error: true coverage: name: Solidity coverage From 9974172eded8212c783828f9700bb9020181ebd3 Mon Sep 17 00:00:00 2001 From: Alexey Potapkin Date: Wed, 22 Feb 2023 16:20:59 +0200 Subject: [PATCH 14/14] =?UTF-8?q?=F0=9F=A4=96:=20launch=20eslint=20without?= =?UTF-8?q?=20fix=20to=20commit=20hook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 7 ------- .husky/pre-commit | 3 +-- test/0.8.9/oracle/base-oracle-deploy.test.js | 5 +---- 3 files changed, 2 insertions(+), 13 deletions(-) diff --git a/.eslintrc b/.eslintrc index 4e6676456..7028a1e29 100644 --- a/.eslintrc +++ b/.eslintrc @@ -14,16 +14,9 @@ }, "rules": { "prettier/prettier": "error", - "no-undef": "warn", - "no-unused-vars": "warn", - "prefer-const": "warn", "camelcase": "off", - "eol-last": "warn", - "no-multiple-empty-lines": "warn", "quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }], "jsx-quotes": ["error", "prefer-single"], - "no-useless-escape": "off", - "linebreak-style": ["error", "unix"], "no-restricted-modules": ["error", { "name": "@aragon/contract-helpers-test/src/asserts", "message": "Please use helpers/assert instead." diff --git a/.husky/pre-commit b/.husky/pre-commit index 5ea85ee62..c79d6bcc2 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -3,6 +3,5 @@ yarn compile git diff --quiet lib/abi -yarn lint:sol -yarn lint:js:fix +yarn lint diff --git a/test/0.8.9/oracle/base-oracle-deploy.test.js b/test/0.8.9/oracle/base-oracle-deploy.test.js index 92e307651..067039e90 100644 --- a/test/0.8.9/oracle/base-oracle-deploy.test.js +++ b/test/0.8.9/oracle/base-oracle-deploy.test.js @@ -98,11 +98,8 @@ module.exports = { contract('BaseOracle', ([admin]) => { context('Deployment and initial configuration', () => { - let oracle - it('deploying base oracle ', async () => { - const deployed = await deployBaseOracle(admin) - oracle = deployed.oracle + await deployBaseOracle(admin) }) // TODO: add more base tests