diff --git a/.eslintrc.json b/.eslintrc.json index 62f31bd90..9ecbd8766 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,11 +1,8 @@ { - "extends": [ - "eslint:recommended", - "prettier" - ], + "extends": ["eslint:recommended", "prettier"], "env": { "node": true, - "es6": true, + "es2020": true, "commonjs": true, "mocha": true }, @@ -17,7 +14,8 @@ "no-empty": "off", "no-only-tests/no-only-tests": "error" }, - "plugins": [ - "no-only-tests" - ] + "plugins": ["no-only-tests"], + "globals": { + "BigInt": true + } } diff --git a/contracts/protocol/clients/voucher/BosonVoucher.sol b/contracts/protocol/clients/voucher/BosonVoucher.sol index 3ea7bab82..b383f5a64 100644 --- a/contracts/protocol/clients/voucher/BosonVoucher.sol +++ b/contracts/protocol/clients/voucher/BosonVoucher.sol @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.18; + import "../../../domain/BosonConstants.sol"; import { ERC721Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import { IERC721Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; @@ -296,11 +297,6 @@ contract BosonVoucherBase is IBosonVoucher, BeaconClientBase, OwnableUpgradeable // End should be greater than start require(end > start, NOTHING_TO_BURN); - // If amount to burn is more than maxPremintedVouchers, burn only maxPremintedVouchers - if (end > start + maxPremintedVouchers) { - end = start + maxPremintedVouchers; - } - // Burn the range address rangeOwner = range.owner; uint256 burned; diff --git a/package-lock.json b/package-lock.json index 7d44599a9..5f4836a54 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,9 +14,8 @@ }, "devDependencies": { "@bosonprotocol/solidoc": "3.0.3", - "@ethereum-waffle/mock-contract": "^4.0.4", "@nomicfoundation/hardhat-network-helpers": "^1.0.6", - "@nomicfoundation/hardhat-toolbox": "^2.0.2", + "@nomicfoundation/hardhat-toolbox": "^3.0.0", "@nomiclabs/hardhat-web3": "^2.0.0", "@openzeppelin/test-helpers": "^0.5.16", "coveralls": "^3.1.1", @@ -27,6 +26,7 @@ "eslint-config-prettier": "^8.6.0", "eslint-plugin-no-only-tests": "^3.1.0", "ethereum-input-data-decoder": "^0.4.2", + "ethers": "^6.6.0", "glob": "^10.2.7", "hardhat": "^2.14.1", "hardhat-contract-sizer": "^2.7.0", @@ -41,6 +41,12 @@ "web3": "^1.8.1" } }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.9.2.tgz", + "integrity": "sha512-0h+FrQDqe2Wn+IIGFkTCd4aAwTJ+7834Ek1COohCyV26AXhwQ7WQaz+4F/nLOeVl/3BtWHOHLPsq46V8YB46Eg==", + "dev": true + }, "node_modules/@apollo/protobufjs": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/@apollo/protobufjs/-/protobufjs-1.2.7.tgz", @@ -68,9 +74,9 @@ } }, "node_modules/@apollo/usage-reporting-protobuf": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@apollo/usage-reporting-protobuf/-/usage-reporting-protobuf-4.1.0.tgz", - "integrity": "sha512-hXouMuw5pQVkzi8dgMybmr6Y11+eRmMQVoB5TF0HyTwAg9SOq/v3OCuiYqcVUKdBcskU9Msp+XvjAk0GKpWCwQ==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@apollo/usage-reporting-protobuf/-/usage-reporting-protobuf-4.1.1.tgz", + "integrity": "sha512-u40dIUePHaSKVshcedO7Wp+mPiZsaU6xjv9J+VyxpoU/zL6Jle+9zWeG98tr/+SZ0nZ4OXhrbb8SNr0rAPpIDA==", "dev": true, "optional": true, "dependencies": { @@ -219,33 +225,33 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.21.4.tgz", - "integrity": "sha512-LYvhNKfwWSPpocw8GI7gpK2nq3HSDuEPC/uSYaALSJu9xjsalaaYFOq0Pwt5KmVqwEbZlDu81aLXwBOmD/Fv9g==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.5.tgz", + "integrity": "sha512-Xmwn266vad+6DAqEB2A6V/CcZVp62BbwVmcOJc2RPuwih1kw02TjQvWVWlcKGbBPd+8/0V5DEkOcizRGYsspYQ==", "dev": true, "dependencies": { - "@babel/highlight": "^7.18.6" + "@babel/highlight": "^7.22.5" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.19.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", - "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.5.tgz", + "integrity": "sha512-aJXu+6lErq8ltp+JhkJUfk1MTGyuA4v7f3pA+BJ5HLfNC6nAQ0Cpi9uOquUj8Hehg0aUiHzWQbOVJGao6ztBAQ==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/highlight": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", - "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.5.tgz", + "integrity": "sha512-BSKlD1hgnedS5XRnGOljZawtag7H1yPfQp0tdNJCHoH6AZ+Pcm9VvkrK59/Yy593Ypg0zMxH2BxD1VPYUQ7UIw==", "dev": true, "dependencies": { - "@babel/helper-validator-identifier": "^7.18.6", + "@babel/helper-validator-identifier": "^7.22.5", "chalk": "^2.0.0", "js-tokens": "^4.0.0" }, @@ -254,9 +260,9 @@ } }, "node_modules/@babel/runtime": { - "version": "7.22.3", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.3.tgz", - "integrity": "sha512-XsDuspWKLUsxwCp6r7EhsExHtYfbe5oAGQ19kqngTdCPUoPQzOPdUbD/pB9PJiwb2ptYKQDjSJT3R6dC+EPqfQ==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.5.tgz", + "integrity": "sha512-ecjvYlnAaZ/KVneE/OdKYBYfgXV3Ptu6zQWmgEF7vwKhQnvVS6bjMD2XYgj+SNvQ1GfK/pjgokfPkC/2CO8CuA==", "dev": true, "dependencies": { "regenerator-runtime": "^0.13.11" @@ -402,6 +408,54 @@ "js-sha3": "^0.8.0" } }, + "node_modules/@ensdomains/ensjs/node_modules/ethers": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.7.2.tgz", + "integrity": "sha512-wswUsmWo1aOK8rR7DIKiWSw9DbLWe6x98Jrn8wcTflTVvaXhAMaB5zGAXy0GYQEQp9iO1iSHWVyARQm11zUtyg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "dependencies": { + "@ethersproject/abi": "5.7.0", + "@ethersproject/abstract-provider": "5.7.0", + "@ethersproject/abstract-signer": "5.7.0", + "@ethersproject/address": "5.7.0", + "@ethersproject/base64": "5.7.0", + "@ethersproject/basex": "5.7.0", + "@ethersproject/bignumber": "5.7.0", + "@ethersproject/bytes": "5.7.0", + "@ethersproject/constants": "5.7.0", + "@ethersproject/contracts": "5.7.0", + "@ethersproject/hash": "5.7.0", + "@ethersproject/hdnode": "5.7.0", + "@ethersproject/json-wallets": "5.7.0", + "@ethersproject/keccak256": "5.7.0", + "@ethersproject/logger": "5.7.0", + "@ethersproject/networks": "5.7.1", + "@ethersproject/pbkdf2": "5.7.0", + "@ethersproject/properties": "5.7.0", + "@ethersproject/providers": "5.7.2", + "@ethersproject/random": "5.7.0", + "@ethersproject/rlp": "5.7.0", + "@ethersproject/sha2": "5.7.0", + "@ethersproject/signing-key": "5.7.0", + "@ethersproject/solidity": "5.7.0", + "@ethersproject/strings": "5.7.0", + "@ethersproject/transactions": "5.7.0", + "@ethersproject/units": "5.7.0", + "@ethersproject/wallet": "5.7.0", + "@ethersproject/web": "5.7.1", + "@ethersproject/wordlists": "5.7.0" + } + }, "node_modules/@ensdomains/resolver": { "version": "0.2.4", "resolved": "https://registry.npmjs.org/@ensdomains/resolver/-/resolver-0.2.4.tgz", @@ -475,26 +529,14 @@ } }, "node_modules/@eslint/js": { - "version": "8.42.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.42.0.tgz", - "integrity": "sha512-6SWlXpWU5AvId8Ac7zjzmIOqMOba/JWY8XZ4A7q7Gn1Vlfg/SFFIlrtHXt9nPn4op9ZPAkl91Jao+QQv3r/ukw==", + "version": "8.43.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.43.0.tgz", + "integrity": "sha512-s2UHCoiXfxMvmfzqoN+vrQ84ahUSYde9qNO1MdxmoEhyHWsfmwOpFlwYV+ePJEVc7gFnATGUi376WowX1N7tFg==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, - "node_modules/@ethereum-waffle/mock-contract": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@ethereum-waffle/mock-contract/-/mock-contract-4.0.4.tgz", - "integrity": "sha512-LwEj5SIuEe9/gnrXgtqIkWbk2g15imM/qcJcxpLyAkOj981tQxXmtV4XmQMZsdedEsZ/D/rbUAOtZbgwqgUwQA==", - "dev": true, - "engines": { - "node": ">=10.0" - }, - "peerDependencies": { - "ethers": "*" - } - }, "node_modules/@ethereumjs/common": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/@ethereumjs/common/-/common-2.5.0.tgz", @@ -827,6 +869,12 @@ "scrypt-js": "3.0.1" } }, + "node_modules/@ethersproject/json-wallets/node_modules/aes-js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", + "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "dev": true + }, "node_modules/@ethersproject/keccak256": { "version": "5.7.0", "resolved": "https://registry.npmjs.org/@ethersproject/keccak256/-/keccak256-5.7.0.tgz", @@ -959,6 +1007,27 @@ "ws": "7.4.6" } }, + "node_modules/@ethersproject/providers/node_modules/ws": { + "version": "7.4.6", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.4.6.tgz", + "integrity": "sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A==", + "dev": true, + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/@ethersproject/random": { "version": "5.7.0", "resolved": "https://registry.npmjs.org/@ethersproject/random/-/random-5.7.0.tgz", @@ -1232,13 +1301,6 @@ "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" } }, - "node_modules/@graphql-tools/batch-execute/node_modules/tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - }, "node_modules/@graphql-tools/delegate": { "version": "8.8.1", "resolved": "https://registry.npmjs.org/@graphql-tools/delegate/-/delegate-8.8.1.tgz", @@ -1257,13 +1319,6 @@ "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" } }, - "node_modules/@graphql-tools/delegate/node_modules/tslib": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz", - "integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==", - "dev": true, - "optional": true - }, "node_modules/@graphql-tools/merge": { "version": "8.3.1", "resolved": "https://registry.npmjs.org/@graphql-tools/merge/-/merge-8.3.1.tgz", @@ -1278,13 +1333,6 @@ "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" } }, - "node_modules/@graphql-tools/merge/node_modules/tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - }, "node_modules/@graphql-tools/mock": { "version": "8.7.20", "resolved": "https://registry.npmjs.org/@graphql-tools/mock/-/mock-8.7.20.tgz", @@ -1345,13 +1393,6 @@ "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" } }, - "node_modules/@graphql-tools/mock/node_modules/tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - }, "node_modules/@graphql-tools/mock/node_modules/value-or-promise": { "version": "1.0.12", "resolved": "https://registry.npmjs.org/value-or-promise/-/value-or-promise-1.0.12.tgz", @@ -1378,13 +1419,6 @@ "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" } }, - "node_modules/@graphql-tools/schema/node_modules/tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - }, "node_modules/@graphql-tools/utils": { "version": "8.9.0", "resolved": "https://registry.npmjs.org/@graphql-tools/utils/-/utils-8.9.0.tgz", @@ -1398,13 +1432,6 @@ "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" } }, - "node_modules/@graphql-tools/utils/node_modules/tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - }, "node_modules/@graphql-typed-document-node/core": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/@graphql-typed-document-node/core/-/core-3.2.0.tgz", @@ -1477,18 +1504,6 @@ "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, - "node_modules/@isaacs/cliui/node_modules/ansi-styles": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", - "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", - "dev": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, "node_modules/@isaacs/cliui/node_modules/emoji-regex": { "version": "9.2.2", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", @@ -1527,23 +1542,6 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, - "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", - "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, "node_modules/@josephg/resolvable": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@josephg/resolvable/-/resolvable-1.0.1.tgz", @@ -1625,44 +1623,10 @@ "rlp": "^2.2.3" } }, - "node_modules/@morgan-stanley/ts-mocking-bird": { - "version": "0.6.4", - "resolved": "https://registry.npmjs.org/@morgan-stanley/ts-mocking-bird/-/ts-mocking-bird-0.6.4.tgz", - "integrity": "sha512-57VJIflP8eR2xXa9cD1LUawh+Gh+BVQfVu0n6GALyg/AqV/Nz25kDRvws3i9kIe1PTrbsZZOYpsYp6bXPd6nVA==", - "dev": true, - "peer": true, - "dependencies": { - "lodash": "^4.17.16", - "uuid": "^7.0.3" - }, - "peerDependencies": { - "jasmine": "2.x || 3.x || 4.x", - "jest": "26.x || 27.x || 28.x", - "typescript": ">=4.2" - }, - "peerDependenciesMeta": { - "jasmine": { - "optional": true - }, - "jest": { - "optional": true - } - } - }, - "node_modules/@morgan-stanley/ts-mocking-bird/node_modules/uuid": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-7.0.3.tgz", - "integrity": "sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==", - "dev": true, - "peer": true, - "bin": { - "uuid": "dist/bin/uuid" - } - }, "node_modules/@noble/hashes": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz", - "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.1.2.tgz", + "integrity": "sha512-KYRCASVTv6aeUi1tsF8/vpyR7zpfs3FUzy2Jqm+MU+LmUKhQ0y2FpfwqkCcxSg2ua4GALJd8k2R76WxwZGbQpA==", "dev": true, "funding": [ { @@ -1736,6 +1700,54 @@ "node": ">=14" } }, + "node_modules/@nomicfoundation/ethereumjs-block/node_modules/ethers": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.7.2.tgz", + "integrity": "sha512-wswUsmWo1aOK8rR7DIKiWSw9DbLWe6x98Jrn8wcTflTVvaXhAMaB5zGAXy0GYQEQp9iO1iSHWVyARQm11zUtyg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "dependencies": { + "@ethersproject/abi": "5.7.0", + "@ethersproject/abstract-provider": "5.7.0", + "@ethersproject/abstract-signer": "5.7.0", + "@ethersproject/address": "5.7.0", + "@ethersproject/base64": "5.7.0", + "@ethersproject/basex": "5.7.0", + "@ethersproject/bignumber": "5.7.0", + "@ethersproject/bytes": "5.7.0", + "@ethersproject/constants": "5.7.0", + "@ethersproject/contracts": "5.7.0", + "@ethersproject/hash": "5.7.0", + "@ethersproject/hdnode": "5.7.0", + "@ethersproject/json-wallets": "5.7.0", + "@ethersproject/keccak256": "5.7.0", + "@ethersproject/logger": "5.7.0", + "@ethersproject/networks": "5.7.1", + "@ethersproject/pbkdf2": "5.7.0", + "@ethersproject/properties": "5.7.0", + "@ethersproject/providers": "5.7.2", + "@ethersproject/random": "5.7.0", + "@ethersproject/rlp": "5.7.0", + "@ethersproject/sha2": "5.7.0", + "@ethersproject/signing-key": "5.7.0", + "@ethersproject/solidity": "5.7.0", + "@ethersproject/strings": "5.7.0", + "@ethersproject/transactions": "5.7.0", + "@ethersproject/units": "5.7.0", + "@ethersproject/wallet": "5.7.0", + "@ethersproject/web": "5.7.1", + "@ethersproject/wordlists": "5.7.0" + } + }, "node_modules/@nomicfoundation/ethereumjs-blockchain": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-blockchain/-/ethereumjs-blockchain-7.0.1.tgz", @@ -1832,6 +1844,54 @@ "js-sdsl": "^4.1.4" } }, + "node_modules/@nomicfoundation/ethereumjs-statemanager/node_modules/ethers": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.7.2.tgz", + "integrity": "sha512-wswUsmWo1aOK8rR7DIKiWSw9DbLWe6x98Jrn8wcTflTVvaXhAMaB5zGAXy0GYQEQp9iO1iSHWVyARQm11zUtyg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "dependencies": { + "@ethersproject/abi": "5.7.0", + "@ethersproject/abstract-provider": "5.7.0", + "@ethersproject/abstract-signer": "5.7.0", + "@ethersproject/address": "5.7.0", + "@ethersproject/base64": "5.7.0", + "@ethersproject/basex": "5.7.0", + "@ethersproject/bignumber": "5.7.0", + "@ethersproject/bytes": "5.7.0", + "@ethersproject/constants": "5.7.0", + "@ethersproject/contracts": "5.7.0", + "@ethersproject/hash": "5.7.0", + "@ethersproject/hdnode": "5.7.0", + "@ethersproject/json-wallets": "5.7.0", + "@ethersproject/keccak256": "5.7.0", + "@ethersproject/logger": "5.7.0", + "@ethersproject/networks": "5.7.1", + "@ethersproject/pbkdf2": "5.7.0", + "@ethersproject/properties": "5.7.0", + "@ethersproject/providers": "5.7.2", + "@ethersproject/random": "5.7.0", + "@ethersproject/rlp": "5.7.0", + "@ethersproject/sha2": "5.7.0", + "@ethersproject/signing-key": "5.7.0", + "@ethersproject/solidity": "5.7.0", + "@ethersproject/strings": "5.7.0", + "@ethersproject/transactions": "5.7.0", + "@ethersproject/units": "5.7.0", + "@ethersproject/wallet": "5.7.0", + "@ethersproject/web": "5.7.1", + "@ethersproject/wordlists": "5.7.0" + } + }, "node_modules/@nomicfoundation/ethereumjs-trie": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-trie/-/ethereumjs-trie-6.0.1.tgz", @@ -1923,25 +1983,38 @@ } }, "node_modules/@nomicfoundation/hardhat-chai-matchers": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-chai-matchers/-/hardhat-chai-matchers-1.0.6.tgz", - "integrity": "sha512-f5ZMNmabZeZegEfuxn/0kW+mm7+yV7VNDxLpMOMGXWFJ2l/Ct3QShujzDRF9cOkK9Ui/hbDeOWGZqyQALDXVCQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-chai-matchers/-/hardhat-chai-matchers-2.0.1.tgz", + "integrity": "sha512-qWKndseO8IPt8HiVamgEAutcBOYtX7/O6NPfe7uMNWxY2ywWaiWjDcRFuYYqxrZOMyQZl6ZuiHxbaRNctTUgLw==", "dev": true, "peer": true, "dependencies": { - "@ethersproject/abi": "^5.1.2", "@types/chai-as-promised": "^7.1.3", "chai-as-promised": "^7.1.1", "deep-eql": "^4.0.1", "ordinal": "^1.0.3" }, "peerDependencies": { - "@nomiclabs/hardhat-ethers": "^2.0.0", + "@nomicfoundation/hardhat-ethers": "^3.0.0", "chai": "^4.2.0", - "ethers": "^5.0.0", + "ethers": "^6.1.0", "hardhat": "^2.9.4" } }, + "node_modules/@nomicfoundation/hardhat-ethers": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-ethers/-/hardhat-ethers-3.0.2.tgz", + "integrity": "sha512-4Pu3OwyEvnq/gvW2IZ1Lnbcz4yCC4xqzbHze34mXkqbCwV2kHOx6jX3prFDWQ1koxtin725lAazGh9CJtTaYjg==", + "dev": true, + "peer": true, + "dependencies": { + "debug": "^4.1.1" + }, + "peerDependencies": { + "ethers": "^6.1.0", + "hardhat": "^2.0.0" + } + }, "node_modules/@nomicfoundation/hardhat-network-helpers": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-network-helpers/-/hardhat-network-helpers-1.0.8.tgz", @@ -1955,32 +2028,51 @@ } }, "node_modules/@nomicfoundation/hardhat-toolbox": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-toolbox/-/hardhat-toolbox-2.0.2.tgz", - "integrity": "sha512-vnN1AzxbvpSx9pfdRHbUzTRIXpMLPXnUlkW855VaDk6N1pwRaQ2gNzEmFAABk4lWf11E00PKwFd/q27HuwYrYg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-toolbox/-/hardhat-toolbox-3.0.0.tgz", + "integrity": "sha512-MsteDXd0UagMksqm9KvcFG6gNKYNa3GGNCy73iQ6bEasEgg2v8Qjl6XA5hjs8o5UD5A3153B6W2BIVJ8SxYUtA==", "dev": true, "peerDependencies": { - "@ethersproject/abi": "^5.4.7", - "@ethersproject/providers": "^5.4.7", - "@nomicfoundation/hardhat-chai-matchers": "^1.0.0", + "@nomicfoundation/hardhat-chai-matchers": "^2.0.0", + "@nomicfoundation/hardhat-ethers": "^3.0.0", "@nomicfoundation/hardhat-network-helpers": "^1.0.0", - "@nomiclabs/hardhat-ethers": "^2.0.0", - "@nomiclabs/hardhat-etherscan": "^3.0.0", - "@typechain/ethers-v5": "^10.1.0", - "@typechain/hardhat": "^6.1.2", + "@nomicfoundation/hardhat-verify": "^1.0.0", + "@typechain/ethers-v6": "^0.4.0", + "@typechain/hardhat": "^8.0.0", "@types/chai": "^4.2.0", "@types/mocha": ">=9.1.0", "@types/node": ">=12.0.0", "chai": "^4.2.0", - "ethers": "^5.4.7", + "ethers": "^6.4.0", "hardhat": "^2.11.0", "hardhat-gas-reporter": "^1.0.8", "solidity-coverage": "^0.8.1", "ts-node": ">=8.0.0", - "typechain": "^8.1.0", + "typechain": "^8.2.0", "typescript": ">=4.5.0" } }, + "node_modules/@nomicfoundation/hardhat-verify": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-verify/-/hardhat-verify-1.0.2.tgz", + "integrity": "sha512-IBEWGY9EtXhVTChTmA83m/Nd9VZ/u/bCU2SZkF6c01QbQB7qcimzY1V35hiFcpJLVZ39rV8J2rmedVdfXB+99w==", + "dev": true, + "peer": true, + "dependencies": { + "@ethersproject/abi": "^5.1.2", + "@ethersproject/address": "^5.0.2", + "cbor": "^8.1.0", + "chalk": "^2.4.2", + "debug": "^4.1.1", + "lodash.clonedeep": "^4.5.0", + "semver": "^6.3.0", + "table": "^6.8.0", + "undici": "^5.14.0" + }, + "peerDependencies": { + "hardhat": "^2.0.4" + } + }, "node_modules/@nomicfoundation/solidity-analyzer": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/@nomicfoundation/solidity-analyzer/-/solidity-analyzer-0.1.1.tgz", @@ -2162,39 +2254,6 @@ "node": ">= 10" } }, - "node_modules/@nomiclabs/hardhat-ethers": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@nomiclabs/hardhat-ethers/-/hardhat-ethers-2.2.3.tgz", - "integrity": "sha512-YhzPdzb612X591FOe68q+qXVXGG2ANZRvDo0RRUtimev85rCrAlv/TLMEZw5c+kq9AbzocLTVX/h2jVIFPL9Xg==", - "dev": true, - "peer": true, - "peerDependencies": { - "ethers": "^5.0.0", - "hardhat": "^2.0.0" - } - }, - "node_modules/@nomiclabs/hardhat-etherscan": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/@nomiclabs/hardhat-etherscan/-/hardhat-etherscan-3.1.7.tgz", - "integrity": "sha512-tZ3TvSgpvsQ6B6OGmo1/Au6u8BrAkvs1mIC/eURA3xgIfznUZBhmpne8hv7BXUzw9xNL3fXdpOYgOQlVMTcoHQ==", - "dev": true, - "peer": true, - "dependencies": { - "@ethersproject/abi": "^5.1.2", - "@ethersproject/address": "^5.0.2", - "cbor": "^8.1.0", - "chalk": "^2.4.2", - "debug": "^4.1.1", - "fs-extra": "^7.0.1", - "lodash": "^4.17.11", - "semver": "^6.3.0", - "table": "^6.8.0", - "undici": "^5.14.0" - }, - "peerDependencies": { - "hardhat": "^2.0.4" - } - }, "node_modules/@nomiclabs/hardhat-web3": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@nomiclabs/hardhat-web3/-/hardhat-web3-2.0.0.tgz", @@ -2233,9 +2292,9 @@ } }, "node_modules/@openzeppelin/contracts": { - "version": "4.9.0", - "resolved": "https://registry.npmjs.org/@openzeppelin/contracts/-/contracts-4.9.0.tgz", - "integrity": "sha512-DUP74AFGKlic2sQb/CmgrN2aUPMFGxRrmCTUxLHsiU2RzwWqVuMPZBxiAyvlff6Pea77uylAX6B5x9W6evEbhA==" + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@openzeppelin/contracts/-/contracts-4.9.2.tgz", + "integrity": "sha512-mO+y6JaqXjWeMh9glYVzVu8HYPGknAAnWyxTRhGeckOruyXQMNnlcW6w/Dx9ftLeIQk6N+ZJFuVmTwF7lEIFrg==" }, "node_modules/@openzeppelin/contracts-upgradeable": { "version": "4.9.0", @@ -2465,6 +2524,18 @@ "@scure/base": "~1.1.0" } }, + "node_modules/@scure/bip32/node_modules/@noble/hashes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz", + "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ] + }, "node_modules/@scure/bip39": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.1.1.tgz", @@ -2481,6 +2552,18 @@ "@scure/base": "~1.1.0" } }, + "node_modules/@scure/bip39/node_modules/@noble/hashes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz", + "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ] + }, "node_modules/@sentry/core": { "version": "5.30.0", "resolved": "https://registry.npmjs.org/@sentry/core/-/core-5.30.0.tgz", @@ -2497,6 +2580,12 @@ "node": ">=6" } }, + "node_modules/@sentry/core/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, "node_modules/@sentry/hub": { "version": "5.30.0", "resolved": "https://registry.npmjs.org/@sentry/hub/-/hub-5.30.0.tgz", @@ -2511,6 +2600,12 @@ "node": ">=6" } }, + "node_modules/@sentry/hub/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, "node_modules/@sentry/minimal": { "version": "5.30.0", "resolved": "https://registry.npmjs.org/@sentry/minimal/-/minimal-5.30.0.tgz", @@ -2525,6 +2620,12 @@ "node": ">=6" } }, + "node_modules/@sentry/minimal/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, "node_modules/@sentry/node": { "version": "5.30.0", "resolved": "https://registry.npmjs.org/@sentry/node/-/node-5.30.0.tgz", @@ -2545,6 +2646,12 @@ "node": ">=6" } }, + "node_modules/@sentry/node/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, "node_modules/@sentry/tracing": { "version": "5.30.0", "resolved": "https://registry.npmjs.org/@sentry/tracing/-/tracing-5.30.0.tgz", @@ -2561,6 +2668,12 @@ "node": ">=6" } }, + "node_modules/@sentry/tracing/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, "node_modules/@sentry/types": { "version": "5.30.0", "resolved": "https://registry.npmjs.org/@sentry/types/-/types-5.30.0.tgz", @@ -2583,6 +2696,12 @@ "node": ">=6" } }, + "node_modules/@sentry/utils/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, "node_modules/@sindresorhus/is": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", @@ -2629,9 +2748,9 @@ } }, "node_modules/@truffle/blockchain-utils": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@truffle/blockchain-utils/-/blockchain-utils-0.1.7.tgz", - "integrity": "sha512-1nibqGjEHC7KAyDThEFvbm2+EO8zAHee/VjCtxkYBE3ySwP50joh0QCEBjy7K/9z+icpMoDucfxmgaKToBFUgQ==", + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/@truffle/blockchain-utils/-/blockchain-utils-0.1.8.tgz", + "integrity": "sha512-ZskpYDNHkXD3ota4iU3pZz6kLth87RC+wDn66Rp2Or+DqqJCKdnmS9GDctBi1EcMPDEi0BqpkdrfBuzA9uIkGg==", "dev": true }, "node_modules/@truffle/code-utils": { @@ -2675,9 +2794,9 @@ } }, "node_modules/@truffle/codec": { - "version": "0.15.2", - "resolved": "https://registry.npmjs.org/@truffle/codec/-/codec-0.15.2.tgz", - "integrity": "sha512-rLLy1RmDq3stE1Bd6cnPO9kGpoB5QE4caY665ghmAURqlqD0ik1Bhbfi4MIRwM7YVx2sYw485qsxfPzlewnT4g==", + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@truffle/codec/-/codec-0.16.0.tgz", + "integrity": "sha512-cAX2mnkEhvcjG75JvOPvepMZmGSooOYtQpVMJIIGVp1x2B1V9aE+A5tqLEAr0idkFGCthGMvF/FfMRUQ/rWZMw==", "dev": true, "dependencies": { "@truffle/abi-utils": "^1.0.1", @@ -2687,7 +2806,7 @@ "cbor": "^5.2.0", "debug": "^4.3.1", "lodash": "^4.17.21", - "semver": "7.3.7", + "semver": "7.5.2", "utf8": "^3.0.0", "web3-utils": "1.10.0" } @@ -2736,9 +2855,9 @@ } }, "node_modules/@truffle/codec/node_modules/semver": { - "version": "7.3.7", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", - "integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.2.tgz", + "integrity": "sha512-SoftuTROv/cRjCze/scjGyiDtcUyxw1rgYQSZY7XTmtR5hX+dm76iDbTH8TkLPHCQmlbQVSSbNZCPM2hb0knnQ==", "dev": true, "dependencies": { "lru-cache": "^6.0.0" @@ -2767,9 +2886,9 @@ } }, "node_modules/@truffle/config": { - "version": "1.3.57", - "resolved": "https://registry.npmjs.org/@truffle/config/-/config-1.3.57.tgz", - "integrity": "sha512-Cfude7ZMT2pykvMoHZ/47MvlVoZDQLs+Y85ChRw/1RKWsHrzz1BOyjDmnPLnSTOc056OuNOcgID1IdUMorVOIQ==", + "version": "1.3.58", + "resolved": "https://registry.npmjs.org/@truffle/config/-/config-1.3.58.tgz", + "integrity": "sha512-M6e7dAx6QMMskhwpqpOE4dAj72HapcMPtw/7c6bssCZd/E1quyAs/CpiYGDIxp2EuZHxW/9X16VzIac8sIOW7w==", "dev": true, "optional": true, "dependencies": { @@ -2857,17 +2976,17 @@ } }, "node_modules/@truffle/contract": { - "version": "4.6.22", - "resolved": "https://registry.npmjs.org/@truffle/contract/-/contract-4.6.22.tgz", - "integrity": "sha512-081tM5CBBLgTQX0Fhzp0nlZHnfgojRXweV7/d6v7LHe6QGrGBmgvUy3EIbO+R3P1uaxeGVijMvB4Ok8md9IpYQ==", + "version": "4.6.25", + "resolved": "https://registry.npmjs.org/@truffle/contract/-/contract-4.6.25.tgz", + "integrity": "sha512-eDyJx1Yap3e7J4iTKOUKYqUaO/wCayBqBaJnQmqW57LeOVkBQnqwOSNvFFxjcbOlRXGoLFFlTkxDa9lGcLVM7Q==", "dev": true, "dependencies": { "@ensdomains/ensjs": "^2.1.0", - "@truffle/blockchain-utils": "^0.1.7", + "@truffle/blockchain-utils": "^0.1.8", "@truffle/contract-schema": "^3.4.14", - "@truffle/debug-utils": "^6.0.50", - "@truffle/error": "^0.2.0", - "@truffle/interface-adapter": "^0.5.33", + "@truffle/debug-utils": "^6.0.53", + "@truffle/error": "^0.2.1", + "@truffle/interface-adapter": "^0.5.34", "bignumber.js": "^7.2.1", "debug": "^4.3.1", "ethers": "^4.0.32", @@ -2888,6 +3007,12 @@ "debug": "^4.3.1" } }, + "node_modules/@truffle/contract/node_modules/aes-js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", + "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "dev": true + }, "node_modules/@truffle/contract/node_modules/bn.js": { "version": "4.12.0", "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", @@ -2964,6 +3089,28 @@ "ws": "^7.2.0" } }, + "node_modules/@truffle/dashboard-message-bus-client/node_modules/ws": { + "version": "7.5.9", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz", + "integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==", + "dev": true, + "optional": true, + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/@truffle/dashboard-message-bus-common": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/@truffle/dashboard-message-bus-common/-/dashboard-message-bus-common-0.1.6.tgz", @@ -2972,9 +3119,9 @@ "optional": true }, "node_modules/@truffle/db": { - "version": "2.0.28", - "resolved": "https://registry.npmjs.org/@truffle/db/-/db-2.0.28.tgz", - "integrity": "sha512-R9FfBeVxd/SEIdw6IrMwg2vLMNXuiHMJ5XwW7ivCSyNMYXesJMA85fWYPe9bWyJ8eufLOAWlX8xr55vua4DwZQ==", + "version": "2.0.30", + "resolved": "https://registry.npmjs.org/@truffle/db/-/db-2.0.30.tgz", + "integrity": "sha512-vbOt7r3ybmoo3xZjyTyWe9SC98b6JcMeOpmi59Trdxwp+h3Lo9wdqdvv4595QxwDwzHvISSFTJRGKNDMtRD2rg==", "dev": true, "optional": true, "dependencies": { @@ -2982,7 +3129,7 @@ "@graphql-tools/schema": "^8.3.1", "@truffle/abi-utils": "^1.0.1", "@truffle/code-utils": "^3.0.3", - "@truffle/config": "^1.3.57", + "@truffle/config": "^1.3.58", "abstract-leveldown": "^7.2.0", "apollo-server": "^3.11.0", "debug": "^4.3.1", @@ -3000,12 +3147,12 @@ } }, "node_modules/@truffle/db-loader": { - "version": "0.2.28", - "resolved": "https://registry.npmjs.org/@truffle/db-loader/-/db-loader-0.2.28.tgz", - "integrity": "sha512-oVXQXtYhM3Mu/pnfLR5KoqqEdw6GO6FDAFM7zZm647mIAtXCqv+EYSNt3efyqsFgQZwv3UZY6KP8TMxnjeWWGA==", + "version": "0.2.30", + "resolved": "https://registry.npmjs.org/@truffle/db-loader/-/db-loader-0.2.30.tgz", + "integrity": "sha512-dQv8Q/JY+toSgOH5kHzVhEt1Ig6Wg0onn219qo2terL8xX5g5Ia2mM0Pg82Ba+B8ZCkCnz+kYC/htscF8d6ugw==", "dev": true, "optionalDependencies": { - "@truffle/db": "^2.0.28" + "@truffle/db": "^2.0.30" } }, "node_modules/@truffle/db/node_modules/fs-extra": { @@ -3048,12 +3195,12 @@ } }, "node_modules/@truffle/debug-utils": { - "version": "6.0.50", - "resolved": "https://registry.npmjs.org/@truffle/debug-utils/-/debug-utils-6.0.50.tgz", - "integrity": "sha512-OWdSoOsPW7/jvcO7ASBRzXDzXQNb7dg8UqwoBAI7j7UpdQoCAhz7JQsusSNiFN6g1qrxEpGzeh5iIMDq9WxO3w==", + "version": "6.0.53", + "resolved": "https://registry.npmjs.org/@truffle/debug-utils/-/debug-utils-6.0.53.tgz", + "integrity": "sha512-czfIjw41UA7eEX0Z660JAQkxyqjr4+B/ecDHFia/feIprLAdFz3VDuhqf/zoMnrKczqS2qbMtnknExgbbrH+eg==", "dev": true, "dependencies": { - "@truffle/codec": "^0.15.1", + "@truffle/codec": "^0.16.0", "@trufflesuite/chromafi": "^3.0.0", "bn.js": "^5.1.3", "chalk": "^2.4.2", @@ -3062,15 +3209,15 @@ } }, "node_modules/@truffle/debugger": { - "version": "11.1.4", - "resolved": "https://registry.npmjs.org/@truffle/debugger/-/debugger-11.1.4.tgz", - "integrity": "sha512-dWpf89fHZYaW/18x1ZfQhZozg3hZqxz7Czd6vIWVQc3OiV59xpA0+YLm+aumrebj6vmjqzGWu+iHfCaLiYhwQA==", + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@truffle/debugger/-/debugger-12.0.0.tgz", + "integrity": "sha512-ICJPM4R2VjwWJI85r7R2TzmmL0VqZoCdPyFJ1JXYXhK/gmuRyPHb0wmSALgu4edXyyauN4ekDc2qi/lX/oU/hg==", "dev": true, "dependencies": { "@ensdomains/ensjs": "^2.1.0", "@truffle/abi-utils": "^1.0.1", - "@truffle/codec": "^0.15.2", - "@truffle/source-map-utils": "^1.3.113", + "@truffle/codec": "^0.16.0", + "@truffle/source-map-utils": "^1.3.115", "bn.js": "^5.1.3", "debug": "^4.3.1", "json-pointer": "^0.6.1", @@ -3079,7 +3226,7 @@ "redux": "^3.7.2", "redux-saga": "1.0.0", "reselect-tree": "^1.3.7", - "semver": "7.3.7", + "semver": "7.5.2", "web3": "1.10.0", "web3-eth-abi": "1.10.0" } @@ -3097,9 +3244,9 @@ } }, "node_modules/@truffle/debugger/node_modules/semver": { - "version": "7.3.7", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", - "integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.2.tgz", + "integrity": "sha512-SoftuTROv/cRjCze/scjGyiDtcUyxw1rgYQSZY7XTmtR5hX+dm76iDbTH8TkLPHCQmlbQVSSbNZCPM2hb0knnQ==", "dev": true, "dependencies": { "lru-cache": "^6.0.0" @@ -3148,6 +3295,12 @@ "web3": "1.10.0" } }, + "node_modules/@truffle/interface-adapter/node_modules/aes-js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", + "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "dev": true + }, "node_modules/@truffle/interface-adapter/node_modules/ethers": { "version": "4.0.49", "resolved": "https://registry.npmjs.org/ethers/-/ethers-4.0.49.tgz", @@ -3227,13 +3380,13 @@ } }, "node_modules/@truffle/source-map-utils": { - "version": "1.3.113", - "resolved": "https://registry.npmjs.org/@truffle/source-map-utils/-/source-map-utils-1.3.113.tgz", - "integrity": "sha512-lzsocqZC0HIJYrPe+V3mSi9Pv0gu9vh8ETZJKe+8lr3prbeWEXeqZYXF+HI8Qw70cPE7or6L5A9d+wGVei5KNA==", + "version": "1.3.115", + "resolved": "https://registry.npmjs.org/@truffle/source-map-utils/-/source-map-utils-1.3.115.tgz", + "integrity": "sha512-NUOj45yLkMjv0x376N4ibgPh9pIp2rMKd2HxmXRbbIv3VHy18WPtgbW7+fkll/rAeTYhXzcyvwu67+dtgVholw==", "dev": true, "dependencies": { "@truffle/code-utils": "^3.0.3", - "@truffle/codec": "^0.15.2", + "@truffle/codec": "^0.16.0", "debug": "^4.3.1", "json-pointer": "^0.6.1", "node-interval-tree": "^1.3.3", @@ -3405,10 +3558,10 @@ "dev": true, "peer": true }, - "node_modules/@typechain/ethers-v5": { - "version": "10.2.1", - "resolved": "https://registry.npmjs.org/@typechain/ethers-v5/-/ethers-v5-10.2.1.tgz", - "integrity": "sha512-n3tQmCZjRE6IU4h6lqUGiQ1j866n5MTCBJreNEHHVWXa2u9GJTaeYyU1/k+1qLutkyw+sS6VAN+AbeiTqsxd/A==", + "node_modules/@typechain/ethers-v6": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@typechain/ethers-v6/-/ethers-v6-0.4.0.tgz", + "integrity": "sha512-vD3Agzz63Gf2XlU3ed2/y+8dLWQj+wf+4Eq+0JXsyOio/plyV5F6r0yYe+s3XdGI858U3Sr263pl8mliDrUqbw==", "dev": true, "peer": true, "dependencies": { @@ -3416,29 +3569,25 @@ "ts-essentials": "^7.0.1" }, "peerDependencies": { - "@ethersproject/abi": "^5.0.0", - "@ethersproject/providers": "^5.0.0", - "ethers": "^5.1.3", - "typechain": "^8.1.1", - "typescript": ">=4.3.0" + "ethers": "6.x", + "typechain": "^8.2.0", + "typescript": ">=4.7.0" } }, "node_modules/@typechain/hardhat": { - "version": "6.1.6", - "resolved": "https://registry.npmjs.org/@typechain/hardhat/-/hardhat-6.1.6.tgz", - "integrity": "sha512-BiVnegSs+ZHVymyidtK472syodx1sXYlYJJixZfRstHVGYTi8V1O7QG4nsjyb0PC/LORcq7sfBUcHto1y6UgJA==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@typechain/hardhat/-/hardhat-8.0.0.tgz", + "integrity": "sha512-XUVbqlMx8tJTOmzZCD/r196CidtNWAnTBZRcYxjLTKgcJMvc/kHQpWBnVMMB5QHxVKpYpCiz8g07FYCpG8rrjA==", "dev": true, "peer": true, "dependencies": { "fs-extra": "^9.1.0" }, "peerDependencies": { - "@ethersproject/abi": "^5.4.7", - "@ethersproject/providers": "^5.4.7", - "@typechain/ethers-v5": "^10.2.1", - "ethers": "^5.4.7", + "@typechain/ethers-v6": "^0.4.0", + "ethers": "^6.1.0", "hardhat": "^2.9.9", - "typechain": "^8.1.1" + "typechain": "^8.2.0" } }, "node_modules/@typechain/hardhat/node_modules/fs-extra": { @@ -3629,6 +3778,13 @@ "integrity": "sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ==", "dev": true }, + "node_modules/@types/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-/K3ds8TRAfBvi5vfjuz8y6+GiAYBZ0x4tXv1Av6CWBWn0IlADc+ZX9pMq7oU0fNQPnBwIZl3rmeLp6SBApbxSQ==", + "dev": true, + "optional": true + }, "node_modules/@types/keyv": { "version": "3.1.4", "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz", @@ -3679,9 +3835,9 @@ "peer": true }, "node_modules/@types/node": { - "version": "20.2.5", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.2.5.tgz", - "integrity": "sha512-JJulVEQXmiY9Px5axXHeYGLSjhkZEnD+MDPDGbCbIAbMslkKwmygtZFy1X6s/075Yo94sf8GuSlFfPzysQrWZQ==", + "version": "20.3.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.2.tgz", + "integrity": "sha512-vOBLVQeCQfIcF/2Y7eKFTqrMnizK5lRNQ7ykML/5RuwVXVWxYkgwS7xbt4B6fKCUPgbSL5FSsjHQpaGQP/dQmw==", "dev": true }, "node_modules/@types/normalize-package-data": { @@ -3700,9 +3856,9 @@ } }, "node_modules/@types/prettier": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", - "integrity": "sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg==", + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.3.tgz", + "integrity": "sha512-+68kP9yzs4LMp7VNh8gdzMSPZFL44MLGqiHWvttYJe+6qnuVr4Ek9wSBQoveqY/r+LwjCcU29kNVkidwim+kYA==", "dev": true, "peer": true }, @@ -3765,12 +3921,13 @@ } }, "node_modules/@types/serve-static": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.1.tgz", - "integrity": "sha512-NUo5XNiAdULrJENtJXZZ3fHtfMolzZwczzBbnAeBbqBwG+LaG6YaJtuwzwGSQZ2wsCrxjEhNNjAkKigy3n8teQ==", + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.2.tgz", + "integrity": "sha512-J2LqtvFYCzaj8pVYKw8klQXrLLk7TBZmQ4ShlcdkELFKGwGMfevMLneMMRkMgZxotOD9wg497LpC7O8PcvAmfw==", "dev": true, "optional": true, "dependencies": { + "@types/http-errors": "*", "@types/mime": "*", "@types/node": "*" } @@ -3909,9 +4066,9 @@ } }, "node_modules/acorn": { - "version": "8.8.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", - "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.9.0.tgz", + "integrity": "sha512-jaVNAFBHNLXspO543WnNNPZFRtavh3skAkITqD0/2aeMkKZTN+254PyhwxFYrk3vQ1xfY+2wbesJMs/JC8/PwQ==", "dev": true, "bin": { "acorn": "bin/acorn" @@ -3959,9 +4116,9 @@ } }, "node_modules/aes-js": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", - "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "version": "4.0.0-beta.5", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.5.tgz", + "integrity": "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q==", "dev": true }, "node_modules/agent-base": { @@ -5045,9 +5202,9 @@ } }, "node_modules/cacheable-request": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.2.tgz", - "integrity": "sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew==", + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz", + "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==", "dev": true, "dependencies": { "clone-response": "^1.0.2", @@ -5497,6 +5654,39 @@ "node": ">=8" } }, + "node_modules/cliui/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/cliui/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/cliui/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, "node_modules/cliui/node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -5509,6 +5699,23 @@ "node": ">=8" } }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/clone-buffer": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/clone-buffer/-/clone-buffer-1.0.0.tgz", @@ -5771,9 +5978,9 @@ } }, "node_modules/conf/node_modules/semver": { - "version": "7.5.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz", - "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==", + "version": "7.5.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", + "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", "dev": true, "optional": true, "dependencies": { @@ -5870,9 +6077,9 @@ } }, "node_modules/cosmiconfig": { - "version": "8.1.3", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.1.3.tgz", - "integrity": "sha512-/UkO2JKI18b5jVMJUp0lvKFMpa/Gye+ZgZjKD+DGEN9y7NRcf/nK1A0sp67ONmKtnDCNMS44E6jrk0Yc3bDuUw==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.2.0.tgz", + "integrity": "sha512-3rTMnFJA1tCOPwRxtgF4wd7Ab2qvDbL8jX+3smjIbS4HlZBagTlpERbdN7iAbWlrfxE3M8c27kTwTawQ7st+OQ==", "dev": true, "dependencies": { "import-fresh": "^3.2.1", @@ -6132,9 +6339,9 @@ } }, "node_modules/decache": { - "version": "4.6.1", - "resolved": "https://registry.npmjs.org/decache/-/decache-4.6.1.tgz", - "integrity": "sha512-ohApBM8u9ygepJCjgBrEZSSxPjc0T/PJkD+uNyxXPkqudyUpdXpwJYp0VISm2WrPVzASU6DZyIi6BWdyw7uJ2Q==", + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/decache/-/decache-4.6.2.tgz", + "integrity": "sha512-2LPqkLeu8XWHU8qNCS3kcF6sCcb5zIzvWaAHYSvPfwhdd7mHuah29NssMzrTYyHN4F5oFy2ko9OBYxegtU0FEw==", "dev": true, "dependencies": { "callsite": "^1.0.0" @@ -6517,9 +6724,9 @@ } }, "node_modules/dotenv": { - "version": "16.3.0", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.0.tgz", - "integrity": "sha512-tHB+hmf8MRCkT3VVivGiG8kq9HiGTmQ3FzOKgztfpJQH1IWuZTOvKSJmHNnQPowecAmkCJhLrxdPhOr06LLqIQ==", + "version": "16.3.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz", + "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==", "dev": true, "engines": { "node": ">=12" @@ -7034,15 +7241,15 @@ } }, "node_modules/eslint": { - "version": "8.42.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.42.0.tgz", - "integrity": "sha512-ulg9Ms6E1WPf67PHaEY4/6E2tEn5/f7FXGzr3t9cBMugOmf1INYvuUwwh1aXQN4MfJ6a5K2iNwP3w4AColvI9A==", + "version": "8.43.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.43.0.tgz", + "integrity": "sha512-aaCpf2JqqKesMFGgmRPessmVKjcGXqdlAYLLC3THM8t5nBRZRQ+st5WM/hoJXkdioEXLLbXgclUpM0TXo5HX5Q==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.4.0", "@eslint/eslintrc": "^2.0.3", - "@eslint/js": "8.42.0", + "@eslint/js": "8.43.0", "@humanwhocodes/config-array": "^0.11.10", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", @@ -7449,6 +7656,26 @@ } } }, + "node_modules/eth-gas-reporter/node_modules/@noble/hashes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz", + "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "peer": true + }, + "node_modules/eth-gas-reporter/node_modules/aes-js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", + "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "dev": true, + "peer": true + }, "node_modules/eth-gas-reporter/node_modules/ansi-colors": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-3.2.3.tgz", @@ -8162,9 +8389,9 @@ } }, "node_modules/ethereum-input-data-decoder/node_modules/@types/node": { - "version": "16.18.34", - "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.34.tgz", - "integrity": "sha512-VmVm7gXwhkUimRfBwVI1CHhwp86jDWR04B5FGebMMyxV90SlCmFujwUHrxTD4oO+SOYU86SoxvhgeRQJY7iXFg==", + "version": "16.18.37", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.37.tgz", + "integrity": "sha512-ql+4dw4PlPFBP495k8JzUX/oMNRI2Ei4PrMHgj8oT4VhGlYUzF4EYr0qk2fW+XBVGIrq8Zzk13m4cvyXZuv4pA==", "dev": true }, "node_modules/ethereum-input-data-decoder/node_modules/bn.js": { @@ -8173,6 +8400,54 @@ "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", "dev": true }, + "node_modules/ethereum-input-data-decoder/node_modules/ethers": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.7.2.tgz", + "integrity": "sha512-wswUsmWo1aOK8rR7DIKiWSw9DbLWe6x98Jrn8wcTflTVvaXhAMaB5zGAXy0GYQEQp9iO1iSHWVyARQm11zUtyg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "dependencies": { + "@ethersproject/abi": "5.7.0", + "@ethersproject/abstract-provider": "5.7.0", + "@ethersproject/abstract-signer": "5.7.0", + "@ethersproject/address": "5.7.0", + "@ethersproject/base64": "5.7.0", + "@ethersproject/basex": "5.7.0", + "@ethersproject/bignumber": "5.7.0", + "@ethersproject/bytes": "5.7.0", + "@ethersproject/constants": "5.7.0", + "@ethersproject/contracts": "5.7.0", + "@ethersproject/hash": "5.7.0", + "@ethersproject/hdnode": "5.7.0", + "@ethersproject/json-wallets": "5.7.0", + "@ethersproject/keccak256": "5.7.0", + "@ethersproject/logger": "5.7.0", + "@ethersproject/networks": "5.7.1", + "@ethersproject/pbkdf2": "5.7.0", + "@ethersproject/properties": "5.7.0", + "@ethersproject/providers": "5.7.2", + "@ethersproject/random": "5.7.0", + "@ethersproject/rlp": "5.7.0", + "@ethersproject/sha2": "5.7.0", + "@ethersproject/signing-key": "5.7.0", + "@ethersproject/solidity": "5.7.0", + "@ethersproject/strings": "5.7.0", + "@ethersproject/transactions": "5.7.0", + "@ethersproject/units": "5.7.0", + "@ethersproject/wallet": "5.7.0", + "@ethersproject/web": "5.7.1", + "@ethersproject/wordlists": "5.7.0" + } + }, "node_modules/ethereumjs-abi": { "version": "0.6.8", "resolved": "https://registry.npmjs.org/ethereumjs-abi/-/ethereumjs-abi-0.6.8.tgz", @@ -8230,14 +8505,14 @@ } }, "node_modules/ethers": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.7.2.tgz", - "integrity": "sha512-wswUsmWo1aOK8rR7DIKiWSw9DbLWe6x98Jrn8wcTflTVvaXhAMaB5zGAXy0GYQEQp9iO1iSHWVyARQm11zUtyg==", + "version": "6.6.1", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.6.1.tgz", + "integrity": "sha512-bjNPf/EU4l1jQlAslOmOlyHqjOnM0W7LRPuSf0Kt0tYV4RpUEZsdGWDhvFXfogIhfzXJ/v2tPz4HqXwBt5T8mA==", "dev": true, "funding": [ { "type": "individual", - "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + "url": "https://github.com/sponsors/ethers-io/" }, { "type": "individual", @@ -8245,38 +8520,24 @@ } ], "dependencies": { - "@ethersproject/abi": "5.7.0", - "@ethersproject/abstract-provider": "5.7.0", - "@ethersproject/abstract-signer": "5.7.0", - "@ethersproject/address": "5.7.0", - "@ethersproject/base64": "5.7.0", - "@ethersproject/basex": "5.7.0", - "@ethersproject/bignumber": "5.7.0", - "@ethersproject/bytes": "5.7.0", - "@ethersproject/constants": "5.7.0", - "@ethersproject/contracts": "5.7.0", - "@ethersproject/hash": "5.7.0", - "@ethersproject/hdnode": "5.7.0", - "@ethersproject/json-wallets": "5.7.0", - "@ethersproject/keccak256": "5.7.0", - "@ethersproject/logger": "5.7.0", - "@ethersproject/networks": "5.7.1", - "@ethersproject/pbkdf2": "5.7.0", - "@ethersproject/properties": "5.7.0", - "@ethersproject/providers": "5.7.2", - "@ethersproject/random": "5.7.0", - "@ethersproject/rlp": "5.7.0", - "@ethersproject/sha2": "5.7.0", - "@ethersproject/signing-key": "5.7.0", - "@ethersproject/solidity": "5.7.0", - "@ethersproject/strings": "5.7.0", - "@ethersproject/transactions": "5.7.0", - "@ethersproject/units": "5.7.0", - "@ethersproject/wallet": "5.7.0", - "@ethersproject/web": "5.7.1", - "@ethersproject/wordlists": "5.7.0" + "@adraffy/ens-normalize": "1.9.2", + "@noble/hashes": "1.1.2", + "@noble/secp256k1": "1.7.1", + "@types/node": "18.15.13", + "aes-js": "4.0.0-beta.5", + "tslib": "2.4.0", + "ws": "8.5.0" + }, + "engines": { + "node": ">=14.0.0" } }, + "node_modules/ethers/node_modules/@types/node": { + "version": "18.15.13", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.13.tgz", + "integrity": "sha512-N+0kuo9KgrUQ1Sn/ifDXsvg0TTleP7rIy4zOBGECxAljqvqfqpTfzx0Q1NUedOixRMBfe2Whhb056a42cWs26Q==", + "dev": true + }, "node_modules/ethjs-abi": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/ethjs-abi/-/ethjs-abi-0.2.1.tgz", @@ -8803,18 +9064,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/foreground-child/node_modules/signal-exit": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.0.2.tgz", - "integrity": "sha512-MY2/qGx4enyjprQnFaZsHib3Yadh3IXyV2C321GY0pjGfVBu4un0uDJkwgdxqO+Rdx8JMT8IfJIRwbYVz3Ob3Q==", - "dev": true, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/forever-agent": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", @@ -9663,9 +9912,9 @@ } }, "node_modules/glob": { - "version": "10.2.7", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.2.7.tgz", - "integrity": "sha512-jTKehsravOJo8IJxUGfZILnkvVJM/MOfHRs8QcXolVef2zNI9Tqyy5+SeuOAZd3upViEZQLyFpQhYiHLrMUNmA==", + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.3.0.tgz", + "integrity": "sha512-AQ1/SB9HH0yCx1jXAT4vmCbTOPe5RQ+kCurjbel5xSCGhebumUv+GJZfa1rEqor3XIViqwSEmlkZCQD43RWrBg==", "dev": true, "dependencies": { "foreground-child": "^3.1.0", @@ -9706,9 +9955,9 @@ } }, "node_modules/glob/node_modules/minimatch": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.1.tgz", - "integrity": "sha512-0jWhJpD/MdhPXwPuiRkCbfYfSKp2qnn2eOc279qI7f+osl/l+prKSrvhg157zSYvx/1nmgn2NqdT6k2Z7zSH9w==", + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.2.tgz", + "integrity": "sha512-PZOT9g5v2ojiTL7r1xF6plNHLtOeTpSlDI007As2NlA2aYBMfVom17yqa6QzhmDP8QOhn7LjHTg7DFCVSSa6yg==", "dev": true, "dependencies": { "brace-expansion": "^2.0.1" @@ -9920,13 +10169,6 @@ "graphql": "^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0" } }, - "node_modules/graphql-tag/node_modules/tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - }, "node_modules/growl": { "version": "1.10.5", "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz", @@ -10002,9 +10244,9 @@ } }, "node_modules/hardhat": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/hardhat/-/hardhat-2.14.1.tgz", - "integrity": "sha512-H3Qp/UKyQGmPDDBSfMoSyH18rRnac90rsb0LNer+sKe6at6rxLe4D5j+M+1icqZQF02iLPjNRwc/PA8OPf757A==", + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/hardhat/-/hardhat-2.16.0.tgz", + "integrity": "sha512-7VQEJPQRAZdtrYUZaU9GgCpP3MBNy/pTdscARNJQMWKj5C+R7V32G5uIZKIqZ4QiqXa6CBfxxe+G+ahxUbHZHA==", "dev": true, "dependencies": { "@ethersproject/abi": "^5.1.2", @@ -10046,7 +10288,6 @@ "mnemonist": "^0.38.0", "mocha": "^10.0.0", "p-map": "^4.0.0", - "qs": "^6.7.0", "raw-body": "^2.4.1", "resolve": "1.17.0", "semver": "^6.3.0", @@ -10078,9 +10319,9 @@ } }, "node_modules/hardhat-contract-sizer": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/hardhat-contract-sizer/-/hardhat-contract-sizer-2.9.0.tgz", - "integrity": "sha512-0I5lJo0iVPfK3YQNRv+zF4KHcdPbXPp9VCCOTcpDK/mfjWHiPxQwZv7eVt9S1JjvegjAVRtJPe9U5zQtd8LJGA==", + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/hardhat-contract-sizer/-/hardhat-contract-sizer-2.10.0.tgz", + "integrity": "sha512-QiinUgBD5MqJZJh1hl1jc9dNnpJg7eE/w4/4GEnrcmZJJTDbVFNe3+/3Ep24XqISSkYxRz36czcPHKHd/a0dwA==", "dev": true, "dependencies": { "chalk": "^4.0.0", @@ -10209,6 +10450,18 @@ "hardhat": "^2.0.5" } }, + "node_modules/hardhat/node_modules/@noble/hashes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz", + "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ] + }, "node_modules/hardhat/node_modules/commander": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/commander/-/commander-3.0.2.tgz", @@ -10389,6 +10642,27 @@ "semver": "bin/semver" } }, + "node_modules/hardhat/node_modules/ws": { + "version": "7.5.9", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz", + "integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==", + "dev": true, + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", @@ -11372,9 +11646,9 @@ } }, "node_modules/js-sdsl": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.4.0.tgz", - "integrity": "sha512-FfVSdx6pJ41Oa+CF7RDaFmTnCaFhua+SNYQX74riGOpl96x+2jQCqEfQ2bnXu/5DPCqlRuiqyvTJM0Qjz26IVg==", + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.4.1.tgz", + "integrity": "sha512-6Gsx8R0RucyePbWqPssR8DyfuXmLBooYN5cZFZKjHGnQuaf7pEzhtpceagJxVu4LqhYY5EYA7nko3FmeHZ1KbA==", "dev": true, "funding": { "type": "opencollective", @@ -11992,6 +12266,13 @@ "dev": true, "peer": true }, + "node_modules/lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==", + "dev": true, + "peer": true + }, "node_modules/lodash.flatten": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", @@ -13090,9 +13371,9 @@ } }, "node_modules/normalize-package-data/node_modules/semver": { - "version": "7.5.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz", - "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==", + "version": "7.5.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", + "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", "dev": true, "dependencies": { "lru-cache": "^6.0.0" @@ -13573,9 +13854,9 @@ } }, "node_modules/path-scurry/node_modules/lru-cache": { - "version": "9.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-9.1.1.tgz", - "integrity": "sha512-65/Jky17UwSb0BuB9V+MyDpsOtXKmYwzhyl+cOa9XUiI4uV2Ouy/2voFP3+al0BjZbJgMBD8FojMpAf+Z+qn4A==", + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-9.1.2.tgz", + "integrity": "sha512-ERJq3FOzJTxBbFjZ7iDs+NiK4VI9Wz+RdrrAB8dio1oV+YvdPzUEE4QNiT2VD51DkIbCYRUUzCRkssXCHqSnKQ==", "dev": true, "engines": { "node": "14 || >=16.14" @@ -14190,9 +14471,9 @@ } }, "node_modules/prettier-plugin-solidity/node_modules/semver": { - "version": "7.5.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz", - "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==", + "version": "7.5.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", + "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", "dev": true, "dependencies": { "lru-cache": "^6.0.0" @@ -14305,18 +14586,12 @@ ] }, "node_modules/qs": { - "version": "6.11.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.2.tgz", - "integrity": "sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==", + "version": "6.5.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", + "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", "dev": true, - "dependencies": { - "side-channel": "^1.0.4" - }, "engines": { "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, "node_modules/query-string": { @@ -14713,15 +14988,6 @@ "request": "^2.34" } }, - "node_modules/request/node_modules/qs": { - "version": "6.5.3", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", - "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", - "dev": true, - "engines": { - "node": ">=0.6" - } - }, "node_modules/request/node_modules/uuid": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", @@ -14854,6 +15120,13 @@ "node": ">=8" } }, + "node_modules/restore-cursor/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "optional": true + }, "node_modules/retry": { "version": "0.13.1", "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", @@ -15443,11 +15716,16 @@ } }, "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.0.2.tgz", + "integrity": "sha512-MY2/qGx4enyjprQnFaZsHib3Yadh3IXyV2C321GY0pjGfVBu4un0uDJkwgdxqO+Rdx8JMT8IfJIRwbYVz3Ob3Q==", "dev": true, - "optional": true + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } }, "node_modules/simple-concat": { "version": "1.0.1", @@ -16074,9 +16352,9 @@ "dev": true }, "node_modules/solidity-coverage": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/solidity-coverage/-/solidity-coverage-0.8.2.tgz", - "integrity": "sha512-cv2bWb7lOXPE9/SSleDO6czkFiMHgP4NXPj+iW9W7iEKLBk7Cj0AGBiNmGX3V1totl9wjPrT0gHmABZKZt65rQ==", + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/solidity-coverage/-/solidity-coverage-0.8.3.tgz", + "integrity": "sha512-hbcNgj5z8zzgTlnp4F0pXiqj1v5ua8P4DH5i9cWOBtFPfUuIohLoXu5WiAixexWmpKVjyxXqupnu/mPb4IGr7Q==", "dev": true, "peer": true, "dependencies": { @@ -16466,9 +16744,9 @@ } }, "node_modules/solidity-coverage/node_modules/semver": { - "version": "7.5.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz", - "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==", + "version": "7.5.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", + "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", "dev": true, "peer": true, "dependencies": { @@ -17518,14 +17796,14 @@ } }, "node_modules/truffle": { - "version": "5.9.4", - "resolved": "https://registry.npmjs.org/truffle/-/truffle-5.9.4.tgz", - "integrity": "sha512-35UUp6Y+TAZ/ZTrUUtmIr6XSacKlq36QalC96tABsPdATKe5xBJkUKqbJBKuQcLtV1BL7nOLqgQs7fyecSXKaA==", + "version": "5.10.1", + "resolved": "https://registry.npmjs.org/truffle/-/truffle-5.10.1.tgz", + "integrity": "sha512-U4Mj0I8s/qTCikUIwy0/sJaIroveltNZ1sNq0OTBqQ8Km3Blm8KMBcsIwgTVAEDHx548QKsXF5lkc5dTLEubVg==", "dev": true, "hasInstallScript": true, "dependencies": { - "@truffle/db-loader": "^0.2.28", - "@truffle/debugger": "^11.1.4", + "@truffle/db-loader": "^0.2.30", + "@truffle/debugger": "^12.0.0", "app-module-path": "^2.2.0", "ganache": "7.8.0", "mocha": "10.1.0", @@ -17535,7 +17813,7 @@ "truffle": "build/cli.bundled.js" }, "optionalDependencies": { - "@truffle/db": "^2.0.28" + "@truffle/db": "^2.0.30" } }, "node_modules/truffle/node_modules/ansi-colors": { @@ -17759,13 +18037,12 @@ } }, "node_modules/ts-command-line-args": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-command-line-args/-/ts-command-line-args-2.5.0.tgz", - "integrity": "sha512-Ff7Xt04WWCjj/cmPO9eWTJX3qpBZWuPWyQYG1vnxJao+alWWYjwJBc5aYz3h5p5dE08A6AnpkgiCtP/0KXXBYw==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/ts-command-line-args/-/ts-command-line-args-2.5.1.tgz", + "integrity": "sha512-H69ZwTw3rFHb5WYpQya40YAX2/w7Ut75uUECbgBIsLmM+BNuYnxsltfyyLMxy6sEeKxgijLTnQtLd0nKd6+IYw==", "dev": true, "peer": true, "dependencies": { - "@morgan-stanley/ts-mocking-bird": "^0.6.2", "chalk": "^4.1.0", "command-line-args": "^5.1.1", "command-line-usage": "^6.1.0", @@ -17916,9 +18193,9 @@ } }, "node_modules/tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", + "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==", "dev": true }, "node_modules/tsort": { @@ -18094,9 +18371,9 @@ } }, "node_modules/typescript": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.0.4.tgz", - "integrity": "sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==", + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.3.tgz", + "integrity": "sha512-XH627E9vkeqhlZFQuL+UsyAXEnibT0kWR2FWONlr4sTjvxyJYnyefgrkyECLzM5NenmKzRAy2rR/OlYLA1HkZw==", "dev": true, "peer": true, "bin": { @@ -18104,7 +18381,7 @@ "tsserver": "bin/tsserver" }, "engines": { - "node": ">=12.20" + "node": ">=14.17" } }, "node_modules/typescript-compare": { @@ -18956,17 +19233,17 @@ "dev": true }, "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", "dev": true, "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" }, "engines": { - "node": ">=10" + "node": ">=12" }, "funding": { "url": "https://github.com/chalk/wrap-ansi?sponsor=1" @@ -19045,57 +19322,65 @@ } }, "node_modules/wrap-ansi/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", "dev": true, "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, "node_modules/wrap-ansi/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", "dev": true, - "dependencies": { - "color-convert": "^2.0.1" - }, "engines": { - "node": ">=8" + "node": ">=12" }, "funding": { "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/wrap-ansi/node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "node_modules/wrap-ansi/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", "dev": true, "dependencies": { - "color-name": "~1.1.4" + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" }, "engines": { - "node": ">=7.0.0" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/wrap-ansi/node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - }, "node_modules/wrap-ansi/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", "dev": true, "dependencies": { - "ansi-regex": "^5.0.1" + "ansi-regex": "^6.0.1" }, "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, "node_modules/wrappy": { @@ -19122,12 +19407,12 @@ "optional": true }, "node_modules/ws": { - "version": "7.4.6", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.4.6.tgz", - "integrity": "sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A==", + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.5.0.tgz", + "integrity": "sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg==", "dev": true, "engines": { - "node": ">=8.3.0" + "node": ">=10.0.0" }, "peerDependencies": { "bufferutil": "^4.0.1", @@ -19343,6 +19628,12 @@ } }, "dependencies": { + "@adraffy/ens-normalize": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.9.2.tgz", + "integrity": "sha512-0h+FrQDqe2Wn+IIGFkTCd4aAwTJ+7834Ek1COohCyV26AXhwQ7WQaz+4F/nLOeVl/3BtWHOHLPsq46V8YB46Eg==", + "dev": true + }, "@apollo/protobufjs": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/@apollo/protobufjs/-/protobufjs-1.2.7.tgz", @@ -19365,9 +19656,9 @@ } }, "@apollo/usage-reporting-protobuf": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@apollo/usage-reporting-protobuf/-/usage-reporting-protobuf-4.1.0.tgz", - "integrity": "sha512-hXouMuw5pQVkzi8dgMybmr6Y11+eRmMQVoB5TF0HyTwAg9SOq/v3OCuiYqcVUKdBcskU9Msp+XvjAk0GKpWCwQ==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@apollo/usage-reporting-protobuf/-/usage-reporting-protobuf-4.1.1.tgz", + "integrity": "sha512-u40dIUePHaSKVshcedO7Wp+mPiZsaU6xjv9J+VyxpoU/zL6Jle+9zWeG98tr/+SZ0nZ4OXhrbb8SNr0rAPpIDA==", "dev": true, "optional": true, "requires": { @@ -19477,35 +19768,35 @@ } }, "@babel/code-frame": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.21.4.tgz", - "integrity": "sha512-LYvhNKfwWSPpocw8GI7gpK2nq3HSDuEPC/uSYaALSJu9xjsalaaYFOq0Pwt5KmVqwEbZlDu81aLXwBOmD/Fv9g==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.5.tgz", + "integrity": "sha512-Xmwn266vad+6DAqEB2A6V/CcZVp62BbwVmcOJc2RPuwih1kw02TjQvWVWlcKGbBPd+8/0V5DEkOcizRGYsspYQ==", "dev": true, "requires": { - "@babel/highlight": "^7.18.6" + "@babel/highlight": "^7.22.5" } }, "@babel/helper-validator-identifier": { - "version": "7.19.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", - "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.5.tgz", + "integrity": "sha512-aJXu+6lErq8ltp+JhkJUfk1MTGyuA4v7f3pA+BJ5HLfNC6nAQ0Cpi9uOquUj8Hehg0aUiHzWQbOVJGao6ztBAQ==", "dev": true }, "@babel/highlight": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", - "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.5.tgz", + "integrity": "sha512-BSKlD1hgnedS5XRnGOljZawtag7H1yPfQp0tdNJCHoH6AZ+Pcm9VvkrK59/Yy593Ypg0zMxH2BxD1VPYUQ7UIw==", "dev": true, "requires": { - "@babel/helper-validator-identifier": "^7.18.6", + "@babel/helper-validator-identifier": "^7.22.5", "chalk": "^2.0.0", "js-tokens": "^4.0.0" } }, "@babel/runtime": { - "version": "7.22.3", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.3.tgz", - "integrity": "sha512-XsDuspWKLUsxwCp6r7EhsExHtYfbe5oAGQ19kqngTdCPUoPQzOPdUbD/pB9PJiwb2ptYKQDjSJT3R6dC+EPqfQ==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.5.tgz", + "integrity": "sha512-ecjvYlnAaZ/KVneE/OdKYBYfgXV3Ptu6zQWmgEF7vwKhQnvVS6bjMD2XYgj+SNvQ1GfK/pjgokfPkC/2CO8CuA==", "dev": true, "requires": { "regenerator-runtime": "^0.13.11" @@ -19634,6 +19925,46 @@ "eth-ens-namehash": "^2.0.8", "ethers": "^5.0.13", "js-sha3": "^0.8.0" + }, + "dependencies": { + "ethers": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.7.2.tgz", + "integrity": "sha512-wswUsmWo1aOK8rR7DIKiWSw9DbLWe6x98Jrn8wcTflTVvaXhAMaB5zGAXy0GYQEQp9iO1iSHWVyARQm11zUtyg==", + "dev": true, + "requires": { + "@ethersproject/abi": "5.7.0", + "@ethersproject/abstract-provider": "5.7.0", + "@ethersproject/abstract-signer": "5.7.0", + "@ethersproject/address": "5.7.0", + "@ethersproject/base64": "5.7.0", + "@ethersproject/basex": "5.7.0", + "@ethersproject/bignumber": "5.7.0", + "@ethersproject/bytes": "5.7.0", + "@ethersproject/constants": "5.7.0", + "@ethersproject/contracts": "5.7.0", + "@ethersproject/hash": "5.7.0", + "@ethersproject/hdnode": "5.7.0", + "@ethersproject/json-wallets": "5.7.0", + "@ethersproject/keccak256": "5.7.0", + "@ethersproject/logger": "5.7.0", + "@ethersproject/networks": "5.7.1", + "@ethersproject/pbkdf2": "5.7.0", + "@ethersproject/properties": "5.7.0", + "@ethersproject/providers": "5.7.2", + "@ethersproject/random": "5.7.0", + "@ethersproject/rlp": "5.7.0", + "@ethersproject/sha2": "5.7.0", + "@ethersproject/signing-key": "5.7.0", + "@ethersproject/solidity": "5.7.0", + "@ethersproject/strings": "5.7.0", + "@ethersproject/transactions": "5.7.0", + "@ethersproject/units": "5.7.0", + "@ethersproject/wallet": "5.7.0", + "@ethersproject/web": "5.7.1", + "@ethersproject/wordlists": "5.7.0" + } + } } }, "@ensdomains/resolver": { @@ -19692,18 +20023,11 @@ } }, "@eslint/js": { - "version": "8.42.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.42.0.tgz", - "integrity": "sha512-6SWlXpWU5AvId8Ac7zjzmIOqMOba/JWY8XZ4A7q7Gn1Vlfg/SFFIlrtHXt9nPn4op9ZPAkl91Jao+QQv3r/ukw==", + "version": "8.43.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.43.0.tgz", + "integrity": "sha512-s2UHCoiXfxMvmfzqoN+vrQ84ahUSYde9qNO1MdxmoEhyHWsfmwOpFlwYV+ePJEVc7gFnATGUi376WowX1N7tFg==", "dev": true }, - "@ethereum-waffle/mock-contract": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@ethereum-waffle/mock-contract/-/mock-contract-4.0.4.tgz", - "integrity": "sha512-LwEj5SIuEe9/gnrXgtqIkWbk2g15imM/qcJcxpLyAkOj981tQxXmtV4XmQMZsdedEsZ/D/rbUAOtZbgwqgUwQA==", - "dev": true, - "requires": {} - }, "@ethereumjs/common": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/@ethereumjs/common/-/common-2.5.0.tgz", @@ -19904,6 +20228,14 @@ "@ethersproject/transactions": "^5.7.0", "aes-js": "3.0.0", "scrypt-js": "3.0.1" + }, + "dependencies": { + "aes-js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", + "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "dev": true + } } }, "@ethersproject/keccak256": { @@ -19976,6 +20308,15 @@ "@ethersproject/web": "^5.7.0", "bech32": "1.1.4", "ws": "7.4.6" + }, + "dependencies": { + "ws": { + "version": "7.4.6", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.4.6.tgz", + "integrity": "sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A==", + "dev": true, + "requires": {} + } } }, "@ethersproject/random": { @@ -20136,15 +20477,6 @@ "dataloader": "2.1.0", "tslib": "^2.4.0", "value-or-promise": "1.0.11" - }, - "dependencies": { - "tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - } } }, "@graphql-tools/delegate": { @@ -20160,15 +20492,6 @@ "dataloader": "2.1.0", "tslib": "~2.4.0", "value-or-promise": "1.0.11" - }, - "dependencies": { - "tslib": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz", - "integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==", - "dev": true, - "optional": true - } } }, "@graphql-tools/merge": { @@ -20180,15 +20503,6 @@ "requires": { "@graphql-tools/utils": "8.9.0", "tslib": "^2.4.0" - }, - "dependencies": { - "tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - } } }, "@graphql-tools/mock": { @@ -20239,13 +20553,6 @@ "tslib": "^2.4.0" } }, - "tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - }, "value-or-promise": { "version": "1.0.12", "resolved": "https://registry.npmjs.org/value-or-promise/-/value-or-promise-1.0.12.tgz", @@ -20266,15 +20573,6 @@ "@graphql-tools/utils": "8.9.0", "tslib": "^2.4.0", "value-or-promise": "1.0.11" - }, - "dependencies": { - "tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - } } }, "@graphql-tools/utils": { @@ -20285,15 +20583,6 @@ "optional": true, "requires": { "tslib": "^2.4.0" - }, - "dependencies": { - "tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - } } }, "@graphql-typed-document-node/core": { @@ -20347,12 +20636,6 @@ "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", "dev": true }, - "ansi-styles": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", - "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", - "dev": true - }, "emoji-regex": { "version": "9.2.2", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", @@ -20378,17 +20661,6 @@ "requires": { "ansi-regex": "^6.0.1" } - }, - "wrap-ansi": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", - "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", - "dev": true, - "requires": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - } } } }, @@ -20469,30 +20741,10 @@ } } }, - "@morgan-stanley/ts-mocking-bird": { - "version": "0.6.4", - "resolved": "https://registry.npmjs.org/@morgan-stanley/ts-mocking-bird/-/ts-mocking-bird-0.6.4.tgz", - "integrity": "sha512-57VJIflP8eR2xXa9cD1LUawh+Gh+BVQfVu0n6GALyg/AqV/Nz25kDRvws3i9kIe1PTrbsZZOYpsYp6bXPd6nVA==", - "dev": true, - "peer": true, - "requires": { - "lodash": "^4.17.16", - "uuid": "^7.0.3" - }, - "dependencies": { - "uuid": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-7.0.3.tgz", - "integrity": "sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==", - "dev": true, - "peer": true - } - } - }, "@noble/hashes": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz", - "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.1.2.tgz", + "integrity": "sha512-KYRCASVTv6aeUi1tsF8/vpyR7zpfs3FUzy2Jqm+MU+LmUKhQ0y2FpfwqkCcxSg2ua4GALJd8k2R76WxwZGbQpA==", "dev": true }, "@noble/secp256k1": { @@ -20540,6 +20792,46 @@ "@nomicfoundation/ethereumjs-util": "9.0.1", "ethereum-cryptography": "0.1.3", "ethers": "^5.7.1" + }, + "dependencies": { + "ethers": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.7.2.tgz", + "integrity": "sha512-wswUsmWo1aOK8rR7DIKiWSw9DbLWe6x98Jrn8wcTflTVvaXhAMaB5zGAXy0GYQEQp9iO1iSHWVyARQm11zUtyg==", + "dev": true, + "requires": { + "@ethersproject/abi": "5.7.0", + "@ethersproject/abstract-provider": "5.7.0", + "@ethersproject/abstract-signer": "5.7.0", + "@ethersproject/address": "5.7.0", + "@ethersproject/base64": "5.7.0", + "@ethersproject/basex": "5.7.0", + "@ethersproject/bignumber": "5.7.0", + "@ethersproject/bytes": "5.7.0", + "@ethersproject/constants": "5.7.0", + "@ethersproject/contracts": "5.7.0", + "@ethersproject/hash": "5.7.0", + "@ethersproject/hdnode": "5.7.0", + "@ethersproject/json-wallets": "5.7.0", + "@ethersproject/keccak256": "5.7.0", + "@ethersproject/logger": "5.7.0", + "@ethersproject/networks": "5.7.1", + "@ethersproject/pbkdf2": "5.7.0", + "@ethersproject/properties": "5.7.0", + "@ethersproject/providers": "5.7.2", + "@ethersproject/random": "5.7.0", + "@ethersproject/rlp": "5.7.0", + "@ethersproject/sha2": "5.7.0", + "@ethersproject/signing-key": "5.7.0", + "@ethersproject/solidity": "5.7.0", + "@ethersproject/strings": "5.7.0", + "@ethersproject/transactions": "5.7.0", + "@ethersproject/units": "5.7.0", + "@ethersproject/wallet": "5.7.0", + "@ethersproject/web": "5.7.1", + "@ethersproject/wordlists": "5.7.0" + } + } } }, "@nomicfoundation/ethereumjs-blockchain": { @@ -20621,6 +20913,46 @@ "ethereum-cryptography": "0.1.3", "ethers": "^5.7.1", "js-sdsl": "^4.1.4" + }, + "dependencies": { + "ethers": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.7.2.tgz", + "integrity": "sha512-wswUsmWo1aOK8rR7DIKiWSw9DbLWe6x98Jrn8wcTflTVvaXhAMaB5zGAXy0GYQEQp9iO1iSHWVyARQm11zUtyg==", + "dev": true, + "requires": { + "@ethersproject/abi": "5.7.0", + "@ethersproject/abstract-provider": "5.7.0", + "@ethersproject/abstract-signer": "5.7.0", + "@ethersproject/address": "5.7.0", + "@ethersproject/base64": "5.7.0", + "@ethersproject/basex": "5.7.0", + "@ethersproject/bignumber": "5.7.0", + "@ethersproject/bytes": "5.7.0", + "@ethersproject/constants": "5.7.0", + "@ethersproject/contracts": "5.7.0", + "@ethersproject/hash": "5.7.0", + "@ethersproject/hdnode": "5.7.0", + "@ethersproject/json-wallets": "5.7.0", + "@ethersproject/keccak256": "5.7.0", + "@ethersproject/logger": "5.7.0", + "@ethersproject/networks": "5.7.1", + "@ethersproject/pbkdf2": "5.7.0", + "@ethersproject/properties": "5.7.0", + "@ethersproject/providers": "5.7.2", + "@ethersproject/random": "5.7.0", + "@ethersproject/rlp": "5.7.0", + "@ethersproject/sha2": "5.7.0", + "@ethersproject/signing-key": "5.7.0", + "@ethersproject/solidity": "5.7.0", + "@ethersproject/strings": "5.7.0", + "@ethersproject/transactions": "5.7.0", + "@ethersproject/units": "5.7.0", + "@ethersproject/wallet": "5.7.0", + "@ethersproject/web": "5.7.1", + "@ethersproject/wordlists": "5.7.0" + } + } } }, "@nomicfoundation/ethereumjs-trie": { @@ -20704,19 +21036,28 @@ } }, "@nomicfoundation/hardhat-chai-matchers": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-chai-matchers/-/hardhat-chai-matchers-1.0.6.tgz", - "integrity": "sha512-f5ZMNmabZeZegEfuxn/0kW+mm7+yV7VNDxLpMOMGXWFJ2l/Ct3QShujzDRF9cOkK9Ui/hbDeOWGZqyQALDXVCQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-chai-matchers/-/hardhat-chai-matchers-2.0.1.tgz", + "integrity": "sha512-qWKndseO8IPt8HiVamgEAutcBOYtX7/O6NPfe7uMNWxY2ywWaiWjDcRFuYYqxrZOMyQZl6ZuiHxbaRNctTUgLw==", "dev": true, "peer": true, "requires": { - "@ethersproject/abi": "^5.1.2", "@types/chai-as-promised": "^7.1.3", "chai-as-promised": "^7.1.1", "deep-eql": "^4.0.1", "ordinal": "^1.0.3" } }, + "@nomicfoundation/hardhat-ethers": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-ethers/-/hardhat-ethers-3.0.2.tgz", + "integrity": "sha512-4Pu3OwyEvnq/gvW2IZ1Lnbcz4yCC4xqzbHze34mXkqbCwV2kHOx6jX3prFDWQ1koxtin725lAazGh9CJtTaYjg==", + "dev": true, + "peer": true, + "requires": { + "debug": "^4.1.1" + } + }, "@nomicfoundation/hardhat-network-helpers": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-network-helpers/-/hardhat-network-helpers-1.0.8.tgz", @@ -20727,12 +21068,30 @@ } }, "@nomicfoundation/hardhat-toolbox": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-toolbox/-/hardhat-toolbox-2.0.2.tgz", - "integrity": "sha512-vnN1AzxbvpSx9pfdRHbUzTRIXpMLPXnUlkW855VaDk6N1pwRaQ2gNzEmFAABk4lWf11E00PKwFd/q27HuwYrYg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-toolbox/-/hardhat-toolbox-3.0.0.tgz", + "integrity": "sha512-MsteDXd0UagMksqm9KvcFG6gNKYNa3GGNCy73iQ6bEasEgg2v8Qjl6XA5hjs8o5UD5A3153B6W2BIVJ8SxYUtA==", "dev": true, "requires": {} }, + "@nomicfoundation/hardhat-verify": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@nomicfoundation/hardhat-verify/-/hardhat-verify-1.0.2.tgz", + "integrity": "sha512-IBEWGY9EtXhVTChTmA83m/Nd9VZ/u/bCU2SZkF6c01QbQB7qcimzY1V35hiFcpJLVZ39rV8J2rmedVdfXB+99w==", + "dev": true, + "peer": true, + "requires": { + "@ethersproject/abi": "^5.1.2", + "@ethersproject/address": "^5.0.2", + "cbor": "^8.1.0", + "chalk": "^2.4.2", + "debug": "^4.1.1", + "lodash.clonedeep": "^4.5.0", + "semver": "^6.3.0", + "table": "^6.8.0", + "undici": "^5.14.0" + } + }, "@nomicfoundation/solidity-analyzer": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/@nomicfoundation/solidity-analyzer/-/solidity-analyzer-0.1.1.tgz", @@ -20821,33 +21180,6 @@ "dev": true, "optional": true }, - "@nomiclabs/hardhat-ethers": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@nomiclabs/hardhat-ethers/-/hardhat-ethers-2.2.3.tgz", - "integrity": "sha512-YhzPdzb612X591FOe68q+qXVXGG2ANZRvDo0RRUtimev85rCrAlv/TLMEZw5c+kq9AbzocLTVX/h2jVIFPL9Xg==", - "dev": true, - "peer": true, - "requires": {} - }, - "@nomiclabs/hardhat-etherscan": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/@nomiclabs/hardhat-etherscan/-/hardhat-etherscan-3.1.7.tgz", - "integrity": "sha512-tZ3TvSgpvsQ6B6OGmo1/Au6u8BrAkvs1mIC/eURA3xgIfznUZBhmpne8hv7BXUzw9xNL3fXdpOYgOQlVMTcoHQ==", - "dev": true, - "peer": true, - "requires": { - "@ethersproject/abi": "^5.1.2", - "@ethersproject/address": "^5.0.2", - "cbor": "^8.1.0", - "chalk": "^2.4.2", - "debug": "^4.1.1", - "fs-extra": "^7.0.1", - "lodash": "^4.17.11", - "semver": "^6.3.0", - "table": "^6.8.0", - "undici": "^5.14.0" - } - }, "@nomiclabs/hardhat-web3": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@nomiclabs/hardhat-web3/-/hardhat-web3-2.0.0.tgz", @@ -20881,9 +21213,9 @@ } }, "@openzeppelin/contracts": { - "version": "4.9.0", - "resolved": "https://registry.npmjs.org/@openzeppelin/contracts/-/contracts-4.9.0.tgz", - "integrity": "sha512-DUP74AFGKlic2sQb/CmgrN2aUPMFGxRrmCTUxLHsiU2RzwWqVuMPZBxiAyvlff6Pea77uylAX6B5x9W6evEbhA==" + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/@openzeppelin/contracts/-/contracts-4.9.2.tgz", + "integrity": "sha512-mO+y6JaqXjWeMh9glYVzVu8HYPGknAAnWyxTRhGeckOruyXQMNnlcW6w/Dx9ftLeIQk6N+ZJFuVmTwF7lEIFrg==" }, "@openzeppelin/contracts-upgradeable": { "version": "4.9.0", @@ -21090,6 +21422,14 @@ "@noble/hashes": "~1.2.0", "@noble/secp256k1": "~1.7.0", "@scure/base": "~1.1.0" + }, + "dependencies": { + "@noble/hashes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz", + "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==", + "dev": true + } } }, "@scure/bip39": { @@ -21100,6 +21440,14 @@ "requires": { "@noble/hashes": "~1.2.0", "@scure/base": "~1.1.0" + }, + "dependencies": { + "@noble/hashes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz", + "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==", + "dev": true + } } }, "@sentry/core": { @@ -21113,6 +21461,14 @@ "@sentry/types": "5.30.0", "@sentry/utils": "5.30.0", "tslib": "^1.9.3" + }, + "dependencies": { + "tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + } } }, "@sentry/hub": { @@ -21124,6 +21480,14 @@ "@sentry/types": "5.30.0", "@sentry/utils": "5.30.0", "tslib": "^1.9.3" + }, + "dependencies": { + "tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + } } }, "@sentry/minimal": { @@ -21135,6 +21499,14 @@ "@sentry/hub": "5.30.0", "@sentry/types": "5.30.0", "tslib": "^1.9.3" + }, + "dependencies": { + "tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + } } }, "@sentry/node": { @@ -21152,6 +21524,14 @@ "https-proxy-agent": "^5.0.0", "lru_map": "^0.3.3", "tslib": "^1.9.3" + }, + "dependencies": { + "tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + } } }, "@sentry/tracing": { @@ -21165,6 +21545,14 @@ "@sentry/types": "5.30.0", "@sentry/utils": "5.30.0", "tslib": "^1.9.3" + }, + "dependencies": { + "tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + } } }, "@sentry/types": { @@ -21181,6 +21569,14 @@ "requires": { "@sentry/types": "5.30.0", "tslib": "^1.9.3" + }, + "dependencies": { + "tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + } } }, "@sindresorhus/is": { @@ -21220,9 +21616,9 @@ } }, "@truffle/blockchain-utils": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@truffle/blockchain-utils/-/blockchain-utils-0.1.7.tgz", - "integrity": "sha512-1nibqGjEHC7KAyDThEFvbm2+EO8zAHee/VjCtxkYBE3ySwP50joh0QCEBjy7K/9z+icpMoDucfxmgaKToBFUgQ==", + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/@truffle/blockchain-utils/-/blockchain-utils-0.1.8.tgz", + "integrity": "sha512-ZskpYDNHkXD3ota4iU3pZz6kLth87RC+wDn66Rp2Or+DqqJCKdnmS9GDctBi1EcMPDEi0BqpkdrfBuzA9uIkGg==", "dev": true }, "@truffle/code-utils": { @@ -21259,9 +21655,9 @@ } }, "@truffle/codec": { - "version": "0.15.2", - "resolved": "https://registry.npmjs.org/@truffle/codec/-/codec-0.15.2.tgz", - "integrity": "sha512-rLLy1RmDq3stE1Bd6cnPO9kGpoB5QE4caY665ghmAURqlqD0ik1Bhbfi4MIRwM7YVx2sYw485qsxfPzlewnT4g==", + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@truffle/codec/-/codec-0.16.0.tgz", + "integrity": "sha512-cAX2mnkEhvcjG75JvOPvepMZmGSooOYtQpVMJIIGVp1x2B1V9aE+A5tqLEAr0idkFGCthGMvF/FfMRUQ/rWZMw==", "dev": true, "requires": { "@truffle/abi-utils": "^1.0.1", @@ -21271,7 +21667,7 @@ "cbor": "^5.2.0", "debug": "^4.3.1", "lodash": "^4.17.21", - "semver": "7.3.7", + "semver": "7.5.2", "utf8": "^3.0.0", "web3-utils": "1.10.0" }, @@ -21308,9 +21704,9 @@ "dev": true }, "semver": { - "version": "7.3.7", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", - "integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.2.tgz", + "integrity": "sha512-SoftuTROv/cRjCze/scjGyiDtcUyxw1rgYQSZY7XTmtR5hX+dm76iDbTH8TkLPHCQmlbQVSSbNZCPM2hb0knnQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" @@ -21335,9 +21731,9 @@ } }, "@truffle/config": { - "version": "1.3.57", - "resolved": "https://registry.npmjs.org/@truffle/config/-/config-1.3.57.tgz", - "integrity": "sha512-Cfude7ZMT2pykvMoHZ/47MvlVoZDQLs+Y85ChRw/1RKWsHrzz1BOyjDmnPLnSTOc056OuNOcgID1IdUMorVOIQ==", + "version": "1.3.58", + "resolved": "https://registry.npmjs.org/@truffle/config/-/config-1.3.58.tgz", + "integrity": "sha512-M6e7dAx6QMMskhwpqpOE4dAj72HapcMPtw/7c6bssCZd/E1quyAs/CpiYGDIxp2EuZHxW/9X16VzIac8sIOW7w==", "dev": true, "optional": true, "requires": { @@ -21409,17 +21805,17 @@ } }, "@truffle/contract": { - "version": "4.6.22", - "resolved": "https://registry.npmjs.org/@truffle/contract/-/contract-4.6.22.tgz", - "integrity": "sha512-081tM5CBBLgTQX0Fhzp0nlZHnfgojRXweV7/d6v7LHe6QGrGBmgvUy3EIbO+R3P1uaxeGVijMvB4Ok8md9IpYQ==", + "version": "4.6.25", + "resolved": "https://registry.npmjs.org/@truffle/contract/-/contract-4.6.25.tgz", + "integrity": "sha512-eDyJx1Yap3e7J4iTKOUKYqUaO/wCayBqBaJnQmqW57LeOVkBQnqwOSNvFFxjcbOlRXGoLFFlTkxDa9lGcLVM7Q==", "dev": true, "requires": { "@ensdomains/ensjs": "^2.1.0", - "@truffle/blockchain-utils": "^0.1.7", + "@truffle/blockchain-utils": "^0.1.8", "@truffle/contract-schema": "^3.4.14", - "@truffle/debug-utils": "^6.0.50", - "@truffle/error": "^0.2.0", - "@truffle/interface-adapter": "^0.5.33", + "@truffle/debug-utils": "^6.0.53", + "@truffle/error": "^0.2.1", + "@truffle/interface-adapter": "^0.5.34", "bignumber.js": "^7.2.1", "debug": "^4.3.1", "ethers": "^4.0.32", @@ -21430,6 +21826,12 @@ "web3-utils": "1.10.0" }, "dependencies": { + "aes-js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", + "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "dev": true + }, "bn.js": { "version": "4.12.0", "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", @@ -21515,6 +21917,16 @@ "node-abort-controller": "^3.0.1", "tiny-typed-emitter": "^2.1.0", "ws": "^7.2.0" + }, + "dependencies": { + "ws": { + "version": "7.5.9", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz", + "integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==", + "dev": true, + "optional": true, + "requires": {} + } } }, "@truffle/dashboard-message-bus-common": { @@ -21525,9 +21937,9 @@ "optional": true }, "@truffle/db": { - "version": "2.0.28", - "resolved": "https://registry.npmjs.org/@truffle/db/-/db-2.0.28.tgz", - "integrity": "sha512-R9FfBeVxd/SEIdw6IrMwg2vLMNXuiHMJ5XwW7ivCSyNMYXesJMA85fWYPe9bWyJ8eufLOAWlX8xr55vua4DwZQ==", + "version": "2.0.30", + "resolved": "https://registry.npmjs.org/@truffle/db/-/db-2.0.30.tgz", + "integrity": "sha512-vbOt7r3ybmoo3xZjyTyWe9SC98b6JcMeOpmi59Trdxwp+h3Lo9wdqdvv4595QxwDwzHvISSFTJRGKNDMtRD2rg==", "dev": true, "optional": true, "requires": { @@ -21535,7 +21947,7 @@ "@graphql-tools/schema": "^8.3.1", "@truffle/abi-utils": "^1.0.1", "@truffle/code-utils": "^3.0.3", - "@truffle/config": "^1.3.57", + "@truffle/config": "^1.3.58", "abstract-leveldown": "^7.2.0", "apollo-server": "^3.11.0", "debug": "^4.3.1", @@ -21586,21 +21998,21 @@ } }, "@truffle/db-loader": { - "version": "0.2.28", - "resolved": "https://registry.npmjs.org/@truffle/db-loader/-/db-loader-0.2.28.tgz", - "integrity": "sha512-oVXQXtYhM3Mu/pnfLR5KoqqEdw6GO6FDAFM7zZm647mIAtXCqv+EYSNt3efyqsFgQZwv3UZY6KP8TMxnjeWWGA==", + "version": "0.2.30", + "resolved": "https://registry.npmjs.org/@truffle/db-loader/-/db-loader-0.2.30.tgz", + "integrity": "sha512-dQv8Q/JY+toSgOH5kHzVhEt1Ig6Wg0onn219qo2terL8xX5g5Ia2mM0Pg82Ba+B8ZCkCnz+kYC/htscF8d6ugw==", "dev": true, "requires": { - "@truffle/db": "^2.0.28" + "@truffle/db": "^2.0.30" } }, "@truffle/debug-utils": { - "version": "6.0.50", - "resolved": "https://registry.npmjs.org/@truffle/debug-utils/-/debug-utils-6.0.50.tgz", - "integrity": "sha512-OWdSoOsPW7/jvcO7ASBRzXDzXQNb7dg8UqwoBAI7j7UpdQoCAhz7JQsusSNiFN6g1qrxEpGzeh5iIMDq9WxO3w==", + "version": "6.0.53", + "resolved": "https://registry.npmjs.org/@truffle/debug-utils/-/debug-utils-6.0.53.tgz", + "integrity": "sha512-czfIjw41UA7eEX0Z660JAQkxyqjr4+B/ecDHFia/feIprLAdFz3VDuhqf/zoMnrKczqS2qbMtnknExgbbrH+eg==", "dev": true, "requires": { - "@truffle/codec": "^0.15.1", + "@truffle/codec": "^0.16.0", "@trufflesuite/chromafi": "^3.0.0", "bn.js": "^5.1.3", "chalk": "^2.4.2", @@ -21609,15 +22021,15 @@ } }, "@truffle/debugger": { - "version": "11.1.4", - "resolved": "https://registry.npmjs.org/@truffle/debugger/-/debugger-11.1.4.tgz", - "integrity": "sha512-dWpf89fHZYaW/18x1ZfQhZozg3hZqxz7Czd6vIWVQc3OiV59xpA0+YLm+aumrebj6vmjqzGWu+iHfCaLiYhwQA==", + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@truffle/debugger/-/debugger-12.0.0.tgz", + "integrity": "sha512-ICJPM4R2VjwWJI85r7R2TzmmL0VqZoCdPyFJ1JXYXhK/gmuRyPHb0wmSALgu4edXyyauN4ekDc2qi/lX/oU/hg==", "dev": true, "requires": { "@ensdomains/ensjs": "^2.1.0", "@truffle/abi-utils": "^1.0.1", - "@truffle/codec": "^0.15.2", - "@truffle/source-map-utils": "^1.3.113", + "@truffle/codec": "^0.16.0", + "@truffle/source-map-utils": "^1.3.115", "bn.js": "^5.1.3", "debug": "^4.3.1", "json-pointer": "^0.6.1", @@ -21626,7 +22038,7 @@ "redux": "^3.7.2", "redux-saga": "1.0.0", "reselect-tree": "^1.3.7", - "semver": "7.3.7", + "semver": "7.5.2", "web3": "1.10.0", "web3-eth-abi": "1.10.0" }, @@ -21641,9 +22053,9 @@ } }, "semver": { - "version": "7.3.7", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", - "integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.2.tgz", + "integrity": "sha512-SoftuTROv/cRjCze/scjGyiDtcUyxw1rgYQSZY7XTmtR5hX+dm76iDbTH8TkLPHCQmlbQVSSbNZCPM2hb0knnQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" @@ -21688,6 +22100,12 @@ "web3": "1.10.0" }, "dependencies": { + "aes-js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", + "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "dev": true + }, "ethers": { "version": "4.0.49", "resolved": "https://registry.npmjs.org/ethers/-/ethers-4.0.49.tgz", @@ -21770,13 +22188,13 @@ } }, "@truffle/source-map-utils": { - "version": "1.3.113", - "resolved": "https://registry.npmjs.org/@truffle/source-map-utils/-/source-map-utils-1.3.113.tgz", - "integrity": "sha512-lzsocqZC0HIJYrPe+V3mSi9Pv0gu9vh8ETZJKe+8lr3prbeWEXeqZYXF+HI8Qw70cPE7or6L5A9d+wGVei5KNA==", + "version": "1.3.115", + "resolved": "https://registry.npmjs.org/@truffle/source-map-utils/-/source-map-utils-1.3.115.tgz", + "integrity": "sha512-NUOj45yLkMjv0x376N4ibgPh9pIp2rMKd2HxmXRbbIv3VHy18WPtgbW7+fkll/rAeTYhXzcyvwu67+dtgVholw==", "dev": true, "requires": { "@truffle/code-utils": "^3.0.3", - "@truffle/codec": "^0.15.2", + "@truffle/codec": "^0.16.0", "debug": "^4.3.1", "json-pointer": "^0.6.1", "node-interval-tree": "^1.3.3", @@ -21923,10 +22341,10 @@ "dev": true, "peer": true }, - "@typechain/ethers-v5": { - "version": "10.2.1", - "resolved": "https://registry.npmjs.org/@typechain/ethers-v5/-/ethers-v5-10.2.1.tgz", - "integrity": "sha512-n3tQmCZjRE6IU4h6lqUGiQ1j866n5MTCBJreNEHHVWXa2u9GJTaeYyU1/k+1qLutkyw+sS6VAN+AbeiTqsxd/A==", + "@typechain/ethers-v6": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@typechain/ethers-v6/-/ethers-v6-0.4.0.tgz", + "integrity": "sha512-vD3Agzz63Gf2XlU3ed2/y+8dLWQj+wf+4Eq+0JXsyOio/plyV5F6r0yYe+s3XdGI858U3Sr263pl8mliDrUqbw==", "dev": true, "peer": true, "requires": { @@ -21935,9 +22353,9 @@ } }, "@typechain/hardhat": { - "version": "6.1.6", - "resolved": "https://registry.npmjs.org/@typechain/hardhat/-/hardhat-6.1.6.tgz", - "integrity": "sha512-BiVnegSs+ZHVymyidtK472syodx1sXYlYJJixZfRstHVGYTi8V1O7QG4nsjyb0PC/LORcq7sfBUcHto1y6UgJA==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@typechain/hardhat/-/hardhat-8.0.0.tgz", + "integrity": "sha512-XUVbqlMx8tJTOmzZCD/r196CidtNWAnTBZRcYxjLTKgcJMvc/kHQpWBnVMMB5QHxVKpYpCiz8g07FYCpG8rrjA==", "dev": true, "peer": true, "requires": { @@ -22125,6 +22543,13 @@ "integrity": "sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ==", "dev": true }, + "@types/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-/K3ds8TRAfBvi5vfjuz8y6+GiAYBZ0x4tXv1Av6CWBWn0IlADc+ZX9pMq7oU0fNQPnBwIZl3rmeLp6SBApbxSQ==", + "dev": true, + "optional": true + }, "@types/keyv": { "version": "3.1.4", "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz", @@ -22175,9 +22600,9 @@ "peer": true }, "@types/node": { - "version": "20.2.5", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.2.5.tgz", - "integrity": "sha512-JJulVEQXmiY9Px5axXHeYGLSjhkZEnD+MDPDGbCbIAbMslkKwmygtZFy1X6s/075Yo94sf8GuSlFfPzysQrWZQ==", + "version": "20.3.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.2.tgz", + "integrity": "sha512-vOBLVQeCQfIcF/2Y7eKFTqrMnizK5lRNQ7ykML/5RuwVXVWxYkgwS7xbt4B6fKCUPgbSL5FSsjHQpaGQP/dQmw==", "dev": true }, "@types/normalize-package-data": { @@ -22196,9 +22621,9 @@ } }, "@types/prettier": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", - "integrity": "sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg==", + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.3.tgz", + "integrity": "sha512-+68kP9yzs4LMp7VNh8gdzMSPZFL44MLGqiHWvttYJe+6qnuVr4Ek9wSBQoveqY/r+LwjCcU29kNVkidwim+kYA==", "dev": true, "peer": true }, @@ -22263,12 +22688,13 @@ } }, "@types/serve-static": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.1.tgz", - "integrity": "sha512-NUo5XNiAdULrJENtJXZZ3fHtfMolzZwczzBbnAeBbqBwG+LaG6YaJtuwzwGSQZ2wsCrxjEhNNjAkKigy3n8teQ==", + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.2.tgz", + "integrity": "sha512-J2LqtvFYCzaj8pVYKw8klQXrLLk7TBZmQ4ShlcdkELFKGwGMfevMLneMMRkMgZxotOD9wg497LpC7O8PcvAmfw==", "dev": true, "optional": true, "requires": { + "@types/http-errors": "*", "@types/mime": "*", "@types/node": "*" } @@ -22368,9 +22794,9 @@ } }, "acorn": { - "version": "8.8.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", - "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.9.0.tgz", + "integrity": "sha512-jaVNAFBHNLXspO543WnNNPZFRtavh3skAkITqD0/2aeMkKZTN+254PyhwxFYrk3vQ1xfY+2wbesJMs/JC8/PwQ==", "dev": true }, "acorn-jsx": { @@ -22401,9 +22827,9 @@ "dev": true }, "aes-js": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", - "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "version": "4.0.0-beta.5", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.5.tgz", + "integrity": "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q==", "dev": true }, "agent-base": { @@ -23261,9 +23687,9 @@ "dev": true }, "cacheable-request": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.2.tgz", - "integrity": "sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew==", + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz", + "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==", "dev": true, "requires": { "clone-response": "^1.0.2", @@ -23617,6 +24043,30 @@ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, "strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -23625,6 +24075,17 @@ "requires": { "ansi-regex": "^5.0.1" } + }, + "wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } } } }, @@ -23845,9 +24306,9 @@ "optional": true }, "semver": { - "version": "7.5.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz", - "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==", + "version": "7.5.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", + "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", "dev": true, "optional": true, "requires": { @@ -23928,9 +24389,9 @@ } }, "cosmiconfig": { - "version": "8.1.3", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.1.3.tgz", - "integrity": "sha512-/UkO2JKI18b5jVMJUp0lvKFMpa/Gye+ZgZjKD+DGEN9y7NRcf/nK1A0sp67ONmKtnDCNMS44E6jrk0Yc3bDuUw==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.2.0.tgz", + "integrity": "sha512-3rTMnFJA1tCOPwRxtgF4wd7Ab2qvDbL8jX+3smjIbS4HlZBagTlpERbdN7iAbWlrfxE3M8c27kTwTawQ7st+OQ==", "dev": true, "requires": { "import-fresh": "^3.2.1", @@ -24136,9 +24597,9 @@ } }, "decache": { - "version": "4.6.1", - "resolved": "https://registry.npmjs.org/decache/-/decache-4.6.1.tgz", - "integrity": "sha512-ohApBM8u9ygepJCjgBrEZSSxPjc0T/PJkD+uNyxXPkqudyUpdXpwJYp0VISm2WrPVzASU6DZyIi6BWdyw7uJ2Q==", + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/decache/-/decache-4.6.2.tgz", + "integrity": "sha512-2LPqkLeu8XWHU8qNCS3kcF6sCcb5zIzvWaAHYSvPfwhdd7mHuah29NssMzrTYyHN4F5oFy2ko9OBYxegtU0FEw==", "dev": true, "requires": { "callsite": "^1.0.0" @@ -24414,9 +24875,9 @@ } }, "dotenv": { - "version": "16.3.0", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.0.tgz", - "integrity": "sha512-tHB+hmf8MRCkT3VVivGiG8kq9HiGTmQ3FzOKgztfpJQH1IWuZTOvKSJmHNnQPowecAmkCJhLrxdPhOr06LLqIQ==", + "version": "16.3.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz", + "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==", "dev": true }, "double-ended-queue": { @@ -24837,15 +25298,15 @@ } }, "eslint": { - "version": "8.42.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.42.0.tgz", - "integrity": "sha512-ulg9Ms6E1WPf67PHaEY4/6E2tEn5/f7FXGzr3t9cBMugOmf1INYvuUwwh1aXQN4MfJ6a5K2iNwP3w4AColvI9A==", + "version": "8.43.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.43.0.tgz", + "integrity": "sha512-aaCpf2JqqKesMFGgmRPessmVKjcGXqdlAYLLC3THM8t5nBRZRQ+st5WM/hoJXkdioEXLLbXgclUpM0TXo5HX5Q==", "dev": true, "requires": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.4.0", "@eslint/eslintrc": "^2.0.3", - "@eslint/js": "8.42.0", + "@eslint/js": "8.43.0", "@humanwhocodes/config-array": "^0.11.10", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", @@ -25131,6 +25592,20 @@ "sync-request": "^6.0.0" }, "dependencies": { + "@noble/hashes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz", + "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==", + "dev": true, + "peer": true + }, + "aes-js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", + "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "dev": true, + "peer": true + }, "ansi-colors": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-3.2.3.tgz", @@ -25732,9 +26207,9 @@ }, "dependencies": { "@types/node": { - "version": "16.18.34", - "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.34.tgz", - "integrity": "sha512-VmVm7gXwhkUimRfBwVI1CHhwp86jDWR04B5FGebMMyxV90SlCmFujwUHrxTD4oO+SOYU86SoxvhgeRQJY7iXFg==", + "version": "16.18.37", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.37.tgz", + "integrity": "sha512-ql+4dw4PlPFBP495k8JzUX/oMNRI2Ei4PrMHgj8oT4VhGlYUzF4EYr0qk2fW+XBVGIrq8Zzk13m4cvyXZuv4pA==", "dev": true }, "bn.js": { @@ -25742,6 +26217,44 @@ "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", "dev": true + }, + "ethers": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.7.2.tgz", + "integrity": "sha512-wswUsmWo1aOK8rR7DIKiWSw9DbLWe6x98Jrn8wcTflTVvaXhAMaB5zGAXy0GYQEQp9iO1iSHWVyARQm11zUtyg==", + "dev": true, + "requires": { + "@ethersproject/abi": "5.7.0", + "@ethersproject/abstract-provider": "5.7.0", + "@ethersproject/abstract-signer": "5.7.0", + "@ethersproject/address": "5.7.0", + "@ethersproject/base64": "5.7.0", + "@ethersproject/basex": "5.7.0", + "@ethersproject/bignumber": "5.7.0", + "@ethersproject/bytes": "5.7.0", + "@ethersproject/constants": "5.7.0", + "@ethersproject/contracts": "5.7.0", + "@ethersproject/hash": "5.7.0", + "@ethersproject/hdnode": "5.7.0", + "@ethersproject/json-wallets": "5.7.0", + "@ethersproject/keccak256": "5.7.0", + "@ethersproject/logger": "5.7.0", + "@ethersproject/networks": "5.7.1", + "@ethersproject/pbkdf2": "5.7.0", + "@ethersproject/properties": "5.7.0", + "@ethersproject/providers": "5.7.2", + "@ethersproject/random": "5.7.0", + "@ethersproject/rlp": "5.7.0", + "@ethersproject/sha2": "5.7.0", + "@ethersproject/signing-key": "5.7.0", + "@ethersproject/solidity": "5.7.0", + "@ethersproject/strings": "5.7.0", + "@ethersproject/transactions": "5.7.0", + "@ethersproject/units": "5.7.0", + "@ethersproject/wallet": "5.7.0", + "@ethersproject/web": "5.7.1", + "@ethersproject/wordlists": "5.7.0" + } } } }, @@ -25801,41 +26314,26 @@ } }, "ethers": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.7.2.tgz", - "integrity": "sha512-wswUsmWo1aOK8rR7DIKiWSw9DbLWe6x98Jrn8wcTflTVvaXhAMaB5zGAXy0GYQEQp9iO1iSHWVyARQm11zUtyg==", + "version": "6.6.1", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.6.1.tgz", + "integrity": "sha512-bjNPf/EU4l1jQlAslOmOlyHqjOnM0W7LRPuSf0Kt0tYV4RpUEZsdGWDhvFXfogIhfzXJ/v2tPz4HqXwBt5T8mA==", "dev": true, "requires": { - "@ethersproject/abi": "5.7.0", - "@ethersproject/abstract-provider": "5.7.0", - "@ethersproject/abstract-signer": "5.7.0", - "@ethersproject/address": "5.7.0", - "@ethersproject/base64": "5.7.0", - "@ethersproject/basex": "5.7.0", - "@ethersproject/bignumber": "5.7.0", - "@ethersproject/bytes": "5.7.0", - "@ethersproject/constants": "5.7.0", - "@ethersproject/contracts": "5.7.0", - "@ethersproject/hash": "5.7.0", - "@ethersproject/hdnode": "5.7.0", - "@ethersproject/json-wallets": "5.7.0", - "@ethersproject/keccak256": "5.7.0", - "@ethersproject/logger": "5.7.0", - "@ethersproject/networks": "5.7.1", - "@ethersproject/pbkdf2": "5.7.0", - "@ethersproject/properties": "5.7.0", - "@ethersproject/providers": "5.7.2", - "@ethersproject/random": "5.7.0", - "@ethersproject/rlp": "5.7.0", - "@ethersproject/sha2": "5.7.0", - "@ethersproject/signing-key": "5.7.0", - "@ethersproject/solidity": "5.7.0", - "@ethersproject/strings": "5.7.0", - "@ethersproject/transactions": "5.7.0", - "@ethersproject/units": "5.7.0", - "@ethersproject/wallet": "5.7.0", - "@ethersproject/web": "5.7.1", - "@ethersproject/wordlists": "5.7.0" + "@adraffy/ens-normalize": "1.9.2", + "@noble/hashes": "1.1.2", + "@noble/secp256k1": "1.7.1", + "@types/node": "18.15.13", + "aes-js": "4.0.0-beta.5", + "tslib": "2.4.0", + "ws": "8.5.0" + }, + "dependencies": { + "@types/node": { + "version": "18.15.13", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.13.tgz", + "integrity": "sha512-N+0kuo9KgrUQ1Sn/ifDXsvg0TTleP7rIy4zOBGECxAljqvqfqpTfzx0Q1NUedOixRMBfe2Whhb056a42cWs26Q==", + "dev": true + } } }, "ethjs-abi": { @@ -26277,14 +26775,6 @@ "requires": { "cross-spawn": "^7.0.0", "signal-exit": "^4.0.1" - }, - "dependencies": { - "signal-exit": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.0.2.tgz", - "integrity": "sha512-MY2/qGx4enyjprQnFaZsHib3Yadh3IXyV2C321GY0pjGfVBu4un0uDJkwgdxqO+Rdx8JMT8IfJIRwbYVz3Ob3Q==", - "dev": true - } } }, "forever-agent": { @@ -26914,9 +27404,9 @@ } }, "glob": { - "version": "10.2.7", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.2.7.tgz", - "integrity": "sha512-jTKehsravOJo8IJxUGfZILnkvVJM/MOfHRs8QcXolVef2zNI9Tqyy5+SeuOAZd3upViEZQLyFpQhYiHLrMUNmA==", + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.3.0.tgz", + "integrity": "sha512-AQ1/SB9HH0yCx1jXAT4vmCbTOPe5RQ+kCurjbel5xSCGhebumUv+GJZfa1rEqor3XIViqwSEmlkZCQD43RWrBg==", "dev": true, "requires": { "foreground-child": "^3.1.0", @@ -26936,9 +27426,9 @@ } }, "minimatch": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.1.tgz", - "integrity": "sha512-0jWhJpD/MdhPXwPuiRkCbfYfSKp2qnn2eOc279qI7f+osl/l+prKSrvhg157zSYvx/1nmgn2NqdT6k2Z7zSH9w==", + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.2.tgz", + "integrity": "sha512-PZOT9g5v2ojiTL7r1xF6plNHLtOeTpSlDI007As2NlA2aYBMfVom17yqa6QzhmDP8QOhn7LjHTg7DFCVSSa6yg==", "dev": true, "requires": { "brace-expansion": "^2.0.1" @@ -27109,15 +27599,6 @@ "optional": true, "requires": { "tslib": "^2.1.0" - }, - "dependencies": { - "tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==", - "dev": true, - "optional": true - } } }, "growl": { @@ -27173,9 +27654,9 @@ "dev": true }, "hardhat": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/hardhat/-/hardhat-2.14.1.tgz", - "integrity": "sha512-H3Qp/UKyQGmPDDBSfMoSyH18rRnac90rsb0LNer+sKe6at6rxLe4D5j+M+1icqZQF02iLPjNRwc/PA8OPf757A==", + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/hardhat/-/hardhat-2.16.0.tgz", + "integrity": "sha512-7VQEJPQRAZdtrYUZaU9GgCpP3MBNy/pTdscARNJQMWKj5C+R7V32G5uIZKIqZ4QiqXa6CBfxxe+G+ahxUbHZHA==", "dev": true, "requires": { "@ethersproject/abi": "^5.1.2", @@ -27217,7 +27698,6 @@ "mnemonist": "^0.38.0", "mocha": "^10.0.0", "p-map": "^4.0.0", - "qs": "^6.7.0", "raw-body": "^2.4.1", "resolve": "1.17.0", "semver": "^6.3.0", @@ -27230,6 +27710,12 @@ "ws": "^7.4.6" }, "dependencies": { + "@noble/hashes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz", + "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==", + "dev": true + }, "commander": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/commander/-/commander-3.0.2.tgz", @@ -27372,13 +27858,20 @@ "dev": true } } + }, + "ws": { + "version": "7.5.9", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz", + "integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==", + "dev": true, + "requires": {} } } }, "hardhat-contract-sizer": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/hardhat-contract-sizer/-/hardhat-contract-sizer-2.9.0.tgz", - "integrity": "sha512-0I5lJo0iVPfK3YQNRv+zF4KHcdPbXPp9VCCOTcpDK/mfjWHiPxQwZv7eVt9S1JjvegjAVRtJPe9U5zQtd8LJGA==", + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/hardhat-contract-sizer/-/hardhat-contract-sizer-2.10.0.tgz", + "integrity": "sha512-QiinUgBD5MqJZJh1hl1jc9dNnpJg7eE/w4/4GEnrcmZJJTDbVFNe3+/3Ep24XqISSkYxRz36czcPHKHd/a0dwA==", "dev": true, "requires": { "chalk": "^4.0.0", @@ -28184,9 +28677,9 @@ "dev": true }, "js-sdsl": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.4.0.tgz", - "integrity": "sha512-FfVSdx6pJ41Oa+CF7RDaFmTnCaFhua+SNYQX74riGOpl96x+2jQCqEfQ2bnXu/5DPCqlRuiqyvTJM0Qjz26IVg==", + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.4.1.tgz", + "integrity": "sha512-6Gsx8R0RucyePbWqPssR8DyfuXmLBooYN5cZFZKjHGnQuaf7pEzhtpceagJxVu4LqhYY5EYA7nko3FmeHZ1KbA==", "dev": true }, "js-sha3": { @@ -28686,6 +29179,13 @@ "dev": true, "peer": true }, + "lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==", + "dev": true, + "peer": true + }, "lodash.flatten": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", @@ -29554,9 +30054,9 @@ } }, "semver": { - "version": "7.5.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz", - "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==", + "version": "7.5.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", + "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" @@ -29922,9 +30422,9 @@ }, "dependencies": { "lru-cache": { - "version": "9.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-9.1.1.tgz", - "integrity": "sha512-65/Jky17UwSb0BuB9V+MyDpsOtXKmYwzhyl+cOa9XUiI4uV2Ouy/2voFP3+al0BjZbJgMBD8FojMpAf+Z+qn4A==", + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-9.1.2.tgz", + "integrity": "sha512-ERJq3FOzJTxBbFjZ7iDs+NiK4VI9Wz+RdrrAB8dio1oV+YvdPzUEE4QNiT2VD51DkIbCYRUUzCRkssXCHqSnKQ==", "dev": true } } @@ -30448,9 +30948,9 @@ } }, "semver": { - "version": "7.5.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz", - "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==", + "version": "7.5.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", + "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" @@ -30540,13 +31040,10 @@ "dev": true }, "qs": { - "version": "6.11.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.2.tgz", - "integrity": "sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==", - "dev": true, - "requires": { - "side-channel": "^1.0.4" - } + "version": "6.5.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", + "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", + "dev": true }, "query-string": { "version": "5.1.1", @@ -30831,12 +31328,6 @@ "uuid": "^3.3.2" }, "dependencies": { - "qs": { - "version": "6.5.3", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", - "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", - "dev": true - }, "uuid": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", @@ -30967,6 +31458,15 @@ "requires": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" + }, + "dependencies": { + "signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "optional": true + } } }, "retry": { @@ -31417,11 +31917,10 @@ } }, "signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, - "optional": true + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.0.2.tgz", + "integrity": "sha512-MY2/qGx4enyjprQnFaZsHib3Yadh3IXyV2C321GY0pjGfVBu4un0uDJkwgdxqO+Rdx8JMT8IfJIRwbYVz3Ob3Q==", + "dev": true }, "simple-concat": { "version": "1.0.1", @@ -31923,9 +32422,9 @@ "dev": true }, "solidity-coverage": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/solidity-coverage/-/solidity-coverage-0.8.2.tgz", - "integrity": "sha512-cv2bWb7lOXPE9/SSleDO6czkFiMHgP4NXPj+iW9W7iEKLBk7Cj0AGBiNmGX3V1totl9wjPrT0gHmABZKZt65rQ==", + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/solidity-coverage/-/solidity-coverage-0.8.3.tgz", + "integrity": "sha512-hbcNgj5z8zzgTlnp4F0pXiqj1v5ua8P4DH5i9cWOBtFPfUuIohLoXu5WiAixexWmpKVjyxXqupnu/mPb4IGr7Q==", "dev": true, "peer": true, "requires": { @@ -32227,9 +32726,9 @@ } }, "semver": { - "version": "7.5.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz", - "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==", + "version": "7.5.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", + "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", "dev": true, "peer": true, "requires": { @@ -33102,14 +33601,14 @@ "dev": true }, "truffle": { - "version": "5.9.4", - "resolved": "https://registry.npmjs.org/truffle/-/truffle-5.9.4.tgz", - "integrity": "sha512-35UUp6Y+TAZ/ZTrUUtmIr6XSacKlq36QalC96tABsPdATKe5xBJkUKqbJBKuQcLtV1BL7nOLqgQs7fyecSXKaA==", + "version": "5.10.1", + "resolved": "https://registry.npmjs.org/truffle/-/truffle-5.10.1.tgz", + "integrity": "sha512-U4Mj0I8s/qTCikUIwy0/sJaIroveltNZ1sNq0OTBqQ8Km3Blm8KMBcsIwgTVAEDHx548QKsXF5lkc5dTLEubVg==", "dev": true, "requires": { - "@truffle/db": "^2.0.28", - "@truffle/db-loader": "^0.2.28", - "@truffle/debugger": "^11.1.4", + "@truffle/db": "^2.0.30", + "@truffle/db-loader": "^0.2.30", + "@truffle/debugger": "^12.0.0", "app-module-path": "^2.2.0", "ganache": "7.8.0", "mocha": "10.1.0", @@ -33273,13 +33772,12 @@ } }, "ts-command-line-args": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-command-line-args/-/ts-command-line-args-2.5.0.tgz", - "integrity": "sha512-Ff7Xt04WWCjj/cmPO9eWTJX3qpBZWuPWyQYG1vnxJao+alWWYjwJBc5aYz3h5p5dE08A6AnpkgiCtP/0KXXBYw==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/ts-command-line-args/-/ts-command-line-args-2.5.1.tgz", + "integrity": "sha512-H69ZwTw3rFHb5WYpQya40YAX2/w7Ut75uUECbgBIsLmM+BNuYnxsltfyyLMxy6sEeKxgijLTnQtLd0nKd6+IYw==", "dev": true, "peer": true, "requires": { - "@morgan-stanley/ts-mocking-bird": "^0.6.2", "chalk": "^4.1.0", "command-line-args": "^5.1.1", "command-line-usage": "^6.1.0", @@ -33383,9 +33881,9 @@ } }, "tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", + "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==", "dev": true }, "tsort": { @@ -33524,9 +34022,9 @@ } }, "typescript": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.0.4.tgz", - "integrity": "sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==", + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.3.tgz", + "integrity": "sha512-XH627E9vkeqhlZFQuL+UsyAXEnibT0kWR2FWONlr4sTjvxyJYnyefgrkyECLzM5NenmKzRAy2rR/OlYLA1HkZw==", "dev": true, "peer": true }, @@ -34239,53 +34737,52 @@ "dev": true }, "wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", "dev": true, "requires": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" }, "dependencies": { "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", "dev": true }, "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "requires": { - "color-convert": "^2.0.1" - } + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true + }, + "string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", "dev": true, "requires": { - "color-name": "~1.1.4" + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" } }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - }, "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", "dev": true, "requires": { - "ansi-regex": "^5.0.1" + "ansi-regex": "^6.0.1" } } } @@ -34368,9 +34865,9 @@ } }, "ws": { - "version": "7.4.6", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.4.6.tgz", - "integrity": "sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A==", + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.5.0.tgz", + "integrity": "sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg==", "dev": true, "requires": {} }, diff --git a/package.json b/package.json index 86720802b..a14a805ec 100644 --- a/package.json +++ b/package.json @@ -74,9 +74,8 @@ }, "devDependencies": { "@bosonprotocol/solidoc": "3.0.3", - "@ethereum-waffle/mock-contract": "^4.0.4", "@nomicfoundation/hardhat-network-helpers": "^1.0.6", - "@nomicfoundation/hardhat-toolbox": "^2.0.2", + "@nomicfoundation/hardhat-toolbox": "^3.0.0", "@nomiclabs/hardhat-web3": "^2.0.0", "@openzeppelin/test-helpers": "^0.5.16", "coveralls": "^3.1.1", @@ -98,6 +97,7 @@ "simple-statistics": "^7.8.2", "solhint": "^3.3.8", "truffle": "^5.9.4", - "web3": "^1.8.1" + "web3": "^1.8.1", + "ethers": "^6.6.0" } } diff --git a/scripts/config/facet-deploy.js b/scripts/config/facet-deploy.js index fcc292d16..c2d9f0edd 100644 --- a/scripts/config/facet-deploy.js +++ b/scripts/config/facet-deploy.js @@ -26,9 +26,7 @@ function getConfigHandlerInitArgs() { * @returns {Object} - array of function hashes */ async function getMetaTransactionsHandlerFacetInitArgs(facets) { - const getFunctionHashesClosure = getStateModifyingFunctionsHashes(facets, [ - "executeMetaTransaction(address,string,bytes,uint256,bytes32,bytes32,uint8)", - ]); + const getFunctionHashesClosure = getStateModifyingFunctionsHashes(facets, ["executeMetaTransaction"]); return await getFunctionHashesClosure(); } diff --git a/scripts/config/protocol-parameters.js b/scripts/config/protocol-parameters.js index 6fc9ceab7..c222d16c6 100644 --- a/scripts/config/protocol-parameters.js +++ b/scripts/config/protocol-parameters.js @@ -20,13 +20,13 @@ module.exports = { maxOffersPerBatch: "12", maxTokensPerWithdrawal: "125", maxFeesPerDisputeResolver: "75", - maxEscalationResponsePeriod: ninetyDays, + maxEscalationResponsePeriod: ninetyDays.toString(), maxDisputesPerBatch: "75", maxAllowedSellers: "140", maxTotalOfferFeePercentage: "10000", // 100% maxRoyaltyPecentage: "10000", //100% - maxResolutionPeriod: ninetyDays, - minDisputePeriod: oneWeek, + maxResolutionPeriod: ninetyDays.toString(), + minDisputePeriod: oneWeek.toString(), maxPremintedVouchers: "10000", }, diff --git a/scripts/deploy-suite.js b/scripts/deploy-suite.js index b24551b69..186f60a93 100644 --- a/scripts/deploy-suite.js +++ b/scripts/deploy-suite.js @@ -1,11 +1,11 @@ const environments = require("../environments"); const hre = require("hardhat"); -const ethers = hre.ethers; +const { ZeroAddress, getContractAt, getSigners } = hre.ethers; const network = hre.network.name; const confirmations = network == "hardhat" ? 1 : environments.confirmations; -const tipMultiplier = ethers.BigNumber.from(environments.tipMultiplier); +const tipMultiplier = BigInt(environments.tipMultiplier); const tipSuggestion = "1500000000"; // ethers.js always returns this constant, it does not vary per block -const maxPriorityFeePerGas = ethers.BigNumber.from(tipSuggestion).mul(tipMultiplier); +const maxPriorityFeePerGas = BigInt(tipSuggestion) * tipMultiplier; const packageFile = require("../package.json"); const authTokenAddresses = require("./config/auth-token-addresses"); @@ -61,19 +61,19 @@ async function main(env, facetConfig) { const authTokenContracts = getAuthTokenContracts(); // Get the accounts - const accounts = await ethers.getSigners(); + const accounts = await getSigners(); const deployer = accounts[0]; // If hardhat, get an address generated by the mnemonic const adminAddress = network === "hardhat" ? accounts[1].address : environments[network].adminAddress; // If admin address is unspecified, exit the deployment process - if (adminAddress == ethers.constants.AddressZero || !adminAddress) { + if (adminAddress == ZeroAddress || !adminAddress) { console.log("Admin address must not be zero address"); process.exit(1); } - console.log("🔱 Deployer account: ", deployer ? deployer.address : "not found" && process.exit()); + console.log("🔱 Deployer account: ", deployer ? await deployer.getAddress() : "not found" && process.exit()); console.log(divider); console.log(`💎 Deploying AccessController, ProtocolDiamond, and Diamond utility facets...`); @@ -82,18 +82,30 @@ async function main(env, facetConfig) { const [protocolDiamond, dlf, dcf, erc165f, accessController, diamondArgs] = await deployProtocolDiamond( maxPriorityFeePerGas ); - deploymentComplete("AccessController", accessController.address, [], "", contracts); - deploymentComplete("DiamondLoupeFacet", dlf.address, [], interfaceIdFromFacetName("DiamondLoupeFacet"), contracts); - deploymentComplete("DiamondCutFacet", dcf.address, [], interfaceIdFromFacetName("DiamondCutFacet"), contracts); - deploymentComplete("ERC165Facet", erc165f.address, [], interfaceIdFromFacetName("ERC165Facet"), contracts); - deploymentComplete("ProtocolDiamond", protocolDiamond.address, diamondArgs, "", contracts); + deploymentComplete("AccessController", await accessController.getAddress(), [], "", contracts); + deploymentComplete( + "DiamondLoupeFacet", + await dlf.getAddress(), + [], + interfaceIdFromFacetName("DiamondLoupeFacet"), + contracts + ); + deploymentComplete( + "DiamondCutFacet", + await dcf.getAddress(), + [], + interfaceIdFromFacetName("DiamondCutFacet"), + contracts + ); + deploymentComplete("ERC165Facet", await erc165f.getAddress(), [], interfaceIdFromFacetName("ERC165Facet"), contracts); + deploymentComplete("ProtocolDiamond", await protocolDiamond.getAddress(), diamondArgs, "", contracts); console.log(`\n💎 Granting UPGRADER role...`); // Temporarily grant UPGRADER role to deployer account transactionResponse = await accessController.grantRole( Role.UPGRADER, - deployer.address, + await deployer.getAddress(), await getFees(maxPriorityFeePerGas) ); await transactionResponse.wait(confirmations); @@ -113,12 +125,17 @@ async function main(env, facetConfig) { } const { version } = packageFile; - let { deployedFacets } = await deployAndCutFacets(protocolDiamond.address, facetData, maxPriorityFeePerGas, version); + let { deployedFacets } = await deployAndCutFacets( + await protocolDiamond.getAddress(), + facetData, + maxPriorityFeePerGas, + version + ); for (const deployedFacet of deployedFacets) { deploymentComplete( deployedFacet.name, - deployedFacet.contract.address, + deployedFacet.contract.target, deployedFacet.constructorArgs, interfaceIdFromFacetName(deployedFacet.name), contracts @@ -128,7 +145,7 @@ async function main(env, facetConfig) { console.log(`\n⧉ Deploying Protocol Client implementation/proxy pairs...`); // Deploy the Protocol Client implementation/proxy pairs - const protocolClientArgs = [protocolDiamond.address]; + const protocolClientArgs = [await protocolDiamond.getAddress()]; const clientImplementationArgs = Object.values(clientConfig).map( (config) => process.env.FORWARDER_ADDRESS || config[network] ); @@ -142,27 +159,27 @@ async function main(env, facetConfig) { const [bosonVoucherProxy] = proxies; // Gather the complete args that were used to create the proxies - const bosonVoucherProxyArgs = [...protocolClientArgs, bosonVoucherImpl.address]; + const bosonVoucherProxyArgs = [...protocolClientArgs, await bosonVoucherImpl.getAddress()]; // Report and prepare for verification - deploymentComplete("BosonVoucher Logic", bosonVoucherImpl.address, [], "", contracts); - deploymentComplete("BosonVoucher Beacon", bosonClientBeacon.address, bosonVoucherProxyArgs, "", contracts); - deploymentComplete("BosonVoucher Proxy", bosonVoucherProxy.address, [], "", contracts); + deploymentComplete("BosonVoucher Logic", await bosonVoucherImpl.getAddress(), [], "", contracts); + deploymentComplete("BosonVoucher Beacon", await bosonClientBeacon.getAddress(), bosonVoucherProxyArgs, "", contracts); + deploymentComplete("BosonVoucher Proxy", await bosonVoucherProxy.getAddress(), [], "", contracts); console.log(`\n🌐️Configuring and granting roles...`); // Cast Diamond to the IBosonConfigHandler interface for further interaction with it - const bosonConfigHandler = await ethers.getContractAt("IBosonConfigHandler", protocolDiamond.address); + const bosonConfigHandler = await getContractAt("IBosonConfigHandler", await protocolDiamond.getAddress()); // Add Voucher addresses to protocol config transactionResponse = await bosonConfigHandler.setVoucherBeaconAddress( - bosonClientBeacon.address, + await bosonClientBeacon.getAddress(), await getFees(maxPriorityFeePerGas) ); await transactionResponse.wait(confirmations); transactionResponse = await bosonConfigHandler.setBeaconProxyAddress( - bosonVoucherProxy.address, + await bosonVoucherProxy.getAddress(), await getFees(maxPriorityFeePerGas) ); await transactionResponse.wait(confirmations); @@ -192,7 +209,7 @@ async function main(env, facetConfig) { // Renounce temporarily granted UPGRADER role for deployer account transactionResponse = await accessController.renounceRole( Role.UPGRADER, - deployer.address, + await deployer.getAddress(), await getFees(maxPriorityFeePerGas) ); await transactionResponse.wait(confirmations); @@ -200,12 +217,12 @@ async function main(env, facetConfig) { // Grant PROTOCOL role to the ProtocolDiamond contract transactionResponse = await accessController.grantRole( Role.PROTOCOL, - protocolDiamond.address, + await protocolDiamond.getAddress(), await getFees(maxPriorityFeePerGas) ); await transactionResponse.wait(confirmations); - if (adminAddress.toLowerCase() != deployer.address.toLowerCase()) { + if (adminAddress.toLowerCase() != (await deployer.getAddress()).toLowerCase()) { // Grant ADMIN role to the specified admin address // Skip this step if adminAddress is the deployer transactionResponse = await accessController.grantRole( diff --git a/scripts/domain/AuthToken.js b/scripts/domain/AuthToken.js index f5d965a04..cdfdad661 100644 --- a/scripts/domain/AuthToken.js +++ b/scripts/domain/AuthToken.js @@ -42,7 +42,7 @@ class AuthToken { return AuthToken.fromObject({ tokenId: tokenId.toString(), - tokenType: tokenType, + tokenType: Number(tokenType), }); } diff --git a/scripts/domain/Condition.js b/scripts/domain/Condition.js index 21a4930af..79a10e136 100644 --- a/scripts/domain/Condition.js +++ b/scripts/domain/Condition.js @@ -51,7 +51,7 @@ class Condition { return Condition.fromObject({ method: parseInt(method), - tokenType, + tokenType: Number(tokenType), tokenAddress, tokenId: tokenId.toString(), threshold: threshold.toString(), diff --git a/scripts/domain/Dispute.js b/scripts/domain/Dispute.js index 6f9037a7a..9e6dd9038 100644 --- a/scripts/domain/Dispute.js +++ b/scripts/domain/Dispute.js @@ -43,7 +43,7 @@ class Dispute { return Dispute.fromObject({ exchangeId: exchangeId.toString(), buyerPercent: buyerPercent.toString(), - state, + state: Number(state), }); } diff --git a/scripts/domain/DisputeDates.js b/scripts/domain/DisputeDates.js index 3f50a1ab9..9dfbd2cb1 100644 --- a/scripts/domain/DisputeDates.js +++ b/scripts/domain/DisputeDates.js @@ -16,10 +16,10 @@ class DisputeDates { */ constructor(disputed, escalated, finalized, timeout) { - this.disputed = disputed; - this.escalated = escalated; - this.finalized = finalized; - this.timeout = timeout; + this.disputed = disputed?.toString(); + this.escalated = escalated?.toString(); + this.finalized = finalized?.toString(); + this.timeout = timeout?.toString(); } /** diff --git a/scripts/domain/Exchange.js b/scripts/domain/Exchange.js index 03db4eb9a..f330eb857 100644 --- a/scripts/domain/Exchange.js +++ b/scripts/domain/Exchange.js @@ -51,7 +51,7 @@ class Exchange { offerId: offerId.toString(), buyerId: buyerId.toString(), finalizedDate: finalizedDate.toString(), - state, + state: Number(state), }); } diff --git a/scripts/domain/Funds.js b/scripts/domain/Funds.js index 702abce69..2e3fffad3 100644 --- a/scripts/domain/Funds.js +++ b/scripts/domain/Funds.js @@ -17,7 +17,7 @@ class Funds { constructor(tokenAddress, tokenName, availableAmount) { this.tokenAddress = tokenAddress; this.tokenName = tokenName; - this.availableAmount = availableAmount; + this.availableAmount = availableAmount.toString(); } /** diff --git a/scripts/domain/Receipt.js b/scripts/domain/Receipt.js index 50ac308c4..8b38eaa7d 100644 --- a/scripts/domain/Receipt.js +++ b/scripts/domain/Receipt.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { ZeroAddress } = hre.ethers; const DisputeState = require("./DisputeState"); const OfferFees = require("./OfferFees.js"); const TwinReceipt = require("./TwinReceipt.js"); @@ -70,7 +70,7 @@ class Receipt { this.agentId = agentId ?? "0"; this.exchangeToken = exchangeToken; this.finalizedDate = finalizedDate; - this.condition = condition ?? new Condition(0, 0, ethers.constants.AddressZero, "0", "0", "0"); + this.condition = condition ?? new Condition(0, 0, ZeroAddress, "0", "0", "0"); this.committedDate = committedDate; this.redeemedDate = redeemedDate; this.voucherExpired = voucherExpired; @@ -140,7 +140,7 @@ class Receipt { disputeResolverId: disputeResolverId.toString(), disputedDate: disputedDate.toString(), escalatedDate: escalatedDate.toString(), - disputeState, + disputeState: Number(disputeState), twinReceipts: twinReceipts.map((twinReceipt) => TwinReceipt.fromStruct(twinReceipt)), }); } diff --git a/scripts/domain/Role.js b/scripts/domain/Role.js index b27f53df6..92e185337 100644 --- a/scripts/domain/Role.js +++ b/scripts/domain/Role.js @@ -1,6 +1,5 @@ -const ethers = require("ethers"); -const keccak256 = ethers.utils.keccak256; -const toUtf8Bytes = ethers.utils.toUtf8Bytes; +const hre = require("hardhat"); +const { keccak256, toUtf8Bytes } = hre.ethers; /** * Boson Protocol Domain Enum: Role diff --git a/scripts/domain/Twin.js b/scripts/domain/Twin.js index 176d8129b..ca16e0ea3 100644 --- a/scripts/domain/Twin.js +++ b/scripts/domain/Twin.js @@ -55,9 +55,9 @@ class Twin { sellerId: sellerId.toString(), amount: amount.toString(), supplyAvailable: supplyAvailable ? supplyAvailable.toString() : "", - tokenId: tokenId ? tokenId.toString() : "", + tokenId: tokenId ? tokenId.toString() : "0", tokenAddress, - tokenType, + tokenType: Number(tokenType), }); } diff --git a/scripts/domain/TwinReceipt.js b/scripts/domain/TwinReceipt.js index bb0db399e..1ff00b649 100644 --- a/scripts/domain/TwinReceipt.js +++ b/scripts/domain/TwinReceipt.js @@ -48,7 +48,7 @@ class TwinReceipt { tokenId: tokenId.toString(), amount: amount.toString(), tokenAddress: tokenAddress, - tokenType, + tokenType: Number(tokenType), }); } diff --git a/scripts/example/SnapshotGate/deploy-snapshot-gate.js b/scripts/example/SnapshotGate/deploy-snapshot-gate.js index cb14a40de..9361157a3 100644 --- a/scripts/example/SnapshotGate/deploy-snapshot-gate.js +++ b/scripts/example/SnapshotGate/deploy-snapshot-gate.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractFactory } = hre.ethers; const environments = require("../../../environments"); const confirmations = hre.network.name == "hardhat" ? 1 : environments.confirmations; const { getFees } = require("../../util/utils"); @@ -22,9 +22,9 @@ const { getFees } = require("../../util/utils"); */ async function deploySnapshotGateExample(snapshotGateArgs, maxPriorityFeePerGas) { // Deploy the SnapshotGate - const SnapshotGate = await ethers.getContractFactory("SnapshotGate"); + const SnapshotGate = await getContractFactory("SnapshotGate"); const snapshotGate = await SnapshotGate.deploy(...snapshotGateArgs, await getFees(maxPriorityFeePerGas)); - await snapshotGate.deployTransaction.wait(confirmations); + await snapshotGate.waitForDeployment(confirmations); return [snapshotGate]; } diff --git a/scripts/manage-roles.js b/scripts/manage-roles.js index e103bfe62..8ca209e5f 100644 --- a/scripts/manage-roles.js +++ b/scripts/manage-roles.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractAt, provider } = hre.ethers; const network = hre.network.name; const { RoleAssignments } = require("./config/role-assignments"); const { readContracts } = require("./util/utils"); @@ -31,7 +31,7 @@ async function main(env) { // Bail now if hardhat network if (network === "hardhat") process.exit(); - const chainId = (await hre.ethers.provider.getNetwork()).chainId; + const chainId = (await provider.getNetwork()).chainId; const contractsFile = readContracts(chainId, network, env); const divider = "-".repeat(80); @@ -39,7 +39,7 @@ async function main(env) { console.log(`⛓ Network: ${hre.network.name}\n📅 ${new Date()}`); // Get the accounts - const accounts = await ethers.provider.listAccounts(); + const accounts = await provider.listAccounts(); const admin = accounts[0]; console.log("🔱 Admin account: ", admin ? admin : "not found" && process.exit()); console.log(divider); @@ -49,7 +49,7 @@ async function main(env) { const accessControllerInfo = contractsFile.contracts.find((i) => i.name === "AccessController"); // Get AccessController abstraction - const accessController = await ethers.getContractAt("AccessController", accessControllerInfo.address); + const accessController = await getContractAt("AccessController", await accessControllerInfo.getAddress()); // Loop through assignments for this network const assignments = Object.entries(RoleAssignments[network]); @@ -63,19 +63,19 @@ async function main(env) { let contractInfo; contractInfo = contractsFile.contracts.find((i) => i.name === name); - config.address = name === "AdminAddress" ? environments[network].adminAddress : contractInfo.address; + config.address = name === "AdminAddress" ? environments[network].adminAddress : await contractInfo.getAddress(); - console.log(` 👉 ${config.address}`); + console.log(` 👉 ${await config.getAddress()}`); // Loop through assigned roles for address for (let j = 0; j < config.roles.length; j++) { // Check if role already assigned const role = config.roles[j]; - const hasRole = await accessController.hasRole(role, config.address); + const hasRole = await accessController.hasRole(role, await config.getAddress()); // Grant role if not already granted if (!hasRole) { - await accessController.grantRole(role, config.address); + await accessController.grantRole(role, await config.getAddress()); } // Report status @@ -88,11 +88,11 @@ async function main(env) { for (let j = 0; j < unassigned.length; j++) { // Check if role currently assigned const role = Role[unassigned[j]]; - const hasRole = await accessController.hasRole(role, config.address); + const hasRole = await accessController.hasRole(role, await config.getAddress()); // Revoke role if previously granted if (hasRole) { - await accessController.revokeRole(role, config.address); + await accessController.revokeRole(role, await config.getAddress()); } // Report status diff --git a/scripts/migrations/migrate_2.2.1.js b/scripts/migrations/migrate_2.2.1.js index 0ebbce5e8..a11a5f543 100644 --- a/scripts/migrations/migrate_2.2.1.js +++ b/scripts/migrations/migrate_2.2.1.js @@ -1,7 +1,7 @@ const shell = require("shelljs"); const { readContracts } = require("../util/utils.js"); const hre = require("hardhat"); -const ethers = hre.ethers; +const { provider, getContractAt } = hre.ethers; const network = hre.network.name; const { getStateModifyingFunctionsHashes } = require("../../scripts/util/diamond-utils.js"); const tag = "v2.2.1"; @@ -40,7 +40,7 @@ async function migrate(env) { shell.exec(`npm install`); } - const { chainId } = await ethers.provider.getNetwork(); + const { chainId } = await provider.getNetwork(); const contractsFile = readContracts(chainId, network, env); if (contractsFile?.protocolVersion != "2.2.0") { @@ -86,7 +86,7 @@ async function migrate(env) { const selectorsToAdd = await getFunctionHashesClosure(); - const metaTransactionHandlerFacet = await ethers.getContractAt("MetaTransactionsHandlerFacet", protocolAddress); + const metaTransactionHandlerFacet = await getContractAt("MetaTransactionsHandlerFacet", protocolAddress); console.log("Removing selectors", selectorsToRemove.join(",")); await metaTransactionHandlerFacet.setAllowlistedFunctions(selectorsToRemove, false); diff --git a/scripts/upgrade-clients.js b/scripts/upgrade-clients.js index 7facc38aa..df0549401 100644 --- a/scripts/upgrade-clients.js +++ b/scripts/upgrade-clients.js @@ -1,10 +1,10 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { provider, ZeroAddress, getSigners, getSigner, getContractAt } = hre.ethers; const network = hre.network.name; const environments = require("../environments"); -const tipMultiplier = ethers.BigNumber.from(environments.tipMultiplier); -const tipSuggestion = "1500000000"; // ethers.js always returns this constant, it does not vary per block -const maxPriorityFeePerGas = ethers.BigNumber.from(tipSuggestion).mul(tipMultiplier); +const tipMultiplier = BigInt(environments.tipMultiplier); +const tipSuggestion = "1500000000"; // js always returns this constant, it does not vary per block +const maxPriorityFeePerGas = BigInt(tipSuggestion).mul(tipMultiplier); const { deploymentComplete, getFees, @@ -29,7 +29,7 @@ async function main(env, clientConfig, version) { // Bail now if hardhat network, unless the upgrade is tested if (network === "hardhat" && env !== "upgrade-test") process.exit(); - const { chainId } = await ethers.provider.getNetwork(); + const { chainId } = await provider.getNetwork(); let { contracts } = readContracts(chainId, network, env); const divider = "-".repeat(80); @@ -37,17 +37,16 @@ async function main(env, clientConfig, version) { console.log(`⛓ Network: ${network}\n📅 ${new Date()}`); // If hardhat, get an address generated by the mnemonic - const adminAddress = - network === "hardhat" ? (await ethers.getSigners())[0].address : environments[network].adminAddress; + const adminAddress = network === "hardhat" ? (await getSigners())[0].address : environments[network].adminAddress; // If admin address is unspecified, exit the process - if (adminAddress == ethers.constants.AddressZero || !adminAddress) { + if (adminAddress == ZeroAddress || !adminAddress) { console.log("Admin address must not be zero address"); process.exit(1); } // Get list of accounts managed by node - const nodeAccountList = (await ethers.provider.listAccounts()).map((address) => address.toLowerCase()); + const nodeAccountList = (await provider.listAccounts()).map((address) => address.toLowerCase()); if (nodeAccountList.includes(adminAddress.toLowerCase())) { console.log("🔱 Admin account: ", adminAddress); @@ -58,7 +57,7 @@ async function main(env, clientConfig, version) { console.log(divider); // Get signer for admin address - const adminSigner = await ethers.getSigner(adminAddress); + const adminSigner = await getSigner(adminAddress); // Get addresses of currently deployed Beacon contract const beaconAddress = contracts.find((c) => c.name === "BosonVoucher Beacon")?.address; @@ -81,14 +80,20 @@ async function main(env, clientConfig, version) { // Update implementation address on beacon contract console.log(`\n📋 Updating implementation address on beacon`); - const beacon = await ethers.getContractAt("BosonClientBeacon", beaconAddress); + const beacon = await getContractAt("BosonClientBeacon", beaconAddress); await beacon .connect(adminSigner) - .setImplementation(bosonVoucherImplementation.address, await getFees(maxPriorityFeePerGas)); + .setImplementation(await bosonVoucherImplementation.getAddress(), await getFees(maxPriorityFeePerGas)); // Remove old entry from contracts contracts = contracts.filter((i) => i.name !== "BosonVoucher Logic"); - deploymentComplete("BosonVoucher Logic", bosonVoucherImplementation.address, clientImplementationArgs, "", contracts); + deploymentComplete( + "BosonVoucher Logic", + await bosonVoucherImplementation.getAddress(), + clientImplementationArgs, + "", + contracts + ); const contractsPath = await writeContracts(contracts, env, version); console.log(divider); diff --git a/scripts/upgrade-facets.js b/scripts/upgrade-facets.js index 9a494dada..81bcd3a42 100644 --- a/scripts/upgrade-facets.js +++ b/scripts/upgrade-facets.js @@ -1,12 +1,12 @@ const fs = require("fs"); const hre = require("hardhat"); -const ethers = hre.ethers; +const { ZeroAddress, getContractAt, provider, getSigners, getContractFactory } = hre.ethers; const network = hre.network.name; const { getFacets } = require("./config/facet-upgrade"); const environments = require("../environments"); -const tipMultiplier = ethers.BigNumber.from(environments.tipMultiplier); -const tipSuggestion = "1500000000"; // ethers.js always returns this constant, it does not vary per block -const maxPriorityFeePerGas = ethers.BigNumber.from(tipSuggestion).mul(tipMultiplier); +const tipMultiplier = BigInt(environments.tipMultiplier); +const tipSuggestion = "1500000000"; // js always returns this constant, it does not vary per block +const maxPriorityFeePerGas = BigInt(tipSuggestion).mul(tipMultiplier); const { deploymentComplete, readContracts, writeContracts, checkRole, addressNotFound } = require("./util/utils.js"); const { deployProtocolFacets } = requireUncached("./util/deploy-protocol-handler-facets.js"); const { @@ -44,7 +44,7 @@ async function main(env, facetConfig, version) { // Bail now if hardhat network, unless the upgrade is tested if (network === "hardhat" && env !== "upgrade-test") process.exit(); - const { chainId } = await ethers.provider.getNetwork(); + const { chainId } = await provider.getNetwork(); const contractsFile = readContracts(chainId, network, env); let contracts = contractsFile.contracts; const interfaceIds = await getInterfaceIds(false); @@ -81,17 +81,16 @@ async function main(env, facetConfig, version) { } // If hardhat, get an address generated by the mnemonic - const adminAddress = - network === "hardhat" ? (await ethers.getSigners())[0].address : environments[network].adminAddress; + const adminAddress = network === "hardhat" ? (await getSigners())[0].address : environments[network].adminAddress; // If admin address is unspecified, exit the process - if (adminAddress == ethers.constants.AddressZero || !adminAddress) { + if (adminAddress == ZeroAddress || !adminAddress) { console.log("Admin address must not be zero address"); process.exit(1); } // Get list of accounts managed by node - const nodeAccountList = (await ethers.provider.listAccounts()).map((address) => address.toLowerCase()); + const nodeAccountList = (await provider.listAccounts()).map((address) => address.toLowerCase()); if (nodeAccountList.includes(adminAddress.toLowerCase())) { console.log("🔱 Admin account: ", adminAddress); @@ -131,8 +130,8 @@ async function main(env, facetConfig, version) { let deployedFacets = await deployProtocolFacets(facets.addOrUpgrade, facets.facetsToInit, maxPriorityFeePerGas); // Cast Diamond to DiamondCutFacet, DiamondLoupeFacet and IERC165Extended - const diamondCutFacet = await ethers.getContractAt("DiamondCutFacet", protocolAddress); - const diamondLoupe = await ethers.getContractAt("DiamondLoupeFacet", protocolAddress); + const diamondCutFacet = await getContractAt("DiamondCutFacet", protocolAddress); + const diamondLoupe = await getContractAt("DiamondLoupeFacet", protocolAddress); const facetCutRemove = []; const interfacesToRemove = {}, @@ -147,7 +146,7 @@ async function main(env, facetConfig, version) { let registeredSelectors; if (oldFacet) { // Facet exists, so all selectors should be removed - registeredSelectors = await diamondLoupe.facetFunctionSelectors(oldFacet.address); + registeredSelectors = await diamondLoupe.facetFunctionSelectors(await oldFacet.getAddress()); } else { // Facet does not exist, skip next steps continue; @@ -161,7 +160,7 @@ async function main(env, facetConfig, version) { removedSelectors.push(selectorsToRemove); // add to global list // Removing the selectors - facetCutRemove.push([ethers.constants.AddressZero, FacetCutAction.Remove, selectorsToRemove]); + facetCutRemove.push([ZeroAddress, FacetCutAction.Remove, selectorsToRemove]); if (oldFacet) { // Remove support for old interface @@ -191,7 +190,7 @@ async function main(env, facetConfig, version) { let registeredSelectors; if (oldFacet) { // Facet already exists and is only upgraded - registeredSelectors = await diamondLoupe.facetFunctionSelectors(oldFacet.address); + registeredSelectors = await diamondLoupe.facetFunctionSelectors(await oldFacet.getAddress()); } else { // Facet is new registeredSelectors = []; @@ -201,20 +200,14 @@ async function main(env, facetConfig, version) { contracts = contracts.filter((i) => i.name !== newFacet.name); const newFacetInterfaceId = interfaceIdFromFacetName(newFacet.name); - deploymentComplete( - newFacet.name, - newFacet.contract.address, - newFacet.constructorArgs, - newFacetInterfaceId, - contracts - ); + deploymentComplete(newFacet.name, newFacet.contract, newFacet.constructorArgs, newFacetInterfaceId, contracts); // Get new selectors from compiled contract const selectors = getSelectors(newFacet.contract, true); let newSelectors = selectors.selectors; // Initialize selectors should not be added - const facetFactory = await ethers.getContractFactory(newFacet.name); + const facetFactory = await getContractFactory(newFacet.name); const functionFragment = facetFactory.interface.getFunction("initialize"); const signature = facetFactory.interface.getSighash(functionFragment); newSelectors = selectors.selectors.remove([signature]); @@ -237,7 +230,7 @@ async function main(env, facetConfig, version) { if (removedSelectors.flat().includes(selectorToAdd)) continue; // skip if selector is already marked for removal from another facet const existingFacetAddress = await diamondLoupe.facetAddress(selectorToAdd); - if (existingFacetAddress != ethers.constants.AddressZero) { + if (existingFacetAddress != ZeroAddress) { // Selector exist on some other facet const selectorName = selectors.signatureToNameMapping[selectorToAdd]; let answer; @@ -262,7 +255,7 @@ async function main(env, facetConfig, version) { } } - const newFacetAddress = newFacet.contract.address; + const newFacetAddress = newFacet.contract; if (selectorsToAdd.length > 0) { deployedFacets[index].cut.push([newFacetAddress, FacetCutAction.Add, selectorsToAdd]); } @@ -270,7 +263,7 @@ async function main(env, facetConfig, version) { deployedFacets[index].cut.push([newFacetAddress, FacetCutAction.Replace, selectorsToReplace]); } if (selectorsToRemove.length > 0) { - deployedFacets[index].cut.push([ethers.constants.AddressZero, FacetCutAction.Remove, selectorsToRemove]); + deployedFacets[index].cut.push([ZeroAddress, FacetCutAction.Remove, selectorsToRemove]); } if (oldFacet && (selectorsToAdd.length > 0 || selectorsToRemove.length > 0)) { @@ -295,7 +288,7 @@ async function main(env, facetConfig, version) { }); } - const erc165 = await ethers.getContractAt("contracts/interfaces/IERC165.sol:IERC165", protocolAddress); + const erc165 = await getContractAt("contracts/interfaces/IERC165.sol:IERC165", protocolAddress); const support = await erc165.supportsInterface(newFacetInterfaceId); if (!support) { interfacesToAdd[oldFacet.name] = newFacetInterfaceId; @@ -306,7 +299,7 @@ async function main(env, facetConfig, version) { // Get ProtocolInitializationHandlerFacet from deployedFacets when added/replaced in this upgrade or get it from contracts if already deployed let protocolInitializationFacet = await getInitializationFacet(deployedFacets, contracts); const facetsToInit = deployedFacets.filter((facet) => facet.initialize) ?? []; - const initializeCalldata = getInitializeCalldata( + const initializeCalldata = await getInitializeCalldata( facetsToInit, version, true, @@ -317,10 +310,10 @@ async function main(env, facetConfig, version) { ); await cutDiamond( - diamondCutFacet.address, + await diamondCutFacet.getAddress(), maxPriorityFeePerGas, deployedFacets, - protocolInitializationFacet.address, + await protocolInitializationFacet.getAddress(), initializeCalldata, facetCutRemove ); @@ -362,7 +355,7 @@ async function main(env, facetConfig, version) { } // Cast diamond to ProtocolInitializationHandlerFacet - protocolInitializationFacet = await ethers.getContractAt("ProtocolInitializationHandlerFacet", protocolAddress); + protocolInitializationFacet = await getContractAt("ProtocolInitializationHandlerFacet", protocolAddress); const newVersion = (await protocolInitializationFacet.getVersion()).replace(/\0/g, ""); console.log(`\n📋 New version: ${newVersion}`); @@ -404,7 +397,7 @@ const getInitializationFacet = async (deployedFacets, contracts) => { if (protocolInitializationDeployed) { protocolInitializationFacet = protocolInitializationDeployed.contract; } else { - protocolInitializationFacet = await ethers.getContractAt( + protocolInitializationFacet = await getContractAt( protocolInitializationName, contracts.find((i) => i.name == protocolInitializationName).address ); diff --git a/scripts/upgrade-hooks/2.2.0.js b/scripts/upgrade-hooks/2.2.0.js index b103388a7..b439d59bb 100644 --- a/scripts/upgrade-hooks/2.2.0.js +++ b/scripts/upgrade-hooks/2.2.0.js @@ -1,8 +1,9 @@ const { ethers } = require("hardhat"); +const { getContractAt } = ethers; const environments = require("../../environments"); -const tipMultiplier = ethers.BigNumber.from(environments.tipMultiplier); -const tipSuggestion = "1500000000"; // ethers.js always returns this constant, it does not vary per block -const maxPriorityFeePerGas = ethers.BigNumber.from(tipSuggestion).mul(tipMultiplier); +const tipMultiplier = BigInt(environments.tipMultiplier); +const tipSuggestion = "1500000000"; // js always returns this constant, it does not vary per block +const maxPriorityFeePerGas = BigInt(tipSuggestion).mul(tipMultiplier); const { getFees } = require("./../util/utils"); const PausableRegion = require("../domain/PausableRegion.js"); @@ -10,11 +11,11 @@ const PausableRegion = require("../domain/PausableRegion.js"); async function preUpgrade(protocolAddress, facets) { // Pause the exchanges region of the protocol console.log("Pausing the protocol..."); - const pauseHandler = await ethers.getContractAt("IBosonPauseHandler", protocolAddress); + const pauseHandler = await getContractAt("IBosonPauseHandler", protocolAddress); await pauseHandler.pause([PausableRegion.Exchanges], await getFees(maxPriorityFeePerGas)); // Get next exchange Id - const exchangeHandler = await ethers.getContractAt("IBosonExchangeHandler", protocolAddress); + const exchangeHandler = await getContractAt("IBosonExchangeHandler", protocolAddress); const nextExchangeId = await exchangeHandler.getNextExchangeId(); facets.facetsToInit.ExchangeHandlerFacet.constructorArgs = [nextExchangeId]; @@ -24,7 +25,7 @@ async function preUpgrade(protocolAddress, facets) { async function postUpgrade(protocolAddress) { // Unpause the protocol console.log("Unpausing the protocol..."); - const pauseHandler = await ethers.getContractAt("IBosonPauseHandler", protocolAddress); + const pauseHandler = await getContractAt("IBosonPauseHandler", protocolAddress); await pauseHandler.unpause(await getFees(maxPriorityFeePerGas)); } diff --git a/scripts/util/cast-protocol-client-proxies.js b/scripts/util/cast-protocol-client-proxies.js index 8a0ee6713..7552aac99 100644 --- a/scripts/util/cast-protocol-client-proxies.js +++ b/scripts/util/cast-protocol-client-proxies.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractAt } = hre.ethers; /** * Cast the Protocol Client Proxy contracts to their implementation interfaces @@ -25,7 +25,7 @@ async function castProtocolClientProxies(protocolClientProxies) { [bosonVoucherProxy] = protocolClientProxies; // Cast the Proxies to the appropriate interfaces for further interaction - const bosonVoucher = await ethers.getContractAt("IBosonVoucher", bosonVoucherProxy.address); + const bosonVoucher = await getContractAt("IBosonVoucher", await bosonVoucherProxy.getAddress()); return [bosonVoucher]; } diff --git a/scripts/util/create-dispute-resolver.js b/scripts/util/create-dispute-resolver.js index 9e6513c63..13e260023 100644 --- a/scripts/util/create-dispute-resolver.js +++ b/scripts/util/create-dispute-resolver.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { ZeroAddress, getContractAt, getSigner, Wallet, provider } = hre.ethers; const fs = require("fs").promises; const environments = require("../../environments"); const network = hre.network.name; @@ -47,13 +47,13 @@ const createDisputeResolver = async (path) => { const adminAddress = environments[network].adminAddress; // If admin address is unspecified, exit the process - if (adminAddress == ethers.constants.AddressZero || !adminAddress) { + if (adminAddress == ZeroAddress || !adminAddress) { console.log("Admin address must not be zero address"); process.exit(1); } // Find protocol diamond and accessController addresses - const chainId = (await hre.ethers.provider.getNetwork()).chainId; + const chainId = (await provider.getNetwork()).chainId; const addressList = require(`../../addresses/${chainId}-${network}.json`).contracts; const protocolAddress = addressList.find((c) => c.name === "ProtocolDiamond").address; const accessControllerAddress = addressList.find((c) => c.name === "AccessController").address; @@ -67,10 +67,10 @@ const createDisputeResolver = async (path) => { } // Cast protocol diamond to IBosonAccountHandler - const accountHandler = await ethers.getContractAt("IBosonAccountHandler", protocolAddress); + const accountHandler = await getContractAt("IBosonAccountHandler", protocolAddress); // Get signer for admin address - const protocolAdminSigner = await ethers.getSigner(adminAddress); + const protocolAdminSigner = await getSigner(adminAddress); let tx, receipt; // Create dispute resolver @@ -79,14 +79,14 @@ const createDisputeResolver = async (path) => { if (!privateKey) { disputeResolverSigner = protocolAdminSigner; } else { - disputeResolverSigner = new ethers.Wallet(privateKey, protocolAdminSigner.provider); + disputeResolverSigner = new Wallet(privateKey, protocolAdminSigner.provider); } // create dispute resolver with callers account let initialDisputeResolver = { ...disputeResolver }; - initialDisputeResolver.admin = disputeResolverSigner.address; - initialDisputeResolver.assistant = disputeResolverSigner.address; - initialDisputeResolver.clerk = ethers.constants.AddressZero; + initialDisputeResolver.admin = await disputeResolverSigner.getAddress(); + initialDisputeResolver.assistant = await disputeResolverSigner.getAddress(); + initialDisputeResolver.clerk = ZeroAddress; tx = await accountHandler .connect(disputeResolverSigner) diff --git a/scripts/util/deploy-mock-tokens.js b/scripts/util/deploy-mock-tokens.js index fb8eb8611..b42d11ffe 100644 --- a/scripts/util/deploy-mock-tokens.js +++ b/scripts/util/deploy-mock-tokens.js @@ -1,7 +1,7 @@ const hre = require("hardhat"); const { expect } = require("chai"); const environments = require("../../environments"); -const ethers = hre.ethers; +const { getContractFactory, provider, ZeroAddress, getAddress } = hre.ethers; const network = hre.network.name; const confirmations = hre.network.name == "hardhat" ? 1 : environments.confirmations; @@ -18,9 +18,9 @@ async function deployMockTokens(tokens = ["BosonToken", "Foreign721", "Foreign11 // Deploy all the mock tokens while (tokens.length) { let token = tokens.shift(); - let TokenContractFactory = await ethers.getContractFactory(token); + let TokenContractFactory = await getContractFactory(token); const tokenContract = await TokenContractFactory.deploy(); - await tokenContract.deployed(); + await tokenContract.waitForDeployment(); deployedTokens.push(tokenContract); } @@ -39,16 +39,16 @@ async function deployAndMintMockNFTAuthTokens() { let tx1, tx2; //Deploy a mock NFT to represent the Lens Protocol profile NFT - let lensTokenContractFactory = await ethers.getContractFactory("MockNFTAuth721"); + let lensTokenContractFactory = await getContractFactory("MockNFTAuth721"); const lensTokenContract = await lensTokenContractFactory.deploy(); - await lensTokenContract.deployTransaction.wait(confirmations); - console.log(`✅ Mock Lens NFT Token deployed to: ${lensTokenContract.address}`); + await lensTokenContract.waitForDeployment(confirmations); + console.log(`✅ Mock Lens NFT Token deployed to: ${await lensTokenContract.getAddress()}`); //Deploy a mock NFT to represent the ENS NFT - let ensTokenContractFactory = await ethers.getContractFactory("MockNFTAuth721"); + let ensTokenContractFactory = await getContractFactory("MockNFTAuth721"); const ensTokenContract = await ensTokenContractFactory.deploy(); - await ensTokenContract.deployTransaction.wait(confirmations); - console.log(`✅ Mock ENS NFT Token deployed to: ${ensTokenContract.address}`); + await ensTokenContract.waitForDeployment(confirmations); + console.log(`✅ Mock ENS NFT Token deployed to: ${await ensTokenContract.getAddress()}`); if (network == "test" || network == "localhost") { //We want to mint auth tokens to specific addresses @@ -57,7 +57,7 @@ async function deployAndMintMockNFTAuthTokens() { console.log("\n Tokens will be minted to addresses ", addresses); } } else if (network == "hardhat") { - [...addresses] = await ethers.provider.listAccounts(); + [...addresses] = await provider.listAccounts(); //We only need auth tokens for 3 addresses addresses.splice(3, 18); @@ -69,19 +69,15 @@ async function deployAndMintMockNFTAuthTokens() { // Mint tokens for testing while (addresses.length) { let to = addresses.shift(); - tx1 = await lensTokenContract.mint(to, ethers.BigNumber.from(lensTokenId)); - tx2 = await ensTokenContract.mint(to, ethers.BigNumber.from(ensTokenId)); + tx1 = await lensTokenContract.mint(to, BigInt(lensTokenId)); + tx2 = await ensTokenContract.mint(to, BigInt(ensTokenId)); - await expect(tx1) - .to.emit(lensTokenContract, "Transfer") - .withArgs(ethers.constants.AddressZero, ethers.utils.getAddress(to), lensTokenId); + await expect(tx1).to.emit(lensTokenContract, "Transfer").withArgs(ZeroAddress, getAddress(to), lensTokenId); - await expect(tx2) - .to.emit(ensTokenContract, "Transfer") - .withArgs(ethers.constants.AddressZero, ethers.utils.getAddress(to), ensTokenId); + await expect(tx2).to.emit(ensTokenContract, "Transfer").withArgs(ZeroAddress, getAddress(to), ensTokenId); - let lensOwner = await lensTokenContract.ownerOf(ethers.BigNumber.from(lensTokenId)); - let ensOwner = await ensTokenContract.ownerOf(ethers.BigNumber.from(ensTokenId)); + let lensOwner = await lensTokenContract.ownerOf(BigInt(lensTokenId)); + let ensOwner = await ensTokenContract.ownerOf(BigInt(ensTokenId)); console.log("✅ Owner of Lens token Id %s is ", lensTokenId, lensOwner); console.log("✅ Owner of ENS token Id %s is ", ensTokenId, ensOwner); @@ -90,7 +86,7 @@ async function deployAndMintMockNFTAuthTokens() { ensTokenId++; } return { - addresses: [lensTokenContract.address, ensTokenContract.address], + addresses: [await lensTokenContract.getAddress(), await ensTokenContract.getAddress()], }; } diff --git a/scripts/util/deploy-protocol-client-beacons.js b/scripts/util/deploy-protocol-client-beacons.js index 30e2ef9dc..6443b1854 100644 --- a/scripts/util/deploy-protocol-client-beacons.js +++ b/scripts/util/deploy-protocol-client-beacons.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractFactory } = hre.ethers; const environments = require("../../environments"); const confirmations = hre.network.name === "hardhat" ? 1 : environments.confirmations; const { getFees } = require("./utils"); @@ -28,13 +28,13 @@ async function deployProtocolClientBeacons(protocolClients, protocolClientArgs, [bosonVoucherImpl] = protocolClients; // Deploy the ClientBeacon for BosonVoucher - const ClientBeacon = await ethers.getContractFactory("BosonClientBeacon"); + const ClientBeacon = await getContractFactory("BosonClientBeacon"); const clientBeacon = await ClientBeacon.deploy( ...protocolClientArgs, - bosonVoucherImpl.address, + await bosonVoucherImpl.getAddress(), await getFees(maxPriorityFeePerGas) ); - await clientBeacon.deployTransaction.wait(confirmations); + await clientBeacon.waitForDeployment(confirmations); return [clientBeacon]; } diff --git a/scripts/util/deploy-protocol-client-impls.js b/scripts/util/deploy-protocol-client-impls.js index b48a73557..928b89990 100644 --- a/scripts/util/deploy-protocol-client-impls.js +++ b/scripts/util/deploy-protocol-client-impls.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractFactory } = hre.ethers; const environments = require("../../environments"); const confirmations = hre.network.name === "hardhat" ? 1 : environments.confirmations; const { getFees } = require("./utils"); @@ -21,9 +21,9 @@ const { getFees } = require("./utils"); */ async function deployProtocolClientImpls(implementationArgs, maxPriorityFeePerGas) { // Deploy the BosonVoucher contract - const BosonVoucher = await ethers.getContractFactory("BosonVoucher"); + const BosonVoucher = await getContractFactory("BosonVoucher"); const bosonVoucher = await BosonVoucher.deploy(...implementationArgs, await getFees(maxPriorityFeePerGas)); - await bosonVoucher.deployTransaction.wait(confirmations); + await bosonVoucher.waitForDeployment(confirmations); return [bosonVoucher]; } diff --git a/scripts/util/deploy-protocol-client-proxies.js b/scripts/util/deploy-protocol-client-proxies.js index 3853f26bb..0f537b673 100644 --- a/scripts/util/deploy-protocol-client-proxies.js +++ b/scripts/util/deploy-protocol-client-proxies.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractFactory } = hre.ethers; const environments = require("../../environments"); const confirmations = hre.network.name === "hardhat" ? 1 : environments.confirmations; const { getFees } = require("./utils"); @@ -29,13 +29,13 @@ async function deployProtocolClientProxies(protocolClients, maxPriorityFeePerGas [bosonClientBeacon] = protocolClients; // Deploy the ClientProxy for BosonVoucher - const ClientProxy = await ethers.getContractFactory("BeaconClientProxy"); + const ClientProxy = await getContractFactory("BeaconClientProxy"); const clientProxy = await ClientProxy.deploy(await getFees(maxPriorityFeePerGas)); - await clientProxy.deployTransaction.wait(confirmations); + await clientProxy.waitForDeployment(confirmations); // init instead of constructors let transactionResponse = await clientProxy.initialize( - bosonClientBeacon.address, + await bosonClientBeacon.getAddress(), await getFees(maxPriorityFeePerGas) ); await transactionResponse.wait(confirmations); diff --git a/scripts/util/deploy-protocol-clients.js b/scripts/util/deploy-protocol-clients.js index c1e69ba11..aa633802f 100644 --- a/scripts/util/deploy-protocol-clients.js +++ b/scripts/util/deploy-protocol-clients.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { ZeroAddress } = hre.ethers; const { deployProtocolClientImpls } = require("./deploy-protocol-client-impls.js"); const { deployProtocolClientProxies } = require("./deploy-protocol-client-proxies.js"); @@ -22,11 +22,7 @@ const { castProtocolClientProxies } = require("./cast-protocol-client-proxies.js * @param implementationArgs - array of arguments to send to implementation constructor * @returns {Promise<(*|*|*)[]>} */ -async function deployProtocolClients( - protocolClientArgs, - maxPriorityFeePerGas, - implementationArgs = [ethers.constants.AddressZero] -) { +async function deployProtocolClients(protocolClientArgs, maxPriorityFeePerGas, implementationArgs = [ZeroAddress]) { // Deploy Protocol Client implementation contracts const protocolClientImpls = await deployProtocolClientImpls(implementationArgs, maxPriorityFeePerGas); diff --git a/scripts/util/deploy-protocol-diamond.js b/scripts/util/deploy-protocol-diamond.js index a444e47c7..eee90237a 100644 --- a/scripts/util/deploy-protocol-diamond.js +++ b/scripts/util/deploy-protocol-diamond.js @@ -1,7 +1,7 @@ const { getFacetAddCut } = require("./diamond-utils.js"); const { getInterfaceIds } = require("../config/supported-interfaces.js"); const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractFactory } = hre.ethers; const environments = require("../../environments"); const confirmations = hre.network.name === "hardhat" ? 1 : environments.confirmations; const { getFees } = require("./utils"); @@ -27,36 +27,36 @@ async function deployProtocolDiamond(maxPriorityFeePerGas) { ]; // Deploy the AccessController contract - const AccessController = await ethers.getContractFactory("AccessController"); + const AccessController = await getContractFactory("AccessController"); const accessController = await AccessController.deploy(await getFees(maxPriorityFeePerGas)); - await accessController.deployTransaction.wait(confirmations); + await accessController.deploymentTransaction().wait(confirmations); // Diamond Loupe Facet - const DiamondLoupeFacet = await ethers.getContractFactory("DiamondLoupeFacet"); + const DiamondLoupeFacet = await getContractFactory("DiamondLoupeFacet"); const dlf = await DiamondLoupeFacet.deploy(await getFees(maxPriorityFeePerGas)); - await dlf.deployTransaction.wait(confirmations); + await dlf.deploymentTransaction().wait(confirmations); // Diamond Cut Facet - const DiamondCutFacet = await ethers.getContractFactory("DiamondCutFacet"); + const DiamondCutFacet = await getContractFactory("DiamondCutFacet"); const dcf = await DiamondCutFacet.deploy(await getFees(maxPriorityFeePerGas)); - await dcf.deployTransaction.wait(confirmations); + await dcf.deploymentTransaction().wait(confirmations); // ERC165 Facet - const ERC165Facet = await ethers.getContractFactory("ERC165Facet"); + const ERC165Facet = await getContractFactory("ERC165Facet"); const erc165f = await ERC165Facet.deploy(await getFees(maxPriorityFeePerGas)); - await erc165f.deployTransaction.wait(confirmations); + await erc165f.deploymentTransaction().wait(confirmations); // Arguments for Diamond constructor const diamondArgs = [ - accessController.address, - [getFacetAddCut(dlf), getFacetAddCut(dcf), getFacetAddCut(erc165f)], + await accessController.getAddress(), + [await getFacetAddCut(dlf), await getFacetAddCut(dcf), await getFacetAddCut(erc165f)], interfaces, ]; // Deploy Protocol Diamond - const ProtocolDiamond = await ethers.getContractFactory("ProtocolDiamond"); + const ProtocolDiamond = await getContractFactory("ProtocolDiamond"); const protocolDiamond = await ProtocolDiamond.deploy(...diamondArgs, await getFees(maxPriorityFeePerGas)); - await protocolDiamond.deployTransaction.wait(confirmations); + await protocolDiamond.deploymentTransaction().wait(confirmations); return [protocolDiamond, dlf, dcf, erc165f, accessController, diamondArgs]; } diff --git a/scripts/util/deploy-protocol-handler-facets.js b/scripts/util/deploy-protocol-handler-facets.js index bb9c0d34b..4178d7e53 100644 --- a/scripts/util/deploy-protocol-handler-facets.js +++ b/scripts/util/deploy-protocol-handler-facets.js @@ -1,6 +1,6 @@ const { getFacetAddCut, cutDiamond, getInitializeCalldata } = require("./diamond-utils.js"); const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractFactory } = hre.ethers; const environments = require("../../environments"); const confirmations = hre.network.name === "hardhat" ? 1 : environments.confirmations; const { getFees } = require("./utils"); @@ -35,7 +35,7 @@ async function deployAndCutFacets( initializationFacet = initializationFacet || deployedFacets.find((f) => f.name == "ProtocolInitializationHandlerFacet").contract; - const initializeCalldata = getInitializeCalldata( + const initializeCalldata = await getInitializeCalldata( facetsToInit, version, false, @@ -45,20 +45,23 @@ async function deployAndCutFacets( interfacesToAdd ); - deployedFacets = deployedFacets.map((facet) => { - const cut = - facet.name == "ProtocolInitializationHandlerFacet" - ? getFacetAddCut(facet.contract, [initializeCalldata.slice(0, 10)]) - : getFacetAddCut(facet.contract, [facet.initialize && facet.initialize.slice(0, 10)] || []); - facet.cut.push(cut); - return facet; - }); + deployedFacets = await Promise.all( + deployedFacets.map(async (facet) => { + const cut = + facet.name === "ProtocolInitializationHandlerFacet" + ? await getFacetAddCut(facet.contract, [initializeCalldata.slice(0, 10)]) + : await getFacetAddCut(facet.contract, facet.initialize ? [facet.initialize.slice(0, 10)] : []); + + facet.cut.push(cut); + return facet; + }) + ); const cutTransaction = await cutDiamond( diamond, maxPriorityFeePerGas, deployedFacets, - initializationFacet.address, + await initializationFacet.getAddress(), initializeCalldata ); @@ -82,10 +85,10 @@ async function deployProtocolFacets(facetNames, facetsToInit, maxPriorityFeePerG // Deploy all handler facets for (const facetName of facetNames) { - let FacetContractFactory = await ethers.getContractFactory(facetName); + let FacetContractFactory = await getContractFactory(facetName); const constructorArgs = (facetsToInit[facetName] && facetsToInit[facetName].constructorArgs) || []; const facetContract = await FacetContractFactory.deploy(...constructorArgs, await getFees(maxPriorityFeePerGas)); - await facetContract.deployTransaction.wait(confirmations); + await facetContract.waitForDeployment(confirmations); const deployedFacet = { name: facetName, diff --git a/scripts/util/detect-changed-contracts.js b/scripts/util/detect-changed-contracts.js index ee08a4a85..31598c09a 100644 --- a/scripts/util/detect-changed-contracts.js +++ b/scripts/util/detect-changed-contracts.js @@ -124,7 +124,7 @@ async function getBytecodes() { // Abstract contracts do not have bytecode, and factory creation fails. Skip them. try { - const contract = await hre.ethers.getContractFactory(name); + const contract = await hre.getContractFactory(name); // Store the bytecode byteCodes[name] = contract.bytecode; diff --git a/scripts/util/diamond-utils.js b/scripts/util/diamond-utils.js index a27559b8a..1262fc48e 100644 --- a/scripts/util/diamond-utils.js +++ b/scripts/util/diamond-utils.js @@ -1,12 +1,12 @@ const hre = require("hardhat"); +const { keccak256, toUtf8Bytes, getContractAt, ZeroAddress, Interface, getContractFactory, encodeBytes32String } = + hre.ethers; const environments = "../../environments.js"; + const confirmations = hre.network.name === "hardhat" ? 1 : environments.confirmations; const FacetCutAction = require("../domain/FacetCutAction"); const { interfacesWithMultipleArtifacts } = require("./constants"); -const { getFees } = require("./utils"); -const ethers = hre.ethers; -const keccak256 = ethers.utils.keccak256; -const toUtf8Bytes = ethers.utils.toUtf8Bytes; +const { getFees, toHexString } = require("./utils"); /** * Utilities for testing and interacting with Diamond @@ -15,16 +15,14 @@ const toUtf8Bytes = ethers.utils.toUtf8Bytes; */ // get function selectors from ABI function getSelectors(contract, returnSignatureToNameMapping = false) { - const signatures = Object.keys(contract.interface.functions); let signatureToNameMapping = {}; - const selectors = signatures.reduce((acc, val) => { - if (val !== "init(bytes)") { - const signature = contract.interface.getSighash(val); - acc.push(signature); - if (returnSignatureToNameMapping) signatureToNameMapping[signature] = val; - } - return acc; - }, []); + const selectors = contract.interface.fragments + .filter((f) => f.type == "function" && f.name !== "init") + .map((f) => { + if (returnSignatureToNameMapping) signatureToNameMapping[f.selector] = f.name; + return f.selector; + }); + selectors.contract = contract; selectors.remove = remove; selectors.get = get; @@ -34,14 +32,14 @@ function getSelectors(contract, returnSignatureToNameMapping = false) { // get interface id async function getInterfaceId(contractName, skipBaseCheck = false, isFullPath = false) { - const contract = await ethers.getContractAt(contractName, ethers.constants.AddressZero); - const signatures = Object.keys(contract.interface.functions); - const selectors = signatures.reduce((acc, val) => { - acc.push(ethers.BigNumber.from(contract.interface.getSighash(val))); + const contract = await getContractAt(contractName, ZeroAddress); + const fragments = contract.interface.fragments.filter((f) => f.type == "function"); + const selectors = fragments.reduce((acc, val) => { + acc.push(val.selector); return acc; }, []); - let interfaceId = selectors.reduce((pv, cv) => pv.xor(cv), ethers.BigNumber.from("0x00000000")); + let interfaceId = selectors.reduce((pv, cv) => pv ^ BigInt(cv), BigInt(0x00000000)); // If contract inherits other contracts, their interfaces must be xor-ed if (!skipBaseCheck) { @@ -63,7 +61,7 @@ async function getInterfaceId(contractName, skipBaseCheck = false, isFullPath = isFullPath = interfacesWithMultipleArtifacts.includes(baseName); - const baseContractInterfaceId = ethers.BigNumber.from( + const baseContractInterfaceId = BigInt( await getInterfaceId( interfacesWithMultipleArtifacts.includes(baseName) ? `contracts/interfaces/${baseName}.sol:${baseName}` @@ -74,24 +72,17 @@ async function getInterfaceId(contractName, skipBaseCheck = false, isFullPath = ); // Remove interface id of base contracts - interfaceId = interfaceId.xor(baseContractInterfaceId); + interfaceId = interfaceId ^ baseContractInterfaceId; } } - return interfaceId.isZero() ? "0x00000000" : ethers.utils.hexZeroPad(interfaceId.toHexString(), 4); -} - -// get function selector from function signature -function getSelector(func) { - const abiInterface = new ethers.utils.Interface([func]); - return abiInterface.getSighash(ethers.utils.Fragment.from(func)); + return interfaceId == 0n ? "0x00000000" : toHexString(interfaceId, { startPad: 8 }); } // used with getSelectors to remove selectors from an array of selectors -// functionNames argument is an array of function signatures -function remove(functionNamesOrSignature) { +function remove(selectorsToRemove) { const selectors = this.filter((v) => { - for (const functionName of functionNamesOrSignature) { - if (v === this.contract.interface.getSighash(functionName)) { + for (const selector of selectorsToRemove) { + if (v === selector) { return false; } } @@ -106,14 +97,11 @@ function remove(functionNamesOrSignature) { // used with getSelectors to get selectors from an array of selectors // functionNames argument is an array of function signatures function get(functionNames) { - const selectors = this.filter((v) => { - for (const functionName of functionNames) { - if (v === this.contract.interface.getSighash(functionName)) { - return true; - } - } - return false; - }); + const selectors = this.contract.interface.fragments + .filter((f) => f.type == "function") + .filter((f) => functionNames.includes(f.name)) + .map((f) => f.selector); + selectors.contract = this.contract; selectors.remove = this.remove; selectors.get = this.get; @@ -122,8 +110,8 @@ function get(functionNames) { // remove selectors using an array of signatures function removeSelectors(selectors, signatures) { - const iface = new ethers.utils.Interface(signatures.map((v) => "function " + v)); - const removeSelectors = signatures.map((v) => iface.getSighash(v)); + const iface = new Interface(signatures.map((v) => "function " + v)); + const removeSelectors = iface.fragments.map((f) => f.selector); selectors = selectors.filter((v) => !removeSelectors.includes(v)); return selectors; } @@ -137,40 +125,42 @@ function findAddressPositionInFacets(facetAddress, facets) { } } -function getFacetAddCut(facet, omitFunctions = []) { +async function getFacetAddCut(facet, omitFunctions = []) { let selectors = omitFunctions.length ? getSelectors(facet).remove(omitFunctions) : getSelectors(facet); - return [facet.address, FacetCutAction.Add, selectors]; + const address = await facet.getAddress(); + return [address, FacetCutAction.Add, selectors]; } -function getFacetReplaceCut(facet, omitFunctions = []) { +async function getFacetReplaceCut(facet, omitFunctions = []) { let selectors = omitFunctions.length ? getSelectors(facet).remove(omitFunctions) : getSelectors(facet); - return [facet.address, FacetCutAction.Replace, selectors]; + const address = await facet.getAddress(); + return [address, FacetCutAction.Replace, selectors]; } -function getFacetRemoveCut(facet, omitFunctions = []) { +async function getFacetRemoveCut(facet, omitFunctions = []) { let selectors = omitFunctions.length ? getSelectors(facet).remove(omitFunctions) : getSelectors(facet); - return [facet.address, FacetCutAction.Remove, selectors]; + const address = await facet.getAddress(); + return [address, FacetCutAction.Remove, selectors]; } async function getStateModifyingFunctions(facetNames, omitFunctions = [], onlyFunctions = []) { let stateModifyingFunctions = []; for (const facetName of facetNames) { - let FacetContractFactory = await ethers.getContractFactory(facetName); - const functions = FacetContractFactory.interface.functions; - const functionNames = Object.keys(functions); - const facetStateModifyingFunctions = functionNames.filter((fn) => { - if (functions[fn].stateMutability !== "view" && !omitFunctions.includes(fn)) { - if (onlyFunctions.length === 0) { - return true; - } - for (const func of onlyFunctions) { - if (fn.includes(func)) { + let FacetContractFactory = await getContractFactory(facetName); + const functions = FacetContractFactory.interface.fragments; + const facetStateModifyingFunctions = functions + .filter((fn) => { + if (fn.type == "function" && fn.stateMutability !== "view" && !omitFunctions.includes(fn.name)) { + if (onlyFunctions.length === 0) { + return true; + } + if (onlyFunctions.includes(fn.name)) { return true; } } - } - return false; - }); + return false; + }) + .map((fn) => fn.format("sighash")); stateModifyingFunctions = stateModifyingFunctions.concat(facetStateModifyingFunctions); } @@ -183,7 +173,7 @@ function getStateModifyingFunctionsHashes(facetNames, omitFunctions = [], onlyFu // Allowlist contract methods const stateModifyingFunctions = await getStateModifyingFunctions( facetNames, - [...omitFunctions, "initialize()"], + [...omitFunctions, "initialize"], onlyFunctions ); return stateModifyingFunctions.map((smf) => keccak256(toUtf8Bytes(smf))); @@ -191,17 +181,18 @@ function getStateModifyingFunctionsHashes(facetNames, omitFunctions = [], onlyFu } // Get ProtocolInitializationHandlerFacet initialize calldata to be called on diamondCut -function getInitializeCalldata( +async function getInitializeCalldata( facetsToInitialize, version, isUpgrade, initializationData, - initializationFacet, + initializationFacet = "0x", interfacesToRemove = [], interfacesToAdd = [] ) { - version = ethers.utils.formatBytes32String(version); - const addresses = facetsToInitialize.map((f) => f.contract.address); + version = encodeBytes32String(version); + const addresses = await facetsToInitialize.map((f) => f.contract.target); + const calldata = facetsToInitialize.map((f) => f.initialize); return initializationFacet.interface.encodeFunctionData("initialize", [ @@ -224,7 +215,7 @@ async function cutDiamond( initializeCalldata, facetsToRemove = [] ) { - const diamondCutFacet = await ethers.getContractAt("DiamondCutFacet", diamond); + const diamondCutFacet = await getContractAt("DiamondCutFacet", diamond); const cut = deployedFacets.reduce((acc, val) => { val.cut.forEach((c) => acc.push(c)); @@ -244,7 +235,6 @@ async function cutDiamond( } exports.getSelectors = getSelectors; -exports.getSelector = getSelector; exports.FacetCutAction = FacetCutAction; exports.remove = remove; exports.removeSelectors = removeSelectors; diff --git a/scripts/util/estimate-limits.js b/scripts/util/estimate-limits.js index e05a0e7b7..5ec712ad7 100644 --- a/scripts/util/estimate-limits.js +++ b/scripts/util/estimate-limits.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { Wallet, provider, ZeroAddress, parseEther, MaxUint256, getContractAt, getSigners, parseUnits } = hre.ethers; const simpleStatistic = require("simple-statistics"); const fs = require("fs"); @@ -85,45 +85,65 @@ setupEnvironment["maxAllowedSellers"] = async function (sellerCount = 10) { const voucherInitValues = mockVoucherInitValues(); for (let i = 0; i < sellerCount; i++) { - const wallet = ethers.Wallet.createRandom(); + const wallet = Wallet.createRandom(); //Random wallet has no provider. Connect wallet to ethers provider. The connected wallet will have no ETH - const connectedWallet = wallet.connect(ethers.provider); + const connectedWallet = wallet.connect(provider); //Fund the new wallet let tx = { - to: connectedWallet.address, + to: await connectedWallet.getAddress(), // Convert currency unit from ether to wei - value: ethers.utils.parseEther("1"), + value: parseEther("1"), }; await other1.sendTransaction(tx); - const seller = mockSeller(wallet.address, wallet.address, wallet.address, wallet.address); + const seller = mockSeller( + await wallet.getAddress(), + await wallet.getAddress(), + await wallet.getAddress(), + await wallet.getAddress() + ); await accountHandler.connect(connectedWallet).createSeller(seller, emptyAuthToken, voucherInitValues); } //Create DisputeResolverFee array const disputeResolverFees = [ - new DisputeResolverFee(other1.address, "MockToken1", "0"), - new DisputeResolverFee(other2.address, "MockToken2", "0"), - new DisputeResolverFee(other3.address, "MockToken3", "0"), + new DisputeResolverFee(await other1.getAddress(), "MockToken1", "0"), + new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0"), + new DisputeResolverFee(await other3.getAddress(), "MockToken3", "0"), ]; const sellerAllowList = [...Array(sellerCount + 1).keys()].slice(1); // Dispute resolver 2 - used in "addSellersToAllowList" - const disputeResolver2 = mockDisputeResolver(dr2.address, dr2.address, dr2.address, dr2.address); + const disputeResolver2 = mockDisputeResolver( + await dr2.getAddress(), + await dr2.getAddress(), + await dr2.getAddress(), + await dr2.getAddress() + ); await accountHandler.connect(dr2).createDisputeResolver(disputeResolver2, disputeResolverFees, []); const args_2 = [disputeResolver2.id, sellerAllowList]; const arrayIndex_2 = 1; // Dispute resolver 3 - used in "removeSellersFromAllowList" - const disputeResolver3 = mockDisputeResolver(dr3.address, dr3.address, dr3.address, dr3.address); + const disputeResolver3 = mockDisputeResolver( + await dr3.getAddress(), + await dr3.getAddress(), + await dr3.getAddress(), + await dr3.getAddress() + ); await accountHandler.connect(dr3).createDisputeResolver(disputeResolver3, disputeResolverFees, sellerAllowList); const args_3 = [disputeResolver3.id, sellerAllowList]; const arrayIndex_3 = 1; - const disputeResolver1 = mockDisputeResolver(dr1.address, dr1.address, dr1.address, dr1.address); + const disputeResolver1 = mockDisputeResolver( + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress() + ); const args_1 = [disputeResolver1, disputeResolverFees, sellerAllowList]; const arrayIndex_1 = 2; @@ -144,24 +164,39 @@ setupEnvironment["maxFeesPerDisputeResolver"] = async function (feesCount = 10) //Create DisputeResolverFee array let disputeResolverFees = []; for (let i = 0; i < feesCount; i++) { - const wallet = ethers.Wallet.createRandom(); - disputeResolverFees.push(new DisputeResolverFee(wallet.address, `MockToken${i}`, "0")); + const wallet = Wallet.createRandom(); + disputeResolverFees.push(new DisputeResolverFee(await wallet.getAddress(), `MockToken${i}`, "0")); } // Dispute resolver 2 - used in "addFeesToDisputeResolver" - const disputeResolver2 = mockDisputeResolver(dr2.address, dr2.address, dr2.address, dr2.address); + const disputeResolver2 = mockDisputeResolver( + await dr2.getAddress(), + await dr2.getAddress(), + await dr2.getAddress(), + await dr2.getAddress() + ); await accountHandler.connect(dr2).createDisputeResolver(disputeResolver2, [], []); const args_2 = [disputeResolver2.id, disputeResolverFees]; const arrayIndex_2 = 1; // Dispute resolver 3 - used in "removeFeesFromDisputeResolver" - const disputeResolver3 = mockDisputeResolver(dr3.address, dr3.address, dr3.address, dr3.address); + const disputeResolver3 = mockDisputeResolver( + await dr3.getAddress(), + await dr3.getAddress(), + await dr3.getAddress(), + await dr3.getAddress() + ); await accountHandler.connect(dr3).createDisputeResolver(disputeResolver3, disputeResolverFees, [], { gasLimit }); const feeTokenAddressesToRemove = disputeResolverFees.map((DRfee) => DRfee.tokenAddress); const args_3 = [disputeResolver3.id, feeTokenAddressesToRemove]; const arrayIndex_3 = 1; - const disputeResolver1 = mockDisputeResolver(dr1.address, dr1.address, dr1.address, dr1.address); + const disputeResolver1 = mockDisputeResolver( + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress() + ); const args_1 = [disputeResolver1, disputeResolverFees, []]; const arrayIndex_1 = 1; @@ -184,10 +219,10 @@ setupEnvironment["maxOffersPerBatch"] = async function (offerCount = 10) { const agentId = "0"; // agent id is optional while creating an offer const seller1 = mockSeller( - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress() ); const voucherInitValues = mockVoucherInitValues(); const emptyAuthToken = mockAuthToken(); @@ -196,26 +231,32 @@ setupEnvironment["maxOffersPerBatch"] = async function (offerCount = 10) { // Seller 2 - used in "voidOfferBatch" const seller2 = mockSeller( - sellerWallet2.address, - sellerWallet2.address, - sellerWallet2.address, - sellerWallet2.address + await sellerWallet2.getAddress(), + await sellerWallet2.getAddress(), + await sellerWallet2.getAddress(), + await sellerWallet2.getAddress() ); await accountHandler.connect(sellerWallet2).createSeller(seller2, emptyAuthToken, voucherInitValues); // Seller 3 - used in "extendOfferBatch" const seller3 = mockSeller( - sellerWallet3.address, - sellerWallet3.address, - sellerWallet3.address, - sellerWallet3.address + await sellerWallet3.getAddress(), + await sellerWallet3.getAddress(), + await sellerWallet3.getAddress(), + await sellerWallet3.getAddress() ); await accountHandler.connect(sellerWallet3).createSeller(seller3, emptyAuthToken, voucherInitValues); - const disputeResolver = mockDisputeResolver(dr1.address, dr1.address, dr1.address, dr1.address, true); + const disputeResolver = mockDisputeResolver( + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + true + ); await accountHandler .connect(dr1) - .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")], []); + .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ZeroAddress, "Native", "0")], []); const { offer, offerDates, offerDurations } = await mockOffer(); const offers = new Array(offerCount).fill(offer); @@ -244,7 +285,7 @@ setupEnvironment["maxOffersPerBatch"] = async function (offerCount = 10) { const arrayIndex_2 = 0; // extendOfferBatch - const newValidUntilDate = ethers.BigNumber.from(offerDates.validUntil).add("10000").toString(); + const newValidUntilDate = BigInt(offerDates.validUntil).add("10000").toString(); const args_3 = [offerIds.map((offerId) => 2 * offerId), newValidUntilDate]; const arrayIndex_3 = 0; @@ -268,10 +309,10 @@ setupEnvironment["maxOffersPerGroup"] = async function (offerCount = 10) { const agentId = "0"; // agent id is optional while creating an offer const seller1 = mockSeller( - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress() ); const voucherInitValues = mockVoucherInitValues(); const emptyAuthToken = mockAuthToken(); @@ -280,26 +321,32 @@ setupEnvironment["maxOffersPerGroup"] = async function (offerCount = 10) { // Seller 2 - used in "addOffersToGroup" const seller2 = mockSeller( - sellerWallet2.address, - sellerWallet2.address, - sellerWallet2.address, - sellerWallet2.address + await sellerWallet2.getAddress(), + await sellerWallet2.getAddress(), + await sellerWallet2.getAddress(), + await sellerWallet2.getAddress() ); await accountHandler.connect(sellerWallet2).createSeller(seller2, emptyAuthToken, voucherInitValues); // Seller 3 - used in "removeOffersFromGroup" const seller3 = mockSeller( - sellerWallet3.address, - sellerWallet3.address, - sellerWallet3.address, - sellerWallet3.address + await sellerWallet3.getAddress(), + await sellerWallet3.getAddress(), + await sellerWallet3.getAddress(), + await sellerWallet3.getAddress() ); await accountHandler.connect(sellerWallet3).createSeller(seller3, emptyAuthToken, voucherInitValues); - const disputeResolver = mockDisputeResolver(dr1.address, dr1.address, dr1.address, dr1.address, true); + const disputeResolver = mockDisputeResolver( + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + true + ); await accountHandler .connect(dr1) - .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")], []); + .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ZeroAddress, "Native", "0")], []); // Mock offer, offerDates and offerDurations const { offer, offerDates, offerDurations } = await mockOffer(); @@ -357,20 +404,26 @@ setupEnvironment["maxOffersPerBundle"] = async function (offerCount = 10) { const agentId = "0"; // agent id is optional while creating an offer const seller1 = mockSeller( - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress() ); const voucherInitValues = mockVoucherInitValues(); const emptyAuthToken = mockAuthToken(); await accountHandler.connect(sellerWallet1).createSeller(seller1, emptyAuthToken, voucherInitValues); - const disputeResolver = mockDisputeResolver(dr1.address, dr1.address, dr1.address, dr1.address, true); + const disputeResolver = mockDisputeResolver( + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + true + ); await accountHandler .connect(dr1) - .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")], []); + .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ZeroAddress, "Native", "0")], []); // Mock offer, offerDates and offerDurations const { offer, offerDates, offerDurations } = await mockOffer(); @@ -384,11 +437,11 @@ setupEnvironment["maxOffersPerBundle"] = async function (offerCount = 10) { // Create a valid twin. const [bosonToken] = await deployMockTokens(); - const twin = mockTwin(bosonToken.address); - twin.supplyAvailable = ethers.BigNumber.from(twin.amount).mul(offerCount); + const twin = mockTwin(await bosonToken.getAddress()); + twin.supplyAvailable = BigInt(twin.amount).mul(offerCount); // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(sellerWallet1).approve(twinHandler.address, twin.supplyAvailable); // approving the twin handler + await bosonToken.connect(sellerWallet1).approve(await twinHandler.getAddress(), twin.supplyAvailable); // approving the twin handler // Create a twin. await twinHandler.connect(sellerWallet1).createTwin(twin); @@ -417,27 +470,33 @@ setupEnvironment["maxTwinsPerBundle"] = async function (twinCount = 10) { const agentId = "0"; // agent id is optional while creating an offer const seller1 = mockSeller( - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress() ); const voucherInitValues = mockVoucherInitValues(); const emptyAuthToken = mockAuthToken(); await accountHandler.connect(sellerWallet1).createSeller(seller1, emptyAuthToken, voucherInitValues); - const disputeResolver = mockDisputeResolver(dr1.address, dr1.address, dr1.address, dr1.address, true); + const disputeResolver = mockDisputeResolver( + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + true + ); await accountHandler .connect(dr1) - .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")], []); + .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ZeroAddress, "Native", "0")], []); for (let i = 0; i < twinCount; i++) { const [twinContract] = await deployMockTokens(["Foreign20"]); - const twin = mockTwin(twinContract.address); + const twin = mockTwin(await twinContract.getAddress()); // Approving the twinHandler contract to transfer seller's tokens - await twinContract.connect(sellerWallet1).approve(twinHandler.address, twin.supplyAvailable); // approving the twin handler + await twinContract.connect(sellerWallet1).approve(await twinHandler.getAddress(), twin.supplyAvailable); // approving the twin handler // Create a twin. await twinHandler.connect(sellerWallet1).createTwin(twin); @@ -474,20 +533,26 @@ setupEnvironment["maxExchangesPerBatch"] = async function (exchangesCount = 10) const agentId = "0"; // agent id is optional while creating an offer const seller1 = mockSeller( - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress() ); const voucherInitValues = mockVoucherInitValues(); const emptyAuthToken = mockAuthToken(); await accountHandler.connect(sellerWallet1).createSeller(seller1, emptyAuthToken, voucherInitValues); - const disputeResolver = mockDisputeResolver(dr1.address, dr1.address, dr1.address, dr1.address, true); + const disputeResolver = mockDisputeResolver( + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + true + ); await accountHandler .connect(dr1) - .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")], []); + .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ZeroAddress, "Native", "0")], []); // Create an offer with big enough quantity const { offer, offerDates, offerDurations } = await mockOffer(); @@ -496,24 +561,22 @@ setupEnvironment["maxExchangesPerBatch"] = async function (exchangesCount = 10) await offerHandler.connect(sellerWallet1).createOffer(offer, offerDates, offerDurations, disputeResolver.id, agentId); // Deposit seller funds so the commit will succeed - const sellerPool = ethers.BigNumber.from(offer.price).mul(exchangesCount); - await fundsHandler - .connect(sellerWallet1) - .depositFunds(seller1.id, ethers.constants.AddressZero, sellerPool, { value: sellerPool }); + const sellerPool = BigInt(offer.price).mul(exchangesCount); + await fundsHandler.connect(sellerWallet1).depositFunds(seller1.id, ZeroAddress, sellerPool, { value: sellerPool }); await setNextBlockTimestamp(Number(offerDates.voucherRedeemableFrom)); for (let i = 1; i < exchangesCount + 1; i++) { // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id, { value: offer.price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offer.id, { value: offer.price }); // Redeem voucher await exchangeHandler.connect(buyer).redeemVoucher(i); } // Set time forward to run out the dispute period - const blockNumber = await ethers.provider.getBlockNumber(); - const block = await ethers.provider.getBlock(blockNumber); - const newTime = ethers.BigNumber.from(block.timestamp).add(offerDurations.disputePeriod).add(1).toNumber(); + const blockNumber = await provider.getBlockNumber(); + const block = await provider.getBlock(blockNumber); + const newTime = Number(BigInt(block.timestamp) + BigInt(offerDurations.disputePeriod) + 1n); await setNextBlockTimestamp(newTime); const exchangeIds = [...Array(exchangesCount + 1).keys()].slice(1); @@ -536,20 +599,26 @@ setupEnvironment["maxDisputesPerBatch"] = async function (exchangesCount = 10) { const agentId = "0"; // agent id is optional while creating an offer const seller1 = mockSeller( - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress() ); const voucherInitValues = mockVoucherInitValues(); const emptyAuthToken = mockAuthToken(); await accountHandler.connect(sellerWallet1).createSeller(seller1, emptyAuthToken, voucherInitValues); - const disputeResolver = mockDisputeResolver(dr1.address, dr1.address, dr1.address, dr1.address, true); + const disputeResolver = mockDisputeResolver( + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + true + ); await accountHandler .connect(dr1) - .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")], []); + .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ZeroAddress, "Native", "0")], []); // Create an offer with big enough quantity const { offer, offerDates, offerDurations } = await mockOffer(); @@ -558,15 +627,13 @@ setupEnvironment["maxDisputesPerBatch"] = async function (exchangesCount = 10) { await offerHandler.connect(sellerWallet1).createOffer(offer, offerDates, offerDurations, disputeResolver.id, agentId); // Deposit seller funds so the commit will succeed - const sellerPool = ethers.BigNumber.from(offer.price).mul(exchangesCount); - await fundsHandler - .connect(sellerWallet1) - .depositFunds(seller1.id, ethers.constants.AddressZero, sellerPool, { value: sellerPool }); + const sellerPool = BigInt(offer.price).mul(exchangesCount); + await fundsHandler.connect(sellerWallet1).depositFunds(seller1.id, ZeroAddress, sellerPool, { value: sellerPool }); await setNextBlockTimestamp(Number(offerDates.voucherRedeemableFrom)); for (let i = 1; i < exchangesCount + 1; i++) { // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id, { value: offer.price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offer.id, { value: offer.price }); // Redeem voucher await exchangeHandler.connect(buyer).redeemVoucher(i); @@ -576,9 +643,9 @@ setupEnvironment["maxDisputesPerBatch"] = async function (exchangesCount = 10) { } // Set time forward to run out the dispute period - const blockNumber = await ethers.provider.getBlockNumber(); - const block = await ethers.provider.getBlock(blockNumber); - const newTime = ethers.BigNumber.from(block.timestamp).add(offerDurations.resolutionPeriod).add(1).toNumber(); + const blockNumber = await provider.getBlockNumber(); + const block = await provider.getBlock(blockNumber); + const newTime = Number(BigInt(block.timestamp) + BigInt(offerDurations.resolutionPeriod) + 1n); await setNextBlockTimestamp(newTime); const exchangeIds = [...Array(exchangesCount + 1).keys()].slice(1); @@ -602,20 +669,26 @@ setupEnvironment["maxTokensPerWithdrawal"] = async function (tokenCount = 10) { const agentId = "0"; // agent id is optional while creating an offer const seller1 = mockSeller( - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress() ); const voucherInitValues = mockVoucherInitValues(); const emptyAuthToken = mockAuthToken(); await accountHandler.connect(sellerWallet1).createSeller(seller1, emptyAuthToken, voucherInitValues); - const disputeResolver = mockDisputeResolver(dr1.address, dr1.address, dr1.address, dr1.address, true); + const disputeResolver = mockDisputeResolver( + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + true + ); await accountHandler .connect(dr1) - .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")], []); + .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ZeroAddress, "Native", "0")], []); const { offer, offerDates, offerDurations } = await mockOffer(); offerDates.voucherRedeemableFrom = offerDates.validFrom; @@ -623,19 +696,23 @@ setupEnvironment["maxTokensPerWithdrawal"] = async function (tokenCount = 10) { for (let i = 1; i < tokenCount + 1; i++) { // create a token const [tokenContract] = await deployMockTokens(["Foreign20"]); - tokenAddresses.push(tokenContract.address); - - offer.exchangeToken = tokenContract.address; - await tokenContract.mint(sellerWallet1.address, offer.sellerDeposit); - await tokenContract.mint(buyer.address, offer.price); - await tokenContract.connect(sellerWallet1).approve(protocolDiamond.address, offer.sellerDeposit); - await tokenContract.connect(buyer).approve(protocolDiamond.address, offer.price); - await fundsHandler.connect(sellerWallet1).depositFunds(seller1.id, tokenContract.address, offer.sellerDeposit); + tokenAddresses.push(await tokenContract.getAddress()); + + offer.exchangeToken = await tokenContract.getAddress(); + await tokenContract.mint(await sellerWallet1.getAddress(), offer.sellerDeposit); + await tokenContract.mint(await buyer.getAddress(), offer.price); + await tokenContract.connect(sellerWallet1).approve(await protocolDiamond.getAddress(), offer.sellerDeposit); + await tokenContract.connect(buyer).approve(await protocolDiamond.getAddress(), offer.price); + await fundsHandler + .connect(sellerWallet1) + .depositFunds(seller1.id, await tokenContract.getAddress(), offer.sellerDeposit); // add token to DR accepted tokens await accountHandler .connect(dr1) - .addFeesToDisputeResolver(disputeResolver.id, [new DisputeResolverFee(tokenContract.address, `Token${i}`, "0")]); + .addFeesToDisputeResolver(disputeResolver.id, [ + new DisputeResolverFee(await tokenContract.getAddress(), `Token${i}`, "0"), + ]); // create the offer await offerHandler @@ -643,7 +720,7 @@ setupEnvironment["maxTokensPerWithdrawal"] = async function (tokenCount = 10) { .createOffer(offer, offerDates, offerDurations, disputeResolver.id, agentId); // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, i); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), i); // Redeem voucher await exchangeHandler.connect(buyer).redeemVoucher(i); @@ -658,8 +735,8 @@ setupEnvironment["maxTokensPerWithdrawal"] = async function (tokenCount = 10) { const arrayIndex_1 = [1, 2]; // protocol fee withdrawal - await accessController.grantRole(Role.FEE_COLLECTOR, feeCollector.address); - const protocolFee = ethers.BigNumber.from(offer.price).mul(protocolFeePercentage).div(10000); + await accessController.grantRole(Role.FEE_COLLECTOR, await feeCollector.getAddress()); + const protocolFee = BigInt(offer.price).mul(protocolFeePercentage).div(10000); const tokenAmounts_2 = new Array(tokenCount).fill(protocolFee); const args_2 = [tokenAddresses, tokenAmounts_2]; const arrayIndex_2 = [0, 1]; @@ -680,32 +757,38 @@ setupEnvironment["maxPremintedVouchers"] = async function (tokenCount = 10) { const agentId = "0"; // agent id is optional while creating an offer const seller1 = mockSeller( - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address, - sellerWallet1.address + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress(), + await sellerWallet1.getAddress() ); const voucherInitValues = mockVoucherInitValues(); const emptyAuthToken = mockAuthToken(); await accountHandler.connect(sellerWallet1).createSeller(seller1, emptyAuthToken, voucherInitValues); - const disputeResolver = mockDisputeResolver(dr1.address, dr1.address, dr1.address, dr1.address, true); + const disputeResolver = mockDisputeResolver( + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + await dr1.getAddress(), + true + ); await accountHandler .connect(dr1) - .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")], []); + .createDisputeResolver(disputeResolver, [new DisputeResolverFee(ZeroAddress, "Native", "0")], []); // create the offer const { offer, offerDates, offerDurations } = await mockOffer(); - offer.quantityAvailable = ethers.constants.MaxUint256; + offer.quantityAvailable = MaxUint256; await offerHandler.connect(sellerWallet1).createOffer(offer, offerDates, offerDurations, disputeResolver.id, agentId); // reserve range - let length = ethers.BigNumber.from(2).pow(128).sub(1); + let length = BigInt(2).pow(128).sub(1); await offerHandler.connect(sellerWallet1).reserveRange(offer.id, length); // update bosonVoucher address - handlers.IBosonVoucher = bosonVoucher.attach(calculateContractAddress(accountHandler.address, seller1.id)); + handlers.IBosonVoucher = bosonVoucher.attach(calculateContractAddress(await accountHandler.getAddress(), seller1.id)); // make an empty array of length tokenCount const amounts = new Array(tokenCount); @@ -791,8 +874,8 @@ async function estimateLimit(limit, inputs, safeGasLimitPercent) { const gasEstimate = await handlers[handler] .connect(methodInputs.account) .estimateGas[method](...adjustedArgs, { gasLimit }); - console.log("Length:", arrayLength, "Gas:", gasEstimate.toNumber()); - gasEstimates.push([gasEstimate.toNumber(), arrayLength]); + console.log("Length:", arrayLength, "Gas:", Number(gasEstimate)); + gasEstimates.push([Number(gasEstimate), arrayLength]); } catch (e) { // console.log(e) console.log("Block gas limit already hit"); @@ -842,23 +925,23 @@ async function setupCommonEnvironment() { protocolAdmin, feeCollector, other1, - ] = await ethers.getSigners(); + ] = await getSigners(); // Deploy the Protocol Diamond [protocolDiamond, , , , accessController] = await deployProtocolDiamond(); // Temporarily grant UPGRADER role to deployer account - await accessController.grantRole(Role.UPGRADER, deployer.address); + await accessController.grantRole(Role.UPGRADER, await deployer.getAddress()); // Grant PROTOCOL role to ProtocolDiamond address and renounces admin - await accessController.grantRole(Role.PROTOCOL, protocolDiamond.address); + await accessController.grantRole(Role.PROTOCOL, await protocolDiamond.getAddress()); // Grant ADMIN role to and address that can call restricted functions. // This ADMIN role is a protocol-level role. It is not the same an admin address for an account type - await accessController.grantRole(Role.ADMIN, protocolAdmin.address); + await accessController.grantRole(Role.ADMIN, await protocolAdmin.getAddress()); // Deploy the Protocol client implementation/proxy pairs (currently just the Boson Voucher) - const protocolClientArgs = [protocolDiamond.address]; + const protocolClientArgs = [await protocolDiamond.getAddress()]; const [, beacons, proxies, bv] = await deployProtocolClients(protocolClientArgs, gasLimit); const [beacon] = beacons; const [proxy] = proxies; @@ -866,17 +949,17 @@ async function setupCommonEnvironment() { // Set protocolFees protocolFeePercentage = "200"; // 2 % - protocolFeeFlatBoson = ethers.utils.parseUnits("0.01", "ether").toString(); + protocolFeeFlatBoson = parseUnits("0.01", "ether").toString(); buyerEscalationDepositPercentage = "1000"; // 10% // Add config Handler, so ids start at 1, and so voucher address can be found const protocolConfig = [ // Protocol addresses { - treasury: rando.address, - token: rando.address, - voucherBeacon: beacon.address, - beaconProxy: proxy.address, + treasury: await rando.getAddress(), + token: await rando.getAddress(), + voucherBeacon: await beacon.getAddress(), + beaconProxy: await proxy.getAddress(), }, // Protocol limits { @@ -922,16 +1005,16 @@ async function setupCommonEnvironment() { const facetsToDeploy = await getFacetsWithArgs(facetNames, protocolConfig); // Cut the protocol handler facets into the Diamond - await deployAndCutFacets(protocolDiamond.address, facetsToDeploy, gasLimit); + await deployAndCutFacets(await protocolDiamond.getAddress(), facetsToDeploy, gasLimit); // Cast Diamond to handlers - accountHandler = await ethers.getContractAt("IBosonAccountHandler", protocolDiamond.address); - bundleHandler = await ethers.getContractAt("IBosonBundleHandler", protocolDiamond.address); - disputeHandler = await ethers.getContractAt("IBosonDisputeHandler", protocolDiamond.address); - exchangeHandler = await ethers.getContractAt("IBosonExchangeHandler", protocolDiamond.address); - fundsHandler = await ethers.getContractAt("IBosonFundsHandler", protocolDiamond.address); - groupHandler = await ethers.getContractAt("IBosonGroupHandler", protocolDiamond.address); - offerHandler = await ethers.getContractAt("IBosonOfferHandler", protocolDiamond.address); - twinHandler = await ethers.getContractAt("IBosonTwinHandler", protocolDiamond.address); + accountHandler = await getContractAt("IBosonAccountHandler", await protocolDiamond.getAddress()); + bundleHandler = await getContractAt("IBosonBundleHandler", await protocolDiamond.getAddress()); + disputeHandler = await getContractAt("IBosonDisputeHandler", await protocolDiamond.getAddress()); + exchangeHandler = await getContractAt("IBosonExchangeHandler", await protocolDiamond.getAddress()); + fundsHandler = await getContractAt("IBosonFundsHandler", await protocolDiamond.getAddress()); + groupHandler = await getContractAt("IBosonGroupHandler", await protocolDiamond.getAddress()); + offerHandler = await getContractAt("IBosonOfferHandler", await protocolDiamond.getAddress()); + twinHandler = await getContractAt("IBosonTwinHandler", await protocolDiamond.getAddress()); handlers = { IBosonAccountHandler: accountHandler, diff --git a/scripts/util/report-verify-deployments.js b/scripts/util/report-verify-deployments.js index 1c9b9448c..62c44e60c 100644 --- a/scripts/util/report-verify-deployments.js +++ b/scripts/util/report-verify-deployments.js @@ -15,12 +15,12 @@ async function verifyOnBlockExplorer(contract) { if (contract.name == "BosonVoucher Beacon") { await hre.run("verify:verify", { contract: "contracts/protocol/clients/proxy/BosonClientBeacon.sol:BosonClientBeacon", - address: contract.address, + address: await contract.getAddress(), constructorArguments: contract.args, }); } else { await hre.run("verify:verify", { - address: contract.address, + address: await contract.getAddress(), constructorArguments: contract.args, }); } @@ -33,7 +33,7 @@ async function verifyOnTestEnv(contracts) { for (const contract of contracts) { console.log(`\n📋 Verifying on test env ${contract.name}`); try { - const code = await hre.ethers.provider.getCode(contract.address); + const code = await hre.provider.getCode(await contract.getAddress()); if (code === "0x0" || code === "0x") { console.log(`❌ Failed to verify ${contract.name} on test env.`); } diff --git a/scripts/util/utils.js b/scripts/util/utils.js index fad8a280d..96dd28e88 100644 --- a/scripts/util/utils.js +++ b/scripts/util/utils.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { provider, getContractAt } = hre.ethers; const fs = require("fs"); const addressesDirPath = __dirname + `/../../addresses`; @@ -12,6 +12,7 @@ function delay(ms) { } function deploymentComplete(name, address, args, interfaceId, contracts) { + console.log("address", address); contracts.push({ name, address, args, interfaceId }); console.log(`✅ ${name} deployed to: ${address}`); } @@ -21,7 +22,7 @@ async function writeContracts(contracts, env, version) { fs.mkdirSync(addressesDirPath); } - const chainId = (await hre.ethers.provider.getNetwork()).chainId; + const chainId = Number((await provider.getNetwork()).chainId); const network = hre.network.name; const path = getAddressesFilePath(chainId, network, env); fs.writeFileSync( @@ -52,7 +53,7 @@ async function getBaseFee() { // getBlock("pending") doesn't work with hardhat. This is the value one gets by calling getBlock("0") return "1000000000"; } - const { baseFeePerGas } = await ethers.provider.getBlock("pending"); + const { baseFeePerGas } = await provider.getBlock("pending"); return baseFeePerGas; } @@ -61,10 +62,10 @@ async function getMaxFeePerGas(maxPriorityFeePerGas) { } async function getFees() { - // maxPriorityFeePerGas TODO add back as an argument when ethers.js supports 1559 on polygon - const { gasPrice } = await ethers.provider.getFeeData(); - const newGasPrice = gasPrice.mul(ethers.BigNumber.from("2")); - // return { maxPriorityFeePerGas, maxFeePerGas: await getMaxFeePerGas(maxPriorityFeePerGas) }; // TODO use when ethers.js supports 1559 on polygon + // maxPriorityFeePerGas TODO add back as an argument when js supports 1559 on polygon + const { gasPrice } = await provider.getFeeData(); + const newGasPrice = gasPrice * BigInt("2"); + // return { maxPriorityFeePerGas, maxFeePerGas: await getMaxFeePerGas(maxPriorityFeePerGas) }; // TODO use when js supports 1559 on polygon return { gasPrice: newGasPrice }; } @@ -77,7 +78,7 @@ async function checkRole(contracts, role, address) { } // Get AccessController abstraction - const accessController = await ethers.getContractAt("AccessController", accessControllerAddress); + const accessController = await getContractAt("AccessController", accessControllerAddress); // Check that caller has upgrader role. const hasRole = await accessController.hasRole(role, address); @@ -91,6 +92,10 @@ const addressNotFound = (address) => { process.exit(1); }; +function toHexString(bigNumber, { startPad } = { startPad: 8 }) { + return "0x" + (startPad ? bigNumber.toString(16).padStart(startPad, "0") : bigNumber.toString(16)); +} + exports.getAddressesFilePath = getAddressesFilePath; exports.writeContracts = writeContracts; exports.readContracts = readContracts; @@ -101,3 +106,4 @@ exports.getMaxFeePerGas = getMaxFeePerGas; exports.getFees = getFees; exports.checkRole = checkRole; exports.addressNotFound = addressNotFound; +exports.toHexString = toHexString; diff --git a/scripts/util/validations.js b/scripts/util/validations.js index 07b6db318..f29da1cee 100644 --- a/scripts/util/validations.js +++ b/scripts/util/validations.js @@ -1,5 +1,3 @@ -const hre = require("hardhat"); -const ethers = hre.ethers; const eip55 = require("eip55"); /** @@ -13,23 +11,24 @@ const eip55 = require("eip55"); * @returns {boolean} */ function bigNumberIsValid(bigNumber, { optional, gt, lte, empty } = {}) { - let valid = false; + let valid = true; + if (optional && (bigNumber == undefined || bigNumber == null)) { - return true; - } - try { - valid = - typeof bigNumber === "string" && - (empty - ? bigNumber === "" || typeof ethers.BigNumber.from(bigNumber) === "object" - : typeof ethers.BigNumber.from(bigNumber) === "object"); - if (gt != undefined) { - valid = valid && ethers.BigNumber.from(bigNumber).gt(gt); + valid = true; + } else if (empty && bigNumber === "") { + valid = true; + } else { + try { + const bigNumberValue = BigInt(bigNumber); + valid = + (typeof bigNumber === "string" || typeof bigNumber === "bigint") && + (gt == undefined || bigNumberValue > BigInt(gt)) && + (lte == undefined || bigNumberValue <= BigInt(lte)); + } catch (e) { + valid = false; } - if (lte != undefined) { - valid = valid && ethers.BigNumber.from(bigNumber).lte(lte); - } - } catch (e) {} + } + return valid; } @@ -101,7 +100,7 @@ function stringIsValid(string) { function bytes4IsValid(bytes4) { let valid = false; try { - valid = ethers.BigNumber.from(bytes4).gte("0") && ethers.BigNumber.from(bytes4).lte("4294967295"); // max bytes4 value + valid = BigInt(bytes4) >= 0n && BigInt(bytes4) <= 4294967295n; // max bytes4 value } catch (e) {} return valid; } diff --git a/test/access/AccessControllerTest.js b/test/access/AccessControllerTest.js index 3bc2fe409..024f6e1ea 100644 --- a/test/access/AccessControllerTest.js +++ b/test/access/AccessControllerTest.js @@ -1,5 +1,5 @@ -const hre = require("hardhat"); -const ethers = hre.ethers; +const { ethers } = require("hardhat"); +const { getContractFactory, getSigners, keccak256, toUtf8Bytes } = ethers; const { expect } = require("chai"); const Role = require("../../scripts/domain/Role"); const { getInterfaceIds } = require("../../scripts/config/supported-interfaces.js"); @@ -21,12 +21,12 @@ describe("AccessController", function () { beforeEach(async function () { // Make accounts available - [deployer, admin, protocol, upgrader, associate, pauser, client, feeCollector, rando] = await ethers.getSigners(); + [deployer, admin, protocol, upgrader, associate, pauser, client, feeCollector, rando] = await getSigners(); // Deploy the contract - AccessController = await ethers.getContractFactory("AccessController"); + AccessController = await getContractFactory("AccessController"); accessController = await AccessController.deploy(); - await accessController.deployed(); + await accessController.waitForDeployment(); }); context("📋 Interfaces", async function () { @@ -44,43 +44,58 @@ describe("AccessController", function () { context("📋 Deployer is limited to initial ADMIN role", async function () { it("Deployer should have ADMIN role", async function () { // Check role - expect(await accessController.hasRole(Role.ADMIN, deployer.address), "Deployer doesn't have ADMIN role").is.true; + expect( + await accessController.hasRole(Role.ADMIN, await deployer.getAddress()), + "Deployer doesn't have ADMIN role" + ).is.true; }); it("Deployer should not have PROTOCOL role", async function () { // Check role - expect(await accessController.hasRole(Role.PROTOCOL, deployer.address), "Deployer has PROTOCOL role").is.false; + expect( + await accessController.hasRole(Role.PROTOCOL, await deployer.getAddress()), + "Deployer has PROTOCOL role" + ).is.false; }); it("Deployer should not have UPGRADER role", async function () { // Check role - expect(await accessController.hasRole(Role.UPGRADER, deployer.address), "Deployer has UPGRADER role").is.false; + expect( + await accessController.hasRole(Role.UPGRADER, await deployer.getAddress()), + "Deployer has UPGRADER role" + ).is.false; }); it("Deployer should not have PAUSER role", async function () { // Check role - expect(await accessController.hasRole(Role.PAUSER, deployer.address), "Deployer has PAUSER role").is.false; + expect( + await accessController.hasRole(Role.PAUSER, await deployer.getAddress()), + "Deployer has PAUSER role" + ).is.false; }); it("Deployer should not have CLIENT role", async function () { // Check role - expect(await accessController.hasRole(Role.CLIENT, deployer.address), "Deployer has CLIENT role").is.false; + expect( + await accessController.hasRole(Role.CLIENT, await deployer.getAddress()), + "Deployer has CLIENT role" + ).is.false; }); it("Deployer should not have FEE_COLLECTOR role", async function () { // Check role expect( - await accessController.hasRole(Role.FEE_COLLECTOR, deployer.address), + await accessController.hasRole(Role.FEE_COLLECTOR, await deployer.getAddress()), "Deployer has FEE_COLLECTOR role" ).is.false; }); it("Deployer should not have any un managed value as role", async function () { // Random unknown role - let role = ethers.utils.keccak256(ethers.utils.toUtf8Bytes("random")); + let role = keccak256(toUtf8Bytes("random")); // Check role - expect(await accessController.hasRole(role, deployer.address), "Deployer has a random role").is.false; + expect(await accessController.hasRole(role, await deployer.getAddress()), "Deployer has a random role").is.false; }); }); @@ -137,78 +152,84 @@ describe("AccessController", function () { context("📋 Any ADMIN can grant all other roles", async function () { beforeEach(async function () { // Deployer grants ADMIN to another admin address - await accessController.grantRole(Role.ADMIN, admin.address); - expect(await accessController.hasRole(Role.ADMIN, admin.address)).is.true; + await accessController.grantRole(Role.ADMIN, await admin.getAddress()); + expect(await accessController.hasRole(Role.ADMIN, await admin.getAddress())).is.true; }); it("ADMIN role should be able to grant ADMIN role", async function () { // Grant Role, expecting the event - await expect(accessController.connect(admin).grantRole(Role.ADMIN, associate.address)) + await expect(accessController.connect(admin).grantRole(Role.ADMIN, await associate.getAddress())) .to.emit(accessController, "RoleGranted") - .withArgs(Role.ADMIN, associate.address, admin.address); + .withArgs(Role.ADMIN, await associate.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.ADMIN, associate.address), + await accessController.hasRole(Role.ADMIN, await associate.getAddress()), "ADMIN role can't grant ADMIN role" ).is.true; }); it("ADMIN role should be able to grant PROTOCOL role", async function () { // Grant Role, expecting the event - await expect(accessController.connect(admin).grantRole(Role.PROTOCOL, protocol.address)) + await expect(accessController.connect(admin).grantRole(Role.PROTOCOL, await protocol.getAddress())) .to.emit(accessController, "RoleGranted") - .withArgs(Role.PROTOCOL, protocol.address, admin.address); + .withArgs(Role.PROTOCOL, await protocol.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.PROTOCOL, protocol.address), + await accessController.hasRole(Role.PROTOCOL, await protocol.getAddress()), "ADMIN role can't grant PROTOCOL role" ).is.true; }); it("ADMIN role should be able to grant UPGRADER role", async function () { // Grant Role, expecting the event - await expect(accessController.connect(admin).grantRole(Role.UPGRADER, upgrader.address)) + await expect(accessController.connect(admin).grantRole(Role.UPGRADER, await upgrader.getAddress())) .to.emit(accessController, "RoleGranted") - .withArgs(Role.UPGRADER, upgrader.address, admin.address); + .withArgs(Role.UPGRADER, await upgrader.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.UPGRADER, upgrader.address), + await accessController.hasRole(Role.UPGRADER, await upgrader.getAddress()), "ADMIN role can't grant UPGRADER role" ).is.true; }); it("ADMIN role should be able to grant PAUSER role", async function () { // Grant Role, expecting the event - await expect(accessController.connect(admin).grantRole(Role.PAUSER, pauser.address)) + await expect(accessController.connect(admin).grantRole(Role.PAUSER, await pauser.getAddress())) .to.emit(accessController, "RoleGranted") - .withArgs(Role.PAUSER, pauser.address, admin.address); + .withArgs(Role.PAUSER, await pauser.getAddress(), await admin.getAddress()); // Test - expect(await accessController.hasRole(Role.PAUSER, pauser.address), "ADMIN role can't grant PAUSER role").is.true; + expect( + await accessController.hasRole(Role.PAUSER, await pauser.getAddress()), + "ADMIN role can't grant PAUSER role" + ).is.true; }); it("ADMIN role should be able to grant CLIENT role", async function () { // Grant Role, expecting the event - await expect(accessController.connect(admin).grantRole(Role.CLIENT, client.address)) + await expect(accessController.connect(admin).grantRole(Role.CLIENT, await client.getAddress())) .to.emit(accessController, "RoleGranted") - .withArgs(Role.CLIENT, client.address, admin.address); + .withArgs(Role.CLIENT, await client.getAddress(), await admin.getAddress()); // Test - expect(await accessController.hasRole(Role.CLIENT, client.address), "ADMIN role can't grant CLIENT role").is.true; + expect( + await accessController.hasRole(Role.CLIENT, await client.getAddress()), + "ADMIN role can't grant CLIENT role" + ).is.true; }); it("ADMIN role should be able to grant FEE_COLLECTOR role", async function () { // Grant Role, expecting the event - await expect(accessController.connect(admin).grantRole(Role.FEE_COLLECTOR, feeCollector.address)) + await expect(accessController.connect(admin).grantRole(Role.FEE_COLLECTOR, await feeCollector.getAddress())) .to.emit(accessController, "RoleGranted") - .withArgs(Role.FEE_COLLECTOR, feeCollector.address, admin.address); + .withArgs(Role.FEE_COLLECTOR, await feeCollector.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.FEE_COLLECTOR, feeCollector.address), + await accessController.hasRole(Role.FEE_COLLECTOR, await feeCollector.getAddress()), "ADMIN role can't grant FEE_COLLECTOR role" ).is.true; }); @@ -217,254 +238,258 @@ describe("AccessController", function () { context("📋 Any ADMIN can revoke all other roles", async function () { beforeEach(async function () { // Deployer grants roles to other addresses - await accessController.connect(deployer).grantRole(Role.ADMIN, admin.address); - await accessController.connect(deployer).grantRole(Role.PROTOCOL, protocol.address); - await accessController.connect(deployer).grantRole(Role.UPGRADER, upgrader.address); - await accessController.connect(deployer).grantRole(Role.PAUSER, pauser.address); - await accessController.connect(deployer).grantRole(Role.CLIENT, client.address); - await accessController.connect(deployer).grantRole(Role.FEE_COLLECTOR, feeCollector.address); + await accessController.connect(deployer).grantRole(Role.ADMIN, await admin.getAddress()); + await accessController.connect(deployer).grantRole(Role.PROTOCOL, await protocol.getAddress()); + await accessController.connect(deployer).grantRole(Role.UPGRADER, await upgrader.getAddress()); + await accessController.connect(deployer).grantRole(Role.PAUSER, await pauser.getAddress()); + await accessController.connect(deployer).grantRole(Role.CLIENT, await client.getAddress()); + await accessController.connect(deployer).grantRole(Role.FEE_COLLECTOR, await feeCollector.getAddress()); }); it("ADMIN role should be able to revoke ADMIN role", async function () { // Revoke Role, expecting the event - await expect(accessController.connect(admin).revokeRole(Role.ADMIN, deployer.address)) + await expect(accessController.connect(admin).revokeRole(Role.ADMIN, await deployer.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.ADMIN, deployer.address, admin.address); + .withArgs(Role.ADMIN, await deployer.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.ADMIN, deployer.address), + await accessController.hasRole(Role.ADMIN, await deployer.getAddress()), "ADMIN role can't revoke ADMIN role" ).is.false; }); it("ADMIN role should be able to revoke PROTOCOL role", async function () { // Revoke Role, expecting the event - await expect(accessController.connect(admin).revokeRole(Role.PROTOCOL, protocol.address)) + await expect(accessController.connect(admin).revokeRole(Role.PROTOCOL, await protocol.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.PROTOCOL, protocol.address, admin.address); + .withArgs(Role.PROTOCOL, await protocol.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.PROTOCOL, protocol.address), + await accessController.hasRole(Role.PROTOCOL, await protocol.getAddress()), "ADMIN role can't revoke PROTOCOL role" ).is.false; }); it("ADMIN role should be able to revoke UPGRADER role", async function () { // Revoke Role, expecting the event - await expect(accessController.connect(admin).revokeRole(Role.UPGRADER, upgrader.address)) + await expect(accessController.connect(admin).revokeRole(Role.UPGRADER, await upgrader.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.UPGRADER, upgrader.address, admin.address); + .withArgs(Role.UPGRADER, await upgrader.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.UPGRADER, upgrader.address), + await accessController.hasRole(Role.UPGRADER, await upgrader.getAddress()), "ADMIN role can't revoke UPGRADER role" ).is.false; }); it("ADMIN role should be able to revoke PAUSER role", async function () { // Revoke Role, expecting the event - await expect(accessController.connect(admin).revokeRole(Role.PAUSER, pauser.address)) + await expect(accessController.connect(admin).revokeRole(Role.PAUSER, await pauser.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.PAUSER, pauser.address, admin.address); + .withArgs(Role.PAUSER, await pauser.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.PAUSER, pauser.address), + await accessController.hasRole(Role.PAUSER, await pauser.getAddress()), "ADMIN role can't revoke PAUSER role" ).is.false; }); it("ADMIN role should be able to revoke CLIENT role", async function () { // Revoke Role, expecting the event - await expect(accessController.connect(admin).revokeRole(Role.CLIENT, client.address)) + await expect(accessController.connect(admin).revokeRole(Role.CLIENT, await client.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.CLIENT, client.address, admin.address); + .withArgs(Role.CLIENT, await client.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.CLIENT, client.address), + await accessController.hasRole(Role.CLIENT, await client.getAddress()), "ADMIN role can't revoke CLIENT role" ).is.false; }); it("ADMIN role should be able to revoke FEE_COLLECTOR role", async function () { // Revoke Role, expecting the event - await expect(accessController.connect(admin).revokeRole(Role.FEE_COLLECTOR, feeCollector.address)) + await expect(accessController.connect(admin).revokeRole(Role.FEE_COLLECTOR, await feeCollector.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.FEE_COLLECTOR, feeCollector.address, admin.address); + .withArgs(Role.FEE_COLLECTOR, await feeCollector.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.FEE_COLLECTOR, feeCollector.address), + await accessController.hasRole(Role.FEE_COLLECTOR, await feeCollector.getAddress()), "ADMIN role can't revoke FEE_COLLECTOR role" ).is.false; }); it("Should not emit 'RoleRevoked' event if revoking a role that was not granted", async function () { // Revoke Role, should not emit the event - await expect(accessController.connect(admin).revokeRole(Role.ADMIN, rando.address)).to.not.emit( + await expect(accessController.connect(admin).revokeRole(Role.ADMIN, await rando.getAddress())).to.not.emit( accessController, "RoleRevoked" ); // Test - expect(await accessController.hasRole(Role.ADMIN, rando.address)).is.false; + expect(await accessController.hasRole(Role.ADMIN, await rando.getAddress())).is.false; }); }); context("📋 Any roled address can renounce its roles", async function () { beforeEach(async function () { // Deployer grants roles to other addresses - await accessController.connect(deployer).grantRole(Role.ADMIN, admin.address); - await accessController.connect(deployer).grantRole(Role.PROTOCOL, protocol.address); - await accessController.connect(deployer).grantRole(Role.UPGRADER, upgrader.address); - await accessController.connect(deployer).grantRole(Role.PAUSER, pauser.address); - await accessController.connect(deployer).grantRole(Role.CLIENT, client.address); - await accessController.connect(deployer).grantRole(Role.FEE_COLLECTOR, feeCollector.address); + await accessController.connect(deployer).grantRole(Role.ADMIN, await admin.getAddress()); + await accessController.connect(deployer).grantRole(Role.PROTOCOL, await protocol.getAddress()); + await accessController.connect(deployer).grantRole(Role.UPGRADER, await upgrader.getAddress()); + await accessController.connect(deployer).grantRole(Role.PAUSER, await pauser.getAddress()); + await accessController.connect(deployer).grantRole(Role.CLIENT, await client.getAddress()); + await accessController.connect(deployer).grantRole(Role.FEE_COLLECTOR, await feeCollector.getAddress()); }); it("ADMIN role should be able to renounce ADMIN role", async function () { // Renounce Role, expecting the event - await expect(accessController.connect(admin).renounceRole(Role.ADMIN, admin.address)) + await expect(accessController.connect(admin).renounceRole(Role.ADMIN, await admin.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.ADMIN, admin.address, admin.address); + .withArgs(Role.ADMIN, await admin.getAddress(), await admin.getAddress()); // Test expect( - await accessController.hasRole(Role.ADMIN, admin.address), + await accessController.hasRole(Role.ADMIN, await admin.getAddress()), "ADMIN role can't renounce ADMIN role" ).is.false; }); it("PROTOCOL role should be able to renounce PROTOCOL role", async function () { // Renounce Role, expecting the event - await expect(accessController.connect(protocol).renounceRole(Role.PROTOCOL, protocol.address)) + await expect(accessController.connect(protocol).renounceRole(Role.PROTOCOL, await protocol.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.PROTOCOL, protocol.address, protocol.address); + .withArgs(Role.PROTOCOL, await protocol.getAddress(), await protocol.getAddress()); // Test expect( - await accessController.hasRole(Role.PROTOCOL, protocol.address), + await accessController.hasRole(Role.PROTOCOL, await protocol.getAddress()), "PROTOCOL role can't renounce PROTOCOL role" ).is.false; }); it("UPGRADER role should be able to renounce UPGRADER role", async function () { // Renounce Role, expecting the event - await expect(accessController.connect(upgrader).renounceRole(Role.UPGRADER, upgrader.address)) + await expect(accessController.connect(upgrader).renounceRole(Role.UPGRADER, await upgrader.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.UPGRADER, upgrader.address, upgrader.address); + .withArgs(Role.UPGRADER, await upgrader.getAddress(), await upgrader.getAddress()); // Test expect( - await accessController.hasRole(Role.UPGRADER, upgrader.address), + await accessController.hasRole(Role.UPGRADER, await upgrader.getAddress()), "UPGRADER role can't renounce UPGRADER role" ).is.false; }); it("PAUSER role should be able to renounce PAUSER role", async function () { // Renounce Role, expecting the event - await expect(accessController.connect(pauser).renounceRole(Role.PAUSER, pauser.address)) + await expect(accessController.connect(pauser).renounceRole(Role.PAUSER, await pauser.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.PAUSER, pauser.address, pauser.address); + .withArgs(Role.PAUSER, await pauser.getAddress(), await pauser.getAddress()); // Test expect( - await accessController.hasRole(Role.PAUSER, pauser.address), + await accessController.hasRole(Role.PAUSER, await pauser.getAddress()), "PAUSER role can't renounce PAUSER role" ).is.false; }); it("CLIENT role should be able to renounce CLIENT role", async function () { // Renounce Role, expecting the event - await expect(accessController.connect(client).renounceRole(Role.CLIENT, client.address)) + await expect(accessController.connect(client).renounceRole(Role.CLIENT, await client.getAddress())) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.CLIENT, client.address, client.address); + .withArgs(Role.CLIENT, await client.getAddress(), await client.getAddress()); // Test expect( - await accessController.hasRole(Role.CLIENT, client.address), + await accessController.hasRole(Role.CLIENT, await client.getAddress()), "CLIENT role can't renounce CLIENT role" ).is.false; }); it("FEE_COLLECTOR role should be able to renounce FEE_COLLECTOR role", async function () { // Renounce Role, expecting the event - await expect(accessController.connect(feeCollector).renounceRole(Role.FEE_COLLECTOR, feeCollector.address)) + await expect( + accessController.connect(feeCollector).renounceRole(Role.FEE_COLLECTOR, await feeCollector.getAddress()) + ) .to.emit(accessController, "RoleRevoked") - .withArgs(Role.FEE_COLLECTOR, feeCollector.address, feeCollector.address); + .withArgs(Role.FEE_COLLECTOR, await feeCollector.getAddress(), await feeCollector.getAddress()); // Test expect( - await accessController.hasRole(Role.FEE_COLLECTOR, feeCollector.address), + await accessController.hasRole(Role.FEE_COLLECTOR, await feeCollector.getAddress()), "FEE_COLLECTOR role can't renounce FEE_COLLECTOR role" ).is.false; }); it("Should not emit 'RoleRevoked' event if renouncing a role that was not granted", async function () { // Renounce Role, should not emit the event - await expect(accessController.connect(rando).renounceRole(Role.ADMIN, rando.address)).to.not.emit( + await expect(accessController.connect(rando).renounceRole(Role.ADMIN, await rando.getAddress())).to.not.emit( accessController, "RoleRevoked" ); // Test - expect(await accessController.hasRole(Role.ADMIN, rando.address)).is.false; + expect(await accessController.hasRole(Role.ADMIN, await rando.getAddress())).is.false; }); }); context("📋 Any address can have multiple roles", async function () { beforeEach(async function () { // Deployer grants ADMIN to another address - await accessController.connect(deployer).grantRole(Role.ADMIN, admin.address); + await accessController.connect(deployer).grantRole(Role.ADMIN, await admin.getAddress()); }); it("ADMIN role should be able to grant multiple roles to same address", async function () { // Grant all roles to associate try { - await accessController.connect(admin).grantRole(Role.ADMIN, associate.address); - await accessController.connect(admin).grantRole(Role.PROTOCOL, associate.address); - await accessController.connect(admin).grantRole(Role.UPGRADER, associate.address); - await accessController.connect(admin).grantRole(Role.PAUSER, associate.address); - await accessController.connect(admin).grantRole(Role.CLIENT, associate.address); - await accessController.connect(admin).grantRole(Role.FEE_COLLECTOR, associate.address); + await accessController.connect(admin).grantRole(Role.ADMIN, await associate.getAddress()); + await accessController.connect(admin).grantRole(Role.PROTOCOL, await associate.getAddress()); + await accessController.connect(admin).grantRole(Role.UPGRADER, await associate.getAddress()); + await accessController.connect(admin).grantRole(Role.PAUSER, await associate.getAddress()); + await accessController.connect(admin).grantRole(Role.CLIENT, await associate.getAddress()); + await accessController.connect(admin).grantRole(Role.FEE_COLLECTOR, await associate.getAddress()); } catch (e) {} // Check roles all apply for associate - expect(await accessController.hasRole(Role.ADMIN, associate.address)).is.true; - expect(await accessController.hasRole(Role.PROTOCOL, associate.address)).is.true; - expect(await accessController.hasRole(Role.UPGRADER, associate.address)).is.true; - expect(await accessController.hasRole(Role.PAUSER, associate.address)).is.true; - expect(await accessController.hasRole(Role.CLIENT, associate.address)).is.true; - expect(await accessController.hasRole(Role.FEE_COLLECTOR, associate.address)).is.true; + expect(await accessController.hasRole(Role.ADMIN, await associate.getAddress())).is.true; + expect(await accessController.hasRole(Role.PROTOCOL, await associate.getAddress())).is.true; + expect(await accessController.hasRole(Role.UPGRADER, await associate.getAddress())).is.true; + expect(await accessController.hasRole(Role.PAUSER, await associate.getAddress())).is.true; + expect(await accessController.hasRole(Role.CLIENT, await associate.getAddress())).is.true; + expect(await accessController.hasRole(Role.FEE_COLLECTOR, await associate.getAddress())).is.true; }); }); context("💔 Revert Reasons", async function () { it("Caller is different from account to be renounced", async function () { // Renounce Role, expecting revert - await expect(accessController.connect(admin).renounceRole(Role.ADMIN, deployer.address)).to.be.revertedWith( - RevertReasons.CAN_ONLY_REVOKE_SELF - ); + await expect( + accessController.connect(admin).renounceRole(Role.ADMIN, await deployer.getAddress()) + ).to.be.revertedWith(RevertReasons.CAN_ONLY_REVOKE_SELF); }); it("Should revert if caller tries to grantRole but doesn't have ADMIN role", async function () { // Grant Role, expecting revert - await expect(accessController.connect(rando).grantRole(Role.ADMIN, rando.address)).to.be.revertedWith( - `AccessControl: account ${rando.address.toLowerCase()} is missing role ${Role.ADMIN}` + await expect(accessController.connect(rando).grantRole(Role.ADMIN, await rando.getAddress())).to.be.revertedWith( + `AccessControl: account ${(await rando.getAddress()).toLowerCase()} is missing role ${Role.ADMIN}` ); }); it("Should revert if caller tries to revokeRole but doesn't have ADMIN role", async function () { // Grant role - await accessController.connect(deployer).grantRole(Role.PAUSER, pauser.address); + await accessController.connect(deployer).grantRole(Role.PAUSER, await pauser.getAddress()); // Revoke Role, expecting revert - await expect(accessController.connect(rando).revokeRole(Role.PAUSER, pauser.address)).to.be.revertedWith( - `AccessControl: account ${rando.address.toLowerCase()} is missing role ${Role.ADMIN}` + await expect( + accessController.connect(rando).revokeRole(Role.PAUSER, await pauser.getAddress()) + ).to.be.revertedWith( + `AccessControl: account ${(await rando.getAddress()).toLowerCase()} is missing role ${Role.ADMIN}` ); }); }); diff --git a/test/domain/AgentTest.js b/test/domain/AgentTest.js index 195ea2385..f355f1be0 100644 --- a/test/domain/AgentTest.js +++ b/test/domain/AgentTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners } = hre.ethers; const { expect } = require("chai"); const Agent = require("../../scripts/domain/Agent"); @@ -14,7 +14,7 @@ describe("Agent", function () { context("📋 Constructor", async function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); wallet = accounts[1].address; // Required constructor params @@ -39,7 +39,7 @@ describe("Agent", function () { context("📋 Field validations", async function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); wallet = accounts[1].address; // Required constructor params @@ -63,11 +63,6 @@ describe("Agent", function () { expect(agent.idIsValid()).is.false; expect(agent.isValid()).is.false; - // Invalid field value - agent.id = 12; - expect(agent.idIsValid()).is.false; - expect(agent.isValid()).is.false; - // Valid field value agent.id = "0"; expect(agent.idIsValid()).is.true; @@ -90,11 +85,6 @@ describe("Agent", function () { expect(agent.feePercentageIsValid()).is.false; expect(agent.isValid()).is.false; - // Invalid field value - agent.feePercentage = 12; - expect(agent.feePercentageIsValid()).is.false; - expect(agent.isValid()).is.false; - // Invalid field value agent.feePercentage = "10001"; // Value greater than 100% should be invalid expect(agent.feePercentageIsValid()).is.false; @@ -159,7 +149,7 @@ describe("Agent", function () { context("📋 Utility functions", async function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); wallet = accounts[1].address; // Required constructor params diff --git a/test/domain/AuthTokenTest.js b/test/domain/AuthTokenTest.js index 94d8416a3..d7130bb68 100644 --- a/test/domain/AuthTokenTest.js +++ b/test/domain/AuthTokenTest.js @@ -48,11 +48,6 @@ describe("AuthToken", function () { expect(authToken.tokenIdIsValid()).is.false; expect(authToken.isValid()).is.false; - // Invalid field value - authToken.tokenId = 12; - expect(authToken.tokenIdIsValid()).is.false; - expect(authToken.isValid()).is.false; - // Valid field value authToken.tokenId = "0"; expect(authToken.tokenIdIsValid()).is.true; diff --git a/test/domain/BundleTest.js b/test/domain/BundleTest.js index 1b4b2e86f..a9e5a75b0 100644 --- a/test/domain/BundleTest.js +++ b/test/domain/BundleTest.js @@ -45,11 +45,6 @@ describe("Bundle", function () { expect(bundle.idIsValid()).is.false; expect(bundle.isValid()).is.false; - // Invalid field value - bundle.id = 12; - expect(bundle.idIsValid()).is.false; - expect(bundle.isValid()).is.false; - // Valid field value bundle.id = "0"; expect(bundle.idIsValid()).is.true; @@ -67,16 +62,6 @@ describe("Bundle", function () { expect(bundle.sellerIdIsValid()).is.false; expect(bundle.isValid()).is.false; - // Invalid field value - bundle.sellerId = new Date(); - expect(bundle.sellerIdIsValid()).is.false; - expect(bundle.isValid()).is.false; - - // Invalid field value - bundle.sellerId = 12; - expect(bundle.sellerIdIsValid()).is.false; - expect(bundle.isValid()).is.false; - // Valid field value bundle.sellerId = "0"; expect(bundle.sellerIdIsValid()).is.true; diff --git a/test/domain/BuyerTest.js b/test/domain/BuyerTest.js index fea4d63a9..0e506033c 100644 --- a/test/domain/BuyerTest.js +++ b/test/domain/BuyerTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners } = hre.ethers; const { expect } = require("chai"); const Buyer = require("../../scripts/domain/Buyer"); @@ -14,7 +14,7 @@ describe("Buyer", function () { context("📋 Constructor", async function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); wallet = accounts[1].address; // Required constructor params @@ -50,21 +50,16 @@ describe("Buyer", function () { expect(buyer.idIsValid()).is.false; expect(buyer.isValid()).is.false; - // Invalid field value - buyer.id = new Date(); - expect(buyer.idIsValid()).is.false; - expect(buyer.isValid()).is.false; - - // Invalid field value - buyer.id = 12; - expect(buyer.idIsValid()).is.false; - expect(buyer.isValid()).is.false; - // Valid field value buyer.id = "0"; expect(buyer.idIsValid()).is.true; expect(buyer.isValid()).is.true; + // Invalid field value + buyer.id = new Date(); + expect(buyer.idIsValid()).is.false; + expect(buyer.isValid()).is.false; + // Valid field value buyer.id = "126"; expect(buyer.idIsValid()).is.true; diff --git a/test/domain/ConditionTest.js b/test/domain/ConditionTest.js index 9f894086f..b746edec6 100644 --- a/test/domain/ConditionTest.js +++ b/test/domain/ConditionTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners } = hre.ethers; const { expect } = require("chai"); const Condition = require("../../scripts/domain/Condition"); const EvaluationMethod = require("../../scripts/domain/EvaluationMethod"); @@ -12,21 +12,20 @@ describe("Condition", function () { // Suite-wide scope let condition, object, promoted, clone, dehydrated, rehydrated, key, value, struct; let accounts, method, tokenType, tokenAddress, tokenId, threshold, maxCommits; + beforeEach(async function () { + // Get a list of accounts + accounts = await getSigners(); + tokenAddress = accounts[1].address; + + // Required constructor params + method = EvaluationMethod.None; + tokenType = TokenType.MultiToken; + tokenId = "1"; + threshold = "1"; + maxCommits = "3"; + }); context("📋 Constructor", async function () { - beforeEach(async function () { - // Get a list of accounts - accounts = await ethers.getSigners(); - tokenAddress = accounts[1].address; - - // Required constructor params - method = EvaluationMethod.None; - tokenType = TokenType.MultiToken; - tokenId = "1"; - threshold = "1"; - maxCommits = "3"; - }); - it("Should allow creation of valid, fully populated Condition instance", async function () { // Create a valid condition condition = new Condition(method, tokenType, tokenAddress, tokenId, threshold, maxCommits); @@ -61,6 +60,11 @@ describe("Condition", function () { expect(condition.methodIsValid()).is.false; expect(condition.isValid()).is.false; + // Invalid field value + condition.method = new Date(); + expect(condition.methodIsValid()).is.false; + expect(condition.isValid()).is.false; + // Invalid field value condition.method = "126"; expect(condition.methodIsValid()).is.false; @@ -105,16 +109,6 @@ describe("Condition", function () { expect(condition.tokenIdIsValid()).is.false; expect(condition.isValid()).is.false; - // Invalid field value - condition.tokenId = new Date(); - expect(condition.tokenIdIsValid()).is.false; - expect(condition.isValid()).is.false; - - // Invalid field value - condition.tokenId = 12; - expect(condition.tokenIdIsValid()).is.false; - expect(condition.isValid()).is.false; - // Valid field value condition.tokenId = "0"; expect(condition.tokenIdIsValid()).is.true; @@ -132,21 +126,16 @@ describe("Condition", function () { expect(condition.thresholdIsValid()).is.false; expect(condition.isValid()).is.false; - // Invalid field value - condition.threshold = new Date(); - expect(condition.thresholdIsValid()).is.false; - expect(condition.isValid()).is.false; - - // Invalid field value - condition.threshold = 12; - expect(condition.thresholdIsValid()).is.false; - expect(condition.isValid()).is.false; - // Valid field value condition.threshold = "0"; expect(condition.thresholdIsValid()).is.true; expect(condition.isValid()).is.true; + // Invalid field value + condition.threshold = new Date(); + expect(condition.thresholdIsValid()).is.false; + expect(condition.isValid()).is.false; + // Valid field value condition.threshold = "126"; expect(condition.thresholdIsValid()).is.true; @@ -159,16 +148,6 @@ describe("Condition", function () { expect(condition.maxCommitsIsValid()).is.false; expect(condition.isValid()).is.false; - // Invalid field value - condition.maxCommits = new Date(); - expect(condition.maxCommitsIsValid()).is.false; - expect(condition.isValid()).is.false; - - // Invalid field value - condition.maxCommits = 12; - expect(condition.maxCommitsIsValid()).is.false; - expect(condition.isValid()).is.false; - // Valid field value condition.maxCommits = "0"; expect(condition.maxCommitsIsValid()).is.true; @@ -178,6 +157,11 @@ describe("Condition", function () { condition.maxCommits = "126"; expect(condition.maxCommitsIsValid()).is.true; expect(condition.isValid()).is.true; + + // Invalid field value + condition.maxCommits = new Date(); + expect(condition.maxCommitsIsValid()).is.false; + expect(condition.isValid()).is.false; }); }); diff --git a/test/domain/DisputeDatesTest.js b/test/domain/DisputeDatesTest.js index 75627bbdf..20d2b62f8 100644 --- a/test/domain/DisputeDatesTest.js +++ b/test/domain/DisputeDatesTest.js @@ -46,11 +46,6 @@ describe("DisputeDates", function () { expect(disputeDates.disputedIsValid()).is.false; expect(disputeDates.isValid()).is.false; - // Invalid field value - disputeDates.disputed = 12; - expect(disputeDates.disputedIsValid()).is.false; - expect(disputeDates.isValid()).is.false; - // Valid field value disputeDates.disputed = "0"; expect(disputeDates.disputedIsValid()).is.true; @@ -68,16 +63,6 @@ describe("DisputeDates", function () { expect(disputeDates.escalatedIsValid()).is.false; expect(disputeDates.isValid()).is.false; - // Invalid field value - disputeDates.escalated = new Date(); - expect(disputeDates.escalatedIsValid()).is.false; - expect(disputeDates.isValid()).is.false; - - // Invalid field value - disputeDates.escalated = 12; - expect(disputeDates.escalatedIsValid()).is.false; - expect(disputeDates.isValid()).is.false; - // Valid field value disputeDates.escalated = "0"; expect(disputeDates.escalatedIsValid()).is.true; @@ -88,6 +73,11 @@ describe("DisputeDates", function () { expect(disputeDates.escalatedIsValid()).is.true; expect(disputeDates.isValid()).is.true; + // Invalid field value + disputeDates.escalated = new Date(); + expect(disputeDates.escalatedIsValid()).is.false; + expect(disputeDates.isValid()).is.false; + // Valid field value disputeDates.escalated = null; expect(disputeDates.escalatedIsValid()).is.true; @@ -105,16 +95,6 @@ describe("DisputeDates", function () { expect(disputeDates.finalizedIsValid()).is.false; expect(disputeDates.isValid()).is.false; - // Invalid field value - disputeDates.finalized = new Date(); - expect(disputeDates.finalizedIsValid()).is.false; - expect(disputeDates.isValid()).is.false; - - // Invalid field value - disputeDates.finalized = 12; - expect(disputeDates.finalizedIsValid()).is.false; - expect(disputeDates.isValid()).is.false; - // Valid field value disputeDates.finalized = "0"; expect(disputeDates.finalizedIsValid()).is.true; @@ -125,6 +105,11 @@ describe("DisputeDates", function () { expect(disputeDates.finalizedIsValid()).is.true; expect(disputeDates.isValid()).is.true; + // Invalid field value + disputeDates.finalized = new Date(); + expect(disputeDates.finalizedIsValid()).is.false; + expect(disputeDates.isValid()).is.false; + // Valid field value disputeDates.finalized = null; expect(disputeDates.finalizedIsValid()).is.true; @@ -142,16 +127,6 @@ describe("DisputeDates", function () { expect(disputeDates.timeoutIsValid()).is.false; expect(disputeDates.isValid()).is.false; - // Invalid field value - disputeDates.timeout = new Date(); - expect(disputeDates.timeoutIsValid()).is.false; - expect(disputeDates.isValid()).is.false; - - // Invalid field value - disputeDates.timeout = 12; - expect(disputeDates.timeoutIsValid()).is.false; - expect(disputeDates.isValid()).is.false; - // Valid field value disputeDates.timeout = "0"; expect(disputeDates.timeoutIsValid()).is.true; @@ -161,6 +136,11 @@ describe("DisputeDates", function () { disputeDates.timeout = "126"; expect(disputeDates.timeoutIsValid()).is.true; expect(disputeDates.isValid()).is.true; + + // Invalid field value + disputeDates.timeout = new Date(); + expect(disputeDates.timeoutIsValid()).is.false; + expect(disputeDates.isValid()).is.false; }); }); diff --git a/test/domain/DisputeResolutionTermsTest.js b/test/domain/DisputeResolutionTermsTest.js index 14ca7e8fc..d254a4530 100644 --- a/test/domain/DisputeResolutionTermsTest.js +++ b/test/domain/DisputeResolutionTermsTest.js @@ -52,21 +52,16 @@ describe("DisputeResolutionTerms", function () { expect(disputeResolutionTerms.disputeResolverIdIsValid()).is.false; expect(disputeResolutionTerms.isValid()).is.false; - // Invalid field value - disputeResolutionTerms.disputeResolverId = new Date(); - expect(disputeResolutionTerms.disputeResolverIdIsValid()).is.false; - expect(disputeResolutionTerms.isValid()).is.false; - - // Invalid field value - disputeResolutionTerms.disputeResolverId = 12; - expect(disputeResolutionTerms.disputeResolverIdIsValid()).is.false; - expect(disputeResolutionTerms.isValid()).is.false; - // Valid field value disputeResolutionTerms.disputeResolverId = "0"; expect(disputeResolutionTerms.disputeResolverIdIsValid()).is.true; expect(disputeResolutionTerms.isValid()).is.true; + // Invalid field value + disputeResolutionTerms.disputeResolverId = new Date(); + expect(disputeResolutionTerms.disputeResolverIdIsValid()).is.false; + expect(disputeResolutionTerms.isValid()).is.false; + // Valid field value disputeResolutionTerms.disputeResolverId = "126"; expect(disputeResolutionTerms.disputeResolverIdIsValid()).is.true; @@ -79,21 +74,16 @@ describe("DisputeResolutionTerms", function () { expect(disputeResolutionTerms.escalationResponsePeriodIsValid()).is.false; expect(disputeResolutionTerms.isValid()).is.false; - // Invalid field value - disputeResolutionTerms.escalationResponsePeriod = new Date(); - expect(disputeResolutionTerms.escalationResponsePeriodIsValid()).is.false; - expect(disputeResolutionTerms.isValid()).is.false; - - // Invalid field value - disputeResolutionTerms.escalationResponsePeriod = 12; - expect(disputeResolutionTerms.escalationResponsePeriodIsValid()).is.false; - expect(disputeResolutionTerms.isValid()).is.false; - // Valid field value disputeResolutionTerms.escalationResponsePeriod = "0"; expect(disputeResolutionTerms.escalationResponsePeriodIsValid()).is.true; expect(disputeResolutionTerms.isValid()).is.true; + // Invalid field value + disputeResolutionTerms.escalationResponsePeriod = new Date(); + expect(disputeResolutionTerms.escalationResponsePeriodIsValid()).is.false; + expect(disputeResolutionTerms.isValid()).is.false; + // Valid field value disputeResolutionTerms.escalationResponsePeriod = "126"; expect(disputeResolutionTerms.escalationResponsePeriodIsValid()).is.true; @@ -106,16 +96,6 @@ describe("DisputeResolutionTerms", function () { expect(disputeResolutionTerms.feeAmountIsValid()).is.false; expect(disputeResolutionTerms.isValid()).is.false; - // Invalid field value - disputeResolutionTerms.feeAmount = new Date(); - expect(disputeResolutionTerms.feeAmountIsValid()).is.false; - expect(disputeResolutionTerms.isValid()).is.false; - - // Invalid field value - disputeResolutionTerms.feeAmount = 12; - expect(disputeResolutionTerms.feeAmountIsValid()).is.false; - expect(disputeResolutionTerms.isValid()).is.false; - // Invalid field value disputeResolutionTerms.feeAmount = "12345"; expect(disputeResolutionTerms.feeAmountIsValid()).is.false; @@ -126,6 +106,11 @@ describe("DisputeResolutionTerms", function () { expect(disputeResolutionTerms.feeAmountIsValid()).is.true; expect(disputeResolutionTerms.isValid()).is.true; + // Invalid field value + disputeResolutionTerms.feeAmount = new Date(); + expect(disputeResolutionTerms.feeAmountIsValid()).is.false; + expect(disputeResolutionTerms.isValid()).is.false; + // Valid field value disputeResolutionTerms.feeAmount = "126"; expect(disputeResolutionTerms.feeAmountIsValid()).is.true; @@ -138,16 +123,6 @@ describe("DisputeResolutionTerms", function () { expect(disputeResolutionTerms.buyerEscalationDepositIsValid()).is.false; expect(disputeResolutionTerms.isValid()).is.false; - // Invalid field value - disputeResolutionTerms.buyerEscalationDeposit = new Date(); - expect(disputeResolutionTerms.buyerEscalationDepositIsValid()).is.false; - expect(disputeResolutionTerms.isValid()).is.false; - - // Invalid field value - disputeResolutionTerms.buyerEscalationDeposit = 12; - expect(disputeResolutionTerms.buyerEscalationDepositIsValid()).is.false; - expect(disputeResolutionTerms.isValid()).is.false; - // Valid field value disputeResolutionTerms.buyerEscalationDeposit = "0"; expect(disputeResolutionTerms.buyerEscalationDepositIsValid()).is.true; @@ -157,6 +132,11 @@ describe("DisputeResolutionTerms", function () { disputeResolutionTerms.buyerEscalationDeposit = "126"; expect(disputeResolutionTerms.buyerEscalationDepositIsValid()).is.true; expect(disputeResolutionTerms.isValid()).is.true; + + // Invalid field value + disputeResolutionTerms.buyerEscalationDeposit = new Date(); + expect(disputeResolutionTerms.buyerEscalationDepositIsValid()).is.false; + expect(disputeResolutionTerms.isValid()).is.false; }); }); diff --git a/test/domain/DisputeResolverFeeTest.js b/test/domain/DisputeResolverFeeTest.js index a00df624c..338373451 100644 --- a/test/domain/DisputeResolverFeeTest.js +++ b/test/domain/DisputeResolverFeeTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners } = hre.ethers; const { expect } = require("chai"); const { DisputeResolverFee, DisputeResolverFeeList } = require("../../scripts/domain/DisputeResolverFee"); @@ -13,7 +13,7 @@ describe("DisputeResolverFee", function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); tokenAddress = accounts[1].address; // Required constructor params @@ -94,11 +94,6 @@ describe("DisputeResolverFee", function () { expect(disputeResolverFee.feeAmountIsValid()).is.false; expect(disputeResolverFee.isValid()).is.false; - // Invalid field value - disputeResolverFee.feeAmount = 12; - expect(disputeResolverFee.feeAmountIsValid()).is.false; - expect(disputeResolverFee.isValid()).is.false; - // Valid field value disputeResolverFee.feeAmount = "0"; expect(disputeResolverFee.feeAmountIsValid()).is.true; @@ -218,7 +213,7 @@ describe("DisputeResolverFeeList", function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); // Required constructor params disputeResolverFees = [ diff --git a/test/domain/DisputeResolverTest.js b/test/domain/DisputeResolverTest.js index e0441abf5..9f9fc8fc6 100644 --- a/test/domain/DisputeResolverTest.js +++ b/test/domain/DisputeResolverTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners } = hre.ethers; const { expect } = require("chai"); const DisputeResolver = require("../../scripts/domain/DisputeResolver"); const { oneMonth } = require("../util/constants"); @@ -14,7 +14,7 @@ describe("DisputeResolver", function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); assistant = accounts[0].address; admin = accounts[1].address; clerk = accounts[2].address; @@ -79,11 +79,6 @@ describe("DisputeResolver", function () { expect(disputeResolver.idIsValid()).is.false; expect(disputeResolver.isValid()).is.false; - // Invalid field value - disputeResolver.id = 12; - expect(disputeResolver.idIsValid()).is.false; - expect(disputeResolver.isValid()).is.false; - // Valid field value disputeResolver.id = "0"; expect(disputeResolver.idIsValid()).is.true; @@ -101,21 +96,16 @@ describe("DisputeResolver", function () { expect(disputeResolver.escalationResponsePeriodIsValid()).is.false; expect(disputeResolver.isValid()).is.false; - // Invalid field value - disputeResolver.escalationResponsePeriod = new Date(); - expect(disputeResolver.escalationResponsePeriodIsValid()).is.false; - expect(disputeResolver.isValid()).is.false; - - // Invalid field value - disputeResolver.escalationResponsePeriod = 12; - expect(disputeResolver.escalationResponsePeriodIsValid()).is.false; - expect(disputeResolver.isValid()).is.false; - // Valid field value disputeResolver.escalationResponsePeriod = "0"; expect(disputeResolver.escalationResponsePeriodIsValid()).is.true; expect(disputeResolver.isValid()).is.true; + // Invalid field value + disputeResolver.escalationResponsePeriod = new Date(); + expect(disputeResolver.escalationResponsePeriodIsValid()).is.false; + expect(disputeResolver.isValid()).is.false; + // Valid field value disputeResolver.escalationResponsePeriod = "126"; expect(disputeResolver.escalationResponsePeriodIsValid()).is.true; diff --git a/test/domain/DisputeTest.js b/test/domain/DisputeTest.js index 6f94c273e..21f327f05 100644 --- a/test/domain/DisputeTest.js +++ b/test/domain/DisputeTest.js @@ -45,11 +45,6 @@ describe("Dispute", function () { expect(dispute.exchangeIdIsValid()).is.false; expect(dispute.isValid()).is.false; - // Invalid field value - dispute.exchangeId = 12; - expect(dispute.exchangeIdIsValid()).is.false; - expect(dispute.isValid()).is.false; - // Valid field value dispute.exchangeId = "0"; expect(dispute.exchangeIdIsValid()).is.true; @@ -77,30 +72,20 @@ describe("Dispute", function () { expect(dispute.stateIsValid()).is.false; expect(dispute.isValid()).is.false; - // Invalid field value - dispute.state = new Date(); - expect(dispute.stateIsValid()).is.false; - expect(dispute.isValid()).is.false; - // Valid field value dispute.state = DisputeState.Resolving; expect(dispute.stateIsValid()).is.true; expect(dispute.isValid()).is.true; - }); - - it("Always present, buyerPercent must be the string representation of a BigNumber", async function () { - // Invalid field value - dispute.buyerPercent = "zedzdeadbaby"; - expect(dispute.buyerPercentIsValid()).is.false; - expect(dispute.isValid()).is.false; // Invalid field value - dispute.buyerPercent = new Date(); - expect(dispute.buyerPercentIsValid()).is.false; + dispute.state = new Date(); + expect(dispute.stateIsValid()).is.false; expect(dispute.isValid()).is.false; + }); + it("Always present, buyerPercent must be the string representation of a BigNumber", async function () { // Invalid field value - dispute.buyerPercent = 12; + dispute.buyerPercent = "zedzdeadbaby"; expect(dispute.buyerPercentIsValid()).is.false; expect(dispute.isValid()).is.false; @@ -109,6 +94,11 @@ describe("Dispute", function () { expect(dispute.buyerPercentIsValid()).is.true; expect(dispute.isValid()).is.true; + // Invalid field value + dispute.buyerPercent = new Date(); + expect(dispute.buyerPercentIsValid()).is.false; + expect(dispute.isValid()).is.false; + // Valid field value dispute.buyerPercent = "126"; expect(dispute.buyerPercentIsValid()).is.true; diff --git a/test/domain/ExchangeTest.js b/test/domain/ExchangeTest.js index e4bc01e4e..ea8e7b158 100644 --- a/test/domain/ExchangeTest.js +++ b/test/domain/ExchangeTest.js @@ -51,11 +51,6 @@ describe("Exchange", function () { expect(exchange.idIsValid()).is.false; expect(exchange.isValid()).is.false; - // Invalid field value - exchange.id = 12; - expect(exchange.idIsValid()).is.false; - expect(exchange.isValid()).is.false; - // Invalid field value exchange.id = "0"; expect(exchange.idIsValid()).is.false; @@ -73,18 +68,13 @@ describe("Exchange", function () { expect(exchange.offerIdIsValid()).is.false; expect(exchange.isValid()).is.false; - // Invalid field value - exchange.offerId = new Date(); + // Valid field value + exchange.offerId = "0"; expect(exchange.offerIdIsValid()).is.false; expect(exchange.isValid()).is.false; // Invalid field value - exchange.offerId = 12; - expect(exchange.offerIdIsValid()).is.false; - expect(exchange.isValid()).is.false; - - // Valid field value - exchange.offerId = "0"; + exchange.offerId = new Date(); expect(exchange.offerIdIsValid()).is.false; expect(exchange.isValid()).is.false; @@ -100,16 +90,6 @@ describe("Exchange", function () { expect(exchange.buyerIdIsValid()).is.false; expect(exchange.isValid()).is.false; - // Invalid field value - exchange.buyerId = new Date(); - expect(exchange.buyerIdIsValid()).is.false; - expect(exchange.isValid()).is.false; - - // Invalid field value - exchange.buyerId = 12; - expect(exchange.buyerIdIsValid()).is.false; - expect(exchange.isValid()).is.false; - // Valid field value exchange.buyerId = "0"; expect(exchange.buyerIdIsValid()).is.false; @@ -119,21 +99,16 @@ describe("Exchange", function () { exchange.buyerId = "126"; expect(exchange.buyerIdIsValid()).is.true; expect(exchange.isValid()).is.true; - }); - it("If present, finalizedDate must be the string representation of a non-zero BigNumber", async function () { // Invalid field value - exchange.finalizedDate = "zedzdeadbaby"; - expect(exchange.finalizedDateIsValid()).is.false; - expect(exchange.isValid()).is.false; - - // Invalid field value - exchange.finalizedDate = new Date(); - expect(exchange.finalizedDateIsValid()).is.false; + exchange.buyerId = new Date(); + expect(exchange.buyerIdIsValid()).is.false; expect(exchange.isValid()).is.false; + }); + it("If present, finalizedDate must be the string representation of a non-zero BigNumber", async function () { // Invalid field value - exchange.finalizedDate = 12; + exchange.finalizedDate = "zedzdeadbaby"; expect(exchange.finalizedDateIsValid()).is.false; expect(exchange.isValid()).is.false; @@ -152,6 +127,11 @@ describe("Exchange", function () { expect(exchange.finalizedDateIsValid()).is.true; expect(exchange.isValid()).is.true; + // Invalid field value + exchange.finalizedDate = new Date(); + expect(exchange.finalizedDateIsValid()).is.false; + expect(exchange.isValid()).is.false; + // Valid field value exchange.finalizedDate = undefined; expect(exchange.finalizedDateIsValid()).is.true; diff --git a/test/domain/FacetCutTest.js b/test/domain/FacetCutTest.js index cd1a0e8ab..d29b18451 100644 --- a/test/domain/FacetCutTest.js +++ b/test/domain/FacetCutTest.js @@ -76,11 +76,6 @@ describe("FacetCut", function () { expect(facet.actionIsValid()).is.false; expect(facet.isValid()).is.false; - // Invalid field value - facet.action = 12; - expect(facet.actionIsValid()).is.false; - expect(facet.isValid()).is.false; - // Invalid field value facet.action = "0"; expect(facet.actionIsValid()).is.false; diff --git a/test/domain/FundsTest.js b/test/domain/FundsTest.js index e4adcc825..fd249d3bd 100644 --- a/test/domain/FundsTest.js +++ b/test/domain/FundsTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners } = hre.ethers; const { expect } = require("chai"); const { Funds, FundsList } = require("../../scripts/domain/Funds"); @@ -13,7 +13,7 @@ describe("Funds", function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); tokenAddress = accounts[1].address; // Required constructor params @@ -94,11 +94,6 @@ describe("Funds", function () { expect(funds.availableAmountIsValid()).is.false; expect(funds.isValid()).is.false; - // Invalid field value - funds.availableAmount = 12; - expect(funds.availableAmountIsValid()).is.false; - expect(funds.isValid()).is.false; - // Valid field value funds.availableAmount = "0"; expect(funds.availableAmountIsValid()).is.true; @@ -208,7 +203,7 @@ describe("FundsList", function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); // Required constructor params funds = [ diff --git a/test/domain/GroupTest.js b/test/domain/GroupTest.js index ce240fbb6..8148baf43 100644 --- a/test/domain/GroupTest.js +++ b/test/domain/GroupTest.js @@ -44,21 +44,16 @@ describe("Group", function () { expect(group.idIsValid()).is.false; expect(group.isValid()).is.false; - // Invalid field value - group.id = new Date(); - expect(group.idIsValid()).is.false; - expect(group.isValid()).is.false; - - // Invalid field value - group.id = 12; - expect(group.idIsValid()).is.false; - expect(group.isValid()).is.false; - // Valid field value group.id = "0"; expect(group.idIsValid()).is.true; expect(group.isValid()).is.true; + // Invalid field value + group.id = new Date(); + expect(group.idIsValid()).is.false; + expect(group.isValid()).is.false; + // Valid field value group.id = "126"; expect(group.idIsValid()).is.true; @@ -71,21 +66,16 @@ describe("Group", function () { expect(group.sellerIdIsValid()).is.false; expect(group.isValid()).is.false; - // Invalid field value - group.sellerId = new Date(); - expect(group.sellerIdIsValid()).is.false; - expect(group.isValid()).is.false; - - // Invalid field value - group.sellerId = 12; - expect(group.sellerIdIsValid()).is.false; - expect(group.isValid()).is.false; - // Valid field value group.sellerId = "0"; expect(group.sellerIdIsValid()).is.true; expect(group.isValid()).is.true; + // Invalid field value + group.sellerId = new Date(); + expect(group.sellerIdIsValid()).is.false; + expect(group.isValid()).is.false; + // Valid field value group.sellerId = "126"; expect(group.sellerIdIsValid()).is.true; @@ -98,15 +88,6 @@ describe("Group", function () { expect(group.offerIdsIsValid()).is.false; expect(group.isValid()).is.false; - // Invalid field value - group.offerIds = new Date(); - expect(group.offerIdsIsValid()).is.false; - - // Invalid field value - group.offerIds = 12; - expect(group.offerIdsIsValid()).is.false; - expect(group.isValid()).is.false; - // Valid field value group.offerIds = ["1", "2"]; expect(group.offerIdsIsValid()).is.true; @@ -116,6 +97,10 @@ describe("Group", function () { group.offerIds = ["126"]; expect(group.offerIdsIsValid()).is.true; expect(group.isValid()).is.true; + + // Invalid field value + group.offerIds = new Date(); + expect(group.offerIdsIsValid()).is.false; }); }); diff --git a/test/domain/OfferDatesTest.js b/test/domain/OfferDatesTest.js index 3ebc52662..5cd5baead 100644 --- a/test/domain/OfferDatesTest.js +++ b/test/domain/OfferDatesTest.js @@ -1,5 +1,3 @@ -const hre = require("hardhat"); -const ethers = hre.ethers; const { expect } = require("chai"); const OfferDates = require("../../scripts/domain/OfferDates"); const { oneWeek, oneMonth } = require("../util/constants"); @@ -14,10 +12,10 @@ describe("OfferDates", function () { beforeEach(async function () { // Required constructor params - validFrom = ethers.BigNumber.from(Date.now()).toString(); // valid from now - validUntil = ethers.BigNumber.from(Date.now() + oneMonth * 6).toString(); // until 6 months - voucherRedeemableFrom = ethers.BigNumber.from(Date.now() + oneWeek).toString(); // redeemable in 1 week - voucherRedeemableUntil = ethers.BigNumber.from(Date.now() + oneWeek * 3).toString(); // redeemable for 2 weeks + validFrom = BigInt(Date.now()).toString(); // valid from now + validUntil = (BigInt(Date.now()) + oneMonth * 6n).toString(); // until 6 months + voucherRedeemableFrom = (BigInt(Date.now()) + oneWeek).toString(); // redeemable in 1 week + voucherRedeemableUntil = (BigInt(Date.now()) + oneWeek * 3n).toString(); // redeemable for 2 weeks }); context("📋 Constructor", async function () { @@ -45,21 +43,16 @@ describe("OfferDates", function () { expect(offerDates.validFromIsValid()).is.false; expect(offerDates.isValid()).is.false; - // Invalid field value - offerDates.validFrom = new Date(); - expect(offerDates.validFromIsValid()).is.false; - expect(offerDates.isValid()).is.false; - - // Invalid field value - offerDates.validFrom = 12; - expect(offerDates.validFromIsValid()).is.false; - expect(offerDates.isValid()).is.false; - // Valid field value offerDates.validFrom = "0"; expect(offerDates.validFromIsValid()).is.true; expect(offerDates.isValid()).is.true; + // Invalid field value + offerDates.validFrom = new Date(); + expect(offerDates.validFromIsValid()).is.false; + expect(offerDates.isValid()).is.false; + // Valid field value offerDates.validFrom = "126"; expect(offerDates.validFromIsValid()).is.true; @@ -72,16 +65,6 @@ describe("OfferDates", function () { expect(offerDates.validUntilIsValid()).is.false; expect(offerDates.isValid()).is.false; - // Invalid field value - offerDates.validUntil = new Date(); - expect(offerDates.validUntilIsValid()).is.false; - expect(offerDates.isValid()).is.false; - - // Invalid field value - offerDates.validUntil = 12; - expect(offerDates.validUntilIsValid()).is.false; - expect(offerDates.isValid()).is.false; - // Valid field value offerDates.validUntil = "0"; expect(offerDates.validUntilIsValid()).is.true; @@ -91,21 +74,16 @@ describe("OfferDates", function () { offerDates.validUntil = "126"; expect(offerDates.validUntilIsValid()).is.true; expect(offerDates.isValid()).is.true; - }); - - it("Always present, voucherRedeemableFrom must be the string representation of a BigNumber", async function () { - // Invalid field value - offerDates.voucherRedeemableFrom = "zedzdeadbaby"; - expect(offerDates.voucherRedeemableFromIsValid()).is.false; - expect(offerDates.isValid()).is.false; // Invalid field value - offerDates.voucherRedeemableFrom = new Date(); - expect(offerDates.voucherRedeemableFromIsValid()).is.false; + offerDates.validUntil = new Date(); + expect(offerDates.validUntilIsValid()).is.false; expect(offerDates.isValid()).is.false; + }); + it("Always present, voucherRedeemableFrom must be the string representation of a BigNumber", async function () { // Invalid field value - offerDates.voucherRedeemableFrom = 12; + offerDates.voucherRedeemableFrom = "zedzdeadbaby"; expect(offerDates.voucherRedeemableFromIsValid()).is.false; expect(offerDates.isValid()).is.false; @@ -131,11 +109,6 @@ describe("OfferDates", function () { expect(offerDates.voucherRedeemableUntilIsValid()).is.false; expect(offerDates.isValid()).is.false; - // Invalid field value - offerDates.voucherRedeemableUntil = 12; - expect(offerDates.voucherRedeemableUntilIsValid()).is.false; - expect(offerDates.isValid()).is.false; - // Valid field value offerDates.voucherRedeemableUntil = "0"; expect(offerDates.voucherRedeemableUntilIsValid()).is.true; diff --git a/test/domain/OfferDurationsTest.js b/test/domain/OfferDurationsTest.js index 42ecdc4eb..79f7ac16d 100644 --- a/test/domain/OfferDurationsTest.js +++ b/test/domain/OfferDurationsTest.js @@ -46,11 +46,6 @@ describe("OfferDurations", function () { expect(offerDurations.disputePeriodIsValid()).is.false; expect(offerDurations.isValid()).is.false; - // Invalid field value - offerDurations.disputePeriod = 12; - expect(offerDurations.disputePeriodIsValid()).is.false; - expect(offerDurations.isValid()).is.false; - // Valid field value offerDurations.disputePeriod = "0"; expect(offerDurations.disputePeriodIsValid()).is.true; @@ -68,21 +63,16 @@ describe("OfferDurations", function () { expect(offerDurations.voucherValidIsValid()).is.false; expect(offerDurations.isValid()).is.false; - // Invalid field value - offerDurations.voucherValid = new Date(); - expect(offerDurations.voucherValidIsValid()).is.false; - expect(offerDurations.isValid()).is.false; - - // Invalid field value - offerDurations.voucherValid = 12; - expect(offerDurations.voucherValidIsValid()).is.false; - expect(offerDurations.isValid()).is.false; - // Valid field value offerDurations.voucherValid = "0"; expect(offerDurations.voucherValidIsValid()).is.true; expect(offerDurations.isValid()).is.true; + // Invalid field value + offerDurations.voucherValid = new Date(); + expect(offerDurations.voucherValidIsValid()).is.false; + expect(offerDurations.isValid()).is.false; + // Valid field value offerDurations.voucherValid = "126"; expect(offerDurations.voucherValidIsValid()).is.true; @@ -95,16 +85,6 @@ describe("OfferDurations", function () { expect(offerDurations.resolutionPeriodIsValid()).is.false; expect(offerDurations.isValid()).is.false; - // Invalid field value - offerDurations.resolutionPeriod = new Date(); - expect(offerDurations.resolutionPeriodIsValid()).is.false; - expect(offerDurations.isValid()).is.false; - - // Invalid field value - offerDurations.resolutionPeriod = 12; - expect(offerDurations.resolutionPeriodIsValid()).is.false; - expect(offerDurations.isValid()).is.false; - // Valid field value offerDurations.resolutionPeriod = "0"; expect(offerDurations.resolutionPeriodIsValid()).is.true; @@ -114,6 +94,11 @@ describe("OfferDurations", function () { offerDurations.resolutionPeriod = "126"; expect(offerDurations.resolutionPeriodIsValid()).is.true; expect(offerDurations.isValid()).is.true; + + // Invalid field value + offerDurations.resolutionPeriod = new Date(); + expect(offerDurations.resolutionPeriodIsValid()).is.false; + expect(offerDurations.isValid()).is.false; }); }); diff --git a/test/domain/OfferFeesTest.js b/test/domain/OfferFeesTest.js index cc5bf664d..759f01781 100644 --- a/test/domain/OfferFeesTest.js +++ b/test/domain/OfferFeesTest.js @@ -43,11 +43,6 @@ describe("OfferFees", function () { expect(offerFees.protocolFeeIsValid()).is.false; expect(offerFees.isValid()).is.false; - // Invalid field value - offerFees.protocolFee = 12; - expect(offerFees.protocolFeeIsValid()).is.false; - expect(offerFees.isValid()).is.false; - // Valid field value offerFees.protocolFee = "0"; expect(offerFees.protocolFeeIsValid()).is.true; @@ -65,21 +60,16 @@ describe("OfferFees", function () { expect(offerFees.agentFeeIsValid()).is.false; expect(offerFees.isValid()).is.false; - // Invalid field value - offerFees.agentFee = new Date(); - expect(offerFees.agentFeeIsValid()).is.false; - expect(offerFees.isValid()).is.false; - - // Invalid field value - offerFees.agentFee = 12; - expect(offerFees.agentFeeIsValid()).is.false; - expect(offerFees.isValid()).is.false; - // Valid field value offerFees.agentFee = "0"; expect(offerFees.agentFeeIsValid()).is.true; expect(offerFees.isValid()).is.true; + // Invalid field value + offerFees.agentFee = new Date(); + expect(offerFees.agentFeeIsValid()).is.false; + expect(offerFees.isValid()).is.false; + // Valid field value offerFees.agentFee = "126"; expect(offerFees.agentFeeIsValid()).is.true; diff --git a/test/domain/OfferTest.js b/test/domain/OfferTest.js index d5e4c3064..8ecdc7e8a 100644 --- a/test/domain/OfferTest.js +++ b/test/domain/OfferTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners, parseUnits, ZeroAddress } = hre.ethers; const { expect } = require("chai"); const Offer = require("../../scripts/domain/Offer"); @@ -23,15 +23,15 @@ describe("Offer", function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); // Required constructor params id = sellerId = "0"; - price = ethers.utils.parseUnits("1.5", "ether").toString(); - sellerDeposit = ethers.utils.parseUnits("0.25", "ether").toString(); - buyerCancelPenalty = ethers.utils.parseUnits("0.05", "ether").toString(); + price = parseUnits("1.5", "ether").toString(); + sellerDeposit = parseUnits("0.25", "ether").toString(); + buyerCancelPenalty = parseUnits("0.05", "ether").toString(); quantityAvailable = "1"; - exchangeToken = ethers.constants.AddressZero.toString(); // Zero addy ~ chain base currency + exchangeToken = ZeroAddress.toString(); // Zero addy ~ chain base currency metadataHash = "QmYXc12ov6F2MZVZwPs5XeCBbf61cW3wKRk8h3D5NTYj4T"; // not an actual metadataHash, just some data for tests metadataUri = `https://ipfs.io/ipfs/${metadataHash}`; voided = false; @@ -95,11 +95,6 @@ describe("Offer", function () { expect(offer.idIsValid()).is.false; expect(offer.isValid()).is.false; - // Invalid field value - offer.id = 12; - expect(offer.idIsValid()).is.false; - expect(offer.isValid()).is.false; - // Valid field value offer.id = "0"; expect(offer.idIsValid()).is.true; @@ -117,21 +112,16 @@ describe("Offer", function () { expect(offer.priceIsValid()).is.false; expect(offer.isValid()).is.false; - // Invalid field value - offer.price = new Date(); - expect(offer.priceIsValid()).is.false; - expect(offer.isValid()).is.false; - - // Invalid field value - offer.price = 12; - expect(offer.priceIsValid()).is.false; - expect(offer.isValid()).is.false; - // Valid field value offer.price = "0"; expect(offer.priceIsValid()).is.true; expect(offer.isValid()).is.true; + // Invalid field value + offer.price = new Date(); + expect(offer.priceIsValid()).is.false; + expect(offer.isValid()).is.false; + // Valid field value offer.price = "126"; expect(offer.priceIsValid()).is.true; @@ -144,16 +134,6 @@ describe("Offer", function () { expect(offer.sellerDepositIsValid()).is.false; expect(offer.isValid()).is.false; - // Invalid field value - offer.sellerDeposit = new Date(); - expect(offer.sellerDepositIsValid()).is.false; - expect(offer.isValid()).is.false; - - // Invalid field value - offer.sellerDeposit = 12; - expect(offer.sellerDepositIsValid()).is.false; - expect(offer.isValid()).is.false; - // Valid field value offer.sellerDeposit = "0"; expect(offer.sellerDepositIsValid()).is.true; @@ -163,21 +143,16 @@ describe("Offer", function () { offer.sellerDeposit = "126"; expect(offer.sellerDepositIsValid()).is.true; expect(offer.isValid()).is.true; - }); - it("Always present, buyerCancelPenalty must be the string representation of a BigNumber", async function () { // Invalid field value - offer.buyerCancelPenalty = "zedzdeadbaby"; - expect(offer.buyerCancelPenaltyIsValid()).is.false; - expect(offer.isValid()).is.false; - - // Invalid field value - offer.buyerCancelPenalty = new Date(); - expect(offer.buyerCancelPenaltyIsValid()).is.false; + offer.sellerDeposit = new Date(); + expect(offer.sellerDepositIsValid()).is.false; expect(offer.isValid()).is.false; + }); + it("Always present, buyerCancelPenalty must be the string representation of a BigNumber", async function () { // Invalid field value - offer.buyerCancelPenalty = 12; + offer.buyerCancelPenalty = "zedzdeadbaby"; expect(offer.buyerCancelPenaltyIsValid()).is.false; expect(offer.isValid()).is.false; @@ -190,21 +165,16 @@ describe("Offer", function () { offer.buyerCancelPenalty = "126"; expect(offer.buyerCancelPenaltyIsValid()).is.true; expect(offer.isValid()).is.true; - }); - it("Always present, quantityAvailable must be the string representation of a BigNumber", async function () { // Invalid field value - offer.quantityAvailable = "zedzdeadbaby"; - expect(offer.quantityAvailableIsValid()).is.false; - expect(offer.isValid()).is.false; - - // Invalid field value - offer.quantityAvailable = new Date(); - expect(offer.quantityAvailableIsValid()).is.false; + offer.buyerCancelPenalty = new Date(); + expect(offer.buyerCancelPenaltyIsValid()).is.false; expect(offer.isValid()).is.false; + }); + it("Always present, quantityAvailable must be the string representation of a BigNumber", async function () { // Invalid field value - offer.quantityAvailable = 12; + offer.quantityAvailable = "zedzdeadbaby"; expect(offer.quantityAvailableIsValid()).is.false; expect(offer.isValid()).is.false; @@ -217,21 +187,16 @@ describe("Offer", function () { offer.quantityAvailable = "126"; expect(offer.quantityAvailableIsValid()).is.true; expect(offer.isValid()).is.true; - }); - it("Always present, sellerId must be the string representation of a BigNumber", async function () { // Invalid field value - offer.sellerId = "zedzdeadbaby"; - expect(offer.sellerIdIsValid()).is.false; - expect(offer.isValid()).is.false; - - // Invalid field value - offer.sellerId = new Date(); - expect(offer.sellerIdIsValid()).is.false; + offer.quantityAvailable = new Date(); + expect(offer.quantityAvailableIsValid()).is.false; expect(offer.isValid()).is.false; + }); + it("Always present, sellerId must be the string representation of a BigNumber", async function () { // Invalid field value - offer.sellerId = 12; + offer.sellerId = "zedzdeadbaby"; expect(offer.sellerIdIsValid()).is.false; expect(offer.isValid()).is.false; @@ -244,6 +209,11 @@ describe("Offer", function () { offer.sellerId = "126"; expect(offer.sellerIdIsValid()).is.true; expect(offer.isValid()).is.true; + + // Invalid field value + offer.sellerId = new Date(); + expect(offer.sellerIdIsValid()).is.false; + expect(offer.isValid()).is.false; }); it("Always present, exchangeToken must be a string representation of an EIP-55 compliant address", async function () { diff --git a/test/domain/RangeTest.js b/test/domain/RangeTest.js index a8bf3343c..ea7e885b0 100644 --- a/test/domain/RangeTest.js +++ b/test/domain/RangeTest.js @@ -46,11 +46,6 @@ describe("Range", function () { expect(range.startIsValid()).is.false; expect(range.isValid()).is.false; - // Invalid field value - range.start = 12; - expect(range.startIsValid()).is.false; - expect(range.isValid()).is.false; - // Valid field value range.start = "0"; expect(range.startIsValid()).is.true; @@ -68,16 +63,6 @@ describe("Range", function () { expect(range.lengthIsValid()).is.false; expect(range.isValid()).is.false; - // Invalid field value - range.length = new Date(); - expect(range.lengthIsValid()).is.false; - expect(range.isValid()).is.false; - - // Invalid field value - range.length = 12; - expect(range.lengthIsValid()).is.false; - expect(range.isValid()).is.false; - // Valid field value range.length = "0"; expect(range.lengthIsValid()).is.true; @@ -87,21 +72,16 @@ describe("Range", function () { range.length = "126"; expect(range.lengthIsValid()).is.true; expect(range.isValid()).is.true; - }); - it("If present, minted must be the string representation of a BigNumber", async function () { // Invalid field value - range.minted = "zedzdeadbaby"; - expect(range.mintedIsValid()).is.false; - expect(range.isValid()).is.false; - - // Invalid field value - range.minted = new Date(); - expect(range.mintedIsValid()).is.false; + range.length = new Date(); + expect(range.lengthIsValid()).is.false; expect(range.isValid()).is.false; + }); + it("If present, minted must be the string representation of a BigNumber", async function () { // Invalid field value - range.minted = 12; + range.minted = "zedzdeadbaby"; expect(range.mintedIsValid()).is.false; expect(range.isValid()).is.false; @@ -114,21 +94,16 @@ describe("Range", function () { range.minted = "126"; expect(range.mintedIsValid()).is.true; expect(range.isValid()).is.true; - }); - - it("If present, lastBurnedTokenId must be the string representation of a BigNumber", async function () { - // Invalid field value - range.lastBurnedTokenId = "zedzdeadbaby"; - expect(range.lastBurnedTokenIdIsValid()).is.false; - expect(range.isValid()).is.false; // Invalid field value - range.lastBurnedTokenId = new Date(); - expect(range.lastBurnedTokenIdIsValid()).is.false; + range.minted = new Date(); + expect(range.mintedIsValid()).is.false; expect(range.isValid()).is.false; + }); + it("If present, lastBurnedTokenId must be the string representation of a BigNumber", async function () { // Invalid field value - range.lastBurnedTokenId = 12; + range.lastBurnedTokenId = "zedzdeadbaby"; expect(range.lastBurnedTokenIdIsValid()).is.false; expect(range.isValid()).is.false; @@ -141,6 +116,11 @@ describe("Range", function () { range.lastBurnedTokenId = "126"; expect(range.lastBurnedTokenIdIsValid()).is.true; expect(range.isValid()).is.true; + + // Invalid field value + range.lastBurnedTokenId = new Date(); + expect(range.lastBurnedTokenIdIsValid()).is.false; + expect(range.isValid()).is.false; }); }); diff --git a/test/domain/ReceiptTest.js b/test/domain/ReceiptTest.js index 16eefd401..46ae0d974 100644 --- a/test/domain/ReceiptTest.js +++ b/test/domain/ReceiptTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners, ZeroAddress } = hre.ethers; const { expect } = require("chai"); const Receipt = require("../../scripts/domain/Receipt.js"); const { mockReceipt, mockOffer, mockTwinReceipt, mockCondition } = require("../util/mock"); @@ -14,7 +14,7 @@ describe("Receipt", function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); }); context("📋 Constructor", async function () { @@ -62,11 +62,6 @@ describe("Receipt", function () { expect(receipt.exchangeIdIsValid()).is.false; expect(receipt.isValid()).is.false; - // Invalid field value - receipt.exchangeId = 12; - expect(receipt.exchangeIdIsValid()).is.false; - expect(receipt.isValid()).is.false; - // Invalid field value receipt.exchangeId = "0"; expect(receipt.exchangeIdIsValid()).is.false; @@ -85,17 +80,12 @@ describe("Receipt", function () { expect(receipt.isValid()).is.false; // Invalid field value - receipt.offerId = new Date(); - expect(receipt.offerIdIsValid()).is.false; - expect(receipt.isValid()).is.false; - - // Invalid field value - receipt.offerId = 12; + receipt.offerId = "0"; expect(receipt.offerIdIsValid()).is.false; expect(receipt.isValid()).is.false; // Invalid field value - receipt.offerId = "0"; + receipt.offerId = new Date(); expect(receipt.offerIdIsValid()).is.false; expect(receipt.isValid()).is.false; @@ -111,16 +101,6 @@ describe("Receipt", function () { expect(receipt.buyerIdIsValid()).is.false; expect(receipt.isValid()).is.false; - // Invalid field value - receipt.buyerId = new Date(); - expect(receipt.buyerIdIsValid()).is.false; - expect(receipt.isValid()).is.false; - - // Invalid field value - receipt.buyerId = 12; - expect(receipt.buyerIdIsValid()).is.false; - expect(receipt.isValid()).is.false; - // Invalid field value receipt.buyerId = "0"; expect(receipt.buyerIdIsValid()).is.false; @@ -130,21 +110,16 @@ describe("Receipt", function () { receipt.buyerId = "126"; expect(receipt.buyerIdIsValid()).is.true; expect(receipt.isValid()).is.true; - }); - - it("Always present, price must be the string representation of BigNumber", async function () { - // Invalid field value - receipt.price = "zedzdeadbaby"; - expect(receipt.priceIsValid()).is.false; - expect(receipt.isValid()).is.false; // Invalid field value - receipt.price = new Date(); - expect(receipt.priceIsValid()).is.false; + receipt.buyerId = new Date(); + expect(receipt.buyerIdIsValid()).is.false; expect(receipt.isValid()).is.false; + }); + it("Always present, price must be the string representation of BigNumber", async function () { // Invalid field value - receipt.price = 12; + receipt.price = "zedzdeadbaby"; expect(receipt.priceIsValid()).is.false; expect(receipt.isValid()).is.false; @@ -157,21 +132,16 @@ describe("Receipt", function () { receipt.price = "126"; expect(receipt.priceIsValid()).is.true; expect(receipt.isValid()).is.true; - }); - - it("Always present, sellerDeposit must be the string representation of BigNumber", async function () { - // Invalid field value - receipt.sellerDeposit = "zedzdeadbaby"; - expect(receipt.sellerDepositIsValid()).is.false; - expect(receipt.isValid()).is.false; // Invalid field value - receipt.sellerDeposit = new Date(); - expect(receipt.sellerDepositIsValid()).is.false; + receipt.price = new Date(); + expect(receipt.priceIsValid()).is.false; expect(receipt.isValid()).is.false; + }); + it("Always present, sellerDeposit must be the string representation of BigNumber", async function () { // Invalid field value - receipt.sellerDeposit = 12; + receipt.sellerDeposit = "zedzdeadbaby"; expect(receipt.sellerDepositIsValid()).is.false; expect(receipt.isValid()).is.false; @@ -184,21 +154,16 @@ describe("Receipt", function () { receipt.sellerDeposit = "126"; expect(receipt.sellerDepositIsValid()).is.true; expect(receipt.isValid()).is.true; - }); - - it("Always present, buyerCancelPenalty must be the string representation of BigNumber", async function () { - // Invalid field value - receipt.buyerCancelPenalty = "zedzdeadbaby"; - expect(receipt.buyerCancelPenaltyIsValid()).is.false; - expect(receipt.isValid()).is.false; // Invalid field value - receipt.buyerCancelPenalty = new Date(); - expect(receipt.buyerCancelPenaltyIsValid()).is.false; + receipt.sellerDeposit = new Date(); + expect(receipt.sellerDepositIsValid()).is.false; expect(receipt.isValid()).is.false; + }); + it("Always present, buyerCancelPenalty must be the string representation of BigNumber", async function () { // Invalid field value - receipt.buyerCancelPenalty = 12; + receipt.buyerCancelPenalty = "zedzdeadbaby"; expect(receipt.buyerCancelPenaltyIsValid()).is.false; expect(receipt.isValid()).is.false; @@ -211,6 +176,11 @@ describe("Receipt", function () { receipt.buyerCancelPenalty = "126"; expect(receipt.buyerCancelPenaltyIsValid()).is.true; expect(receipt.isValid()).is.true; + + // Invalid field value + receipt.buyerCancelPenalty = new Date(); + expect(receipt.buyerCancelPenaltyIsValid()).is.false; + expect(receipt.isValid()).is.false; }); it("Always present, offerFees must be a valid OfferFees instance", async function () { @@ -229,16 +199,16 @@ describe("Receipt", function () { expect(receipt.offerFeesIsValid()).is.false; expect(receipt.isValid()).is.false; - // Valid field value - receipt.offerFees = new Date(); - expect(receipt.offerFeesIsValid()).is.false; - expect(receipt.isValid()).is.false; - const mo = await mockOffer(); // Valid field value receipt.offerFees = mo.offerFees; expect(receipt.offerFeesIsValid()).is.true; expect(receipt.isValid()).is.true; + + // Valid field value + receipt.offerFees = new Date(); + expect(receipt.offerFeesIsValid()).is.false; + expect(receipt.isValid()).is.false; }); it("If present, agentId must be the string representation of BigNumber", async function () { @@ -247,16 +217,6 @@ describe("Receipt", function () { expect(receipt.agentIdIsValid()).is.false; expect(receipt.isValid()).is.false; - // Invalid field value - receipt.agentId = new Date(); - expect(receipt.agentIdIsValid()).is.false; - expect(receipt.isValid()).is.false; - - // Invalid field value - receipt.agentId = 12; - expect(receipt.agentIdIsValid()).is.false; - expect(receipt.isValid()).is.false; - // Valid field value receipt.agentId = "0"; expect(receipt.priceIsValid()).is.true; @@ -266,6 +226,11 @@ describe("Receipt", function () { receipt.agentId = "126"; expect(receipt.agentIdIsValid()).is.true; expect(receipt.isValid()).is.true; + + // Invalid field value + receipt.agentId = new Date(); + expect(receipt.agentIdIsValid()).is.false; + expect(receipt.isValid()).is.false; }); it("Always present, exchangeToken must be a string representation of an EIP-55 compliant address", async function () { @@ -296,16 +261,6 @@ describe("Receipt", function () { expect(receipt.finalizedDateIsValid()).is.false; expect(receipt.isValid()).is.false; - // Invalid field value - receipt.finalizedDate = new Date(); - expect(receipt.finalizedDateIsValid()).is.false; - expect(receipt.isValid()).is.false; - - // Invalid field value - receipt.finalizedDate = 12; - expect(receipt.finalizedDateIsValid()).is.false; - expect(receipt.isValid()).is.false; - // Invalid field value receipt.finalizedDate = "0"; expect(receipt.finalizedDateIsValid()).is.false; @@ -315,21 +270,16 @@ describe("Receipt", function () { receipt.finalizedDate = "126"; expect(receipt.finalizedDateIsValid()).is.true; expect(receipt.isValid()).is.true; - }); - - it("If present, condition must be a valid Condition instance", async function () { - // Invalid field value - receipt.condition = "zedzdeadbaby"; - expect(receipt.conditionIsValid()).is.false; - expect(receipt.isValid()).is.false; // Invalid field value - receipt.condition = new Date(); - expect(receipt.conditionIsValid()).is.false; + receipt.finalizedDate = new Date(); + expect(receipt.finalizedDateIsValid()).is.false; expect(receipt.isValid()).is.false; + }); + it("If present, condition must be a valid Condition instance", async function () { // Invalid field value - receipt.condition = 12; + receipt.condition = "zedzdeadbaby"; expect(receipt.conditionIsValid()).is.false; expect(receipt.isValid()).is.false; @@ -339,24 +289,19 @@ describe("Receipt", function () { expect(receipt.isValid()).is.false; // Valid field value - receipt.condition = mockCondition(ethers.constants.AddressZero); + receipt.condition = mockCondition(ZeroAddress); expect(receipt.conditionIsValid()).is.true; expect(receipt.isValid()).is.true; - }); - - it("Always present, committedDate must be the string representation of BigNumber", async function () { - // Invalid field value - receipt.committedDate = "zedzdeadbaby"; - expect(receipt.committedDateIsValid()).is.false; - expect(receipt.isValid()).is.false; // Invalid field value - receipt.committedDate = new Date(); - expect(receipt.committedDateIsValid()).is.false; + receipt.condition = new Date(); + expect(receipt.conditionIsValid()).is.false; expect(receipt.isValid()).is.false; + }); + it("Always present, committedDate must be the string representation of BigNumber", async function () { // Invalid field value - receipt.committedDate = 12; + receipt.committedDate = "zedzdeadbaby"; expect(receipt.committedDateIsValid()).is.false; expect(receipt.isValid()).is.false; @@ -364,21 +309,16 @@ describe("Receipt", function () { receipt.committedDate = "126"; expect(receipt.committedDateIsValid()).is.true; expect(receipt.isValid()).is.true; - }); - - it("If present, redeemedDate must be the string representation of BigNumber", async function () { - // Invalid field value - receipt.redeemedDate = "zedzdeadbaby"; - expect(receipt.redeemedDateIsValid()).is.false; - expect(receipt.isValid()).is.false; // Invalid field value - receipt.redeemedDate = new Date(); - expect(receipt.redeemedDateIsValid()).is.false; + receipt.committedDate = new Date(); + expect(receipt.committedDateIsValid()).is.false; expect(receipt.isValid()).is.false; + }); + it("If present, redeemedDate must be the string representation of BigNumber", async function () { // Invalid field value - receipt.redeemedDate = 12; + receipt.redeemedDate = "zedzdeadbaby"; expect(receipt.redeemedDateIsValid()).is.false; expect(receipt.isValid()).is.false; @@ -391,6 +331,11 @@ describe("Receipt", function () { receipt.redeemedDate = "126"; expect(receipt.redeemedDateIsValid()).is.true; expect(receipt.isValid()).is.true; + + // Invalid field value + receipt.redeemedDate = new Date(); + expect(receipt.redeemedDateIsValid()).is.false; + expect(receipt.isValid()).is.false; }); it("Always present, voucherExpired must be a boolean", async function () { @@ -421,16 +366,6 @@ describe("Receipt", function () { expect(receipt.disputeResolverIdIsValid()).is.false; expect(receipt.isValid()).is.false; - // Invalid field value - receipt.disputeResolverId = new Date(); - expect(receipt.disputeResolverIdIsValid()).is.false; - expect(receipt.isValid()).is.false; - - // Invalid field value - receipt.disputeResolverId = 12; - expect(receipt.disputeResolverIdIsValid()).is.false; - expect(receipt.isValid()).is.false; - // Valid field value receipt.disputeResolverId = "0"; expect(receipt.disputeResolverIdIsValid()).is.true; @@ -440,21 +375,16 @@ describe("Receipt", function () { receipt.disputeResolverId = "126"; expect(receipt.disputeResolverIdIsValid()).is.true; expect(receipt.isValid()).is.true; - }); - - it("If present, disputedDate must be the string representation of BigNumber", async function () { - // Invalid field value - receipt.disputedDate = "zedzdeadbaby"; - expect(receipt.disputedDateIsValid()).is.false; - expect(receipt.isValid()).is.false; // Invalid field value - receipt.disputedDate = new Date(); - expect(receipt.disputedDateIsValid()).is.false; + receipt.disputeResolverId = new Date(); + expect(receipt.disputeResolverIdIsValid()).is.false; expect(receipt.isValid()).is.false; + }); + it("If present, disputedDate must be the string representation of BigNumber", async function () { // Invalid field value - receipt.disputedDate = 12; + receipt.disputedDate = "zedzdeadbaby"; expect(receipt.disputedDateIsValid()).is.false; expect(receipt.isValid()).is.false; @@ -467,21 +397,16 @@ describe("Receipt", function () { receipt.disputedDate = "126"; expect(receipt.disputedDateIsValid()).is.true; expect(receipt.isValid()).is.true; - }); - - it("If present, escalatedDate must be the string representation of BigNumber", async function () { - // Invalid field value - receipt.escalatedDate = "zedzdeadbaby"; - expect(receipt.escalatedDateIsValid()).is.false; - expect(receipt.isValid()).is.false; // Invalid field value - receipt.escalatedDate = new Date(); - expect(receipt.escalatedDateIsValid()).is.false; + receipt.disputedDate = new Date(); + expect(receipt.disputedDateIsValid()).is.false; expect(receipt.isValid()).is.false; + }); + it("If present, escalatedDate must be the string representation of BigNumber", async function () { // Invalid field value - receipt.escalatedDate = 12; + receipt.escalatedDate = "zedzdeadbaby"; expect(receipt.escalatedDateIsValid()).is.false; expect(receipt.isValid()).is.false; @@ -494,6 +419,11 @@ describe("Receipt", function () { receipt.escalatedDate = "126"; expect(receipt.escalatedDateIsValid()).is.true; expect(receipt.isValid()).is.true; + + // Invalid field value + receipt.escalatedDate = new Date(); + expect(receipt.escalatedDateIsValid()).is.false; + expect(receipt.isValid()).is.false; }); it("If present, disputeState must be the string representation of a BigNumber", async function () { @@ -545,7 +475,7 @@ describe("Receipt", function () { expect(receipt.isValid()).is.false; // Valid field value - receipt.twinReceipts = [mockTwinReceipt(ethers.constants.AddressZero)]; + receipt.twinReceipts = [mockTwinReceipt(ZeroAddress)]; expect(receipt.twinReceiptsIsValid()).is.true; expect(receipt.isValid()).is.true; }); diff --git a/test/domain/SellerTest.js b/test/domain/SellerTest.js index 0e21c3492..578448929 100644 --- a/test/domain/SellerTest.js +++ b/test/domain/SellerTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners, ZeroAddress } = hre.ethers; const { expect } = require("chai"); const Seller = require("../../scripts/domain/Seller"); @@ -13,10 +13,10 @@ describe("Seller", function () { beforeEach(async function () { // Get a list of accounts - accounts = await ethers.getSigners(); + accounts = await getSigners(); assistant = accounts[0].address; admin = accounts[1].address; - clerk = ethers.constants.AddressZero; + clerk = ZeroAddress; treasury = accounts[3].address; // Required constructor params @@ -53,16 +53,6 @@ describe("Seller", function () { expect(seller.idIsValid()).is.false; expect(seller.isValid()).is.false; - // Invalid field value - seller.id = new Date(); - expect(seller.idIsValid()).is.false; - expect(seller.isValid()).is.false; - - // Invalid field value - seller.id = 12; - expect(seller.idIsValid()).is.false; - expect(seller.isValid()).is.false; - // Valid field value seller.id = "0"; expect(seller.idIsValid()).is.true; @@ -72,6 +62,11 @@ describe("Seller", function () { seller.id = "126"; expect(seller.idIsValid()).is.true; expect(seller.isValid()).is.true; + + // Invalid field value + seller.id = new Date(); + expect(seller.idIsValid()).is.false; + expect(seller.isValid()).is.false; }); it("Always present, assistant must be a string representation of an EIP-55 compliant address", async function () { diff --git a/test/domain/TwinReceiptTest.js b/test/domain/TwinReceiptTest.js index a5ad9cc51..a02f15e14 100644 --- a/test/domain/TwinReceiptTest.js +++ b/test/domain/TwinReceiptTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners } = hre.ethers; const { expect } = require("chai"); const TwinReceipt = require("../../scripts/domain/TwinReceipt.js"); const TokenType = require("../../scripts/domain/TokenType.js"); @@ -15,7 +15,7 @@ describe("TwinReceipt", function () { beforeEach(async function () { // Get a list of accounts - const accounts = await ethers.getSigners(); + const accounts = await getSigners(); tokenAddress = accounts[0].address; }); @@ -49,11 +49,6 @@ describe("TwinReceipt", function () { expect(twinReceipt.twinIdIsValid()).is.false; expect(twinReceipt.isValid()).is.false; - // Invalid field value - twinReceipt.twinId = 12; - expect(twinReceipt.twinIdIsValid()).is.false; - expect(twinReceipt.isValid()).is.false; - // Valid field value twinReceipt.twinId = "0"; expect(twinReceipt.twinIdIsValid()).is.true; @@ -71,21 +66,16 @@ describe("TwinReceipt", function () { expect(twinReceipt.amountIsValid()).is.false; expect(twinReceipt.isValid()).is.false; - // Invalid field value - twinReceipt.amount = new Date(); - expect(twinReceipt.amountIsValid()).is.false; - expect(twinReceipt.isValid()).is.false; - - // Invalid field value - twinReceipt.amount = 12; - expect(twinReceipt.amountIsValid()).is.false; - expect(twinReceipt.isValid()).is.false; - // Valid field value twinReceipt.amount = "0"; expect(twinReceipt.amountIsValid()).is.true; expect(twinReceipt.isValid()).is.true; + // Invalid field value + twinReceipt.amount = new Date(); + expect(twinReceipt.amountIsValid()).is.false; + expect(twinReceipt.isValid()).is.false; + // Valid field value twinReceipt.amount = "126"; expect(twinReceipt.amountIsValid()).is.true; @@ -98,21 +88,15 @@ describe("TwinReceipt", function () { expect(twinReceipt.tokenIdIsValid()).is.false; expect(twinReceipt.isValid()).is.false; - // Invalid field value - twinReceipt.tokenId = new Date(); - expect(twinReceipt.tokenIdIsValid()).is.false; - expect(twinReceipt.isValid()).is.false; - - // Invalid field value - twinReceipt.tokenId = 12; - expect(twinReceipt.tokenIdIsValid()).is.false; - expect(twinReceipt.isValid()).is.false; - // Valid field value twinReceipt.tokenId = "0"; expect(twinReceipt.tokenIdIsValid()).is.true; expect(twinReceipt.isValid()).is.true; + // Invalid field value + twinReceipt.tokenId = new Date(); + expect(twinReceipt.tokenIdIsValid()).is.false; + // Valid field value twinReceipt.tokenId = "126"; expect(twinReceipt.tokenIdIsValid()).is.true; @@ -148,17 +132,12 @@ describe("TwinReceipt", function () { expect(twinReceipt.isValid()).is.false; // Invalid field value - twinReceipt.tokenType = new Date(); - expect(twinReceipt.tokenTypeIsValid()).is.false; - expect(twinReceipt.isValid()).is.false; - - // Invalid field value - twinReceipt.tokenType = 12; + twinReceipt.tokenType = "0"; expect(twinReceipt.tokenTypeIsValid()).is.false; expect(twinReceipt.isValid()).is.false; // Invalid field value - twinReceipt.tokenType = "0"; + twinReceipt.tokenType = new Date(); expect(twinReceipt.tokenTypeIsValid()).is.false; expect(twinReceipt.isValid()).is.false; diff --git a/test/domain/TwinTest.js b/test/domain/TwinTest.js index d3607653a..a5290a5d9 100644 --- a/test/domain/TwinTest.js +++ b/test/domain/TwinTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners } = hre.ethers; const { expect } = require("chai"); const Twin = require("../../scripts/domain/Twin.js"); const TokenType = require("../../scripts/domain/TokenType.js"); @@ -15,7 +15,7 @@ describe("Twin", function () { beforeEach(async function () { // Get a list of accounts - const accounts = await ethers.getSigners(); + const accounts = await getSigners(); tokenAddress = accounts[0].address; }); @@ -51,11 +51,6 @@ describe("Twin", function () { expect(twin.idIsValid()).is.false; expect(twin.isValid()).is.false; - // Invalid field value - twin.id = 12; - expect(twin.idIsValid()).is.false; - expect(twin.isValid()).is.false; - // Valid field value twin.id = "0"; expect(twin.idIsValid()).is.true; @@ -73,21 +68,16 @@ describe("Twin", function () { expect(twin.sellerIdIsValid()).is.false; expect(twin.isValid()).is.false; - // Invalid field value - twin.sellerId = new Date(); - expect(twin.sellerIdIsValid()).is.false; - expect(twin.isValid()).is.false; - - // Invalid field value - twin.sellerId = 12; - expect(twin.sellerIdIsValid()).is.false; - expect(twin.isValid()).is.false; - // Valid field value twin.sellerId = "0"; expect(twin.sellerIdIsValid()).is.true; expect(twin.isValid()).is.true; + // Invalid field value + twin.sellerId = new Date(); + expect(twin.sellerIdIsValid()).is.false; + expect(twin.isValid()).is.false; + // Valid field value twin.sellerId = "126"; expect(twin.sellerIdIsValid()).is.true; @@ -100,21 +90,16 @@ describe("Twin", function () { expect(twin.amountIsValid()).is.false; expect(twin.isValid()).is.false; - // Invalid field value - twin.amount = new Date(); - expect(twin.amountIsValid()).is.false; - expect(twin.isValid()).is.false; - - // Invalid field value - twin.amount = 12; - expect(twin.amountIsValid()).is.false; - expect(twin.isValid()).is.false; - // Valid field value twin.amount = "0"; expect(twin.amountIsValid()).is.true; expect(twin.isValid()).is.true; + // Invalid field value + twin.amount = new Date(); + expect(twin.amountIsValid()).is.false; + expect(twin.isValid()).is.false; + // Valid field value twin.amount = "126"; expect(twin.amountIsValid()).is.true; @@ -128,17 +113,12 @@ describe("Twin", function () { expect(twin.isValid()).is.false; // Invalid field value - twin.supplyAvailable = new Date(); - expect(twin.supplyAvailableIsValid()).is.false; - expect(twin.isValid()).is.false; - - // Invalid field value - twin.supplyAvailable = 12; + twin.supplyAvailable = ["1", "2"]; expect(twin.supplyAvailableIsValid()).is.false; expect(twin.isValid()).is.false; // Invalid field value - twin.supplyAvailable = ["1", "2"]; + twin.supplyAvailable = new Date(); expect(twin.supplyAvailableIsValid()).is.false; expect(twin.isValid()).is.false; @@ -154,16 +134,6 @@ describe("Twin", function () { expect(twin.tokenIdIsValid()).is.false; expect(twin.isValid()).is.false; - // Invalid field value - twin.tokenId = new Date(); - expect(twin.tokenIdIsValid()).is.false; - expect(twin.isValid()).is.false; - - // Invalid field value - twin.tokenId = 12; - expect(twin.tokenIdIsValid()).is.false; - expect(twin.isValid()).is.false; - // Valid field value twin.tokenId = "0"; expect(twin.tokenIdIsValid()).is.true; @@ -173,6 +143,11 @@ describe("Twin", function () { twin.tokenId = "126"; expect(twin.tokenIdIsValid()).is.true; expect(twin.isValid()).is.true; + + // Invalid field value + twin.tokenId = new Date(); + expect(twin.tokenIdIsValid()).is.false; + expect(twin.isValid()).is.false; }); it("Always present, tokenAddress must be a string representation of an EIP-55 compliant address", async function () { diff --git a/test/domain/VoucherInitValuesTest.js b/test/domain/VoucherInitValuesTest.js index 575d89bfc..112ba3e26 100644 --- a/test/domain/VoucherInitValuesTest.js +++ b/test/domain/VoucherInitValuesTest.js @@ -65,11 +65,6 @@ describe("VoucherInitValues", function () { expect(voucherInitValues.royaltyPercentageIsValid()).is.false; expect(voucherInitValues.isValid()).is.false; - // Invalid field value - voucherInitValues.royaltyPercentage = 12; - expect(voucherInitValues.royaltyPercentageIsValid()).is.false; - expect(voucherInitValues.isValid()).is.false; - // Invalid field value voucherInitValues.royaltyPercentage = "10001"; // Value greater than 100% should be invalid expect(voucherInitValues.royaltyPercentageIsValid()).is.false; diff --git a/test/domain/VoucherTest.js b/test/domain/VoucherTest.js index 0bcff4bba..10996ebc6 100644 --- a/test/domain/VoucherTest.js +++ b/test/domain/VoucherTest.js @@ -55,11 +55,6 @@ describe("Voucher", function () { expect(voucher.committedDateIsValid()).is.false; expect(voucher.isValid()).is.false; - // Invalid field value - voucher.committedDate = 12; - expect(voucher.committedDateIsValid()).is.false; - expect(voucher.isValid()).is.false; - // Valid field value voucher.committedDate = "0"; expect(voucher.committedDateIsValid()).is.false; @@ -82,11 +77,6 @@ describe("Voucher", function () { expect(voucher.validUntilDateIsValid()).is.false; expect(voucher.isValid()).is.false; - // Invalid field value - voucher.validUntilDate = 12; - expect(voucher.validUntilDateIsValid()).is.false; - expect(voucher.isValid()).is.false; - // Valid field value voucher.validUntilDate = "0"; expect(voucher.validUntilDateIsValid()).is.false; @@ -109,11 +99,6 @@ describe("Voucher", function () { expect(voucher.redeemedDateIsValid()).is.false; expect(voucher.isValid()).is.false; - // Invalid field value - voucher.redeemedDate = 12; - expect(voucher.redeemedDateIsValid()).is.false; - expect(voucher.isValid()).is.false; - // Valid field value voucher.redeemedDate = "0"; expect(voucher.redeemedDateIsValid()).is.false; diff --git a/test/example/SnapshotGateTest.js b/test/example/SnapshotGateTest.js index 970f7bed8..088f5be6a 100644 --- a/test/example/SnapshotGateTest.js +++ b/test/example/SnapshotGateTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractAt, parseUnits, ZeroAddress, getSigners } = hre.ethers; const { expect } = require("chai"); const Role = require("../../scripts/domain/Role"); @@ -80,44 +80,44 @@ describe("SnapshotGate", function () { holder3, holder4, holder5, - ] = await ethers.getSigners(); + ] = await getSigners(); // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; // Deploy the Protocol Diamond [protocolDiamond, , , , accessController] = await deployProtocolDiamond(maxPriorityFeePerGas); // Temporarily grant UPGRADER role to deployer account - await accessController.grantRole(Role.UPGRADER, deployer.address); + await accessController.grantRole(Role.UPGRADER, await deployer.getAddress()); // Grant PROTOCOL role to ProtocolDiamond address and renounces admin - await accessController.grantRole(Role.PROTOCOL, protocolDiamond.address); + await accessController.grantRole(Role.PROTOCOL, await protocolDiamond.getAddress()); // Temporarily grant PAUSER role to pauser account - await accessController.grantRole(Role.PAUSER, pauser.address); + await accessController.grantRole(Role.PAUSER, await pauser.getAddress()); // Deploy the Protocol client implementation/proxy pairs (currently just the Boson Voucher) - const protocolClientArgs = [protocolDiamond.address]; + const protocolClientArgs = [await protocolDiamond.getAddress()]; const [, beacons, proxies] = await deployProtocolClients(protocolClientArgs, maxPriorityFeePerGas); const [beacon] = beacons; const [proxy] = proxies; // Set protocolFees protocolFeePercentage = "200"; // 2 % - protocolFeeFlatBoson = ethers.utils.parseUnits("0.01", "ether").toString(); + protocolFeeFlatBoson = parseUnits("0.01", "ether").toString(); buyerEscalationDepositPercentage = "1000"; // 10% // Add config Handler, so ids start at 1, and so voucher address can be found const protocolConfig = [ // Protocol addresses { - treasury: protocolTreasury.address, - token: bosonToken.address, - voucherBeacon: beacon.address, - beaconProxy: proxy.address, + treasury: await protocolTreasury.getAddress(), + token: await bosonToken.getAddress(), + voucherBeacon: await beacon.getAddress(), + beaconProxy: await proxy.getAddress(), }, // Protocol limits { @@ -159,23 +159,30 @@ describe("SnapshotGate", function () { const facetsToDeploy = await getFacetsWithArgs(facetNames, protocolConfig); // Cut the protocol handler facets into the Diamond - await deployAndCutFacets(protocolDiamond.address, facetsToDeploy, maxPriorityFeePerGas); + await deployAndCutFacets(await protocolDiamond.getAddress(), facetsToDeploy, maxPriorityFeePerGas); // Cast Diamond to IBosonAccountHandler. Use this interface to call all individual account handlers - accountHandler = await ethers.getContractAt("IBosonAccountHandler", protocolDiamond.address); + accountHandler = await getContractAt("IBosonAccountHandler", await protocolDiamond.getAddress()); // Cast Diamond to IBosonOfferHandler - offerHandler = await ethers.getContractAt("IBosonOfferHandler", protocolDiamond.address); + offerHandler = await getContractAt("IBosonOfferHandler", await protocolDiamond.getAddress()); // Cast Diamond to IGroupHandler - groupHandler = await ethers.getContractAt("IBosonGroupHandler", protocolDiamond.address); + groupHandler = await getContractAt("IBosonGroupHandler", await protocolDiamond.getAddress()); // Cast Diamond to IBosonExchangeHandler - exchangeHandler = await ethers.getContractAt("IBosonExchangeHandler", protocolDiamond.address); + exchangeHandler = await getContractAt("IBosonExchangeHandler", await protocolDiamond.getAddress()); + + accountId.next(true); // Deploy the SnapshotGate example sellerId = "1"; - [snapshotGate] = await deploySnapshotGateExample(["SnapshotGateToken", "SGT", protocolDiamond.address, sellerId]); + [snapshotGate] = await deploySnapshotGateExample([ + "SnapshotGateToken", + "SGT", + await protocolDiamond.getAddress(), + sellerId, + ]); // Deploy the mock tokens [foreign20] = await deployMockTokens(["Foreign20"]); @@ -186,11 +193,21 @@ describe("SnapshotGate", function () { agentId = "0"; // agent id is optional while creating an offer // Create a valid seller - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // Create a second seller - seller2 = mockSeller(assistant2.address, assistant2.address, ethers.constants.AddressZero, assistant2.address); + seller2 = mockSeller( + await assistant2.getAddress(), + await assistant2.getAddress(), + ZeroAddress, + await assistant2.getAddress() + ); expect(seller2.isValid()).is.true; // AuthToken @@ -209,18 +226,19 @@ describe("SnapshotGate", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); + expect(disputeResolver.isValid()).is.true; // Create DisputeResolverFee array so offer creation will succeed disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0"), - new DisputeResolverFee(foreign20.address, "Foriegn20", "0"), + new DisputeResolverFee(ZeroAddress, "Native", "0"), + new DisputeResolverFee(await foreign20.getAddress(), "Foriegn20", "0"), ]; // Make empty seller list, so every seller is allowed @@ -243,19 +261,19 @@ describe("SnapshotGate", function () { ]; holderByAddress = { - [holder1.address]: holder1, - [holder2.address]: holder2, - [holder3.address]: holder3, - [holder4.address]: holder4, - [holder5.address]: holder5, + [await holder1.getAddress()]: holder1, + [await holder2.getAddress()]: holder2, + [await holder3.getAddress()]: holder3, + [await holder4.getAddress()]: holder4, + [await holder5.getAddress()]: holder5, }; // Each holder will have a random amount of each token for (let holder of holders) { // Mint a bunch of exchange tokens for the holder and approve the gate to transfer them const amountToMint = "15000000000000000000"; - await foreign20.connect(holder).mint(holder.address, amountToMint); - await foreign20.connect(holder).approve(snapshotGate.address, amountToMint); + await foreign20.connect(holder).mint(await holder.getAddress(), amountToMint); + await foreign20.connect(holder).approve(await snapshotGate.getAddress(), amountToMint); // Create snapshot entry for holder / token for (let i = 1; i <= snapshotTokenCount; i++) { @@ -270,7 +288,7 @@ describe("SnapshotGate", function () { // Add snapshot entry snapshot.push({ - owner: holder.address, + owner: await holder.getAddress(), tokenId: i.toString(), amount: balance.toString(), }); @@ -301,7 +319,7 @@ describe("SnapshotGate", function () { // Set price in ERC-20 token if on second pass if (j > 0) { - offer.exchangeToken = foreign20.address; + offer.exchangeToken = await foreign20.getAddress(); offer.buyerCancelPenalty = "0"; } @@ -325,7 +343,7 @@ describe("SnapshotGate", function () { // Create Condition condition = mockCondition({ - tokenAddress: snapshotGate.address, + tokenAddress: await snapshotGate.getAddress(), threshold: "0", maxCommits: tokenSupply, tokenType: TokenType.NonFungibleToken, @@ -387,7 +405,7 @@ describe("SnapshotGate", function () { const event = getEvent(txReceipt, snapshotGate, "SnapshotAppended"); // Check executedBy - expect(event.executedBy.toString()).to.equal(deployer.address.toString()); + expect(event.executedBy.toString()).to.equal((await deployer.getAddress()).toString()); // Verify batch contents emitted match what was sent for (let i = 0; i < batch.length; i++) { @@ -410,7 +428,7 @@ describe("SnapshotGate", function () { let event = getEvent(txReceipt, snapshotGate, "SnapshotAppended"); // Check executedBy - expect(event.executedBy.toString()).to.equal(deployer.address.toString()); + expect(event.executedBy.toString()).to.equal((await deployer.getAddress()).toString()); // Verify batch contents emitted match what was sent for (let i = 0; i < batch1.length; i++) { @@ -426,7 +444,7 @@ describe("SnapshotGate", function () { event = getEvent(txReceipt, snapshotGate, "SnapshotAppended"); // Check executedBy - expect(event.executedBy.toString()).to.equal(deployer.address.toString()); + expect(event.executedBy.toString()).to.equal((await deployer.getAddress()).toString()); // Verify batch contents emitted match what was sent for (let i = 0; i < batch2.length; i++) { @@ -446,7 +464,7 @@ describe("SnapshotGate", function () { for (let i = 1; i <= snapshotTokenCount; i++) { const tokenId = i.toString(); const owner = await snapshotGate.ownerOf(tokenId); - expect(owner).to.equal(snapshotGate.address); + expect(owner).to.equal(await snapshotGate.getAddress()); } }); @@ -459,7 +477,7 @@ describe("SnapshotGate", function () { for (let i = 1; i <= snapshotTokenCount; i++) { const tokenId = i.toString(); const owner = await snapshotGate.ownerOf(tokenId); - expect(owner).to.equal(snapshotGate.address); + expect(owner).to.equal(await snapshotGate.getAddress()); } }); @@ -496,7 +514,7 @@ describe("SnapshotGate", function () { it("should emit a SnapshotFrozen event", async function () { await expect(snapshotGate.connect(deployer).freezeSnapshot()) .to.emit(snapshotGate, "SnapshotFrozen") - .withArgs(deployer.address); + .withArgs(await deployer.getAddress()); }); it("should store true value for snapshotFrozen", async function () { @@ -548,7 +566,7 @@ describe("SnapshotGate", function () { snapshotGate.connect(holder).commitToGatedOffer(entry.owner, offerId, entry.tokenId, { value: price }) ) .to.emit(snapshotGate, "SnapshotTokenCommitted") - .withArgs(entry.owner, offerId, entry.tokenId, holder.address); + .withArgs(entry.owner, offerId, entry.tokenId, await holder.getAddress()); }); it("should emit a SnapshotTokenCommitted event when price is in ERC20 token", async function () { @@ -570,7 +588,7 @@ describe("SnapshotGate", function () { // Commit to the offer await expect(snapshotGate.connect(holder).commitToGatedOffer(entry.owner, offerId, entry.tokenId)) .to.emit(snapshotGate, "SnapshotTokenCommitted") - .withArgs(entry.owner, offerId, entry.tokenId, holder.address); + .withArgs(entry.owner, offerId, entry.tokenId, await holder.getAddress()); }); context("💔 Revert Reasons", async function () { @@ -592,7 +610,9 @@ describe("SnapshotGate", function () { // Commit to the offer await expect( - snapshotGate.connect(caller).commitToGatedOffer(caller.address, offerId, entry.tokenId, { value: price }) + snapshotGate + .connect(caller) + .commitToGatedOffer(await caller.getAddress(), offerId, entry.tokenId, { value: price }) ).to.revertedWith("Invalid offer id"); }); @@ -611,7 +631,9 @@ describe("SnapshotGate", function () { // Commit to the offer await expect( - snapshotGate.connect(caller).commitToGatedOffer(caller.address, offerId, entry.tokenId, { value: price }) + snapshotGate + .connect(caller) + .commitToGatedOffer(await caller.getAddress(), offerId, entry.tokenId, { value: price }) ).to.revertedWith("Snapshot is not frozen"); }); @@ -633,7 +655,9 @@ describe("SnapshotGate", function () { // Commit to the offer await expect( - snapshotGate.connect(caller).commitToGatedOffer(caller.address, offerId, entry.tokenId, { value: price }) + snapshotGate + .connect(caller) + .commitToGatedOffer(await caller.getAddress(), offerId, entry.tokenId, { value: price }) ).to.revertedWith("Buyer held no balance of the given token id at time of snapshot"); }); @@ -711,7 +735,7 @@ describe("SnapshotGate", function () { await expect( snapshotGate .connect(caller) - .commitToGatedOffer(caller.address, otherSellerOfferId, entry.tokenId, { value: price }) + .commitToGatedOffer(await caller.getAddress(), otherSellerOfferId, entry.tokenId, { value: price }) ).to.revertedWith("Offer is from another seller"); }); @@ -732,7 +756,7 @@ describe("SnapshotGate", function () { let holder = holderByAddress[entry.owner]; // Wrong price - const halfPrice = ethers.BigNumber.from(price).div(ethers.BigNumber.from(2)).toString(); + const halfPrice = (BigInt(price) / BigInt(2)).toString(); // Commit to the offer await expect( @@ -757,7 +781,7 @@ describe("SnapshotGate", function () { let holder = holderByAddress[entry.owner]; // Zero out the gate's approval to transfer the holder's payment ERC20 tokens - await foreign20.connect(holder).approve(snapshotGate.address, "0"); + await foreign20.connect(holder).approve(await snapshotGate.getAddress(), "0"); // Commit to the offer await expect( @@ -850,7 +874,7 @@ describe("SnapshotGate", function () { for (let i = 1; i <= snapshotTokenCount; i++) { const tokenId = i.toString(); const owner = await snapshotGate.connect(rando).ownerOf(tokenId); - expect(owner).to.equal(snapshotGate.address); + expect(owner).to.equal(await snapshotGate.getAddress()); } }); @@ -890,9 +914,9 @@ describe("SnapshotGate", function () { let holder = holderByAddress[entry.owner]; // Check that holder cannot commit directly to the offer on the protocol itself - await expect(exchangeHandler.connect(holder).commitToOffer(holder.address, offerId)).to.revertedWith( - "Caller cannot commit" - ); + await expect( + exchangeHandler.connect(holder).commitToOffer(await holder.getAddress(), offerId) + ).to.revertedWith("Caller cannot commit"); }); }); }); diff --git a/test/integration/01-update-account-roles-addresses.js b/test/integration/01-update-account-roles-addresses.js index 35087d4ae..9d572ef18 100644 --- a/test/integration/01-update-account-roles-addresses.js +++ b/test/integration/01-update-account-roles-addresses.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, provider } = ethers; const { expect } = require("chai"); const { @@ -56,7 +57,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; // Get snapshot id snapshotId = await getSnapshot(); @@ -75,33 +76,42 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { let expectedCloneAddress, emptyAuthToken, voucherInitValues; beforeEach(async function () { - expectedCloneAddress = calculateContractAddress(accountHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "1"); emptyAuthToken = mockAuthToken(); expect(emptyAuthToken.isValid()).is.true; voucherInitValues = mockVoucherInitValues(); expect(voucherInitValues.isValid()).is.true; // Create a seller account - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); await expect(accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, seller.toStruct(), expectedCloneAddress, emptyAuthToken.toStruct(), admin.address); + .withArgs( + seller.id, + seller.toStruct(), + expectedCloneAddress, + emptyAuthToken.toStruct(), + await admin.getAddress() + ); // Create a dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed disputeResolverFeeNative = "0"; - const disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", disputeResolverFeeNative), - ]; + const disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", disputeResolverFeeNative)]; // Make empty seller list, so every seller is allowed const sellerAllowList = []; @@ -111,7 +121,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { .connect(adminDR) .createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList); - agentAccount = mockAgent(agent.address); + agentAccount = mockAgent(await agent.getAddress()); expect(agentAccount.isValid()).is.true; // Create an agent @@ -120,7 +130,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { // Create an offer ({ offer, offerDates, offerDurations, disputeResolverId } = await mockOffer()); - offerDurations.disputePeriod = (oneMonth * 6).toString(); + offerDurations.disputePeriod = (oneMonth * 6n).toString(); // Check if domains are valid expect(offer.isValid()).is.true; @@ -135,24 +145,24 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { // Deposit seller funds so the commit will succeed await fundsHandler .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, offer.sellerDeposit, { value: offer.sellerDeposit }); + .depositFunds(seller.id, ZeroAddress, offer.sellerDeposit, { value: offer.sellerDeposit }); // Create a buyer account - buyerAccount = mockBuyer(buyer.address); + buyerAccount = mockBuyer(await buyer.getAddress()); expect(await accountHandler.createBuyer(buyerAccount)) .to.emit(accountHandler, "BuyerCreated") - .withArgs(buyerAccount.id, buyerAccount.toStruct(), buyer.address); + .withArgs(buyerAccount.id, buyerAccount.toStruct(), await buyer.getAddress()); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(offerDates.voucherRedeemableFrom)); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id, { value: offer.price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offer.id, { value: offer.price }); exchangeId = "1"; - const addressZero = ethers.constants.AddressZero; + const addressZero = ZeroAddress; sellerPendingUpdate = mockSeller(addressZero, addressZero, addressZero, addressZero); sellerPendingUpdate.id = "0"; sellerPendingUpdate.active = false; @@ -164,16 +174,16 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { }); it("Seller should be able to revoke the voucher after updating assistant address", async function () { - seller.assistant = rando.address; + seller.assistant = await rando.getAddress(); expect(seller.isValid()).is.true; - sellerPendingUpdate.assistant = rando.address; + sellerPendingUpdate.assistant = await rando.getAddress(); // Update the seller wallet, testing for the event await expect(accountHandler.connect(admin).updateSeller(seller, emptyAuthToken)) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), admin.address); + .withArgs(seller.id, sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), await admin.getAddress()); - sellerPendingUpdate.assistant = ethers.constants.AddressZero; + sellerPendingUpdate.assistant = ZeroAddress; // Approve the update await expect(accountHandler.connect(rando).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant])) @@ -184,26 +194,26 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), emptyAuthToken.toStruct(), - rando.address + await rando.getAddress() ); // Revoke the voucher await expect(exchangeHandler.connect(rando).revokeVoucher(exchangeId)) .to.emit(exchangeHandler, "VoucherRevoked") - .withArgs(offer.id, exchangeId, rando.address); + .withArgs(offer.id, exchangeId, await rando.getAddress()); }); it("Seller should be able to extend the voucher after updating assistant address", async function () { - seller.assistant = rando.address; + seller.assistant = await rando.getAddress(); expect(seller.isValid()).is.true; - sellerPendingUpdate.assistant = rando.address; + sellerPendingUpdate.assistant = await rando.getAddress(); // Update the seller wallet, testing for the event await expect(accountHandler.connect(admin).updateSeller(seller, emptyAuthToken)) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), admin.address); + .withArgs(seller.id, sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), await admin.getAddress()); - sellerPendingUpdate.assistant = ethers.constants.AddressZero; + sellerPendingUpdate.assistant = ZeroAddress; // Approve the update await expect(accountHandler.connect(rando).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant])) @@ -214,14 +224,14 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), emptyAuthToken.toStruct(), - rando.address + await rando.getAddress() ); // Extend the voucher const newValidUntil = offerDates.validUntil * 12; await expect(exchangeHandler.connect(rando).extendVoucher(exchangeId, newValidUntil)) .to.emit(exchangeHandler, "VoucherExtended") - .withArgs(offer.id, exchangeId, newValidUntil, rando.address); + .withArgs(offer.id, exchangeId, newValidUntil, await rando.getAddress()); }); context("After cancel actions", function () { @@ -231,44 +241,42 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { await exchangeHandler.connect(buyer).cancelVoucher(exchangeId); // Expected buyer payoff: price - buyerCancelPenalty - buyerPayoff = ethers.BigNumber.from(offer.price).sub(offer.buyerCancelPenalty).toString(); + buyerPayoff = (BigInt(offer.price) - BigInt(offer.buyerCancelPenalty)).toString(); // Expected seller payoff: sellerDeposit + buyerCancelPenalty - sellerPayoff = ethers.BigNumber.from(offer.sellerDeposit).add(offer.buyerCancelPenalty).toString(); + sellerPayoff = (BigInt(offer.sellerDeposit) + BigInt(offer.buyerCancelPenalty)).toString(); }); it("Buyer should be able to withdraw funds after updating wallet address", async function () { - buyerAccount.wallet = rando.address; + buyerAccount.wallet = await rando.getAddress(); expect(buyerAccount.isValid()).is.true; // Update the buyer wallet, testing for the event await expect(accountHandler.connect(buyer).updateBuyer(buyerAccount)) .to.emit(accountHandler, "BuyerUpdated") - .withArgs(buyerAccount.id, buyerAccount.toStruct(), buyer.address); + .withArgs(buyerAccount.id, buyerAccount.toStruct(), await buyer.getAddress()); // Attempt to withdraw funds with old buyer wallet, should fail await expect( - fundsHandler.connect(buyer).withdrawFunds(buyerAccount.id, [ethers.constants.AddressZero], [buyerPayoff]) + fundsHandler.connect(buyer).withdrawFunds(buyerAccount.id, [ZeroAddress], [buyerPayoff]) ).to.revertedWith(RevertReasons.NOT_AUTHORIZED); // Attempt to withdraw funds with new buyer wallet, should succeed - await expect( - fundsHandler.connect(rando).withdrawFunds(buyerAccount.id, [ethers.constants.AddressZero], [buyerPayoff]) - ) + await expect(fundsHandler.connect(rando).withdrawFunds(buyerAccount.id, [ZeroAddress], [buyerPayoff])) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(buyerAccount.id, rando.address, ethers.constants.AddressZero, buyerPayoff, rando.address); + .withArgs(buyerAccount.id, await rando.getAddress(), ZeroAddress, buyerPayoff, await rando.getAddress()); }); it("Seller should be able to withdraw funds after updating assistant address", async function () { - seller.assistant = rando.address; + seller.assistant = await rando.getAddress(); expect(seller.isValid()).is.true; - sellerPendingUpdate.assistant = rando.address; + sellerPendingUpdate.assistant = await rando.getAddress(); // Update the seller wallet, testing for the event await expect(accountHandler.connect(admin).updateSeller(seller, emptyAuthToken)) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), admin.address); + .withArgs(seller.id, sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), await admin.getAddress()); - sellerPendingUpdate.assistant = ethers.constants.AddressZero; + sellerPendingUpdate.assistant = ZeroAddress; // Approve the update await expect(accountHandler.connect(rando).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant])) @@ -279,20 +287,18 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), emptyAuthToken.toStruct(), - rando.address + await rando.getAddress() ); // Attempt to withdraw funds with old seller assistant, should fail await expect( - fundsHandler.connect(assistant).withdrawFunds(seller.id, [ethers.constants.AddressZero], [sellerPayoff]) + fundsHandler.connect(assistant).withdrawFunds(seller.id, [ZeroAddress], [sellerPayoff]) ).to.revertedWith(RevertReasons.NOT_AUTHORIZED); // Attempt to withdraw funds with new seller assistant, should succeed - await expect( - fundsHandler.connect(rando).withdrawFunds(seller.id, [ethers.constants.AddressZero], [sellerPayoff]) - ) + await expect(fundsHandler.connect(rando).withdrawFunds(seller.id, [ZeroAddress], [sellerPayoff])) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(seller.id, treasury.address, ethers.constants.AddressZero, sellerPayoff, rando.address); + .withArgs(seller.id, await treasury.getAddress(), ZeroAddress, sellerPayoff, await rando.getAddress()); }); }); @@ -300,45 +306,43 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { beforeEach(async function () { // Redeem the voucher so that buyer can update the wallet const tx = await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); - const block = await ethers.provider.getBlock(tx.blockNumber); - redeemedDate = ethers.BigNumber.from(block.timestamp); + const block = await provider.getBlock(tx.blockNumber); + redeemedDate = BigInt(block.timestamp); }); it("Agent should be able to withdraw funds after updating wallet address", async function () { // Complete the exchange await exchangeHandler.connect(buyer).completeExchange(exchangeId); - agentAccount.wallet = rando.address; + agentAccount.wallet = await rando.getAddress(); expect(agentAccount.isValid()).is.true; // Update the agent wallet, testing for the event await expect(accountHandler.connect(agent).updateAgent(agentAccount)) .to.emit(accountHandler, "AgentUpdated") - .withArgs(agentAccount.id, agentAccount.toStruct(), agent.address); + .withArgs(agentAccount.id, agentAccount.toStruct(), await agent.getAddress()); const agentPayoff = applyPercentage(offer.price, agentAccount.feePercentage); // Attempt to withdraw funds with old agent wallet, should fail await expect( - fundsHandler.connect(agent).withdrawFunds(agentAccount.id, [ethers.constants.AddressZero], [agentPayoff]) + fundsHandler.connect(agent).withdrawFunds(agentAccount.id, [ZeroAddress], [agentPayoff]) ).to.revertedWith(RevertReasons.NOT_AUTHORIZED); // Attempt to withdraw funds with new agent wallet, should fail - await expect( - fundsHandler.connect(rando).withdrawFunds(agentAccount.id, [ethers.constants.AddressZero], [agentPayoff]) - ) + await expect(fundsHandler.connect(rando).withdrawFunds(agentAccount.id, [ZeroAddress], [agentPayoff])) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(agentAccount.id, rando.address, ethers.constants.AddressZero, agentPayoff, rando.address); + .withArgs(agentAccount.id, await rando.getAddress(), ZeroAddress, agentPayoff, await rando.getAddress()); }); it("Buyer should be able to raise dispute after updating wallet address", async function () { - buyerAccount.wallet = rando.address; + buyerAccount.wallet = await rando.getAddress(); expect(buyerAccount.isValid()).is.true; // Update the buyer wallet, testing for the event await expect(accountHandler.connect(buyer).updateBuyer(buyerAccount)) .to.emit(accountHandler, "BuyerUpdated") - .withArgs(buyerAccount.id, buyerAccount.toStruct(), buyer.address); + .withArgs(buyerAccount.id, buyerAccount.toStruct(), await buyer.getAddress()); // Attempt to raise a dispute with old buyer wallet, should fail await expect(disputeHandler.connect(buyer).raiseDispute(exchangeId)).to.revertedWith( @@ -348,26 +352,26 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { // Attempt to raise a dispute with new buyer wallet, should succeed await expect(disputeHandler.connect(rando).raiseDispute(exchangeId)) .to.emit(disputeHandler, "DisputeRaised") - .withArgs(exchangeId, buyerAccount.id, seller.id, rando.address); + .withArgs(exchangeId, buyerAccount.id, seller.id, await rando.getAddress()); }); it("Buyer should be able to complete exchange before dispute period is over after updating wallet address", async function () { - buyerAccount.wallet = rando.address; + buyerAccount.wallet = await rando.getAddress(); expect(buyerAccount.isValid()).is.true; // Update the buyer wallet, testing for the event await expect(accountHandler.connect(buyer).updateBuyer(buyerAccount)) .to.emit(accountHandler, "BuyerUpdated") - .withArgs(buyerAccount.id, buyerAccount.toStruct(), buyer.address); + .withArgs(buyerAccount.id, buyerAccount.toStruct(), await buyer.getAddress()); // Complete the exchange, expecting event const tx = await exchangeHandler.connect(rando).completeExchange(exchangeId); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offer.id, buyerAccount.id, exchangeId, rando.address); + .withArgs(offer.id, buyerAccount.id, exchangeId, await rando.getAddress()); - const block = await ethers.provider.getBlock(tx.blockNumber); - const disputePeriodEnd = redeemedDate.add(ethers.BigNumber.from(offerDurations.disputePeriod)); + const block = await provider.getBlock(tx.blockNumber); + const disputePeriodEnd = redeemedDate + BigInt(offerDurations.disputePeriod); // Expect the dispute period to not be over expect(block.timestamp).to.be.at.most(disputePeriodEnd); @@ -398,16 +402,16 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { }); it("Seller should be able to resolve dispute after updating assistant address", async function () { - seller.assistant = rando.address; + seller.assistant = await rando.getAddress(); expect(seller.isValid()).is.true; - sellerPendingUpdate.assistant = rando.address; + sellerPendingUpdate.assistant = await rando.getAddress(); // Update the seller wallet, testing for the event await expect(accountHandler.connect(admin).updateSeller(seller, emptyAuthToken)) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), admin.address); + .withArgs(seller.id, sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), await admin.getAddress()); - sellerPendingUpdate.assistant = ethers.constants.AddressZero; + sellerPendingUpdate.assistant = ZeroAddress; // Approve the update await expect(accountHandler.connect(rando).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant])) @@ -418,7 +422,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), emptyAuthToken.toStruct(), - rando.address + await rando.getAddress() ); // Collect the signature components @@ -427,7 +431,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() ); // Attempt to resolve a dispute with old seller assistant, should fail @@ -438,17 +442,17 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { // Attempt to resolve a dispute with new seller assistant, should succeed await expect(disputeHandler.connect(rando).resolveDispute(exchangeId, buyerPercent, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercent, rando.address); + .withArgs(exchangeId, buyerPercent, await rando.getAddress()); }); it("Buyer should be able to resolve dispute after updating wallet address", async function () { - buyerAccount.wallet = rando.address; + buyerAccount.wallet = await rando.getAddress(); expect(buyerAccount.isValid()).is.true; // Update the buyer wallet, testing for the event await expect(accountHandler.connect(buyer).updateBuyer(buyerAccount)) .to.emit(accountHandler, "BuyerUpdated") - .withArgs(buyerAccount.id, buyerAccount.toStruct(), buyer.address); + .withArgs(buyerAccount.id, buyerAccount.toStruct(), await buyer.getAddress()); // Collect the signature components const { r, s, v } = await prepareDataSignatureParameters( @@ -456,7 +460,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() ); // Attempt to resolve a dispute with old buyer wallet, should fail @@ -467,17 +471,17 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { // Attempt to resolve a dispute with new buyer wallet, should succeed await expect(disputeHandler.connect(rando).resolveDispute(exchangeId, buyerPercent, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercent, rando.address); + .withArgs(exchangeId, buyerPercent, await rando.getAddress()); }); it("If the buyer wallet address was changed, the seller should not be able to resolve a dispute with the old signature", async function () { - buyerAccount.wallet = rando.address; + buyerAccount.wallet = await rando.getAddress(); expect(buyerAccount.isValid()).is.true; // Update the buyer wallet, testing for the event await expect(accountHandler.connect(buyer).updateBuyer(buyerAccount)) .to.emit(accountHandler, "BuyerUpdated") - .withArgs(buyerAccount.id, buyerAccount.toStruct(), buyer.address); + .withArgs(buyerAccount.id, buyerAccount.toStruct(), await buyer.getAddress()); // Collect the signature components const { r, s, v } = await prepareDataSignatureParameters( @@ -485,7 +489,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() ); // Attempt to resolve a dispute with old buyer wallet, should fail @@ -495,16 +499,16 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { }); it("If the seller assistant address was changed, the buyer should not be able to resolve a dispute with the old signature", async function () { - seller.assistant = rando.address; + seller.assistant = await rando.getAddress(); expect(seller.isValid()).is.true; - sellerPendingUpdate.assistant = rando.address; + sellerPendingUpdate.assistant = await rando.getAddress(); // Update the seller wallet, testing for the event await expect(accountHandler.connect(admin).updateSeller(seller, emptyAuthToken)) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), admin.address); + .withArgs(seller.id, sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), await admin.getAddress()); - sellerPendingUpdate.assistant = ethers.constants.AddressZero; + sellerPendingUpdate.assistant = ZeroAddress; // Approve the update await expect(accountHandler.connect(rando).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant])) @@ -515,7 +519,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { sellerPendingUpdate.toStruct(), emptyAuthToken.toStruct(), emptyAuthToken.toStruct(), - rando.address + await rando.getAddress() ); // Collect the signature components @@ -524,7 +528,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() ); // Attempt to resolve a dispute with old buyer wallet, should fail @@ -534,13 +538,13 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { }); it("Buyer should be able to retract dispute after updating wallet address", async function () { - buyerAccount.wallet = rando.address; + buyerAccount.wallet = await rando.getAddress(); expect(buyerAccount.isValid()).is.true; // Update the buyer wallet, testing for the event await expect(accountHandler.connect(buyer).updateBuyer(buyerAccount)) .to.emit(accountHandler, "BuyerUpdated") - .withArgs(buyerAccount.id, buyerAccount.toStruct(), buyer.address); + .withArgs(buyerAccount.id, buyerAccount.toStruct(), await buyer.getAddress()); // Attempt to retract a dispute with old buyer, should fail await expect(disputeHandler.connect(buyer).retractDispute(exchangeId)).to.be.revertedWith( @@ -550,7 +554,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { // Attempt to retract a dispute with new buyer, should succeed await expect(disputeHandler.connect(rando).retractDispute(exchangeId)) .to.emit(disputeHandler, "DisputeRetracted") - .withArgs(exchangeId, rando.address); + .withArgs(exchangeId, await rando.getAddress()); }); context("After escalte dispute actions", function () { @@ -563,7 +567,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { // Escalate the dispute await disputeHandler.connect(buyer).escalateDispute(exchangeId, { value: buyerEscalationDepositNative }); - disputeResolver.assistant = rando.address; + disputeResolver.assistant = await rando.getAddress(); expect(disputeResolver.isValid()).is.true; // Update the dispute resolver assistant @@ -584,7 +588,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { // Attempt to decide a dispute with new dispute resolver assistant, should fail await expect(disputeHandler.connect(rando).decideDispute(exchangeId, buyerPercent)) .to.emit(disputeHandler, "DisputeDecided") - .withArgs(exchangeId, buyerPercent, rando.address); + .withArgs(exchangeId, buyerPercent, await rando.getAddress()); }); it("Dispute resolver should be able to refuse to decide a dispute after change the assistant address", async function () { @@ -596,7 +600,7 @@ describe("[@skip-on-coverage] Update account roles addresses", function () { // Attempt to refuse a dispute with new dispute resolver assistant, should fail await expect(disputeHandler.connect(rando).refuseEscalatedDispute(exchangeId)) .to.emit(disputeHandler, "EscalatedDisputeRefused") - .withArgs(exchangeId, rando.address); + .withArgs(exchangeId, await rando.getAddress()); }); }); }); diff --git a/test/integration/02-Upgraded-facet.js b/test/integration/02-Upgraded-facet.js index 3f887cb56..cd8e9357f 100644 --- a/test/integration/02-Upgraded-facet.js +++ b/test/integration/02-Upgraded-facet.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, getContractAt, getContractFactory, provider, parseUnits, getSigners } = ethers; const { expect, assert } = require("chai"); const { DisputeResolverFee } = require("../../scripts/domain/DisputeResolverFee"); const { deployMockTokens } = require("../../scripts/util/deploy-mock-tokens"); @@ -72,8 +73,8 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; - [deployer] = await ethers.getSigners(); + clerk = clerkDR = { address: ZeroAddress }; + [deployer] = await getSigners(); // Initial ids for all the things exchangeId = offerId = "1"; @@ -85,7 +86,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation beforeEach(async function () { // Create a valid seller, then set fields in tests directly - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -101,7 +107,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation [mockToken] = await deployMockTokens(["Foreign20"]); // top up assistants account - await mockToken.mint(assistant.address, "1000000"); + await mockToken.mint(await assistant.getAddress(), "1000000"); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, "1000000"); @@ -115,24 +121,24 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation async function upgradeExchangeHandlerFacet(mockFacet) { // Upgrade the Exchange Handler Facet functions // DiamondCutFacet - const cutFacetViaDiamond = await ethers.getContractAt("DiamondCutFacet", protocolDiamondAddress); + const cutFacetViaDiamond = await getContractAt("DiamondCutFacet", protocolDiamondAddress); // Deploy MockExchangeHandlerFacet - const MockExchangeHandlerFacet = await ethers.getContractFactory(mockFacet); + const MockExchangeHandlerFacet = await getContractFactory(mockFacet); const mockExchangeHandlerFacet = await MockExchangeHandlerFacet.deploy(); - await mockExchangeHandlerFacet.deployed(); + await mockExchangeHandlerFacet.waitForDeployment(); // Define the facet cut const facetCuts = [ { - facetAddress: mockExchangeHandlerFacet.address, + facetAddress: await mockExchangeHandlerFacet.getAddress(), action: FacetCutAction.Replace, functionSelectors: getSelectors(mockExchangeHandlerFacet), }, ]; // Send the DiamondCut transaction - const tx = await cutFacetViaDiamond.connect(deployer).diamondCut(facetCuts, ethers.constants.AddressZero, "0x"); + const tx = await cutFacetViaDiamond.connect(deployer).diamondCut(facetCuts, ZeroAddress, "0x"); // Wait for transaction to confirm const receipt = await tx.wait(); @@ -141,7 +147,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation assert.equal(receipt.status, 1, `Diamond upgrade failed: ${tx.hash}`); // Cast Diamond to the mock exchange handler facet. - mockExchangeHandlerUpgrade = await ethers.getContractAt(mockFacet, protocolDiamondAddress); + mockExchangeHandlerUpgrade = await getContractAt(mockFacet, protocolDiamondAddress); } // Exchange methods @@ -149,16 +155,16 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation beforeEach(async function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed - const disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")]; + const disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", "0")]; // Make empty seller list, so every seller is allowed const sellerAllowList = []; @@ -187,7 +193,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation price = offer.price; voucherRedeemableFrom = offerDates.voucherRedeemableFrom; voucherValid = offerDurations.voucherValid; - sellerPool = ethers.utils.parseUnits("15", "ether").toString(); + sellerPool = parseUnits("15", "ether").toString(); // Required voucher constructor params voucher = mockVoucher(); @@ -201,9 +207,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation exchange.finalizedDate = "0"; // Deposit seller funds so the commit will succeed - await fundsHandler - .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerPool, { value: sellerPool }); + await fundsHandler.connect(assistant).depositFunds(seller.id, ZeroAddress, sellerPool, { value: sellerPool }); }); afterEach(async function () { @@ -214,7 +218,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation context("👉 completeExchange()", async function () { beforeEach(async function () { // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Upgrade Exchange handler facet await upgradeExchangeHandlerFacet("MockExchangeHandlerFacet"); @@ -230,7 +234,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Complete the exchange, expecting event await expect(mockExchangeHandlerUpgrade.connect(buyer).completeExchange(exchange.id)) .to.emit(mockExchangeHandlerUpgrade, "ExchangeCompleted2") - .withArgs(offerId, buyerId, exchange.id, buyer.address); + .withArgs(offerId, buyerId, exchange.id, await buyer.getAddress()); }); }); @@ -241,7 +245,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation for (exchangeId = 1; exchangeId <= 5; exchangeId++) { // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); } // Upgrade Exchange handler facet @@ -258,30 +262,30 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation const tx = await mockExchangeHandlerUpgrade.connect(buyer).completeExchangeBatch(exchangesToComplete); await expect(tx) .to.emit(mockExchangeHandlerUpgrade, "ExchangeCompleted2") - .withArgs(offerId, buyerId, exchangesToComplete[0], buyer.address); + .withArgs(offerId, buyerId, exchangesToComplete[0], await buyer.getAddress()); await expect(tx) .to.emit(mockExchangeHandlerUpgrade, "ExchangeCompleted2") - .withArgs(offerId, buyerId, exchangesToComplete[1], buyer.address); + .withArgs(offerId, buyerId, exchangesToComplete[1], await buyer.getAddress()); await expect(tx) .to.emit(mockExchangeHandlerUpgrade, "ExchangeCompleted2") - .withArgs(offerId, buyerId, exchangesToComplete[2], buyer.address); + .withArgs(offerId, buyerId, exchangesToComplete[2], await buyer.getAddress()); await expect(tx) .to.emit(mockExchangeHandlerUpgrade, "ExchangeCompleted2") - .withArgs(offerId, buyerId, exchangesToComplete[3], buyer.address); + .withArgs(offerId, buyerId, exchangesToComplete[3], await buyer.getAddress()); await expect(tx) .to.emit(mockExchangeHandlerUpgrade, "ExchangeCompleted2") - .withArgs(offerId, buyerId, exchangesToComplete[4], buyer.address); + .withArgs(offerId, buyerId, exchangesToComplete[4], await buyer.getAddress()); }); }); context("👉 revokeVoucher()", async function () { it("should emit an VoucherRevoked2 event when seller's assistant calls", async function () { // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Upgrade Exchange handler facet await upgradeExchangeHandlerFacet("MockExchangeHandlerFacet"); @@ -289,14 +293,14 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Revoke the voucher, expecting event await expect(mockExchangeHandlerUpgrade.connect(assistant).revokeVoucher(exchange.id)) .to.emit(mockExchangeHandlerUpgrade, "VoucherRevoked2") - .withArgs(offerId, exchange.id, assistant.address); + .withArgs(offerId, exchange.id, await assistant.getAddress()); }); }); context("👉 cancelVoucher()", async function () { it("should emit an VoucherCanceled2 event when original buyer calls", async function () { // Commit to offer, retrieving the event - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Upgrade Exchange handler facet await upgradeExchangeHandlerFacet("MockExchangeHandlerFacet"); @@ -304,14 +308,14 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Cancel the voucher, expecting event await expect(mockExchangeHandlerUpgrade.connect(buyer).cancelVoucher(exchange.id)) .to.emit(mockExchangeHandlerUpgrade, "VoucherCanceled2") - .withArgs(offerId, exchange.id, buyer.address); + .withArgs(offerId, exchange.id, await buyer.getAddress()); }); }); context("👉 expireVoucher()", async function () { it("should emit an VoucherExpired2 event when anyone calls and voucher has expired", async function () { // Commit to offer, retrieving the event - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Upgrade Exchange handler facet await upgradeExchangeHandlerFacet("MockExchangeHandlerFacet"); @@ -322,14 +326,14 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Expire the voucher, expecting event await expect(mockExchangeHandlerUpgrade.connect(rando).expireVoucher(exchange.id)) .to.emit(mockExchangeHandlerUpgrade, "VoucherExpired2") - .withArgs(offerId, exchange.id, rando.address); + .withArgs(offerId, exchange.id, await rando.getAddress()); }); }); context("👉 redeemVoucher()", async function () { it("should emit a VoucherRedeemed2 event when buyer calls", async function () { // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Upgrade Exchange handler facet await upgradeExchangeHandlerFacet("MockExchangeHandlerFacet"); @@ -340,18 +344,20 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Redeem the voucher, expecting event await expect(mockExchangeHandlerUpgrade.connect(buyer).redeemVoucher(exchange.id)) .to.emit(mockExchangeHandlerUpgrade, "VoucherRedeemed2") - .withArgs(offerId, exchange.id, buyer.address); + .withArgs(offerId, exchange.id, await buyer.getAddress()); }); }); context("👉 extendVoucher()", async function () { it("should emit an VoucherExtended2 event when seller's assistant calls", async function () { // Commit to offer - const tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + const tx = await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Get the block timestamp of the confirmed tx const blockNumber = tx.blockNumber; - const block = await ethers.provider.getBlock(blockNumber); + const block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -360,7 +366,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation voucher.validUntilDate = calculateVoucherExpiry(block, voucherRedeemableFrom, voucherValid); // New expiry date for extensions - const validUntilDate = ethers.BigNumber.from(voucher.validUntilDate).add(oneMonth).toString(); + const validUntilDate = BigInt(voucher.validUntilDate) + oneMonth.toString(); // Upgrade Exchange handler facet await upgradeExchangeHandlerFacet("MockExchangeHandlerFacet"); @@ -368,7 +374,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Extend the voucher, expecting event await expect(mockExchangeHandlerUpgrade.connect(assistant).extendVoucher(exchange.id, validUntilDate)) .to.emit(mockExchangeHandlerUpgrade, "VoucherExtended2") - .withArgs(offerId, exchange.id, validUntilDate, assistant.address); + .withArgs(offerId, exchange.id, validUntilDate, await assistant.getAddress()); }); }); }); @@ -378,17 +384,17 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation beforeEach(async function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed const DRFeeNative = "0"; - const disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", DRFeeNative)]; + const disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", DRFeeNative)]; // Make empty seller list, so every seller is allowed const sellerAllowList = []; @@ -422,10 +428,10 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation escalationPeriod = disputeResolver.escalationResponsePeriod; // Deposit seller funds so the commit will succeed - const fundsToDeposit = ethers.BigNumber.from(sellerDeposit).mul(quantityAvailable); + const fundsToDeposit = BigInt(sellerDeposit) * BigInt(quantityAvailable); await fundsHandler .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, fundsToDeposit, { value: fundsToDeposit }); + .depositFunds(seller.id, ZeroAddress, fundsToDeposit, { value: fundsToDeposit }); buyerId = accountId.next().value; }); @@ -440,7 +446,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation exchangeId = "1"; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(voucherRedeemableFrom)); @@ -460,7 +466,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Raise a dispute, testing for the event await expect(disputeHandler.connect(buyer).raiseDispute(exchangeId)) .to.emit(disputeHandler, "DisputeRaised") - .withArgs(exchangeId, buyerId, seller.id, buyer.address); + .withArgs(exchangeId, buyerId, seller.id, await buyer.getAddress()); }); }); @@ -472,7 +478,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Retract the dispute, testing for the event await expect(disputeHandler.connect(buyer).retractDispute(exchangeId)) .to.emit(disputeHandler, "DisputeRetracted") - .withArgs(exchangeId, buyer.address); + .withArgs(exchangeId, await buyer.getAddress()); }); }); @@ -483,17 +489,17 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Get the block timestamp of the confirmed tx and set disputedDate const blockNumber = tx.blockNumber; - const block = await ethers.provider.getBlock(blockNumber); + const block = await provider.getBlock(blockNumber); const disputedDate = block.timestamp.toString(); - const timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + const timeout = BigInt(disputedDate) + resolutionPeriod.toString(); // extend timeout for a month - const newDisputeTimeout = ethers.BigNumber.from(timeout).add(oneMonth).toString(); + const newDisputeTimeout = BigInt(timeout) + oneMonth.toString(); // Extend the dispute timeout, testing for the event await expect(disputeHandler.connect(assistant).extendDisputeTimeout(exchangeId, newDisputeTimeout)) .to.emit(disputeHandler, "DisputeTimeoutExtended") - .withArgs(exchangeId, newDisputeTimeout, assistant.address); + .withArgs(exchangeId, newDisputeTimeout, await assistant.getAddress()); }); }); @@ -504,9 +510,9 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Get the block timestamp of the confirmed tx and set disputedDate const blockNumber = tx.blockNumber; - const block = await ethers.provider.getBlock(blockNumber); + const block = await provider.getBlock(blockNumber); const disputedDate = block.timestamp.toString(); - const timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + const timeout = BigInt(disputedDate) + resolutionPeriod.toString(); // Set time forward past the dispute resolution period await setNextBlockTimestamp(Number(timeout) + Number(oneWeek)); @@ -514,7 +520,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Expire the dispute, testing for the event await expect(disputeHandler.connect(rando).expireDispute(exchangeId)) .to.emit(disputeHandler, "DisputeExpired") - .withArgs(exchangeId, rando.address); + .withArgs(exchangeId, await rando.getAddress()); }); }); @@ -549,13 +555,13 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() ); // Resolve the dispute, testing for the event await expect(disputeHandler.connect(buyer).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, buyer.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await buyer.getAddress()); }); }); @@ -567,13 +573,13 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() ); // Resolve the dispute, testing for the event await expect(disputeHandler.connect(assistant).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, assistant.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistant.getAddress()); }); }); }); @@ -588,7 +594,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation disputeHandler.connect(buyer).escalateDispute(exchangeId, { value: buyerEscalationDepositNative }) ) .to.emit(disputeHandler, "DisputeEscalated") - .withArgs(exchangeId, disputeResolverId, buyer.address); + .withArgs(exchangeId, disputeResolverId, await buyer.getAddress()); }); }); @@ -606,7 +612,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Escalate the dispute, testing for the event await expect(disputeHandler.connect(assistantDR).decideDispute(exchangeId, buyerPercentBasisPoints)) .to.emit(disputeHandler, "DisputeDecided") - .withArgs(exchangeId, buyerPercentBasisPoints, assistantDR.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistantDR.getAddress()); }); }); @@ -622,7 +628,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Get the block timestamp of the confirmed tx and set escalatedDate const blockNumber = tx.blockNumber; - const block = await ethers.provider.getBlock(blockNumber); + const block = await provider.getBlock(blockNumber); const escalatedDate = block.timestamp.toString(); // Set time forward past the dispute escalation period @@ -631,7 +637,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Expire the escalated dispute, testing for the event await expect(disputeHandler.connect(rando).expireEscalatedDispute(exchangeId)) .to.emit(disputeHandler, "EscalatedDisputeExpired") - .withArgs(exchangeId, rando.address); + .withArgs(exchangeId, await rando.getAddress()); }); }); @@ -646,7 +652,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Refuse the escalated dispute, testing for the event await expect(disputeHandler.connect(assistantDR).refuseEscalatedDispute(exchangeId)) .to.emit(disputeHandler, "EscalatedDisputeRefused") - .withArgs(exchangeId, assistantDR.address); + .withArgs(exchangeId, await assistantDR.getAddress()); }); }); }); @@ -666,18 +672,18 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed const disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0"), - new DisputeResolverFee(mockToken.address, "mockToken", "0"), + new DisputeResolverFee(ZeroAddress, "Native", "0"), + new DisputeResolverFee(await mockToken.getAddress(), "mockToken", "0"), ]; // Make empty seller list, so every seller is allowed @@ -696,7 +702,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation offerToken = offer.clone(); offerToken.id = "2"; - offerToken.exchangeToken = mockToken.address; + offerToken.exchangeToken = await mockToken.getAddress(); // Check if domais are valid expect(offerNative.isValid()).is.true; @@ -722,7 +728,10 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation sellerDeposit = offerToken.sellerDeposit; // top up seller's and buyer's account - await Promise.all([mockToken.mint(assistant.address, sellerDeposit), mockToken.mint(buyer.address, price)]); + await Promise.all([ + mockToken.mint(await assistant.getAddress(), sellerDeposit), + mockToken.mint(await buyer.getAddress(), price), + ]); // approve protocol to transfer the tokens await Promise.all([ @@ -732,15 +741,15 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // deposit to seller's pool await Promise.all([ - fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, sellerDeposit), - fundsHandler - .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerDeposit, { value: sellerDeposit }), + fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), sellerDeposit), + fundsHandler.connect(assistant).depositFunds(seller.id, ZeroAddress, sellerDeposit, { value: sellerDeposit }), ]); // commit to both offers - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerNative.id, { value: offerNative.price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); + await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerNative.id, { value: offerNative.price }); buyerId = accountId.next().value; }); @@ -761,21 +770,19 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // expected payoffs - they are the same for token and native currency // buyer: price - buyerCancelPenalty - const buyerPayoff = ethers.BigNumber.from(offerToken.price).sub(offerToken.buyerCancelPenalty).toString(); + const buyerPayoff = (BigInt(offerToken.price) - BigInt(offerToken.buyerCancelPenalty)).toString(); // seller: sellerDeposit + buyerCancelPenalty - const sellerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit) - .add(offerToken.buyerCancelPenalty) - .toString(); + const sellerPayoff = (BigInt(offerToken.sellerDeposit) + BigInt(offerToken.buyerCancelPenalty)).toString(); // Withdraw funds, testing for the event // Withdraw tokens - const tokenListSeller = [mockToken.address, ethers.constants.AddressZero]; - const tokenListBuyer = [ethers.constants.AddressZero, mockToken.address]; + const tokenListSeller = [await mockToken.getAddress(), ZeroAddress]; + const tokenListBuyer = [ZeroAddress, await mockToken.getAddress()]; // Withdraw amounts - const tokenAmountsSeller = [sellerPayoff, ethers.BigNumber.from(sellerPayoff).div("2").toString()]; - const tokenAmountsBuyer = [buyerPayoff, ethers.BigNumber.from(buyerPayoff).div("5").toString()]; + const tokenAmountsSeller = [sellerPayoff, (BigInt(sellerPayoff) / 2n).toString()]; + const tokenAmountsBuyer = [buyerPayoff, (BigInt(buyerPayoff) / 5n).toString()]; // seller withdrawal const tx = await fundsHandler @@ -783,33 +790,39 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation .withdrawFunds(seller.id, tokenListSeller, tokenAmountsSeller); await expect(tx) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(seller.id, treasury.address, mockToken.address, sellerPayoff, assistant.address); + .withArgs( + seller.id, + await treasury.getAddress(), + await mockToken.getAddress(), + sellerPayoff, + await assistant.getAddress() + ); await expect(tx) .to.emit(fundsHandler, "FundsWithdrawn") .withArgs( seller.id, - treasury.address, - ethers.constants.Zero, - ethers.BigNumber.from(sellerPayoff).div("2"), - assistant.address + await treasury.getAddress(), + 0n, + BigInt(sellerPayoff) / 2n, + await assistant.getAddress() ); // buyer withdrawal const tx2 = await fundsHandler.connect(buyer).withdrawFunds(buyerId, tokenListBuyer, tokenAmountsBuyer); await expect(tx2) - .to.emit(fundsHandler, "FundsWithdrawn", buyer.address) + .to.emit(fundsHandler, "FundsWithdrawn", await buyer.getAddress()) .withArgs( buyerId, - buyer.address, - mockToken.address, - ethers.BigNumber.from(buyerPayoff).div("5"), - buyer.address + await buyer.getAddress(), + await mockToken.getAddress(), + BigInt(buyerPayoff) / 5n, + await buyer.getAddress() ); await expect(tx2) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(buyerId, buyer.address, ethers.constants.Zero, buyerPayoff, buyer.address); + .withArgs(buyerId, await buyer.getAddress(), 0n, buyerPayoff, await buyer.getAddress()); }); }); @@ -823,21 +836,19 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // expected payoffs - they are the same for token and native currency // buyer: price - buyerCancelPenalty - const buyerPayoff = ethers.BigNumber.from(offerToken.price).sub(offerToken.buyerCancelPenalty).toString(); + const buyerPayoff = (BigInt(offerToken.price) - BigInt(offerToken.buyerCancelPenalty)).toString(); // seller: sellerDeposit + buyerCancelPenalty - const sellerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit) - .add(offerToken.buyerCancelPenalty) - .toString(); + const sellerPayoff = (BigInt(offerToken.sellerDeposit) + BigInt(offerToken.buyerCancelPenalty)).toString(); // Withdraw funds, testing for the event // Withdraw tokens - const tokenListSeller = [mockToken.address, ethers.constants.AddressZero]; - const tokenListBuyer = [ethers.constants.AddressZero, mockToken.address]; + const tokenListSeller = [await mockToken.getAddress(), ZeroAddress]; + const tokenListBuyer = [ZeroAddress, await mockToken.getAddress()]; // Withdraw amounts - const tokenAmountsSeller = [sellerPayoff, ethers.BigNumber.from(sellerPayoff).div("2").toString()]; - const tokenAmountsBuyer = [buyerPayoff, ethers.BigNumber.from(buyerPayoff).div("5").toString()]; + const tokenAmountsSeller = [sellerPayoff, (BigInt(sellerPayoff) / 2n).toString()]; + const tokenAmountsBuyer = [buyerPayoff, (BigInt(buyerPayoff) / 5n).toString()]; // seller withdrawal // Attempt to withdraw the funds, expecting revert diff --git a/test/integration/03-DR-removes-the-seller-from-allowed-list.js b/test/integration/03-DR-removes-the-seller-from-allowed-list.js index 79b6743d9..f0c12904d 100644 --- a/test/integration/03-DR-removes-the-seller-from-allowed-list.js +++ b/test/integration/03-DR-removes-the-seller-from-allowed-list.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress } = ethers; const { expect } = require("chai"); const { DisputeResolverFee } = require("../../scripts/domain/DisputeResolverFee"); @@ -56,7 +57,7 @@ describe("[@skip-on-coverage] DR removes sellers from the approved seller list", // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; // Get snapshot id snapshotId = await getSnapshot(); @@ -74,10 +75,20 @@ describe("[@skip-on-coverage] DR removes sellers from the approved seller list", const agentId = "0"; // agent id is optional while creating an offer // Create a valid seller - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; - const seller2 = mockSeller(other1.address, other1.address, ethers.constants.AddressZero, other1.address); + const seller2 = mockSeller( + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() + ); expect(seller2.isValid()).is.true; // VoucherInitValues @@ -96,17 +107,17 @@ describe("[@skip-on-coverage] DR removes sellers from the approved seller list", // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; // Create DisputeResolverFee array so offer creation will succeed const DRFeeNative = "0"; - const disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", DRFeeNative)]; + const disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", DRFeeNative)]; // Make a sellerAllowList const sellerAllowList = ["2", "1"]; @@ -139,17 +150,17 @@ describe("[@skip-on-coverage] DR removes sellers from the approved seller list", const voucherRedeemableFrom = offerDates.voucherRedeemableFrom; // Deposit seller funds so the commit will succeed - const fundsToDeposit = ethers.BigNumber.from(sellerDeposit).mul(quantityAvailable); + const fundsToDeposit = BigInt(sellerDeposit) * BigInt(quantityAvailable); await fundsHandler .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, fundsToDeposit, { value: fundsToDeposit }); + .depositFunds(seller.id, ZeroAddress, fundsToDeposit, { value: fundsToDeposit }); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(voucherRedeemableFrom)); for (exchangeId = 1; exchangeId <= 3; exchangeId++) { // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Redeem voucher await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); @@ -180,7 +191,7 @@ describe("[@skip-on-coverage] DR removes sellers from the approved seller list", // Decide the dispute await expect(disputeHandler.connect(assistantDR).decideDispute(exchangeId, buyerPercentBasisPoints)) .to.emit(disputeHandler, "DisputeDecided") - .withArgs(exchangeId, buyerPercentBasisPoints, assistantDR.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistantDR.getAddress()); // Remove an approved seller let allowedSellersToRemove = ["1"]; @@ -190,12 +201,12 @@ describe("[@skip-on-coverage] DR removes sellers from the approved seller list", accountHandler.connect(adminDR).removeSellersFromAllowList(disputeResolverId, allowedSellersToRemove) ) .to.emit(accountHandler, "AllowedSellersRemoved") - .withArgs(disputeResolverId, allowedSellersToRemove, adminDR.address); + .withArgs(disputeResolverId, allowedSellersToRemove, await adminDR.getAddress()); // Decide the dispute await expect(disputeHandler.connect(assistantDR).decideDispute(exchangeId, buyerPercentBasisPoints)) .to.emit(disputeHandler, "DisputeDecided") - .withArgs(exchangeId, buyerPercentBasisPoints, assistantDR.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistantDR.getAddress()); // Remove another approved seller allowedSellersToRemove = ["2"]; @@ -205,12 +216,12 @@ describe("[@skip-on-coverage] DR removes sellers from the approved seller list", accountHandler.connect(adminDR).removeSellersFromAllowList(disputeResolverId, allowedSellersToRemove) ) .to.emit(accountHandler, "AllowedSellersRemoved") - .withArgs(disputeResolverId, allowedSellersToRemove, adminDR.address); + .withArgs(disputeResolverId, allowedSellersToRemove, await adminDR.getAddress()); // Decide the dispute await expect(disputeHandler.connect(assistantDR).decideDispute(exchangeId, buyerPercentBasisPoints)) .to.emit(disputeHandler, "DisputeDecided") - .withArgs(exchangeId, buyerPercentBasisPoints, assistantDR.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistantDR.getAddress()); }); }); @@ -230,7 +241,7 @@ describe("[@skip-on-coverage] DR removes sellers from the approved seller list", // Refuse the escalated dispute, testing for the event await expect(disputeHandler.connect(assistantDR).refuseEscalatedDispute(exchangeId)) .to.emit(disputeHandler, "EscalatedDisputeRefused") - .withArgs(exchangeId, assistantDR.address); + .withArgs(exchangeId, await assistantDR.getAddress()); // Remove an approved seller let allowedSellersToRemove = ["1"]; @@ -240,12 +251,12 @@ describe("[@skip-on-coverage] DR removes sellers from the approved seller list", accountHandler.connect(adminDR).removeSellersFromAllowList(disputeResolverId, allowedSellersToRemove) ) .to.emit(accountHandler, "AllowedSellersRemoved") - .withArgs(disputeResolverId, allowedSellersToRemove, adminDR.address); + .withArgs(disputeResolverId, allowedSellersToRemove, await adminDR.getAddress()); // Refuse the escalated dispute, testing for the event await expect(disputeHandler.connect(assistantDR).refuseEscalatedDispute(exchangeId)) .to.emit(disputeHandler, "EscalatedDisputeRefused") - .withArgs(exchangeId, assistantDR.address); + .withArgs(exchangeId, await assistantDR.getAddress()); // Remove another approved seller allowedSellersToRemove = ["2"]; @@ -255,12 +266,12 @@ describe("[@skip-on-coverage] DR removes sellers from the approved seller list", accountHandler.connect(adminDR).removeSellersFromAllowList(disputeResolverId, allowedSellersToRemove) ) .to.emit(accountHandler, "AllowedSellersRemoved") - .withArgs(disputeResolverId, allowedSellersToRemove, adminDR.address); + .withArgs(disputeResolverId, allowedSellersToRemove, await adminDR.getAddress()); // Refuse the escalated dispute, testing for the event await expect(disputeHandler.connect(assistantDR).refuseEscalatedDispute(exchangeId)) .to.emit(disputeHandler, "EscalatedDisputeRefused") - .withArgs(exchangeId, assistantDR.address); + .withArgs(exchangeId, await assistantDR.getAddress()); }); }); }); diff --git a/test/integration/04-DR-removes-fees.js b/test/integration/04-DR-removes-fees.js index 18edbb5ac..044d9794e 100644 --- a/test/integration/04-DR-removes-fees.js +++ b/test/integration/04-DR-removes-fees.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, provider } = ethers; const { expect } = require("chai"); const { @@ -57,35 +58,45 @@ describe("[@skip-on-coverage] DR removes fee", function () { // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; - expectedCloneAddress = calculateContractAddress(accountHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "1"); emptyAuthToken = mockAuthToken(); expect(emptyAuthToken.isValid()).is.true; voucherInitValues = mockVoucherInitValues(); expect(voucherInitValues.isValid()).is.true; // Create a seller account - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); + expect(await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, seller.toStruct(), expectedCloneAddress, emptyAuthToken.toStruct(), admin.address); + .withArgs( + seller.id, + seller.toStruct(), + expectedCloneAddress, + emptyAuthToken.toStruct(), + await admin.getAddress() + ); // Create a dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed disputeResolverFeeNative = "0"; - const disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", disputeResolverFeeNative), - ]; + const disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", disputeResolverFeeNative)]; // Make empty seller list, so every seller is allowed const sellerAllowList = []; @@ -106,24 +117,24 @@ describe("[@skip-on-coverage] DR removes fee", function () { await offerHandler.connect(assistant).createOffer(offer, offerDates, offerDurations, disputeResolverId, "0"); // Deposit seller funds so the commit will succeed - const fundsToDeposit = ethers.BigNumber.from(offer.sellerDeposit).mul(offer.quantityAvailable); - await fundsHandler.connect(assistant).depositFunds(seller.id, ethers.constants.AddressZero, fundsToDeposit, { + const fundsToDeposit = BigInt(offer.sellerDeposit) * BigInt(offer.quantityAvailable); + await fundsHandler.connect(assistant).depositFunds(seller.id, ZeroAddress, fundsToDeposit, { value: fundsToDeposit, }); // Create a buyer account - buyerAccount = mockBuyer(buyer.address); + buyerAccount = mockBuyer(await buyer.getAddress()); expect(await accountHandler.createBuyer(buyerAccount)) .to.emit(accountHandler, "BuyerCreated") - .withArgs(buyerAccount.id, buyerAccount.toStruct(), buyer.address); + .withArgs(buyerAccount.id, buyerAccount.toStruct(), await buyer.getAddress()); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(offerDates.voucherRedeemableFrom)); for (exchangeId = 1; exchangeId <= 2; exchangeId++) { // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id, { value: offer.price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offer.id, { value: offer.price }); // Redeem voucher await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); @@ -140,15 +151,15 @@ describe("[@skip-on-coverage] DR removes fee", function () { it("Buyer should be able to commit to offer even when DR removes fee", async function () { // Removes fee - await expect( - accountHandler.connect(adminDR).removeFeesFromDisputeResolver(disputeResolver.id, [ethers.constants.AddressZero]) - ) + await expect(accountHandler.connect(adminDR).removeFeesFromDisputeResolver(disputeResolver.id, [ZeroAddress])) .to.emit(accountHandler, "DisputeResolverFeesRemoved") - .withArgs(disputeResolver.id, [ethers.constants.AddressZero], adminDR.address); + .withArgs(disputeResolver.id, [ZeroAddress], await adminDR.getAddress()); // Commit to offer - const tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id, { value: offer.price }); - const blockTimestamp = (await ethers.provider.getBlock(tx.blockNumber)).timestamp; + const tx = await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offer.id, { value: offer.price }); + const blockTimestamp = (await provider.getBlock(tx.blockNumber)).timestamp; // Mock voucher const voucher = mockVoucher({ @@ -164,7 +175,14 @@ describe("[@skip-on-coverage] DR removes fee", function () { // Check if offer was committed await expect(tx) .to.emit(exchangeHandler, "BuyerCommitted") - .withArgs(offer.id, buyerAccount.id, exchangeId, exchange.toStruct(), voucher.toStruct(), buyer.address); + .withArgs( + offer.id, + buyerAccount.id, + exchangeId, + exchange.toStruct(), + voucher.toStruct(), + await buyer.getAddress() + ); }); context("👉 After raise dispute actions", async function () { @@ -182,22 +200,18 @@ describe("[@skip-on-coverage] DR removes fee", function () { exchangeId = "1"; await expect(disputeHandler.connect(buyer).escalateDispute(exchangeId, { value: buyerEscalationDepositNative })) .to.emit(disputeHandler, "DisputeEscalated") - .withArgs(exchangeId, disputeResolver.id, buyer.address); + .withArgs(exchangeId, disputeResolver.id, await buyer.getAddress()); // Removes fee - await expect( - accountHandler - .connect(adminDR) - .removeFeesFromDisputeResolver(disputeResolver.id, [ethers.constants.AddressZero]) - ) + await expect(accountHandler.connect(adminDR).removeFeesFromDisputeResolver(disputeResolver.id, [ZeroAddress])) .to.emit(accountHandler, "DisputeResolverFeesRemoved") - .withArgs(disputeResolver.id, [ethers.constants.AddressZero], adminDR.address); + .withArgs(disputeResolver.id, [ZeroAddress], await adminDR.getAddress()); // Escalate dispute after removing fee exchangeId = "2"; await expect(disputeHandler.connect(buyer).escalateDispute(exchangeId, { value: buyerEscalationDepositNative })) .to.emit(disputeHandler, "DisputeEscalated") - .withArgs(exchangeId, disputeResolver.id, buyer.address); + .withArgs(exchangeId, disputeResolver.id, await buyer.getAddress()); }); context("👉 After escalate dispute actions", async function () { @@ -222,22 +236,18 @@ describe("[@skip-on-coverage] DR removes fee", function () { // Decide the dispute befor removing fee await expect(disputeHandler.connect(assistantDR).decideDispute(exchangeId, buyerPercentBasisPoints)) .to.emit(disputeHandler, "DisputeDecided") - .withArgs(exchangeId, buyerPercentBasisPoints, assistantDR.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistantDR.getAddress()); // Removes fee - await expect( - accountHandler - .connect(adminDR) - .removeFeesFromDisputeResolver(disputeResolver.id, [ethers.constants.AddressZero]) - ) + await expect(accountHandler.connect(adminDR).removeFeesFromDisputeResolver(disputeResolver.id, [ZeroAddress])) .to.emit(accountHandler, "DisputeResolverFeesRemoved") - .withArgs(disputeResolver.id, [ethers.constants.AddressZero], adminDR.address); + .withArgs(disputeResolver.id, [ZeroAddress], await adminDR.getAddress()); // Decide the dispute after removing fee exchangeId = "2"; await expect(disputeHandler.connect(assistantDR).decideDispute(exchangeId, buyerPercentBasisPoints)) .to.emit(disputeHandler, "DisputeDecided") - .withArgs(exchangeId, buyerPercentBasisPoints, assistantDR.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistantDR.getAddress()); }); it("DR should be able to refuse to decide dispute even when DR removes fee", async function () { @@ -245,22 +255,18 @@ describe("[@skip-on-coverage] DR removes fee", function () { exchangeId = "1"; await expect(disputeHandler.connect(assistantDR).refuseEscalatedDispute(exchangeId)) .to.emit(disputeHandler, "EscalatedDisputeRefused") - .withArgs(exchangeId, assistantDR.address); + .withArgs(exchangeId, await assistantDR.getAddress()); // Removes fee - await expect( - accountHandler - .connect(adminDR) - .removeFeesFromDisputeResolver(disputeResolver.id, [ethers.constants.AddressZero]) - ) + await expect(accountHandler.connect(adminDR).removeFeesFromDisputeResolver(disputeResolver.id, [ZeroAddress])) .to.emit(accountHandler, "DisputeResolverFeesRemoved") - .withArgs(disputeResolver.id, [ethers.constants.AddressZero], adminDR.address); + .withArgs(disputeResolver.id, [ZeroAddress], await adminDR.getAddress()); // Refuse to decide the dispute after removing fee exchangeId = "2"; await expect(disputeHandler.connect(assistantDR).refuseEscalatedDispute(exchangeId)) .to.emit(disputeHandler, "EscalatedDisputeRefused") - .withArgs(exchangeId, assistantDR.address); + .withArgs(exchangeId, await assistantDR.getAddress()); }); }); }); diff --git a/test/integration/seaport/fixtures.js b/test/integration/seaport/fixtures.js index c7a7e0864..c65b4462a 100644 --- a/test/integration/seaport/fixtures.js +++ b/test/integration/seaport/fixtures.js @@ -1,6 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; -const { constants, BigNumber } = ethers; +const { ZeroHash, ZeroAddress } = hre.ethers; const { getOfferOrConsiderationItem, calculateOrderHash } = require("./utils"); const { expect } = require("chai"); const OrderType = require("./OrderTypeEnum"); @@ -10,13 +9,7 @@ const seaportFixtures = async (seaport) => { return getOfferOrConsiderationItem(2, token, identifierOrCriteria, startAmount, endAmount); }; - const getTestToken = function ( - identifierOrCriteria, - token = constants.AddressZero, - startAmount = 1, - endAmount = 1, - recipient - ) { + const getTestToken = function (identifierOrCriteria, token = ZeroAddress, startAmount = 1, endAmount = 1, recipient) { return getOfferOrConsiderationItem(0, token, identifierOrCriteria, startAmount, endAmount, recipient); }; @@ -29,36 +22,36 @@ const seaportFixtures = async (seaport) => { const getOrder = async function ( offerer, - zone = constants.AddressZero, + zone = ZeroAddress, offer, consideration, orderType = OrderType.FULL_OPEN, startTime, endTime, - zoneHash = constants.HashZero, + zoneHash = ZeroHash, salt = 0, - conduitKey = constants.HashZero + conduitKey = ZeroHash ) { const parameters = { - offerer: offerer.address, - zone: zone?.address ?? constants.AddressZero, + offerer: await offerer.getAddress(), + zone: zone?.address ?? ZeroAddress, offer, consideration, orderType, - startTime: BigNumber.from(startTime), - endTime: BigNumber.from(endTime), + startTime: BigInt(startTime), + endTime: BigInt(endTime), zoneHash, - salt: BigNumber.from(salt), + salt: BigInt(salt), conduitKey, - totalOriginalConsiderationItems: BigNumber.from(consideration.length), + totalOriginalConsiderationItems: BigInt(consideration.length), }; - const counter = await seaport.getCounter(offerer.address); + const counter = await seaport.getCounter(await offerer.getAddress()); const orderComponents = { ...parameters, counter }; const orderHash = await getAndVerifyOrderHash(orderComponents); - const signature = constants.HashZero; + const signature = ZeroHash; const order = { parameters, @@ -67,16 +60,12 @@ const seaportFixtures = async (seaport) => { // How much ether (at most) needs to be supplied when fulfilling the order const value = offer - .map((x) => - x.itemType === 0 ? (x.endAmount.gt(x.startAmount) ? x.endAmount : x.startAmount) : BigNumber.from(0) - ) - .reduce((a, b) => a.add(b), BigNumber.from(0)) + .map((x) => (x.itemType === 0 ? (x.endAmount.gt(x.startAmount) ? x.endAmount : x.startAmount) : BigInt(0))) + .reduce((a, b) => a + b, BigInt(0)) .add( consideration - .map((x) => - x.itemType === 0 ? (x.endAmount.gt(x.startAmount) ? x.endAmount : x.startAmount) : BigNumber.from(0) - ) - .reduce((a, b) => a.add(b), BigNumber.from(0)) + .map((x) => (x.itemType === 0 ? (x.endAmount.gt(x.startAmount) ? x.endAmount : x.startAmount) : BigInt(0))) + .reduce((a, b) => a + b, BigInt(0)) ); return { diff --git a/test/integration/seaport/seaport-integration.js b/test/integration/seaport/seaport-integration.js index c8744419c..86d4181c6 100644 --- a/test/integration/seaport/seaport-integration.js +++ b/test/integration/seaport/seaport-integration.js @@ -1,5 +1,5 @@ const { ethers } = require("hardhat"); -const { constants, BigNumber } = ethers; +const { ZeroAddress, BigNumber, getContractAt, ZeroHash } = ethers; const { setupTestEnvironment, getEvent, calculateContractAddress, objectToArray } = require("../../util/utils"); const { SEAPORT_ADDRESS } = require("../../util/constants"); @@ -28,7 +28,7 @@ describe("[@skip-on-coverage] Seaport integration", function () { before(async function () { accountId.next(true); - seaport = await ethers.getContractAt("Seaport", SEAPORT_ADDRESS); + seaport = await getContractAt("Seaport", SEAPORT_ADDRESS); seaportFixtures = await seaportFixtures(seaport); // Specify contracts needed for this test @@ -44,15 +44,26 @@ describe("[@skip-on-coverage] Seaport integration", function () { contractInstances: { accountHandler, offerHandler, fundsHandler }, } = await setupTestEnvironment(contracts)); - const seller = mockSeller(assistant.address, assistant.address, ethers.constants.AddressZero, assistant.address); + const seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + ZeroAddress, + await assistant.getAddress() + ); const emptyAuthToken = mockAuthToken(); const voucherInitValues = mockVoucherInitValues(); await accountHandler.connect(assistant).createSeller(seller, emptyAuthToken, voucherInitValues); - const disputeResolver = mockDisputeResolver(DR.address, DR.address, ethers.constants.AddressZero, DR.address, true); + const disputeResolver = mockDisputeResolver( + await DR.getAddress(), + await DR.getAddress(), + ZeroAddress, + await DR.getAddress(), + true + ); - const disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")]; + const disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", "0")]; const sellerAllowList = []; await accountHandler.connect(DR).createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList); @@ -64,23 +75,25 @@ describe("[@skip-on-coverage] Seaport integration", function () { .connect(assistant) .createOffer(offer.toStruct(), offerDates.toStruct(), offerDurations.toStruct(), disputeResolverId, "0"); - const voucherAddress = calculateContractAddress(accountHandler.address, seller.id); - bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherAddress); + const voucherAddress = calculateContractAddress(await accountHandler.getAddress(), seller.id); + bosonVoucher = await getContractAt("BosonVoucher", voucherAddress); // Pool needs to cover both seller deposit and price - const pool = ethers.BigNumber.from(offer.sellerDeposit).add(offer.price); - await fundsHandler.connect(assistant).depositFunds(seller.id, ethers.constants.AddressZero, pool, { + const pool = BigInt(offer.sellerDeposit) + offer.price; + await fundsHandler.connect(assistant).depositFunds(seller.id, ZeroAddress, pool, { value: pool, }); // Pre mint range - await offerHandler.connect(assistant).reserveRange(offer.id, offer.quantityAvailable, bosonVoucher.address); + await offerHandler + .connect(assistant) + .reserveRange(offer.id, offer.quantityAvailable, await bosonVoucher.getAddress()); await bosonVoucher.connect(assistant).preMint(offer.id, offer.quantityAvailable); // Create seaport offer which tokenId 1 const endDate = "0xff00000000000000000000000000"; - const seaportOffer = seaportFixtures.getTestVoucher(1, bosonVoucher.address, 1, 1); - const consideration = seaportFixtures.getTestToken(0, undefined, 1, 2, bosonVoucher.address); + const seaportOffer = seaportFixtures.getTestVoucher(1, await bosonVoucher.getAddress(), 1, 1); + const consideration = seaportFixtures.getTestToken(0, undefined, 1, 2, await bosonVoucher.getAddress()); ({ order, orderHash, value } = await seaportFixtures.getOrder( bosonVoucher, undefined, @@ -96,7 +109,7 @@ describe("[@skip-on-coverage] Seaport integration", function () { }); it("Voucher contract can be used to call seaport validate", async function () { - const tx = await bosonVoucher.connect(assistant).callExternalContract(seaport.address, calldata); + const tx = await bosonVoucher.connect(assistant).callExternalContract(await seaport.getAddress(), calldata); const receipt = await tx.wait(); const [, orderParameters] = getEvent(receipt, seaport, "OrderValidated"); @@ -105,22 +118,22 @@ describe("[@skip-on-coverage] Seaport integration", function () { }); it("Seaport is allowed to transfer vouchers", async function () { - await bosonVoucher.connect(assistant).callExternalContract(seaport.address, calldata); - await bosonVoucher.connect(assistant).setApprovalForAllToContract(seaport.address, true); + await bosonVoucher.connect(assistant).callExternalContract(await seaport.getAddress(), calldata); + await bosonVoucher.connect(assistant).setApprovalForAllToContract(await seaport.getAddress(), true); let totalFilled, isValidated; ({ isValidated, totalFilled } = await seaport.getOrderStatus(orderHash)); assert(isValidated, "Order is not validated"); - assert.equal(totalFilled.toNumber(), 0); + assert.equal(totalFilled, 0n); - const tx = await seaport.connect(buyer).fulfillOrder(order, constants.HashZero, { value }); + const tx = await seaport.connect(buyer).fulfillOrder(order, ZeroHash, { value }); const receipt = await tx.wait(); const event = getEvent(receipt, seaport, "OrderFulfilled"); ({ totalFilled } = await seaport.getOrderStatus(orderHash)); - assert.equal(totalFilled.toNumber(), 1); + assert.equal(totalFilled, 1n); assert.equal(orderHash, event[0]); }); @@ -131,9 +144,9 @@ describe("[@skip-on-coverage] Seaport integration", function () { const orders = [objectToArray(order)]; calldata = seaport.interface.encodeFunctionData("validate", [orders]); - await expect(bosonVoucher.connect(assistant).callExternalContract(seaport.address, calldata)).to.be.revertedWith( - "0x466aa616" - ); //MissingOriginalConsiderationItems + await expect( + bosonVoucher.connect(assistant).callExternalContract(await seaport.getAddress(), calldata) + ).to.be.revertedWith("0x466aa616"); //MissingOriginalConsiderationItems }); }); }); diff --git a/test/integration/seaport/utils.js b/test/integration/seaport/utils.js index 19fcfc268..04d49f02c 100644 --- a/test/integration/seaport/utils.js +++ b/test/integration/seaport/utils.js @@ -46,9 +46,9 @@ const calculateOrderHash = (orderComponents) => { offerItemTypeHash.slice(2), offerItem.itemType.toString().padStart(64, "0"), offerItem.token.slice(2).padStart(64, "0"), - BigNumber.from(offerItem.identifierOrCriteria).toHexString().slice(2).padStart(64, "0"), - BigNumber.from(offerItem.startAmount).toHexString().slice(2).padStart(64, "0"), - BigNumber.from(offerItem.endAmount).toHexString().slice(2).padStart(64, "0"), + BigNumber.from(offerItem.identifierOrCriteria).toString(16).slice(2).padStart(64, "0"), + BigNumber.from(offerItem.startAmount).toString(16).slice(2).padStart(64, "0"), + BigNumber.from(offerItem.endAmount).toString(16).slice(2).padStart(64, "0"), ].join("") ) .slice(2); @@ -67,9 +67,9 @@ const calculateOrderHash = (orderComponents) => { considerationItemTypeHash.slice(2), considerationItem.itemType.toString().padStart(64, "0"), considerationItem.token.slice(2).padStart(64, "0"), - BigNumber.from(considerationItem.identifierOrCriteria).toHexString().slice(2).padStart(64, "0"), - BigNumber.from(considerationItem.startAmount).toHexString().slice(2).padStart(64, "0"), - BigNumber.from(considerationItem.endAmount).toHexString().slice(2).padStart(64, "0"), + BigNumber.from(considerationItem.identifierOrCriteria).toString(16).slice(2).padStart(64, "0"), + BigNumber.from(considerationItem.startAmount).toString(16).slice(2).padStart(64, "0"), + BigNumber.from(considerationItem.endAmount).toString(16).slice(2).padStart(64, "0"), considerationItem.recipient.slice(2).padStart(64, "0"), ].join("") ) @@ -87,12 +87,12 @@ const calculateOrderHash = (orderComponents) => { offerHash.slice(2), considerationHash.slice(2), orderComponents.orderType.toString().padStart(64, "0"), - BigNumber.from(orderComponents.startTime).toHexString().slice(2).padStart(64, "0"), - BigNumber.from(orderComponents.endTime).toHexString().slice(2).padStart(64, "0"), + BigNumber.from(orderComponents.startTime).toString(16).slice(2).padStart(64, "0"), + BigNumber.from(orderComponents.endTime).toString(16).slice(2).padStart(64, "0"), orderComponents.zoneHash.slice(2), - BigNumber.from(orderComponents.salt).toHexString().slice(2).padStart(64, "0"), + BigNumber.from(orderComponents.salt).toString(16).slice(2).padStart(64, "0"), orderComponents.conduitKey.slice(2).padStart(64, "0"), - BigNumber.from(orderComponents.counter).toHexString().slice(2).padStart(64, "0"), + BigNumber.from(orderComponents.counter).toString(16).slice(2).padStart(64, "0"), ].join("") ); diff --git a/test/protocol/AccountHandlerTest.js b/test/protocol/AccountHandlerTest.js index 590dbee11..a8b230949 100644 --- a/test/protocol/AccountHandlerTest.js +++ b/test/protocol/AccountHandlerTest.js @@ -1,3 +1,5 @@ +const hre = require("hardhat"); +const { ZeroAddress } = hre.ethers; const { expect } = require("chai"); const { DisputeResolverFee } = require("../../scripts/domain/DisputeResolverFee"); @@ -12,7 +14,6 @@ const { accountId, } = require("../util/mock"); const { setupTestEnvironment, getSnapshot, revertToSnapshot } = require("../util/utils"); -const { ethers } = require("hardhat"); /** * Test the Boson Account Handler interface @@ -51,7 +52,7 @@ describe("IBosonAccountHandler", function () { // make all account the same assistant = admin; - clerk = { address: ethers.constants.AddressZero }; + clerk = { address: ZeroAddress }; // Get snapshot id snapshotId = await getSnapshot(); @@ -82,7 +83,12 @@ describe("IBosonAccountHandler", function () { nextAccountId = "1"; // Create a valid seller, then set fields in tests directly - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -94,26 +100,31 @@ describe("IBosonAccountHandler", function () { expect(emptyAuthToken.isValid()).is.true; // Create a valid buyer - buyer = mockBuyer(other1.address); + buyer = mockBuyer(await other1.getAddress()); expect(buyer.isValid()).is.true; // Create a valid dispute resolver - disputeResolver = mockDisputeResolver(assistant.address, admin.address, clerk.address, treasury.address); + disputeResolver = mockDisputeResolver( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array disputeResolverFees = [ - new DisputeResolverFee(other1.address, "MockToken1", "0"), - new DisputeResolverFee(other2.address, "MockToken2", "0"), - new DisputeResolverFee(other3.address, "MockToken3", "0"), + new DisputeResolverFee(await other1.getAddress(), "MockToken1", "0"), + new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0"), + new DisputeResolverFee(await other3.getAddress(), "MockToken3", "0"), ]; // Make a sellerAllowList sellerAllowList = ["1"]; // Create a valid agent, then set fields in tests directly - agent = mockAgent(other1.address); + agent = mockAgent(await other1.getAddress()); expect(agent.isValid()).is.true; }); @@ -148,9 +159,9 @@ describe("IBosonAccountHandler", function () { it("should be incremented after a seller is created", async function () { //addresses need to be unique to seller Id, so setting them to random addresses here - seller.assistant = rando.address; - seller.admin = rando.address; - seller.clerk = ethers.constants.AddressZero; + seller.assistant = await rando.getAddress(); + seller.admin = await rando.getAddress(); + seller.clerk = ZeroAddress; // Create another seller await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); diff --git a/test/protocol/AgentHandlerTest.js b/test/protocol/AgentHandlerTest.js index 1569d530d..1147cec43 100644 --- a/test/protocol/AgentHandlerTest.js +++ b/test/protocol/AgentHandlerTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { ZeroAddress } = hre.ethers; const { expect } = require("chai"); const Agent = require("../../scripts/domain/Agent"); @@ -51,7 +51,7 @@ describe("AgentHandler", function () { invalidAccountId = "666"; // Create a valid agent, then set fields in tests directly - agent = mockAgent(other1.address); + agent = mockAgent(await other1.getAddress()); expect(agent.isValid()).is.true; // How that agent looks as a returned struct @@ -68,7 +68,7 @@ describe("AgentHandler", function () { // Create an agent, testing for the event await expect(accountHandler.connect(rando).createAgent(agent)) .to.emit(accountHandler, "AgentCreated") - .withArgs(agent.id, agentStruct, rando.address); + .withArgs(agent.id, agentStruct, await rando.getAddress()); }); it("should update state", async function () { @@ -93,7 +93,7 @@ describe("AgentHandler", function () { // Create an agent, testing for the event await expect(accountHandler.connect(rando).createAgent(agent)) .to.emit(accountHandler, "AgentCreated") - .withArgs(nextAccountId, agentStruct, rando.address); + .withArgs(nextAccountId, agentStruct, await rando.getAddress()); // wrong agent id should not exist [exists] = await accountHandler.connect(rando).getAgent(agent.id); @@ -115,7 +115,7 @@ describe("AgentHandler", function () { // Create an agent, testing for the event await expect(accountHandler.connect(rando).createAgent(agent)) .to.emit(accountHandler, "AgentCreated") - .withArgs(nextAccountId, agentStruct, rando.address); + .withArgs(nextAccountId, agentStruct, await rando.getAddress()); // Get the agent as a struct [, agentStruct] = await accountHandler.connect(rando).getAgent(agent.id); @@ -141,7 +141,7 @@ describe("AgentHandler", function () { // Create an agent, testing for the event await expect(accountHandler.connect(rando).createAgent(agent)) .to.emit(accountHandler, "AgentCreated") - .withArgs(nextAccountId, agentStruct, rando.address); + .withArgs(nextAccountId, agentStruct, await rando.getAddress()); // Get the agent as a struct [, agentStruct] = await accountHandler.connect(rando).getAgent(agent.id); @@ -172,7 +172,7 @@ describe("AgentHandler", function () { }); it("addresses are the zero address", async function () { - agent.wallet = ethers.constants.AddressZero; + agent.wallet = ZeroAddress; // Attempt to Create an Agent, expecting revert await expect(accountHandler.connect(rando).createAgent(agent)).to.revertedWith(RevertReasons.INVALID_ADDRESS); @@ -212,7 +212,7 @@ describe("AgentHandler", function () { }); it("should emit an AgentUpdated event with correct values if values change", async function () { - agent.wallet = other2.address; + agent.wallet = await other2.getAddress(); agent.active = false; agent.feePercentage = "3000"; //30% expect(agent.isValid()).is.true; @@ -226,18 +226,18 @@ describe("AgentHandler", function () { //Update a agent, testing for the event await expect(accountHandler.connect(other1).updateAgent(agent)) .to.emit(accountHandler, "AgentUpdated") - .withArgs(agent.id, expectedAgentStruct, other1.address); + .withArgs(agent.id, expectedAgentStruct, await other1.getAddress()); }); it("should emit an AgentUpdated event with correct values if values stay the same", async function () { //Update a agent, testing for the event await expect(accountHandler.connect(other1).updateAgent(agent)) .to.emit(accountHandler, "AgentUpdated") - .withArgs(agent.id, agentStruct, other1.address); + .withArgs(agent.id, agentStruct, await other1.getAddress()); }); it("should update state of all fields except Id and active flag", async function () { - agent.wallet = other2.address; + agent.wallet = await other2.getAddress(); agent.active = false; agent.feePercentage = "3000"; //30% expect(agent.isValid()).is.true; @@ -300,7 +300,7 @@ describe("AgentHandler", function () { }); it("should update only wallet address", async function () { - agent.wallet = other2.address; + agent.wallet = await other2.getAddress(); expect(agent.isValid()).is.true; agentStruct = agent.toStruct(); @@ -323,7 +323,7 @@ describe("AgentHandler", function () { it("should update the correct agent", async function () { // Confgiure another agent id2 = nextAccountId++; - agent2 = mockAgent(other3.address); + agent2 = mockAgent(await other3.getAddress()); agent2.id = id2.toString(); expect(agent2.isValid()).is.true; @@ -332,10 +332,10 @@ describe("AgentHandler", function () { //Create agent2, testing for the event await expect(accountHandler.connect(rando).createAgent(agent2)) .to.emit(accountHandler, "AgentCreated") - .withArgs(agent2.id, agent2Struct, rando.address); + .withArgs(agent2.id, agent2Struct, await rando.getAddress()); //Update first agent - agent.wallet = other2.address; + agent.wallet = await other2.getAddress(); agent.feePercentage = "3000"; //30% expect(agent.isValid()).is.true; @@ -366,21 +366,21 @@ describe("AgentHandler", function () { }); it("should be able to only update second time with new wallet address", async function () { - agent.wallet = other2.address; + agent.wallet = await other2.getAddress(); agentStruct = agent.toStruct(); // Update agent, testing for the event await expect(accountHandler.connect(other1).updateAgent(agent)) .to.emit(accountHandler, "AgentUpdated") - .withArgs(agent.id, agentStruct, other1.address); + .withArgs(agent.id, agentStruct, await other1.getAddress()); - agent.wallet = other3.address; + agent.wallet = await other3.getAddress(); agentStruct = agent.toStruct(); // Update agent, testing for the event await expect(accountHandler.connect(other2).updateAgent(agent)) .to.emit(accountHandler, "AgentUpdated") - .withArgs(agent.id, agentStruct, other2.address); + .withArgs(agent.id, agentStruct, await other2.getAddress()); // Attempt to update the agent with original wallet address, expecting revert await expect(accountHandler.connect(other1).updateAgent(agent)).to.revertedWith(RevertReasons.NOT_AGENT_WALLET); @@ -394,7 +394,7 @@ describe("AgentHandler", function () { // Update agent, testing for the event await expect(accountHandler.connect(other1).updateAgent(agent)) .to.emit(accountHandler, "AgentUpdated") - .withArgs(agent.id, agentStruct, other1.address); + .withArgs(agent.id, agentStruct, await other1.getAddress()); // Get the agent as a struct [, agentStruct] = await accountHandler.connect(rando).getAgent(id); @@ -418,7 +418,7 @@ describe("AgentHandler", function () { // Update agent, testing for the event await expect(accountHandler.connect(other1).updateAgent(agent)) .to.emit(accountHandler, "AgentUpdated") - .withArgs(agent.id, agentStruct, other1.address); + .withArgs(agent.id, agentStruct, await other1.getAddress()); // Get the agent as a struct [, agentStruct] = await accountHandler.connect(rando).getAgent(id); @@ -463,7 +463,7 @@ describe("AgentHandler", function () { }); it("wallet address is the zero address", async function () { - agent.wallet = ethers.constants.AddressZero; + agent.wallet = ZeroAddress; // Attempt to update the agent, expecting revert await expect(accountHandler.connect(other1).updateAgent(agent)).to.revertedWith( @@ -486,7 +486,7 @@ describe("AgentHandler", function () { it("wallet address is not unique to this agent Id", async function () { id = await accountHandler.connect(rando).getNextAccountId(); - agent2 = mockAgent(other2.address); + agent2 = mockAgent(await other2.getAddress()); agent2.id = id.toString(); agent2Struct = agent2.toStruct(); @@ -494,10 +494,10 @@ describe("AgentHandler", function () { //Create second agent, testing for the event await expect(accountHandler.connect(rando).createAgent(agent2)) .to.emit(accountHandler, "AgentCreated") - .withArgs(agent2.id, agent2Struct, rando.address); + .withArgs(agent2.id, agent2Struct, await rando.getAddress()); //Set wallet address value to be same as first agent created in Agent Methods beforeEach - agent2.wallet = other1.address; //already being used by agent 1 + agent2.wallet = await other1.getAddress(); //already being used by agent 1 // Attempt to update agent 2 with non-unique wallet address, expecting revert await expect(accountHandler.connect(other2).updateAgent(agent2)).to.revertedWith( diff --git a/test/protocol/BundleHandlerTest.js b/test/protocol/BundleHandlerTest.js index 5fab960e5..f94d644bd 100644 --- a/test/protocol/BundleHandlerTest.js +++ b/test/protocol/BundleHandlerTest.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, getContractFactory, MaxUint256 } = ethers; const { expect, assert } = require("chai"); const Bundle = require("../../scripts/domain/Bundle"); @@ -95,7 +96,7 @@ describe("IBosonBundleHandler", function () { // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; // Deploy the mock tokens [bosonToken] = await deployMockTokens(); @@ -130,7 +131,12 @@ describe("IBosonBundleHandler", function () { agentId = "0"; // agent id is optional while creating an offer // Create a valid seller, then set fields in tests directly - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -145,16 +151,16 @@ describe("IBosonBundleHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed - disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")]; + disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", "0")]; // Make empty seller list, so every seller is allowed const sellerAllowList = []; @@ -167,11 +173,11 @@ describe("IBosonBundleHandler", function () { // create 5 twins for (let i = 0; i < 5; i++) { // Create a valid twin. - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); expect(twin.isValid()).is.true; // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a twin. await twinHandler.connect(assistant).createTwin(twin); @@ -201,7 +207,7 @@ describe("IBosonBundleHandler", function () { bundleStruct = bundle.toStruct(); // initialize bundleHandler - bundleHandlerFacet_Factory = await ethers.getContractFactory("BundleHandlerFacet"); + bundleHandlerFacet_Factory = await getContractFactory("BundleHandlerFacet"); }); afterEach(async function () { @@ -282,19 +288,19 @@ describe("IBosonBundleHandler", function () { expect(bundleInstance.isValid()).to.be.true; //Get seller id by assistant which created the bundle - const [, sellerStruct] = await accountHandler.connect(rando).getSellerByAddress(assistant.address); + const [, sellerStruct] = await accountHandler.connect(rando).getSellerByAddress(await assistant.getAddress()); let expectedSellerId = sellerStruct.id; assert.equal(event.bundleId.toString(), nextBundleId, "Bundle Id is incorrect"); assert.equal(event.sellerId.toString(), expectedSellerId.toString(), "Seller Id is incorrect"); - assert.equal(event.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal(event.executedBy.toString(), await assistant.getAddress(), "Executed by is incorrect"); assert.equal(bundleInstance.toStruct().toString(), bundleStruct.toString(), "Bundle struct is incorrect"); }); it("If sum of offers' quantities is more than maxUint256, total quantity is maxUint256", async function () { // create two offers with close to unlimited supply const newOffer = offer.clone(); - newOffer.quantityAvailable = ethers.constants.MaxUint256.div(10).mul(9).toString(); + newOffer.quantityAvailable = ((MaxUint256 / 10n) * 9n).toString(); const newOffer2 = newOffer.clone(); const newOfferId = "6"; const newOfferId2 = "7"; @@ -308,12 +314,12 @@ describe("IBosonBundleHandler", function () { .createOffer(newOffer2, offerDates, offerDurations, disputeResolverId, agentId); // create a twin with almost unlimited supply - twin = mockTwin(bosonToken.address); - twin.supplyAvailable = ethers.constants.MaxUint256.sub(1).toString(); + twin = mockTwin(await bosonToken.getAddress()); + twin.supplyAvailable = MaxUint256 - 1n; expect(twin.isValid()).is.true; // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, twin.supplyAvailable); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), twin.supplyAvailable); // approving the twin handler // Create a twin with id 6 await twinHandler.connect(assistant).createTwin(twin); @@ -325,12 +331,12 @@ describe("IBosonBundleHandler", function () { ); // create a twin with unlimited supply - twin = mockTwin(bosonToken.address); - twin.supplyAvailable = ethers.constants.MaxUint256.toString(); + twin = mockTwin(await bosonToken.getAddress()); + twin.supplyAvailable = MaxUint256; expect(twin.isValid()).is.true; // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, twin.supplyAvailable); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), twin.supplyAvailable); // approving the twin handler // Create a twin with id 7 await twinHandler.connect(assistant).createTwin(twin); @@ -386,7 +392,12 @@ describe("IBosonBundleHandler", function () { it("Caller is not the seller of all offers", async function () { // create another seller and an offer let expectedNewOfferId = "6"; - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); const tx = await offerHandler @@ -426,10 +437,15 @@ describe("IBosonBundleHandler", function () { it("Caller is not the seller of all twins", async function () { // create another seller and a twin let expectedNewTwinId = "6"; - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); - await bosonToken.connect(rando).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(rando).approve(await twinHandler.getAddress(), 1); // approving the twin handler const tx = await twinHandler.connect(rando).createTwin(twin); // creates a twin with id 6 const txReceipt = await tx.wait(); const event = getEvent(txReceipt, twinHandler, "TwinCreated"); @@ -519,11 +535,13 @@ describe("IBosonBundleHandler", function () { // Deposit seller funds so the commit will succeed await fundsHandler .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerDeposit, { value: sellerDeposit }); + .depositFunds(seller.id, ZeroAddress, sellerDeposit, { value: sellerDeposit }); // Commit to an offer let offerIdToCommit = bundle.offerIds[0]; - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerIdToCommit, { value: price }); + await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerIdToCommit, { value: price }); // Attempt to Create a bundle, expecting revert await expect(bundleHandler.connect(assistant).createBundle(bundle)).to.revertedWith( @@ -564,7 +582,7 @@ describe("IBosonBundleHandler", function () { it("Offers quantity is unlimited but twin supply is not", async function () { const newOffer = offer.clone(); - newOffer.quantityAvailable = ethers.constants.MaxUint256.toString(); + newOffer.quantityAvailable = MaxUint256; let expectedNewOfferId = "6"; await offerHandler @@ -709,7 +727,7 @@ describe("IBosonBundleHandler", function () { context("👉 getBundleIdByTwin()", async function () { beforeEach(async function () { // Create a twin with id 6 - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler await twinHandler.connect(assistant).createTwin(twin); // Create a bundle diff --git a/test/protocol/BuyerHandlerTest.js b/test/protocol/BuyerHandlerTest.js index 9471e1f85..0f11f47ed 100644 --- a/test/protocol/BuyerHandlerTest.js +++ b/test/protocol/BuyerHandlerTest.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { getContractAt, ZeroAddress } = ethers; const { expect } = require("chai"); const Buyer = require("../../scripts/domain/Buyer"); @@ -54,7 +55,7 @@ describe("BuyerHandler", function () { // make all account the same assistant = admin; - clerk = { address: ethers.constants.AddressZero }; + clerk = { address: ZeroAddress }; // Get snapshot id snapshotId = await getSnapshot(); @@ -72,7 +73,7 @@ describe("BuyerHandler", function () { invalidAccountId = "666"; // Create a valid buyer, then set fields in tests directly - buyer = mockBuyer(other1.address); + buyer = mockBuyer(await other1.getAddress()); expect(buyer.isValid()).is.true; // How that buyer looks as a returned struct @@ -89,7 +90,7 @@ describe("BuyerHandler", function () { // Create a buyer, testing for the event await expect(accountHandler.connect(rando).createBuyer(buyer)) .to.emit(accountHandler, "BuyerCreated") - .withArgs(buyer.id, buyerStruct, rando.address); + .withArgs(buyer.id, buyerStruct, await rando.getAddress()); }); it("should update state", async function () { @@ -112,7 +113,7 @@ describe("BuyerHandler", function () { // Create a buyer, testing for the event await expect(accountHandler.connect(rando).createBuyer({ ...buyer, id: invalidAccountId })) .to.emit(accountHandler, "BuyerCreated") - .withArgs(buyer.id, buyerStruct, rando.address); + .withArgs(buyer.id, buyerStruct, await rando.getAddress()); // wrong buyer id should not exist [exists] = await accountHandler.connect(rando).getBuyer(invalidAccountId); @@ -140,7 +141,7 @@ describe("BuyerHandler", function () { }); it("addresses are the zero address", async function () { - buyer.wallet = ethers.constants.AddressZero; + buyer.wallet = ZeroAddress; // Attempt to Create a Buyer, expecting revert await expect(accountHandler.connect(rando).createBuyer(buyer)).to.revertedWith(RevertReasons.INVALID_ADDRESS); @@ -165,7 +166,7 @@ describe("BuyerHandler", function () { }); it("should emit a BuyerUpdated event with correct values if values change", async function () { - buyer.wallet = other2.address; + buyer.wallet = await other2.getAddress(); buyer.active = false; expect(buyer.isValid()).is.true; @@ -178,18 +179,18 @@ describe("BuyerHandler", function () { //Update a buyer, testing for the event await expect(accountHandler.connect(other1).updateBuyer(buyer)) .to.emit(accountHandler, "BuyerUpdated") - .withArgs(buyer.id, expectedBuyerStruct, other1.address); + .withArgs(buyer.id, expectedBuyerStruct, await other1.getAddress()); }); it("should emit a BuyerUpdated event with correct values if values stay the same", async function () { //Update a buyer, testing for the event await expect(accountHandler.connect(other1).updateBuyer(buyer)) .to.emit(accountHandler, "BuyerUpdated") - .withArgs(buyer.id, buyerStruct, other1.address); + .withArgs(buyer.id, buyerStruct, await other1.getAddress()); }); it("should update state of all fields except Id and active flag", async function () { - buyer.wallet = other2.address; + buyer.wallet = await other2.getAddress(); buyer.active = false; expect(buyer.isValid()).is.true; @@ -230,7 +231,7 @@ describe("BuyerHandler", function () { }); it("should update only wallet address", async function () { - buyer.wallet = other2.address; + buyer.wallet = await other2.getAddress(); expect(buyer.isValid()).is.true; buyerStruct = buyer.toStruct(); @@ -252,7 +253,7 @@ describe("BuyerHandler", function () { it("should update the correct buyer", async function () { // Confgiure another buyer - buyer2 = mockBuyer(other3.address); + buyer2 = mockBuyer(await other3.getAddress()); expect(buyer2.isValid()).is.true; buyer2Struct = buyer2.toStruct(); @@ -260,10 +261,10 @@ describe("BuyerHandler", function () { //Create buyer2, testing for the event await expect(accountHandler.connect(rando).createBuyer(buyer2)) .to.emit(accountHandler, "BuyerCreated") - .withArgs(buyer2.id, buyer2Struct, rando.address); + .withArgs(buyer2.id, buyer2Struct, await rando.getAddress()); //Update first buyer - buyer.wallet = other2.address; + buyer.wallet = await other2.getAddress(); expect(buyer.isValid()).is.true; buyerStruct = buyer.toStruct(); @@ -295,21 +296,21 @@ describe("BuyerHandler", function () { }); it("should be able to only update second time with new wallet address", async function () { - buyer.wallet = other2.address; + buyer.wallet = await other2.getAddress(); buyerStruct = buyer.toStruct(); // Update buyer, testing for the event await expect(accountHandler.connect(other1).updateBuyer(buyer)) .to.emit(accountHandler, "BuyerUpdated") - .withArgs(buyer.id, buyerStruct, other1.address); + .withArgs(buyer.id, buyerStruct, await other1.getAddress()); - buyer.wallet = other3.address; + buyer.wallet = await other3.getAddress(); buyerStruct = buyer.toStruct(); // Update buyer, testing for the event await expect(accountHandler.connect(other2).updateBuyer(buyer)) .to.emit(accountHandler, "BuyerUpdated") - .withArgs(buyer.id, buyerStruct, other2.address); + .withArgs(buyer.id, buyerStruct, await other2.getAddress()); // Attempt to update the buyer with original wallet address, expecting revert await expect(accountHandler.connect(other1).updateBuyer(buyer)).to.revertedWith(RevertReasons.NOT_BUYER_WALLET); @@ -323,7 +324,12 @@ describe("BuyerHandler", function () { let agentId = "0"; // agent id is optional while creating an offer // Create a valid seller - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); seller.id = id.toString(); expect(seller.isValid()).is.true; @@ -338,26 +344,26 @@ describe("BuyerHandler", function () { // Create a seller await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); - [exists] = await accountHandler.connect(rando).getSellerByAddress(assistant.address); + [exists] = await accountHandler.connect(rando).getSellerByAddress(await assistant.getAddress()); expect(exists).is.true; // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistant.address, - admin.address, + await assistant.getAddress(), + await admin.getAddress(), clerk.address, - treasury.address, + await treasury.getAddress(), true ); - disputeResolver.id = id.add(1).toString(); + disputeResolver.id = id + 1n; expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array disputeResolverFees = [ - new DisputeResolverFee(other1.address, "MockToken1", "0"), - new DisputeResolverFee(other2.address, "MockToken2", "0"), - new DisputeResolverFee(other3.address, "MockToken3", "0"), - new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0"), + new DisputeResolverFee(await other1.getAddress(), "MockToken1", "0"), + new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0"), + new DisputeResolverFee(await other3.getAddress(), "MockToken3", "0"), + new DisputeResolverFee(ZeroAddress, "Native", "0"), ]; // Add seller to sellerAllowList @@ -387,14 +393,16 @@ describe("BuyerHandler", function () { // Deposit seller funds so the commit will succeed await fundsHandler .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerDeposit, { value: sellerDeposit }); + .depositFunds(seller.id, ZeroAddress, sellerDeposit, { value: sellerDeposit }); //Commit to offer - await exchangeHandler.connect(other1).commitToOffer(other1.address, offerId, { value: offer.price }); + await exchangeHandler + .connect(other1) + .commitToOffer(await other1.getAddress(), offerId, { value: offer.price }); - const bosonVoucherCloneAddress = calculateContractAddress(exchangeHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", bosonVoucherCloneAddress); - const balance = await bosonVoucher.connect(rando).balanceOf(other1.address); + const bosonVoucherCloneAddress = calculateContractAddress(await exchangeHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", bosonVoucherCloneAddress); + const balance = await bosonVoucher.connect(rando).balanceOf(await other1.getAddress()); expect(balance).equal(1); }); @@ -433,7 +441,7 @@ describe("BuyerHandler", function () { }); it("wallet address is the zero address", async function () { - buyer.wallet = ethers.constants.AddressZero; + buyer.wallet = ZeroAddress; // Attempt to update the buyer, expecting revert await expect(accountHandler.connect(other1).updateBuyer(buyer)).to.revertedWith( @@ -444,17 +452,17 @@ describe("BuyerHandler", function () { it("wallet address is unique to this seller Id", async function () { id = await accountHandler.connect(rando).getNextAccountId(); - buyer2 = mockBuyer(other2.address); + buyer2 = mockBuyer(await other2.getAddress()); buyer2.id = id.toString(); buyer2Struct = buyer2.toStruct(); //Create second buyer, testing for the event await expect(accountHandler.connect(rando).createBuyer(buyer2)) .to.emit(accountHandler, "BuyerCreated") - .withArgs(buyer2.id, buyer2Struct, rando.address); + .withArgs(buyer2.id, buyer2Struct, await rando.getAddress()); //Set wallet address value to be same as first buyer created in Buyer Methods beforeEach - buyer2.wallet = other1.address; //already being used by buyer 1 + buyer2.wallet = await other1.getAddress(); //already being used by buyer 1 // Attempt to update buyer 2 with non-unique wallet address, expecting revert await expect(accountHandler.connect(other2).updateBuyer(buyer2)).to.revertedWith( @@ -463,7 +471,7 @@ describe("BuyerHandler", function () { }); it("current buyer wallet address has outstanding vouchers", async function () { - buyer.wallet = other4.address; + buyer.wallet = await other4.getAddress(); // Attempt to update the buyer, expecting revert await expect(accountHandler.connect(other1).updateBuyer(buyer)).to.revertedWith( diff --git a/test/protocol/ConfigHandlerTest.js b/test/protocol/ConfigHandlerTest.js index fe6705d91..23208c321 100644 --- a/test/protocol/ConfigHandlerTest.js +++ b/test/protocol/ConfigHandlerTest.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { getSigners, getContractAt, ZeroAddress, parseUnits } = ethers; const { expect } = require("chai"); const Role = require("../../scripts/domain/Role"); @@ -42,18 +43,18 @@ describe("IBosonConfigHandler", function () { InterfaceIds = await getInterfaceIds(); // Make accounts available - accounts = await ethers.getSigners(); + accounts = await getSigners(); [deployer, rando, token, treasury, beacon, proxy] = accounts; // Deploy the Protocol Diamond [protocolDiamond, , , , accessController] = await deployProtocolDiamond(maxPriorityFeePerGas); // Temporarily grant UPGRADER role to deployer account - await accessController.grantRole(Role.UPGRADER, deployer.address); + await accessController.grantRole(Role.UPGRADER, await deployer.getAddress()); // Set protocol config protocolFeePercentage = 12; - protocolFeeFlatBoson = ethers.utils.parseUnits("0.01", "ether").toString(); + protocolFeeFlatBoson = parseUnits("0.01", "ether").toString(); maxExchangesPerBatch = 100; maxOffersPerGroup = 100; maxTwinsPerBundle = 100; @@ -72,10 +73,10 @@ describe("IBosonConfigHandler", function () { maxPremintedVouchers = 10000; // Cast Diamond to IERC165 - erc165 = await ethers.getContractAt("ERC165Facet", protocolDiamond.address); + erc165 = await getContractAt("ERC165Facet", await protocolDiamond.getAddress()); // Cast Diamond to IBosonConfigHandler - configHandler = await ethers.getContractAt("IBosonConfigHandler", protocolDiamond.address); + configHandler = await getContractAt("IBosonConfigHandler", await protocolDiamond.getAddress()); // Get snapshot id snapshotId = await getSnapshot(); @@ -92,10 +93,10 @@ describe("IBosonConfigHandler", function () { const protocolConfig = [ // Protocol addresses { - token: token.address, - treasury: treasury.address, - voucherBeacon: beacon.address, - beaconProxy: proxy.address, + token: await token.getAddress(), + treasury: await treasury.getAddress(), + voucherBeacon: await beacon.getAddress(), + beaconProxy: await proxy.getAddress(), }, // Protocol limits { @@ -129,94 +130,94 @@ describe("IBosonConfigHandler", function () { // Cut the protocol handler facets into the Diamond const { cutTransaction } = await deployAndCutFacets( - protocolDiamond.address, + await protocolDiamond.getAddress(), facetsToDeploy, maxPriorityFeePerGas ); await expect(cutTransaction) .to.emit(configHandler, "TokenAddressChanged") - .withArgs(token.address, deployer.address); + .withArgs(await token.getAddress(), await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "TreasuryAddressChanged") - .withArgs(treasury.address, deployer.address); + .withArgs(await treasury.getAddress(), await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "VoucherBeaconAddressChanged") - .withArgs(beacon.address, deployer.address); + .withArgs(await beacon.getAddress(), await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "BeaconProxyAddressChanged") - .withArgs(proxy.address, deployer.address); + .withArgs(await proxy.getAddress(), await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "ProtocolFeePercentageChanged") - .withArgs(protocolFeePercentage, deployer.address); + .withArgs(protocolFeePercentage, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "ProtocolFeeFlatBosonChanged") - .withArgs(protocolFeeFlatBoson, deployer.address); + .withArgs(protocolFeeFlatBoson, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxExchangesPerBatchChanged") - .withArgs(maxExchangesPerBatch, deployer.address); + .withArgs(maxExchangesPerBatch, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxOffersPerGroupChanged") - .withArgs(maxOffersPerGroup, deployer.address); + .withArgs(maxOffersPerGroup, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxTwinsPerBundleChanged") - .withArgs(maxTwinsPerBundle, deployer.address); + .withArgs(maxTwinsPerBundle, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxOffersPerBundleChanged") - .withArgs(maxOffersPerBundle, deployer.address); + .withArgs(maxOffersPerBundle, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxOffersPerBatchChanged") - .withArgs(maxOffersPerBatch, deployer.address); + .withArgs(maxOffersPerBatch, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxTokensPerWithdrawalChanged") - .withArgs(maxTokensPerWithdrawal, deployer.address); + .withArgs(maxTokensPerWithdrawal, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxFeesPerDisputeResolverChanged") - .withArgs(maxFeesPerDisputeResolver, deployer.address); + .withArgs(maxFeesPerDisputeResolver, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxEscalationResponsePeriodChanged") - .withArgs(maxEscalationResponsePeriod, deployer.address); + .withArgs(maxEscalationResponsePeriod, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxDisputesPerBatchChanged") - .withArgs(maxDisputesPerBatch, deployer.address); + .withArgs(maxDisputesPerBatch, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxAllowedSellersChanged") - .withArgs(maxAllowedSellers, deployer.address); + .withArgs(maxAllowedSellers, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "BuyerEscalationFeePercentageChanged") - .withArgs(buyerEscalationDepositPercentage, deployer.address); + .withArgs(buyerEscalationDepositPercentage, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxRoyaltyPercentageChanged") - .withArgs(maxRoyaltyPecentage, deployer.address); + .withArgs(maxRoyaltyPecentage, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxResolutionPeriodChanged") - .withArgs(maxResolutionPeriod, deployer.address); + .withArgs(maxResolutionPeriod, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MinDisputePeriodChanged") - .withArgs(minDisputePeriod, deployer.address); + .withArgs(minDisputePeriod, await deployer.getAddress()); await expect(cutTransaction) .to.emit(configHandler, "MaxPremintedVouchersChanged") - .withArgs(maxPremintedVouchers, deployer.address); + .withArgs(maxPremintedVouchers, await deployer.getAddress()); }); }); }); @@ -227,10 +228,10 @@ describe("IBosonConfigHandler", function () { const protocolConfig = [ // Protocol addresses { - treasury: treasury.address, - token: token.address, - voucherBeacon: beacon.address, - beaconProxy: proxy.address, + treasury: await treasury.getAddress(), + token: await token.getAddress(), + voucherBeacon: await beacon.getAddress(), + beaconProxy: await proxy.getAddress(), }, // Protocol limits { @@ -262,7 +263,7 @@ describe("IBosonConfigHandler", function () { const facetsToDeploy = await getFacetsWithArgs(facetNames, protocolConfig); // Cut the protocol handler facets into the Diamond - await deployAndCutFacets(protocolDiamond.address, facetsToDeploy, maxPriorityFeePerGas); + await deployAndCutFacets(await protocolDiamond.getAddress(), facetsToDeploy, maxPriorityFeePerGas); // Update id snapshotId = await getSnapshot(); @@ -294,7 +295,7 @@ describe("IBosonConfigHandler", function () { // Set new max offer per group, testing for the event await expect(configHandler.connect(deployer).setMaxOffersPerGroup(maxOffersPerGroup)) .to.emit(configHandler, "MaxOffersPerGroupChanged") - .withArgs(maxOffersPerGroup, deployer.address); + .withArgs(maxOffersPerGroup, await deployer.getAddress()); }); it("should update state", async function () { @@ -334,7 +335,7 @@ describe("IBosonConfigHandler", function () { // Set new max twin per bundle, testing for the event await expect(configHandler.connect(deployer).setMaxTwinsPerBundle(maxTwinsPerBundle)) .to.emit(configHandler, "MaxTwinsPerBundleChanged") - .withArgs(maxTwinsPerBundle, deployer.address); + .withArgs(maxTwinsPerBundle, await deployer.getAddress()); }); it("should update state", async function () { @@ -374,7 +375,7 @@ describe("IBosonConfigHandler", function () { // Set new max offer per bundle, testing for the event await expect(configHandler.connect(deployer).setMaxOffersPerBundle(maxOffersPerBundle)) .to.emit(configHandler, "MaxOffersPerBundleChanged") - .withArgs(maxOffersPerBundle, deployer.address); + .withArgs(maxOffersPerBundle, await deployer.getAddress()); }); it("should update state", async function () { @@ -414,7 +415,7 @@ describe("IBosonConfigHandler", function () { // Set new max offer per batch, testing for the event await expect(configHandler.connect(deployer).setMaxOffersPerBatch(maxOffersPerBatch)) .to.emit(configHandler, "MaxOffersPerBatchChanged") - .withArgs(maxOffersPerBatch, deployer.address); + .withArgs(maxOffersPerBatch, await deployer.getAddress()); }); it("should update state", async function () { @@ -454,7 +455,7 @@ describe("IBosonConfigHandler", function () { // Set new max tokens per withdrawal, testing for the event await expect(configHandler.connect(deployer).setMaxTokensPerWithdrawal(maxTokensPerWithdrawal)) .to.emit(configHandler, "MaxTokensPerWithdrawalChanged") - .withArgs(maxTokensPerWithdrawal, deployer.address); + .withArgs(maxTokensPerWithdrawal, await deployer.getAddress()); }); it("should update state", async function () { @@ -492,30 +493,30 @@ describe("IBosonConfigHandler", function () { it("should emit a TokenAddressChanged event", async function () { // Set new token address, testing for the event - await expect(configHandler.connect(deployer).setTokenAddress(token.address)) + await expect(configHandler.connect(deployer).setTokenAddress(await token.getAddress())) .to.emit(configHandler, "TokenAddressChanged") - .withArgs(token.address, deployer.address); + .withArgs(await token.getAddress(), await deployer.getAddress()); }); it("should update state", async function () { // Set new token address - await configHandler.connect(deployer).setTokenAddress(token.address); + await configHandler.connect(deployer).setTokenAddress(await token.getAddress()); // Verify that new value is stored - expect(await configHandler.connect(rando).getTokenAddress()).to.equal(token.address); + expect(await configHandler.connect(rando).getTokenAddress()).to.equal(await token.getAddress()); }); context("💔 Revert Reasons", async function () { it("caller is not the admin", async function () { // Attempt to set new token address, expecting revert - await expect(configHandler.connect(rando).setTokenAddress(token.address)).to.revertedWith( + await expect(configHandler.connect(rando).setTokenAddress(await token.getAddress())).to.revertedWith( RevertReasons.ACCESS_DENIED ); }); it("token address is the zero address", async function () { // Attempt to set new token address, expecting revert - await expect(configHandler.connect(deployer).setTokenAddress(ethers.constants.AddressZero)).to.revertedWith( + await expect(configHandler.connect(deployer).setTokenAddress(ZeroAddress)).to.revertedWith( RevertReasons.INVALID_ADDRESS ); }); @@ -531,32 +532,32 @@ describe("IBosonConfigHandler", function () { it("should emit a TreasuryAddressChanged event", async function () { // Set new treasury address, testing for the event - await expect(configHandler.connect(deployer).setTreasuryAddress(treasury.address)) + await expect(configHandler.connect(deployer).setTreasuryAddress(await treasury.getAddress())) .to.emit(configHandler, "TreasuryAddressChanged") - .withArgs(treasury.address, deployer.address); + .withArgs(await treasury.getAddress(), await deployer.getAddress()); }); it("should update state", async function () { // Set new treasury address - await configHandler.connect(deployer).setTreasuryAddress(treasury.address); + await configHandler.connect(deployer).setTreasuryAddress(await treasury.getAddress()); // Verify that new value is stored - expect(await configHandler.connect(rando).getTreasuryAddress()).to.equal(treasury.address); + expect(await configHandler.connect(rando).getTreasuryAddress()).to.equal(await treasury.getAddress()); }); context("💔 Revert Reasons", async function () { it("caller is not the admin", async function () { // Attempt to set new treasury address, expecting revert - await expect(configHandler.connect(rando).setTreasuryAddress(treasury.address)).to.revertedWith( + await expect(configHandler.connect(rando).setTreasuryAddress(await treasury.getAddress())).to.revertedWith( RevertReasons.ACCESS_DENIED ); }); it("treasury address is the zero address", async function () { // Attempt to set new treasury address, expecting revert - await expect( - configHandler.connect(deployer).setTreasuryAddress(ethers.constants.AddressZero) - ).to.revertedWith(RevertReasons.INVALID_ADDRESS); + await expect(configHandler.connect(deployer).setTreasuryAddress(ZeroAddress)).to.revertedWith( + RevertReasons.INVALID_ADDRESS + ); }); }); }); @@ -570,32 +571,32 @@ describe("IBosonConfigHandler", function () { it("should emit a VoucherAddressChanged event", async function () { // Set new beacon address, testing for the event - await expect(configHandler.connect(deployer).setVoucherBeaconAddress(beacon.address)) + await expect(configHandler.connect(deployer).setVoucherBeaconAddress(await beacon.getAddress())) .to.emit(configHandler, "VoucherBeaconAddressChanged") - .withArgs(beacon.address, deployer.address); + .withArgs(await beacon.getAddress(), await deployer.getAddress()); }); it("should update state", async function () { // Set new beacon address - await configHandler.connect(deployer).setVoucherBeaconAddress(beacon.address); + await configHandler.connect(deployer).setVoucherBeaconAddress(await beacon.getAddress()); // Verify that new value is stored - expect(await configHandler.connect(rando).getVoucherBeaconAddress()).to.equal(beacon.address); + expect(await configHandler.connect(rando).getVoucherBeaconAddress()).to.equal(await beacon.getAddress()); }); context("💔 Revert Reasons", async function () { it("caller is not the admin", async function () { // Attempt to set new beacon address, expecting revert - await expect(configHandler.connect(rando).setVoucherBeaconAddress(beacon.address)).to.revertedWith( - RevertReasons.ACCESS_DENIED - ); + await expect( + configHandler.connect(rando).setVoucherBeaconAddress(await beacon.getAddress()) + ).to.revertedWith(RevertReasons.ACCESS_DENIED); }); it("voucher beacon address is the zero address", async function () { // Attempt to set new beacon address, expecting revert - await expect( - configHandler.connect(deployer).setVoucherBeaconAddress(ethers.constants.AddressZero) - ).to.revertedWith(RevertReasons.INVALID_ADDRESS); + await expect(configHandler.connect(deployer).setVoucherBeaconAddress(ZeroAddress)).to.revertedWith( + RevertReasons.INVALID_ADDRESS + ); }); }); }); @@ -609,32 +610,32 @@ describe("IBosonConfigHandler", function () { it("should emit a VoucherAddressChanged event", async function () { // Set new proxy address, testing for the event - await expect(configHandler.connect(deployer).setBeaconProxyAddress(proxy.address)) + await expect(configHandler.connect(deployer).setBeaconProxyAddress(await proxy.getAddress())) .to.emit(configHandler, "BeaconProxyAddressChanged") - .withArgs(proxy.address, deployer.address); + .withArgs(await proxy.getAddress(), await deployer.getAddress()); }); it("should update state", async function () { // Set new proxy address - await configHandler.connect(deployer).setBeaconProxyAddress(proxy.address); + await configHandler.connect(deployer).setBeaconProxyAddress(await proxy.getAddress()); // Verify that new value is stored - expect(await configHandler.connect(rando).getBeaconProxyAddress()).to.equal(proxy.address); + expect(await configHandler.connect(rando).getBeaconProxyAddress()).to.equal(await proxy.getAddress()); }); context("💔 Revert Reasons", async function () { it("caller is not the admin", async function () { // Attempt to set new proxy address, expecting revert - await expect(configHandler.connect(rando).setBeaconProxyAddress(proxy.address)).to.revertedWith( + await expect(configHandler.connect(rando).setBeaconProxyAddress(await proxy.getAddress())).to.revertedWith( RevertReasons.ACCESS_DENIED ); }); it("beacon proxy address is the zero address", async function () { // Attempt to set new proxy address, expecting revert - await expect( - configHandler.connect(deployer).setBeaconProxyAddress(ethers.constants.AddressZero) - ).to.revertedWith(RevertReasons.INVALID_ADDRESS); + await expect(configHandler.connect(deployer).setBeaconProxyAddress(ZeroAddress)).to.revertedWith( + RevertReasons.INVALID_ADDRESS + ); }); }); }); @@ -650,7 +651,7 @@ describe("IBosonConfigHandler", function () { // Set new protocol fee precentage address, testing for the event await expect(configHandler.connect(deployer).setProtocolFeePercentage(protocolFeePercentage)) .to.emit(configHandler, "ProtocolFeePercentageChanged") - .withArgs(protocolFeePercentage, deployer.address); + .withArgs(protocolFeePercentage, await deployer.getAddress()); }); it("should update state", async function () { @@ -683,14 +684,14 @@ describe("IBosonConfigHandler", function () { let protocolFeeFlatBoson; beforeEach(async function () { // set new value for flat boson protocol fee - protocolFeeFlatBoson = ethers.utils.parseUnits("0.02", "ether").toString(); + protocolFeeFlatBoson = parseUnits("0.02", "ether").toString(); }); it("should emit a ProtocolFeeFlatBosonChanged event", async function () { // Set new flat boson protocol feel, testing for the event await expect(configHandler.connect(deployer).setProtocolFeeFlatBoson(protocolFeeFlatBoson)) .to.emit(configHandler, "ProtocolFeeFlatBosonChanged") - .withArgs(protocolFeeFlatBoson, deployer.address); + .withArgs(protocolFeeFlatBoson, await deployer.getAddress()); }); it("should update state", async function () { @@ -722,7 +723,7 @@ describe("IBosonConfigHandler", function () { // Set new max disputes per batch, testing for the event await expect(configHandler.connect(deployer).setMaxDisputesPerBatch(maxDisputesPerBatch)) .to.emit(configHandler, "MaxDisputesPerBatchChanged") - .withArgs(maxDisputesPerBatch, deployer.address); + .withArgs(maxDisputesPerBatch, await deployer.getAddress()); }); it("should update state", async function () { @@ -762,7 +763,7 @@ describe("IBosonConfigHandler", function () { // Set max fees per dispute resolver await expect(configHandler.connect(deployer).setMaxFeesPerDisputeResolver(maxFeesPerDisputeResolver)) .to.emit(configHandler, "MaxFeesPerDisputeResolverChanged") - .withArgs(maxFeesPerDisputeResolver, deployer.address); + .withArgs(maxFeesPerDisputeResolver, await deployer.getAddress()); }); it("should update state", async function () { @@ -794,14 +795,14 @@ describe("IBosonConfigHandler", function () { let maxEscalationResponsePeriod; beforeEach(async function () { // set new value - maxEscalationResponsePeriod = ethers.BigNumber.from(oneMonth).add(oneWeek); + maxEscalationResponsePeriod = oneMonth + oneWeek; }); it("should emit a MaxEscalationResponsePeriodChanged event", async function () { // Set new escalation response period await expect(configHandler.connect(deployer).setMaxEscalationResponsePeriod(maxEscalationResponsePeriod)) .to.emit(configHandler, "MaxEscalationResponsePeriodChanged") - .withArgs(maxEscalationResponsePeriod, deployer.address); + .withArgs(maxEscalationResponsePeriod, await deployer.getAddress()); }); it("should update state", async function () { @@ -844,7 +845,7 @@ describe("IBosonConfigHandler", function () { configHandler.connect(deployer).setBuyerEscalationDepositPercentage(buyerEscalationDepositPercentage) ) .to.emit(configHandler, "BuyerEscalationFeePercentageChanged") - .withArgs(buyerEscalationDepositPercentage, deployer.address); + .withArgs(buyerEscalationDepositPercentage, await deployer.getAddress()); }); it("should update state", async function () { @@ -886,7 +887,7 @@ describe("IBosonConfigHandler", function () { // Set new max allowed sellers, testing for the event await expect(configHandler.connect(deployer).setMaxAllowedSellers(maxAllowedSellers)) .to.emit(configHandler, "MaxAllowedSellersChanged") - .withArgs(maxAllowedSellers, deployer.address); + .withArgs(maxAllowedSellers, await deployer.getAddress()); }); it("should update state", async function () { @@ -925,7 +926,7 @@ describe("IBosonConfigHandler", function () { // set new value for Max Total Offer Fee Percentage, testing for the event await expect(configHandler.connect(deployer).setMaxTotalOfferFeePercentage(maxTotalOfferFeePercentage)) .to.emit(configHandler, "MaxTotalOfferFeePercentageChanged") - .withArgs(maxTotalOfferFeePercentage, deployer.address); + .withArgs(maxTotalOfferFeePercentage, await deployer.getAddress()); }); it("should update state", async function () { @@ -967,7 +968,7 @@ describe("IBosonConfigHandler", function () { // set new value for Max Royalty Percentage, testing for the event await expect(configHandler.connect(deployer).setMaxRoyaltyPecentage(maxRoyaltyPecentage)) .to.emit(configHandler, "MaxRoyaltyPercentageChanged") - .withArgs(maxRoyaltyPecentage, deployer.address); + .withArgs(maxRoyaltyPecentage, await deployer.getAddress()); }); it("should update state", async function () { @@ -1013,19 +1014,23 @@ describe("IBosonConfigHandler", function () { it("should emit an AuthTokenContractChanged event", async function () { // Set new auth token contract, testing for the event await expect( - configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.Lens, authTokenContract.address) + configHandler + .connect(deployer) + .setAuthTokenContract(AuthTokenType.Lens, await authTokenContract.getAddress()) ) .to.emit(configHandler, "AuthTokenContractChanged") - .withArgs(AuthTokenType.Lens, authTokenContract.address, deployer.address); + .withArgs(AuthTokenType.Lens, await authTokenContract.getAddress(), await deployer.getAddress()); }); it("should update state", async function () { // Set new auth token contract, - await configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.ENS, authTokenContract.address); + await configHandler + .connect(deployer) + .setAuthTokenContract(AuthTokenType.ENS, await authTokenContract.getAddress()); // Verify that new value is stored expect(await configHandler.connect(rando).getAuthTokenContract(AuthTokenType.ENS)).to.equal( - authTokenContract.address + await authTokenContract.getAddress() ); }); @@ -1033,28 +1038,32 @@ describe("IBosonConfigHandler", function () { it("caller is not the admin", async function () { // Attempt to set new auth token contract, expecting revert await expect( - configHandler.connect(rando).setAuthTokenContract(AuthTokenType.ENS, authTokenContract.address) + configHandler.connect(rando).setAuthTokenContract(AuthTokenType.ENS, await authTokenContract.getAddress()) ).to.revertedWith(RevertReasons.ACCESS_DENIED); }); it("_authTokenType is None", async function () { // Attempt to set new auth token contract, expecting revert await expect( - configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.None, authTokenContract.address) + configHandler + .connect(deployer) + .setAuthTokenContract(AuthTokenType.None, await authTokenContract.getAddress()) ).to.revertedWith(RevertReasons.INVALID_AUTH_TOKEN_TYPE); }); it("_authTokenType is Custom", async function () { // Attempt to set new auth token contract, expecting revert await expect( - configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.Custom, authTokenContract.address) + configHandler + .connect(deployer) + .setAuthTokenContract(AuthTokenType.Custom, await authTokenContract.getAddress()) ).to.revertedWith(RevertReasons.INVALID_AUTH_TOKEN_TYPE); }); it("_authTokenContract is the zero address", async function () { // Attempt to set new auth token contract, expecting revert await expect( - configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.ENS, ethers.constants.AddressZero) + configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.ENS, ZeroAddress) ).to.revertedWith(RevertReasons.INVALID_ADDRESS); }); }); @@ -1071,7 +1080,7 @@ describe("IBosonConfigHandler", function () { // Set new max exchange per batch, testing for the event await expect(configHandler.connect(deployer).setMaxExchangesPerBatch(maxExchangesPerBatch)) .to.emit(configHandler, "MaxExchangesPerBatchChanged") - .withArgs(maxExchangesPerBatch, deployer.address); + .withArgs(maxExchangesPerBatch, await deployer.getAddress()); }); it("should update state", async function () { @@ -1103,14 +1112,14 @@ describe("IBosonConfigHandler", function () { let maxResolutionPeriod; beforeEach(async function () { // set new value - maxResolutionPeriod = ethers.BigNumber.from(oneMonth).add(oneWeek); + maxResolutionPeriod = oneMonth + oneWeek; }); it("should emit a MaxResolutionPeriodChanged event", async function () { // Set new resolution period await expect(configHandler.connect(deployer).setMaxResolutionPeriod(maxResolutionPeriod)) .to.emit(configHandler, "MaxResolutionPeriodChanged") - .withArgs(maxResolutionPeriod, deployer.address); + .withArgs(maxResolutionPeriod, await deployer.getAddress()); }); it("should update state", async function () { @@ -1142,14 +1151,14 @@ describe("IBosonConfigHandler", function () { let minDisputePeriod; beforeEach(async function () { // set new value - minDisputePeriod = ethers.BigNumber.from(oneMonth).sub(oneWeek); + minDisputePeriod = oneMonth - oneWeek; }); it("should emit a MinDisputePeriodChanged event", async function () { // Set new minumum dispute period await expect(configHandler.connect(deployer).setMinDisputePeriod(minDisputePeriod)) .to.emit(configHandler, "MinDisputePeriodChanged") - .withArgs(minDisputePeriod, deployer.address); + .withArgs(minDisputePeriod, await deployer.getAddress()); }); it("should update state", async function () { @@ -1188,7 +1197,7 @@ describe("IBosonConfigHandler", function () { // Set new minumum dispute period await expect(configHandler.connect(deployer).setMaxPremintedVouchers(maxPremintedVouchers)) .to.emit(configHandler, "MaxPremintedVouchersChanged") - .withArgs(maxPremintedVouchers, deployer.address); + .withArgs(maxPremintedVouchers, await deployer.getAddress()); }); it("should update state", async function () { @@ -1225,32 +1234,36 @@ describe("IBosonConfigHandler", function () { it("should emit an AccessControllerAddressChanged event", async function () { // Set new access controller address - await expect(configHandler.connect(deployer).setAccessControllerAddress(newAccessController.address)) + await expect( + configHandler.connect(deployer).setAccessControllerAddress(await newAccessController.getAddress()) + ) .to.emit(configHandler, "AccessControllerAddressChanged") - .withArgs(newAccessController.address, deployer.address); + .withArgs(await newAccessController.getAddress(), await deployer.getAddress()); }); it("should update state", async function () { // Set new access controller address - await configHandler.connect(deployer).setAccessControllerAddress(newAccessController.address); + await configHandler.connect(deployer).setAccessControllerAddress(await newAccessController.getAddress()); // Verify that new value is stored - expect(await configHandler.connect(rando).getAccessControllerAddress()).to.equal(newAccessController.address); + expect(await configHandler.connect(rando).getAccessControllerAddress()).to.equal( + await newAccessController.getAddress() + ); }); context("💔 Revert Reasons", async function () { it("caller is not the admin", async function () { // Attempt to set new value, expecting revert await expect( - configHandler.connect(rando).setAccessControllerAddress(newAccessController.address) + configHandler.connect(rando).setAccessControllerAddress(await newAccessController.getAddress()) ).to.revertedWith(RevertReasons.ACCESS_DENIED); }); it("_accessControllerAddress is the zero address", async function () { // Attempt to set new value, expecting revert - await expect( - configHandler.connect(deployer).setAccessControllerAddress(ethers.constants.AddressZero) - ).to.revertedWith(RevertReasons.INVALID_ADDRESS); + await expect(configHandler.connect(deployer).setAccessControllerAddress(ZeroAddress)).to.revertedWith( + RevertReasons.INVALID_ADDRESS + ); }); }); }); @@ -1263,16 +1276,19 @@ describe("IBosonConfigHandler", function () { it("Initial values are correct", async function () { // Verify that initial values matches those in constructor expect(await configHandler.connect(rando).getTreasuryAddress()).to.equal( - treasury.address, + await treasury.getAddress(), "Invalid treasury address" ); - expect(await configHandler.connect(rando).getTokenAddress()).to.equal(token.address, "Invalid token address"); + expect(await configHandler.connect(rando).getTokenAddress()).to.equal( + await token.getAddress(), + "Invalid token address" + ); expect(await configHandler.connect(rando).getVoucherBeaconAddress()).to.equal( - beacon.address, + await beacon.getAddress(), "Invalid voucher address" ); expect(await configHandler.connect(rando).getBeaconProxyAddress()).to.equal( - proxy.address, + await proxy.getAddress(), "Invalid voucher address" ); expect(await configHandler.connect(rando).getProtocolFeePercentage()).to.equal( @@ -1333,15 +1349,15 @@ describe("IBosonConfigHandler", function () { ); //setAuthTokenContract is not called in the initialize function expect(await configHandler.connect(rando).getAuthTokenContract(AuthTokenType.Lens)).to.equal( - ethers.constants.AddressZero, + ZeroAddress, "Invalid auth token contract address" ); expect(await configHandler.connect(rando).getAuthTokenContract(AuthTokenType.ENS)).to.equal( - ethers.constants.AddressZero, + ZeroAddress, "Invalid auth token contract address" ); expect(await configHandler.connect(rando).getAuthTokenContract(AuthTokenType.Custom)).to.equal( - ethers.constants.AddressZero, + ZeroAddress, "Invalid auth token contract address" ); expect(await configHandler.connect(rando).getMaxExchangesPerBatch()).to.equal( diff --git a/test/protocol/DisputeHandlerTest.js b/test/protocol/DisputeHandlerTest.js index 4e6dac311..16b53c529 100644 --- a/test/protocol/DisputeHandlerTest.js +++ b/test/protocol/DisputeHandlerTest.js @@ -1,6 +1,6 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, provider, zeroPadBytes, MaxUint256, parseUnits } = ethers; const { expect, assert } = require("chai"); - const Exchange = require("../../scripts/domain/Exchange"); const Dispute = require("../../scripts/domain/Dispute"); const DisputeState = require("../../scripts/domain/DisputeState"); @@ -9,6 +9,7 @@ const { DisputeResolverFee } = require("../../scripts/domain/DisputeResolverFee" const PausableRegion = require("../../scripts/domain/PausableRegion.js"); const { getInterfaceIds } = require("../../scripts/config/supported-interfaces.js"); const { RevertReasons } = require("../../scripts/config/revert-reasons.js"); +const { toHexString } = require("../../scripts/util/utils.js"); const { deployMockTokens } = require("../../scripts/util/deploy-mock-tokens"); const { setNextBlockTimestamp, @@ -117,7 +118,7 @@ describe("IBosonDisputeHandler", function () { // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; // Get snapshot id snapshotId = await getSnapshot(); @@ -149,7 +150,12 @@ describe("IBosonDisputeHandler", function () { agentId = "0"; // agent id is optional while creating an offer // Create a valid seller - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -164,17 +170,17 @@ describe("IBosonDisputeHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed DRFeeNative = "0"; - disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", DRFeeNative)]; + disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", DRFeeNative)]; // Make empty seller list, so every seller is allowed const sellerAllowList = []; @@ -209,10 +215,10 @@ describe("IBosonDisputeHandler", function () { escalationPeriod = disputeResolver.escalationResponsePeriod; // Deposit seller funds so the commit will succeed - const fundsToDeposit = ethers.BigNumber.from(sellerDeposit).mul(quantityAvailable); + const fundsToDeposit = BigInt(sellerDeposit) * BigInt(quantityAvailable); await fundsHandler .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, fundsToDeposit, { value: fundsToDeposit }); + .depositFunds(seller.id, ZeroAddress, fundsToDeposit, { value: fundsToDeposit }); buyerId = accountId.next().value; }); @@ -227,7 +233,7 @@ describe("IBosonDisputeHandler", function () { exchangeId = "1"; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(voucherRedeemableFrom)); @@ -244,7 +250,7 @@ describe("IBosonDisputeHandler", function () { // Raise a dispute, testing for the event await expect(disputeHandler.connect(buyer).raiseDispute(exchangeId)) .to.emit(disputeHandler, "DisputeRaised") - .withArgs(exchangeId, buyerId, seller.id, buyer.address); + .withArgs(exchangeId, buyerId, seller.id, await buyer.getAddress()); }); it("should update state", async function () { @@ -253,13 +259,13 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); - disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + block = await provider.getBlock(blockNumber); + disputedDate = block.timestamp; + timeout = BigInt(disputedDate) + BigInt(resolutionPeriod); // expected values dispute = new Dispute(exchangeId, DisputeState.Resolving, buyerPercentBasisPoints); - disputeDates = new DisputeDates(disputedDate, "0", "0", timeout); + disputeDates = new DisputeDates(disputedDate.toString(), "0", "0", timeout.toString()); // Get the dispute as a struct [, disputeStruct, disputeDatesStruct] = await disputeHandler.connect(rando).getDispute(exchangeId); @@ -306,8 +312,8 @@ describe("IBosonDisputeHandler", function () { }); it("exchange is not in a redeemed state - completed", async function () { - const blockNumber = await ethers.provider.getBlockNumber(); - const block = await ethers.provider.getBlock(blockNumber); + const blockNumber = await provider.getBlockNumber(); + const block = await provider.getBlock(blockNumber); const currentTime = block.timestamp; // Set time forward to run out the dispute period @@ -344,7 +350,7 @@ describe("IBosonDisputeHandler", function () { const voucherRedeemedDate = voucherStruct.redeemedDate; // Set time forward past the dispute period - await setNextBlockTimestamp(voucherRedeemedDate.add(disputePeriod).add(1).toNumber()); + await setNextBlockTimestamp(Number(voucherRedeemedDate + BigInt(disputePeriod) + 1n)); // Attempt to raise a dispute, expecting revert await expect(disputeHandler.connect(buyer).raiseDispute(exchangeId)).to.revertedWith( @@ -361,16 +367,16 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = BigInt(disputedDate) + BigInt(resolutionPeriod); }); it("should emit a DisputeRetracted event", async function () { // Retract the dispute, testing for the event await expect(disputeHandler.connect(buyer).retractDispute(exchangeId)) .to.emit(disputeHandler, "DisputeRetracted") - .withArgs(exchangeId, buyer.address); + .withArgs(exchangeId, await buyer.getAddress()); }); it("should update state", async function () { @@ -379,7 +385,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set finalizedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); finalizedDate = block.timestamp.toString(); dispute = new Dispute(exchangeId, DisputeState.Retracted, buyerPercentBasisPoints); @@ -424,7 +430,7 @@ describe("IBosonDisputeHandler", function () { // Retract the dispute, testing for the event await expect(disputeHandler.connect(buyer).retractDispute(exchangeId)) .to.emit(disputeHandler, "DisputeRetracted") - .withArgs(exchangeId, buyer.address); + .withArgs(exchangeId, await buyer.getAddress()); }); context("💔 Revert Reasons", async function () { @@ -452,7 +458,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Attempt to retract the dispute, expecting revert await expect(disputeHandler.connect(buyer).retractDispute(exchangeId)).to.revertedWith( @@ -484,7 +490,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); escalatedDate = block.timestamp.toString(); await setNextBlockTimestamp(Number(escalatedDate) + Number(escalationPeriod)); @@ -503,19 +509,19 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = BigInt(disputedDate) + BigInt(resolutionPeriod); // extend timeout for a month - newDisputeTimeout = ethers.BigNumber.from(timeout).add(oneMonth).toString(); + newDisputeTimeout = BigInt(timeout) + oneMonth; }); it("should emit a DisputeTimeoutExtended event", async function () { // Extend the dispute timeout, testing for the event await expect(disputeHandler.connect(assistant).extendDisputeTimeout(exchangeId, newDisputeTimeout)) .to.emit(disputeHandler, "DisputeTimeoutExtended") - .withArgs(exchangeId, newDisputeTimeout, assistant.address); + .withArgs(exchangeId, newDisputeTimeout, await assistant.getAddress()); }); it("should update state", async function () { @@ -555,12 +561,12 @@ describe("IBosonDisputeHandler", function () { await setNextBlockTimestamp(Number(timeout) + Number(oneWeek)); // extend for another week - newDisputeTimeout = ethers.BigNumber.from(newDisputeTimeout).add(oneWeek).toString(); + newDisputeTimeout = BigInt(newDisputeTimeout) + oneWeek; // Extend the dispute timeout, testing for the event await expect(disputeHandler.connect(assistant).extendDisputeTimeout(exchangeId, newDisputeTimeout)) .to.emit(disputeHandler, "DisputeTimeoutExtended") - .withArgs(exchangeId, newDisputeTimeout, assistant.address); + .withArgs(exchangeId, newDisputeTimeout, await assistant.getAddress()); }); context("💔 Revert Reasons", async function () { @@ -588,7 +594,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Attempt to extend the dispute timeout, expecting revert await expect( @@ -614,7 +620,7 @@ describe("IBosonDisputeHandler", function () { }); it("new dispute timeout is before the current dispute timeout", async function () { - newDisputeTimeout = ethers.BigNumber.from(timeout).sub(oneWeek).toString(); + newDisputeTimeout = BigInt(timeout) - oneWeek; // Attempt to extend the dispute timeout, expecting revert await expect( @@ -641,9 +647,9 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = BigInt(disputedDate) + BigInt(resolutionPeriod); }); it("should emit a DisputeExpired event", async function () { @@ -653,7 +659,7 @@ describe("IBosonDisputeHandler", function () { // Expire the dispute, testing for the event await expect(disputeHandler.connect(rando).expireDispute(exchangeId)) .to.emit(disputeHandler, "DisputeExpired") - .withArgs(exchangeId, rando.address); + .withArgs(exchangeId, await rando.getAddress()); }); it("should update state", async function () { @@ -665,7 +671,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set finalizedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); finalizedDate = block.timestamp.toString(); dispute = new Dispute(exchangeId, DisputeState.Retracted, buyerPercentBasisPoints); @@ -731,7 +737,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Attempt to expire the dispute, expecting revert await expect(disputeHandler.connect(rando).expireDispute(exchangeId)).to.revertedWith( @@ -780,9 +786,9 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = BigInt(disputedDate) + BigInt(resolutionPeriod); buyerPercentBasisPoints = "1234"; @@ -810,7 +816,7 @@ describe("IBosonDisputeHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() )); }); @@ -818,7 +824,7 @@ describe("IBosonDisputeHandler", function () { // Resolve the dispute, testing for the event await expect(disputeHandler.connect(buyer).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, buyer.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await buyer.getAddress()); }); it("should update state", async function () { @@ -827,7 +833,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set finalizedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); finalizedDate = block.timestamp.toString(); dispute = new Dispute(exchangeId, DisputeState.Resolved, buyerPercentBasisPoints); @@ -867,7 +873,12 @@ describe("IBosonDisputeHandler", function () { it("Buyer can also have a seller account and this will work", async function () { // Create a valid seller with buyer's wallet - seller = mockSeller(buyer.address, buyer.address, ethers.constants.AddressZero, buyer.address); + seller = mockSeller( + await buyer.getAddress(), + await buyer.getAddress(), + ZeroAddress, + await buyer.getAddress() + ); expect(seller.isValid()).is.true; await accountHandler.connect(buyer).createSeller(seller, emptyAuthToken, voucherInitValues); @@ -875,7 +886,7 @@ describe("IBosonDisputeHandler", function () { // Resolve the dispute, testing for the event await expect(disputeHandler.connect(buyer).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, buyer.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await buyer.getAddress()); }); it("Dispute can be mutually resolved even if it's in escalated state", async function () { @@ -885,16 +896,12 @@ describe("IBosonDisputeHandler", function () { // Resolve the dispute, testing for the event await expect(disputeHandler.connect(buyer).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, buyer.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await buyer.getAddress()); }); it("Dispute can be mutually resolved even if it's in escalated state and past the resolution period", async function () { // Set time forward before the dispute original expiration date - await setNextBlockTimestamp( - ethers.BigNumber.from(disputedDate) - .add(resolutionPeriod / 2) - .toNumber() - ); + await setNextBlockTimestamp(Number(BigInt(disputedDate) + BigInt(resolutionPeriod) / 2n)); // escalate dispute await disputeHandler.connect(buyer).escalateDispute(exchangeId, { value: buyerEscalationDepositNative }); @@ -905,7 +912,7 @@ describe("IBosonDisputeHandler", function () { // Resolve the dispute, testing for the event await expect(disputeHandler.connect(buyer).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, buyer.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await buyer.getAddress()); }); it("Dispute can be mutually resolved if it's past original timeout, but it was extended", async function () { @@ -920,7 +927,7 @@ describe("IBosonDisputeHandler", function () { // Resolve the dispute, testing for the event await expect(disputeHandler.connect(buyer).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, buyer.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await buyer.getAddress()); }); }); @@ -932,7 +939,7 @@ describe("IBosonDisputeHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() )); }); @@ -940,7 +947,7 @@ describe("IBosonDisputeHandler", function () { // Resolve the dispute, testing for the event await expect(disputeHandler.connect(assistant).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, assistant.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistant.getAddress()); }); it("should update state", async function () { @@ -949,7 +956,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set finalizedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); finalizedDate = block.timestamp.toString(); dispute = new Dispute(exchangeId, DisputeState.Resolved, buyerPercentBasisPoints); @@ -989,14 +996,14 @@ describe("IBosonDisputeHandler", function () { it("Assistant can also have a buyer account and this will work", async function () { // Create a valid buyer with assistant's wallet - let buyer = mockBuyer(assistant.address); + let buyer = mockBuyer(await assistant.getAddress()); expect(buyer.isValid()).is.true; await accountHandler.connect(assistant).createBuyer(buyer); // Resolve the dispute, testing for the event await expect(disputeHandler.connect(assistant).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, assistant.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistant.getAddress()); }); it("Dispute can be mutually resolved even if it's in escalated state", async function () { @@ -1006,16 +1013,12 @@ describe("IBosonDisputeHandler", function () { // Resolve the dispute, testing for the event await expect(disputeHandler.connect(assistant).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, assistant.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistant.getAddress()); }); it("Dispute can be mutually resolved even if it's in escalated state and past the resolution period", async function () { // Set time forward before the dispute original expiration date - await setNextBlockTimestamp( - ethers.BigNumber.from(disputedDate) - .add(resolutionPeriod / 2) - .toNumber() - ); + await setNextBlockTimestamp(Number(BigInt(disputedDate) + BigInt(resolutionPeriod) / 2n)); // escalate dispute await disputeHandler.connect(buyer).escalateDispute(exchangeId, { value: buyerEscalationDepositNative }); @@ -1026,7 +1029,7 @@ describe("IBosonDisputeHandler", function () { // Resolve the dispute, testing for the event await expect(disputeHandler.connect(assistant).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, assistant.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistant.getAddress()); }); it("Dispute can be mutually resolved if it's past original timeout, but it was extended", async function () { @@ -1041,7 +1044,7 @@ describe("IBosonDisputeHandler", function () { // Resolve the dispute, testing for the event await expect(disputeHandler.connect(assistant).resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v)) .to.emit(disputeHandler, "DisputeResolved") - .withArgs(exchangeId, buyerPercentBasisPoints, assistant.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistant.getAddress()); }); }); @@ -1053,7 +1056,7 @@ describe("IBosonDisputeHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() )); }); @@ -1101,7 +1104,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Attempt to resolve the dispute, expecting revert await expect( @@ -1118,7 +1121,12 @@ describe("IBosonDisputeHandler", function () { // Wallet with seller account, but not the seller in this exchange // Create a valid seller - seller = mockSeller(other1.address, other1.address, ethers.constants.AddressZero, other1.address); + seller = mockSeller( + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() + ); expect(seller.isValid()).is.true; await accountHandler.connect(other1).createSeller(seller, emptyAuthToken, voucherInitValues); @@ -1129,7 +1137,7 @@ describe("IBosonDisputeHandler", function () { // Wallet with buyer account, but not the buyer in this exchange // Create a valid buyer - let buyer = mockBuyer(other2.address); + let buyer = mockBuyer(await other2.getAddress()); expect(buyer.isValid()).is.true; await accountHandler.connect(other2).createBuyer(buyer); @@ -1146,7 +1154,7 @@ describe("IBosonDisputeHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() )); // Attempt to resolve the dispute, expecting revert @@ -1178,17 +1186,17 @@ describe("IBosonDisputeHandler", function () { await expect( disputeHandler .connect(assistant) - .resolveDispute(exchangeId, buyerPercentBasisPoints, r, ethers.utils.hexZeroPad("0x", 32), v) + .resolveDispute(exchangeId, buyerPercentBasisPoints, r, zeroPadBytes("0x", 32), v) ).to.revertedWith(RevertReasons.INVALID_SIGNATURE); await expect( disputeHandler .connect(assistant) - .resolveDispute(exchangeId, buyerPercentBasisPoints, ethers.utils.hexZeroPad("0x", 32), s, v) + .resolveDispute(exchangeId, buyerPercentBasisPoints, zeroPadBytes("0x", 32), s, v) ).to.revertedWith(RevertReasons.INVALID_SIGNATURE); await expect( disputeHandler .connect(assistant) - .resolveDispute(exchangeId, buyerPercentBasisPoints, r, ethers.constants.MaxUint256, v) + .resolveDispute(exchangeId, buyerPercentBasisPoints, r, toHexString(MaxUint256), v) ).to.revertedWith(RevertReasons.INVALID_SIGNATURE); }); @@ -1215,11 +1223,11 @@ describe("IBosonDisputeHandler", function () { await accountHandler .connect(adminDR) .addFeesToDisputeResolver(disputeResolverId, [ - new DisputeResolverFee(mockToken.address, "MockToken", DRFeeToken), + new DisputeResolverFee(await mockToken.getAddress(), "MockToken", DRFeeToken), ]); // create an offer with a mock token contract - offer.exchangeToken = mockToken.address; + offer.exchangeToken = await mockToken.getAddress(); offer.sellerDeposit = offer.price = offer.buyerCancelPenalty = "0"; offer.id++; @@ -1230,11 +1238,11 @@ describe("IBosonDisputeHandler", function () { // mint tokens to buyer and approve the protocol buyerEscalationDepositToken = applyPercentage(DRFeeToken, buyerEscalationDepositPercentage); - await mockToken.mint(buyer.address, buyerEscalationDepositToken); - await mockToken.connect(buyer).approve(disputeHandler.address, buyerEscalationDepositToken); + await mockToken.mint(await buyer.getAddress(), buyerEscalationDepositToken); + await mockToken.connect(buyer).approve(await disputeHandler.getAddress(), buyerEscalationDepositToken); // Commit to offer and put exchange all the way to dispute - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offer.id); await exchangeHandler.connect(buyer).redeemVoucher(++exchangeId); await disputeHandler.connect(buyer).raiseDispute(exchangeId); @@ -1247,9 +1255,9 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = BigInt(disputedDate) + resolutionPeriod.toString(); }); it("should emit a DisputeEscalated event", async function () { @@ -1258,21 +1266,21 @@ describe("IBosonDisputeHandler", function () { disputeHandler.connect(buyer).escalateDispute(exchangeId, { value: buyerEscalationDepositNative }) ) .to.emit(disputeHandler, "DisputeEscalated") - .withArgs(exchangeId, disputeResolverId, buyer.address); + .withArgs(exchangeId, disputeResolverId, await buyer.getAddress()); }); it("should update state", async function () { // Protocol balance before - const escrowBalanceBefore = await ethers.provider.getBalance(disputeHandler.address); + const escrowBalanceBefore = await provider.getBalance(await disputeHandler.getAddress()); // Escalate the dispute tx = await disputeHandler.connect(buyer).escalateDispute(exchangeId, { value: buyerEscalationDepositNative }); // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); escalatedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(escalatedDate).add(escalationPeriod).toString(); + timeout = BigInt(escalatedDate) + BigInt(escalationPeriod); dispute = new Dispute(exchangeId, DisputeState.Escalated, "0"); disputeDates = new DisputeDates(disputedDate, escalatedDate, "0", timeout); @@ -1299,8 +1307,8 @@ describe("IBosonDisputeHandler", function () { assert.equal(response, DisputeState.Escalated, "Dispute state is incorrect"); // Protocol balance should increase for buyer escalation deposit - const escrowBalanceAfter = await ethers.provider.getBalance(disputeHandler.address); - expect(escrowBalanceAfter.sub(escrowBalanceBefore)).to.equal( + const escrowBalanceAfter = await provider.getBalance(await disputeHandler.getAddress()); + expect(escrowBalanceAfter - escrowBalanceBefore).to.equal( buyerEscalationDepositNative, "Escrow balance mismatch" ); @@ -1310,16 +1318,16 @@ describe("IBosonDisputeHandler", function () { const mockToken = await createDisputeExchangeWithToken(); // Protocol balance before - const escrowBalanceBefore = await mockToken.balanceOf(disputeHandler.address); + const escrowBalanceBefore = await mockToken.balanceOf(await disputeHandler.getAddress()); // Escalate the dispute, testing for the event await expect(disputeHandler.connect(buyer).escalateDispute(exchangeId)) .to.emit(disputeHandler, "DisputeEscalated") - .withArgs(exchangeId, disputeResolverId, buyer.address); + .withArgs(exchangeId, disputeResolverId, await buyer.getAddress()); // Protocol balance should increase for buyer escalation deposit - const escrowBalanceAfter = await mockToken.balanceOf(disputeHandler.address); - expect(escrowBalanceAfter.sub(escrowBalanceBefore)).to.equal( + const escrowBalanceAfter = await mockToken.balanceOf(await disputeHandler.getAddress()); + expect(escrowBalanceAfter - escrowBalanceBefore).to.equal( buyerEscalationDepositToken, "Escrow balance mismatch" ); @@ -1350,7 +1358,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Attempt to escalate the dispute, expecting revert await expect(disputeHandler.connect(buyer).escalateDispute(exchangeId), { @@ -1367,7 +1375,7 @@ describe("IBosonDisputeHandler", function () { it("Dispute has expired", async function () { // Set time forward past the dispute resolution period - await setNextBlockTimestamp(Number(timeout) + oneWeek); + await setNextBlockTimestamp(Number(timeout + oneWeek)); // Attempt to escalate the dispute, expecting revert await expect(disputeHandler.connect(buyer).escalateDispute(exchangeId), { @@ -1398,7 +1406,7 @@ describe("IBosonDisputeHandler", function () { .createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // Commit to offer and put exchange all the way to dispute - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offer.id); await exchangeHandler.connect(buyer).redeemVoucher(++exchangeId); await disputeHandler.connect(buyer).raiseDispute(exchangeId); @@ -1412,7 +1420,7 @@ describe("IBosonDisputeHandler", function () { // Attempt to escalate the dispute, expecting revert await expect( disputeHandler.connect(buyer).escalateDispute(exchangeId, { - value: ethers.BigNumber.from(buyerEscalationDepositNative).sub("1").toString(), + value: BigInt(buyerEscalationDepositNative) - 1n, }) ).to.revertedWith(RevertReasons.INSUFFICIENT_VALUE_RECEIVED); }); @@ -1423,7 +1431,7 @@ describe("IBosonDisputeHandler", function () { // Attempt to escalate the dispute, expecting revert await expect( disputeHandler.connect(buyer).escalateDispute(exchangeId, { - value: ethers.BigNumber.from("1").toString(), + value: 1n, }) ).to.revertedWith(RevertReasons.NATIVE_NOT_ALLOWED); }); @@ -1446,7 +1454,7 @@ describe("IBosonDisputeHandler", function () { const mockToken = await createDisputeExchangeWithToken(); // get rid of some tokens, so buyer has insufficient funds - await mockToken.connect(buyer).transfer(other1.address, buyerEscalationDepositToken); + await mockToken.connect(buyer).transfer(await other1.getAddress(), buyerEscalationDepositToken); // Attempt to commit to an offer, expecting revert await expect(disputeHandler.connect(buyer).escalateDispute(exchangeId)).to.revertedWith( @@ -1456,7 +1464,7 @@ describe("IBosonDisputeHandler", function () { // not approved await mockToken .connect(buyer) - .approve(protocolDiamond.address, ethers.BigNumber.from(buyerEscalationDepositToken).sub("1").toString()); + .approve(await protocolDiamond.getAddress(), BigInt(buyerEscalationDepositToken) - "1".toString()); // Attempt to commit to an offer, expecting revert await expect(disputeHandler.connect(buyer).escalateDispute(exchangeId)).to.revertedWith( @@ -1469,16 +1477,16 @@ describe("IBosonDisputeHandler", function () { const [Foreign20WithFee] = await deployMockTokens(["Foreign20WithFee"]); // add to DR fees - DRFeeToken = ethers.utils.parseUnits("2", "ether").toString(); + DRFeeToken = parseUnits("2", "ether").toString(); await accountHandler .connect(adminDR) .addFeesToDisputeResolver(disputeResolverId, [ - new DisputeResolverFee(Foreign20WithFee.address, "Foreign20WithFee", "0"), + new DisputeResolverFee(await Foreign20WithFee.getAddress(), "Foreign20WithFee", "0"), ]); // Create an offer with ERC20 with fees // Prepare an absolute zero offer - offer.exchangeToken = Foreign20WithFee.address; + offer.exchangeToken = await Foreign20WithFee.getAddress(); offer.sellerDeposit = offer.price = offer.buyerCancelPenalty = "0"; offer.id++; @@ -1489,11 +1497,14 @@ describe("IBosonDisputeHandler", function () { // mint tokens and approve buyerEscalationDepositToken = applyPercentage(DRFeeToken, buyerEscalationDepositPercentage); - await Foreign20WithFee.mint(buyer.address, buyerEscalationDepositToken); - await Foreign20WithFee.connect(buyer).approve(protocolDiamond.address, buyerEscalationDepositToken); + await Foreign20WithFee.mint(await buyer.getAddress(), buyerEscalationDepositToken); + await Foreign20WithFee.connect(buyer).approve( + await protocolDiamond.getAddress(), + buyerEscalationDepositToken + ); // Commit to offer and put exchange all the way to dispute - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offer.id); await exchangeHandler.connect(buyer).redeemVoucher(++exchangeId); await disputeHandler.connect(buyer).raiseDispute(exchangeId); @@ -1512,7 +1523,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); // Escalate the dispute @@ -1520,9 +1531,9 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); escalatedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(escalatedDate).add(escalationPeriod).toString(); + timeout = BigInt(escalatedDate) + BigInt(escalationPeriod); // buyer percent used in tests buyerPercentBasisPoints = "4321"; @@ -1532,7 +1543,7 @@ describe("IBosonDisputeHandler", function () { // Escalate the dispute, testing for the event await expect(disputeHandler.connect(assistantDR).decideDispute(exchangeId, buyerPercentBasisPoints)) .to.emit(disputeHandler, "DisputeDecided") - .withArgs(exchangeId, buyerPercentBasisPoints, assistantDR.address); + .withArgs(exchangeId, buyerPercentBasisPoints, await assistantDR.getAddress()); }); it("should update state", async function () { @@ -1541,7 +1552,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set finalizedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); finalizedDate = block.timestamp.toString(); dispute = new Dispute(exchangeId, DisputeState.Decided, buyerPercentBasisPoints); @@ -1604,7 +1615,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Attempt to decide the dispute, expecting revert await expect( @@ -1623,7 +1634,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Redeem voucher await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); @@ -1656,7 +1667,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); // Escalate the dispute @@ -1664,9 +1675,9 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); escalatedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(escalatedDate).add(escalationPeriod).toString(); + timeout = BigInt(escalatedDate) + BigInt(escalationPeriod); }); it("should emit a EscalatedDisputeExpired event", async function () { @@ -1676,7 +1687,7 @@ describe("IBosonDisputeHandler", function () { // Expire the escalated dispute, testing for the event await expect(disputeHandler.connect(rando).expireEscalatedDispute(exchangeId)) .to.emit(disputeHandler, "EscalatedDisputeExpired") - .withArgs(exchangeId, rando.address); + .withArgs(exchangeId, await rando.getAddress()); }); it("should update state", async function () { @@ -1688,7 +1699,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set finalizedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); finalizedDate = block.timestamp.toString(); dispute = new Dispute(exchangeId, DisputeState.Refused, buyerPercentBasisPoints); @@ -1754,7 +1765,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Attempt to expire the escalated dispute, expecting revert await expect(disputeHandler.connect(rando).expireEscalatedDispute(exchangeId)).to.revertedWith( @@ -1773,7 +1784,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Redeem voucher await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); @@ -1805,7 +1816,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); // Escalate the dispute @@ -1813,16 +1824,16 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); escalatedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(escalatedDate).add(escalationPeriod).toString(); + timeout = BigInt(escalatedDate) + BigInt(escalationPeriod); }); it("should emit a EscalatedDisputeRefused event", async function () { // Refuse the escalated dispute, testing for the event await expect(disputeHandler.connect(assistantDR).refuseEscalatedDispute(exchangeId)) .to.emit(disputeHandler, "EscalatedDisputeRefused") - .withArgs(exchangeId, assistantDR.address); + .withArgs(exchangeId, await assistantDR.getAddress()); }); it("should update state", async function () { @@ -1831,7 +1842,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set finalizedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); finalizedDate = block.timestamp.toString(); dispute = new Dispute(exchangeId, DisputeState.Refused, buyerPercentBasisPoints); @@ -1894,7 +1905,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Attempt to refuse the escalated dispute, expecting revert await expect(disputeHandler.connect(assistantDR).refuseEscalatedDispute(exchangeId)).to.revertedWith( @@ -1906,7 +1917,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Redeem voucher await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); @@ -1955,9 +1966,9 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = BigInt(disputedDate) + BigInt(resolutionPeriod); // Expected value for dispute dispute = new Dispute(exchangeId, DisputeState.Resolving, buyerPercentBasisPoints); @@ -1999,7 +2010,7 @@ describe("IBosonDisputeHandler", function () { exchangeId++; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Get the exchange [exists, response] = await exchangeHandler.connect(rando).getExchange(exchangeId); @@ -2041,9 +2052,9 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = (BigInt(disputedDate) + BigInt(resolutionPeriod)).toString(); }); it("should return true for exists if exchange id is valid", async function () { @@ -2098,9 +2109,9 @@ describe("IBosonDisputeHandler", function () { it("should return the expected dispute state if exchange id is valid and dispute has been resolved", async function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = (BigInt(disputedDate) + BigInt(resolutionPeriod)).toString(); buyerPercentBasisPoints = "1234"; @@ -2125,7 +2136,7 @@ describe("IBosonDisputeHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() )); // Buyer resolves dispute @@ -2155,9 +2166,9 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); escalatedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(escalatedDate).add(escalationPeriod).toString(); + timeout = (BigInt(escalatedDate) + BigInt(escalationPeriod)).toString(); // buyer percent used in tests buyerPercentBasisPoints = "4321"; @@ -2194,9 +2205,9 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = BigInt(disputedDate) + BigInt(resolutionPeriod); }); it("should return true for exists if exchange id is valid", async function () { @@ -2294,7 +2305,7 @@ describe("IBosonDisputeHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() )); // Retract dispute @@ -2333,7 +2344,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); escalatedDate = block.timestamp.toString(); await setNextBlockTimestamp(Number(escalatedDate) + Number(escalationPeriod)); @@ -2359,7 +2370,7 @@ describe("IBosonDisputeHandler", function () { for (exchangeId = 1; exchangeId <= 5; exchangeId++) { // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Redeem voucher await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); @@ -2381,9 +2392,9 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); - disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + block = await provider.getBlock(blockNumber); + disputedDate = block.timestamp; + timeout = BigInt(disputedDate) + BigInt(resolutionPeriod); dispute[exchangeId] = new Dispute(exchangeId, DisputeState.Retracted, buyerPercentBasisPoints); disputeDates[exchangeId] = new DisputeDates(disputedDate, "0", finalizedDate, timeout); @@ -2396,11 +2407,17 @@ describe("IBosonDisputeHandler", function () { // Expire the disputes, testing for the event const tx = disputeHandler.connect(rando).expireDisputeBatch(disputesToExpire); - await expect(tx).to.emit(disputeHandler, "DisputeExpired").withArgs("2", rando.address); + await expect(tx) + .to.emit(disputeHandler, "DisputeExpired") + .withArgs("2", await rando.getAddress()); - await expect(tx).to.emit(disputeHandler, "DisputeExpired").withArgs("3", rando.address); + await expect(tx) + .to.emit(disputeHandler, "DisputeExpired") + .withArgs("3", await rando.getAddress()); - await expect(tx).to.emit(disputeHandler, "DisputeExpired").withArgs("4", rando.address); + await expect(tx) + .to.emit(disputeHandler, "DisputeExpired") + .withArgs("4", await rando.getAddress()); }); it("should update state", async function () { @@ -2412,7 +2429,7 @@ describe("IBosonDisputeHandler", function () { // Get the block timestamp of the confirmed tx and set finalizedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); finalizedDate = block.timestamp.toString(); // verify that state for all disputes was updated diff --git a/test/protocol/DisputeResolverHandlerTest.js b/test/protocol/DisputeResolverHandlerTest.js index 40e25a6f5..4fd81e164 100644 --- a/test/protocol/DisputeResolverHandlerTest.js +++ b/test/protocol/DisputeResolverHandlerTest.js @@ -1,5 +1,6 @@ const { ethers } = require("hardhat"); const { expect, assert } = require("chai"); +const { ZeroAddress } = ethers; const DisputeResolver = require("../../scripts/domain/DisputeResolver"); const { DisputeResolverFee, DisputeResolverFeeList } = require("../../scripts/domain/DisputeResolverFee"); @@ -104,7 +105,7 @@ describe("DisputeResolverHandler", function () { // make all account the same assistant = admin; - clerk = { address: ethers.constants.AddressZero }; + clerk = { address: ZeroAddress }; // Get snapshot id snapshotId = await getSnapshot(); @@ -126,9 +127,24 @@ describe("DisputeResolverHandler", function () { expect(emptyAuthToken.isValid()).is.true; // Create two additional sellers and create seller allow list - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); - seller2 = mockSeller(other1.address, other1.address, ethers.constants.AddressZero, other1.address); - let seller3 = mockSeller(other2.address, other2.address, ethers.constants.AddressZero, other2.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); + seller2 = mockSeller( + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() + ); + let seller3 = mockSeller( + await other2.getAddress(), + await other2.getAddress(), + ZeroAddress, + await other2.getAddress() + ); // VoucherInitValues voucherInitValues = mockVoucherInitValues(); @@ -142,7 +158,12 @@ describe("DisputeResolverHandler", function () { sellerAllowList = ["3", "1"]; // Create a valid dispute resolver, then set fields in tests directly - disputeResolver = mockDisputeResolver(assistant.address, admin.address, clerk.address, treasury.address); + disputeResolver = mockDisputeResolver( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(disputeResolver.isValid()).is.true; // How that dispute resolver looks as a returned struct @@ -150,10 +171,10 @@ describe("DisputeResolverHandler", function () { disputeResolverPendingUpdate = disputeResolver.clone(); disputeResolverPendingUpdate.id = "0"; - disputeResolverPendingUpdate.admin = ethers.constants.AddressZero; - disputeResolverPendingUpdate.clerk = ethers.constants.AddressZero; - disputeResolverPendingUpdate.treasury = ethers.constants.AddressZero; - disputeResolverPendingUpdate.assistant = ethers.constants.AddressZero; + disputeResolverPendingUpdate.admin = ZeroAddress; + disputeResolverPendingUpdate.clerk = ZeroAddress; + disputeResolverPendingUpdate.treasury = ZeroAddress; + disputeResolverPendingUpdate.assistant = ZeroAddress; disputeResolverPendingUpdate.escalationResponsePeriod = "0"; disputeResolverPendingUpdate.metadataUri = ""; disputeResolverPendingUpdate.active = false; @@ -162,9 +183,9 @@ describe("DisputeResolverHandler", function () { //Create DisputeResolverFee array disputeResolverFees = [ - new DisputeResolverFee(other1.address, "MockToken1", "0"), - new DisputeResolverFee(other2.address, "MockToken2", "0"), - new DisputeResolverFee(other3.address, "MockToken3", "0"), + new DisputeResolverFee(await other1.getAddress(), "MockToken1", "0"), + new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0"), + new DisputeResolverFee(await other3.getAddress(), "MockToken3", "0"), ]; disputeResolverFeeList = new DisputeResolverFeeList(disputeResolverFees); @@ -194,7 +215,7 @@ describe("DisputeResolverHandler", function () { disputeResolverFeeList, 2, sellerAllowList, - admin.address + await admin.getAddress() ); expect(valid).is.true; }); @@ -213,7 +234,7 @@ describe("DisputeResolverHandler", function () { disputeResolverFeeList, 2, sellerAllowList, - admin.address + await admin.getAddress() ); expect(valid).is.true; }); @@ -328,10 +349,10 @@ describe("DisputeResolverHandler", function () { // Create a dispute resolver 2 disputeResolver2 = mockDisputeResolver( - other1.address, - other1.address, - ethers.constants.AddressZero, - other1.address, + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress(), true ); expect(disputeResolver2.isValid()).is.true; @@ -381,7 +402,7 @@ describe("DisputeResolverHandler", function () { disputeResolverFeeList, 2, sellerAllowList, - admin.address + await admin.getAddress() ); expect(valid).is.true; @@ -406,16 +427,16 @@ describe("DisputeResolverHandler", function () { disputeResolverFeeList, 2, sellerAllowList, - admin.address + await admin.getAddress() ); expect(valid).is.true; // Create a valid dispute resolver, then set fields in tests directly disputeResolver2 = mockDisputeResolver( - other1.address, - other1.address, - ethers.constants.AddressZero, - treasury.address, + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await treasury.getAddress(), true ); expect(disputeResolver2.isValid()).is.true; @@ -432,7 +453,7 @@ describe("DisputeResolverHandler", function () { disputeResolverFeeList, 2, sellerAllowList, - other1.address + await other1.getAddress() ); expect(valid).is.true; }); @@ -449,23 +470,23 @@ describe("DisputeResolverHandler", function () { }); it("Any address is the zero address", async function () { - disputeResolver.assistant = ethers.constants.AddressZero; + disputeResolver.assistant = ZeroAddress; // Attempt to Create a DisputeResolver, expecting revert await expect( accountHandler.connect(admin).createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList) ).to.revertedWith(RevertReasons.INVALID_ADDRESS); - disputeResolver.assistant = assistant.address; - disputeResolver.admin = ethers.constants.AddressZero; + disputeResolver.assistant = await assistant.getAddress(); + disputeResolver.admin = ZeroAddress; // Attempt to Create a DisputeResolver, expecting revert await expect( accountHandler.connect(admin).createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList) ).to.revertedWith(RevertReasons.INVALID_ADDRESS); - disputeResolver.admin = admin.address; - disputeResolver.treasury = ethers.constants.AddressZero; + disputeResolver.admin = await admin.getAddress(); + disputeResolver.treasury = ZeroAddress; // Attempt to Create a DisputeResolver, expecting revert await expect( @@ -474,7 +495,7 @@ describe("DisputeResolverHandler", function () { }); it("Supplied clerk is not a zero address", async function () { - disputeResolver.clerk = rando.address; + disputeResolver.clerk = await rando.getAddress(); // Attempt to Create a DisputeResolver, expecting revert await expect( @@ -484,10 +505,10 @@ describe("DisputeResolverHandler", function () { it("Address is not unique to this dispute resolver Id", async function () { disputeResolver2 = mockDisputeResolver( - assistant.address, - assistant.address, - ethers.constants.AddressZero, - assistant.address + await assistant.getAddress(), + await assistant.getAddress(), + ZeroAddress, + await assistant.getAddress() ); expect(disputeResolver2.isValid()).is.true; disputeResolver2Struct = disputeResolver2.toStruct(); @@ -529,10 +550,10 @@ describe("DisputeResolverHandler", function () { it("Duplicate dispute resolver fees", async function () { //Create new DisputeResolverFee array disputeResolverFees2 = [ - new DisputeResolverFee(other1.address, "MockToken1", "0"), - new DisputeResolverFee(other3.address, "MockToken3", "0"), - new DisputeResolverFee(other2.address, "MockToken2", "0"), - new DisputeResolverFee(other2.address, "MockToken2", "0"), + new DisputeResolverFee(await other1.getAddress(), "MockToken1", "0"), + new DisputeResolverFee(await other3.getAddress(), "MockToken3", "0"), + new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0"), + new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0"), ]; // Create a dispute resolver @@ -571,7 +592,7 @@ describe("DisputeResolverHandler", function () { }); it("Caller is not the supplied admin", async function () { - disputeResolver.assistant = rando.address; + disputeResolver.assistant = await rando.getAddress(); // Create a dispute resolver await expect( @@ -580,7 +601,7 @@ describe("DisputeResolverHandler", function () { }); it("Caller is not the supplied assistant", async function () { - disputeResolver.admin = rando.address; + disputeResolver.admin = await rando.getAddress(); // Create a dispute resolver await expect( @@ -612,9 +633,9 @@ describe("DisputeResolverHandler", function () { beforeEach(async function () { //Create DisputeResolverFee array disputeResolverFees = [ - new DisputeResolverFee(other1.address, "MockToken1", "0"), - new DisputeResolverFee(other2.address, "MockToken2", "0"), - new DisputeResolverFee(other3.address, "MockToken3", "0"), + new DisputeResolverFee(await other1.getAddress(), "MockToken1", "0"), + new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0"), + new DisputeResolverFee(await other3.getAddress(), "MockToken3", "0"), ]; sellerAllowList = ["1"]; @@ -659,7 +680,7 @@ describe("DisputeResolverHandler", function () { Array.isArray(returnedSellerAllowList) && returnedSellerAllowList.reduce( (previousAllowedSeller, currentAllowedSeller) => - previousAllowedSeller && typeof ethers.BigNumber.from(currentAllowedSeller) === "object", + previousAllowedSeller && typeof BigInt(currentAllowedSeller) === "bigint", true ); expect(valid).to.be.true; @@ -669,7 +690,7 @@ describe("DisputeResolverHandler", function () { context("👉 areSellersAllowed()", async function () { beforeEach(async function () { //Create DisputeResolverFee array - disputeResolverFees = [new DisputeResolverFee(other1.address, "MockToken1", "0")]; + disputeResolverFees = [new DisputeResolverFee(await other1.getAddress(), "MockToken1", "0")]; }); it("Dispute resolver allows all sellers", async function () { @@ -734,12 +755,12 @@ describe("DisputeResolverHandler", function () { }); it("should emit a DisputeResolverUpdatePending event with correct values if values change", async function () { - disputeResolver.escalationResponsePeriod = Number( - Number(disputeResolver.escalationResponsePeriod) - oneWeek + disputeResolver.escalationResponsePeriod = ( + BigInt(disputeResolver.escalationResponsePeriod) - oneWeek ).toString(); - disputeResolver.assistant = disputeResolverPendingUpdate.assistant = other1.address; - disputeResolver.admin = disputeResolverPendingUpdate.admin = other2.address; - disputeResolver.treasury = other4.address; + disputeResolver.assistant = disputeResolverPendingUpdate.assistant = await other1.getAddress(); + disputeResolver.admin = disputeResolverPendingUpdate.admin = await other2.getAddress(); + disputeResolver.treasury = await other4.getAddress(); disputeResolver.metadataUri = "https://ipfs.io/ipfs/updatedUri"; disputeResolver.active = true; expect(disputeResolver.isValid()).is.true; @@ -754,12 +775,12 @@ describe("DisputeResolverHandler", function () { // Testing for the DisputeResolverUpdatePending event await expect(tx) .to.emit(accountHandler, "DisputeResolverUpdatePending") - .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, admin.address); + .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, await admin.getAddress()); // Assistant and admin needs owner approval and won't be updated until then - expectedDisputeResolver.assistant = assistant.address; - expectedDisputeResolver.admin = admin.address; - expectedDisputeResolver.clerk = ethers.constants.AddressZero; + expectedDisputeResolver.assistant = await assistant.getAddress(); + expectedDisputeResolver.admin = await admin.getAddress(); + expectedDisputeResolver.clerk = ZeroAddress; expectedDisputeResolverStruct = expectedDisputeResolver.toStruct(); // Testing for the DisputeResolverUpdateApplied event @@ -769,18 +790,18 @@ describe("DisputeResolverHandler", function () { disputeResolver.id, expectedDisputeResolverStruct, disputeResolverPendingUpdateStruct, - admin.address + await admin.getAddress() ); }); it("should update state of all fields except Id and active flag and fees", async function () { - disputeResolver.escalationResponsePeriod = Number( - Number(disputeResolver.escalationResponsePeriod) - oneWeek + disputeResolver.escalationResponsePeriod = ( + BigInt(disputeResolver.escalationResponsePeriod) - oneWeek ).toString(); - disputeResolver.assistant = other1.address; - disputeResolver.admin = other2.address; - disputeResolver.clerk = ethers.constants.AddressZero; - disputeResolver.treasury = other4.address; + disputeResolver.assistant = await other1.getAddress(); + disputeResolver.admin = await other2.getAddress(); + disputeResolver.clerk = ZeroAddress; + disputeResolver.treasury = await other4.getAddress(); disputeResolver.metadataUri = "https://ipfs.io/ipfs/updatedUri"; disputeResolver.active = true; expect(disputeResolver.isValid()).is.true; @@ -822,10 +843,10 @@ describe("DisputeResolverHandler", function () { ); //Check that old addresses are no longer mapped. We don't map the treasury address. - [exists] = await accountHandler.connect(rando).getDisputeResolverByAddress(assistant.address); + [exists] = await accountHandler.connect(rando).getDisputeResolverByAddress(await assistant.getAddress()); expect(exists).to.be.false; - [exists] = await accountHandler.connect(rando).getDisputeResolverByAddress(admin.address); + [exists] = await accountHandler.connect(rando).getDisputeResolverByAddress(await admin.getAddress()); expect(exists).to.be.false; [exists] = await accountHandler.connect(rando).getDisputeResolverByAddress(clerk.address); @@ -841,7 +862,7 @@ describe("DisputeResolverHandler", function () { it("should ignore active flag passed in", async function () { disputeResolver.active = true; - disputeResolver.assistant = other2.address; + disputeResolver.assistant = await other2.getAddress(); expect(disputeResolver.isValid()).is.true; // Update disupte resolver @@ -879,7 +900,7 @@ describe("DisputeResolverHandler", function () { }); it("should update only one address", async function () { - disputeResolver.assistant = other2.address; + disputeResolver.assistant = await other2.getAddress(); expect(disputeResolver.isValid()).is.true; expectedDisputeResolver = disputeResolver.clone(); @@ -908,10 +929,10 @@ describe("DisputeResolverHandler", function () { it("should update the correct dispute resolver", async function () { // Configure another dispute resolver disputeResolver2 = mockDisputeResolver( - other1.address, - other1.address, - ethers.constants.AddressZero, - other1.address + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() ); expect(disputeResolver2.isValid()).is.true; @@ -919,7 +940,7 @@ describe("DisputeResolverHandler", function () { const expectedDisputeResolverStruct2 = expectedDisputeResolver2.toStruct(); //Create DisputeResolverFee array - disputeResolverFees2 = [new DisputeResolverFee(rando.address, "RandomToken", "0")]; + disputeResolverFees2 = [new DisputeResolverFee(await rando.getAddress(), "RandomToken", "0")]; const disputeResolverFeeList2 = new DisputeResolverFeeList(disputeResolverFees2); @@ -935,18 +956,18 @@ describe("DisputeResolverHandler", function () { disputeResolverFeeList2, 2, sellerAllowList, - other1.address + await other1.getAddress() ); expect(valid).is.true; //Update first dispute resolver values - disputeResolver.escalationResponsePeriod = Number( - Number(disputeResolver.escalationResponsePeriod) - oneWeek + disputeResolver.escalationResponsePeriod = ( + BigInt(disputeResolver.escalationResponsePeriod) - oneWeek ).toString(); - disputeResolver.assistant = rando.address; - disputeResolver.admin = rando.address; - disputeResolver.clerk = ethers.constants.AddressZero; - disputeResolver.treasury = rando.address; + disputeResolver.assistant = await rando.getAddress(); + disputeResolver.admin = await rando.getAddress(); + disputeResolver.clerk = ZeroAddress; + disputeResolver.treasury = await rando.getAddress(); disputeResolver.metadataUri = "https://ipfs.io/ipfs/updatedUri"; expect(disputeResolver.isValid()).is.true; @@ -1009,19 +1030,19 @@ describe("DisputeResolverHandler", function () { }); it("should be able to only update second time with new admin address", async function () { - disputeResolver.admin = other2.address; + disputeResolver.admin = await other2.getAddress(); expectedDisputeResolver = disputeResolver.clone(); expectedDisputeResolverStruct = expectedDisputeResolver.toStruct(); - disputeResolverPendingUpdate.admin = other2.address; + disputeResolverPendingUpdate.admin = await other2.getAddress(); disputeResolverPendingUpdateStruct = disputeResolverPendingUpdate.toStruct(); // Update a dispute resolver, testing for the event await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)) .to.emit(accountHandler, "DisputeResolverUpdatePending") - .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, admin.address); + .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, await admin.getAddress()); - disputeResolverPendingUpdate.admin = ethers.constants.AddressZero; + disputeResolverPendingUpdate.admin = ZeroAddress; disputeResolverPendingUpdateStruct = disputeResolverPendingUpdate.toStruct(); // Approve admin update @@ -1035,22 +1056,22 @@ describe("DisputeResolverHandler", function () { disputeResolver.id, expectedDisputeResolverStruct, disputeResolverPendingUpdateStruct, - other2.address + await other2.getAddress() ); - disputeResolver.admin = other3.address; + disputeResolver.admin = await other3.getAddress(); expectedDisputeResolver = disputeResolver.clone(); expectedDisputeResolverStruct = expectedDisputeResolver.toStruct(); - disputeResolverPendingUpdate.admin = other3.address; + disputeResolverPendingUpdate.admin = await other3.getAddress(); disputeResolverPendingUpdateStruct = disputeResolverPendingUpdate.toStruct(); //Update a dispute resolver, testing for the event await expect(accountHandler.connect(other2).updateDisputeResolver(disputeResolver)) .to.emit(accountHandler, "DisputeResolverUpdatePending") - .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, other2.address); + .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, await other2.getAddress()); - disputeResolverPendingUpdate.admin = ethers.constants.AddressZero; + disputeResolverPendingUpdate.admin = ZeroAddress; disputeResolverPendingUpdateStruct = disputeResolverPendingUpdate.toStruct(); // Approve admin update @@ -1064,7 +1085,7 @@ describe("DisputeResolverHandler", function () { disputeResolver.id, expectedDisputeResolverStruct, disputeResolverPendingUpdateStruct, - other3.address + await other3.getAddress() ); // Attempt to update the dispute resolver with original admin address, expecting revert @@ -1075,23 +1096,23 @@ describe("DisputeResolverHandler", function () { it("should be possible to use non-unique treasury address", async function () { // Update dispute resolver fields - disputeResolver.assistant = other1.address; - disputeResolver.admin = other2.address; - disputeResolver.clerk = ethers.constants.AddressZero; + disputeResolver.assistant = await other1.getAddress(); + disputeResolver.admin = await other2.getAddress(); + disputeResolver.clerk = ZeroAddress; disputeResolver.active = true; expect(disputeResolver.isValid()).is.true; expectedDisputeResolverStruct = disputeResolver.toStruct(); - disputeResolverPendingUpdate.assistant = other1.address; - disputeResolverPendingUpdate.admin = other2.address; - disputeResolverPendingUpdate.clerk = ethers.constants.AddressZero; + disputeResolverPendingUpdate.assistant = await other1.getAddress(); + disputeResolverPendingUpdate.admin = await other2.getAddress(); + disputeResolverPendingUpdate.clerk = ZeroAddress; disputeResolverPendingUpdateStruct = disputeResolverPendingUpdate.toStruct(); // Request to update a dispute resolver, testing for the DisputeResolerUpdatePending event await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)) .to.emit(accountHandler, "DisputeResolverUpdatePending") - .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, admin.address); + .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, await admin.getAddress()); // Approve assistant update await accountHandler @@ -1105,10 +1126,10 @@ describe("DisputeResolverHandler", function () { // Configure another dispute resolver disputeResolver2 = mockDisputeResolver( - rando.address, - rando.address, - ethers.constants.AddressZero, - rando.address + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() ); expect(disputeResolver2.isValid()).is.true; @@ -1117,38 +1138,43 @@ describe("DisputeResolverHandler", function () { .connect(rando) .createDisputeResolver(disputeResolver2, disputeResolverFees, sellerAllowList); - disputeResolver2.treasury = treasury.address; + disputeResolver2.treasury = await treasury.getAddress(); disputeResolver2Struct = disputeResolver2.toStruct(); - disputeResolverPendingUpdate.admin = ethers.constants.AddressZero; - disputeResolverPendingUpdate.assistant = ethers.constants.AddressZero; - disputeResolverPendingUpdate.clerk = ethers.constants.AddressZero; + disputeResolverPendingUpdate.admin = ZeroAddress; + disputeResolverPendingUpdate.assistant = ZeroAddress; + disputeResolverPendingUpdate.clerk = ZeroAddress; disputeResolverPendingUpdateStruct = disputeResolverPendingUpdate.toStruct(); // Update new dispute resolver with same treasury address, testing for the event await expect(accountHandler.connect(rando).updateDisputeResolver(disputeResolver2)) .to.emit(accountHandler, "DisputeResolverUpdateApplied") - .withArgs(disputeResolver2.id, disputeResolver2Struct, disputeResolverPendingUpdateStruct, rando.address); + .withArgs( + disputeResolver2.id, + disputeResolver2Struct, + disputeResolverPendingUpdateStruct, + await rando.getAddress() + ); }); it("should be possible to use the same address for assistant, admin and treasury", async function () { // Update dispute resolver fields - disputeResolver.assistant = other1.address; - disputeResolver.admin = other1.address; - disputeResolver.clerk = ethers.constants.AddressZero; - disputeResolver.treasury = other1.address; + disputeResolver.assistant = await other1.getAddress(); + disputeResolver.admin = await other1.getAddress(); + disputeResolver.clerk = ZeroAddress; + disputeResolver.treasury = await other1.getAddress(); expect(disputeResolver.isValid()).is.true; // Treasury is the only address that doesn't need owner opt-in expectedDisputeResolver = disputeResolver.clone(); - expectedDisputeResolver.assistant = assistant.address; - expectedDisputeResolver.admin = admin.address; - expectedDisputeResolver.clerk = ethers.constants.AddressZero; + expectedDisputeResolver.assistant = await assistant.getAddress(); + expectedDisputeResolver.admin = await admin.getAddress(); + expectedDisputeResolver.clerk = ZeroAddress; expectedDisputeResolverStruct = expectedDisputeResolver.toStruct(); - disputeResolverPendingUpdate.assistant = other1.address; - disputeResolverPendingUpdate.admin = other1.address; - disputeResolverPendingUpdate.clerk = ethers.constants.AddressZero; + disputeResolverPendingUpdate.assistant = await other1.getAddress(); + disputeResolverPendingUpdate.admin = await other1.getAddress(); + disputeResolverPendingUpdate.clerk = ZeroAddress; disputeResolverPendingUpdateStruct = disputeResolverPendingUpdate.toStruct(); // Update a dispute resolver @@ -1161,20 +1187,20 @@ describe("DisputeResolverHandler", function () { disputeResolver.id, expectedDisputeResolverStruct, disputeResolverPendingUpdateStruct, - admin.address + await admin.getAddress() ); // Testing for the DisputeResolverUpdatePending event await expect(tx) .to.emit(accountHandler, "DisputeResolverUpdatePending") - .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, admin.address); + .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, await admin.getAddress()); expectedDisputeResolver = disputeResolver.clone(); expectedDisputeResolverStruct = expectedDisputeResolver.toStruct(); - disputeResolverPendingUpdate.assistant = ethers.constants.AddressZero; - disputeResolverPendingUpdate.admin = ethers.constants.AddressZero; - disputeResolverPendingUpdate.clerk = ethers.constants.AddressZero; + disputeResolverPendingUpdate.assistant = ZeroAddress; + disputeResolverPendingUpdate.admin = ZeroAddress; + disputeResolverPendingUpdate.clerk = ZeroAddress; disputeResolverPendingUpdateStruct = disputeResolverPendingUpdate.toStruct(); // Approve assistant update @@ -1191,7 +1217,7 @@ describe("DisputeResolverHandler", function () { disputeResolver.id, expectedDisputeResolverStruct, disputeResolverPendingUpdateStruct, - other1.address + await other1.getAddress() ); }); @@ -1232,23 +1258,23 @@ describe("DisputeResolverHandler", function () { }); it("Any address is the zero address", async function () { - disputeResolver.assistant = ethers.constants.AddressZero; + disputeResolver.assistant = ZeroAddress; // Attempt to update the disputer resolver, expecting revert await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)).to.revertedWith( RevertReasons.INVALID_ADDRESS ); - disputeResolver.assistant = assistant.address; - disputeResolver.admin = ethers.constants.AddressZero; + disputeResolver.assistant = await assistant.getAddress(); + disputeResolver.admin = ZeroAddress; // Attempt to update the disputer resolver, expecting revert await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)).to.revertedWith( RevertReasons.INVALID_ADDRESS ); - disputeResolver.admin = admin.address; - disputeResolver.treasury = ethers.constants.AddressZero; + disputeResolver.admin = await admin.getAddress(); + disputeResolver.treasury = ZeroAddress; // Attempt to update the disputer resolver, expecting revert await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)).to.revertedWith( @@ -1257,7 +1283,7 @@ describe("DisputeResolverHandler", function () { }); it("Supplied clerk is not a zero address", async function () { - disputeResolver.clerk = rando.address; + disputeResolver.clerk = await rando.getAddress(); // Attempt to update the disputer resolver, expecting revert await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)).to.revertedWith( @@ -1267,10 +1293,10 @@ describe("DisputeResolverHandler", function () { it("Address is not unique to this dispute resolver Id", async function () { disputeResolver2 = mockDisputeResolver( - other1.address, - other1.address, - ethers.constants.AddressZero, - other1.address + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() ); expect(disputeResolver2.isValid()).is.true; disputeResolver2Struct = disputeResolver2.toStruct(); @@ -1279,15 +1305,15 @@ describe("DisputeResolverHandler", function () { .createDisputeResolver(disputeResolver2, disputeResolverFees, sellerAllowList); //Set each address value to be same as disputeResolver2 and expect revert - disputeResolver.assistant = other1.address; + disputeResolver.assistant = await other1.getAddress(); // Attempt to update dispute resolver 1 with non-unique admin address, expecting revert await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)).to.revertedWith( RevertReasons.DISPUTE_RESOLVER_ADDRESS_MUST_BE_UNIQUE ); - disputeResolver.assistant = assistant.address; - disputeResolver.admin = other1.address; + disputeResolver.assistant = await assistant.getAddress(); + disputeResolver.admin = await other1.getAddress(); // Attempt to update dispute resolver 1 with non-unique admin address, expecting revert await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)).to.revertedWith( @@ -1297,10 +1323,10 @@ describe("DisputeResolverHandler", function () { it("Address is not unique to this dispute resolver Id", async function () { disputeResolver2 = mockDisputeResolver( - other1.address, - other1.address, - ethers.constants.AddressZero, - other1.address + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() ); expect(disputeResolver2.isValid()).is.true; @@ -1309,7 +1335,7 @@ describe("DisputeResolverHandler", function () { .createDisputeResolver(disputeResolver2, disputeResolverFees, sellerAllowList); //Set dispute resolver 2's admin address to dispute resolver 1's assistant address - disputeResolver2.admin = assistant.address; + disputeResolver2.admin = await assistant.getAddress(); // Attempt to update dispute resolver 1 with non-unique admin address, expecting revert await expect(accountHandler.connect(other1).updateDisputeResolver(disputeResolver2)).to.revertedWith( @@ -1317,8 +1343,8 @@ describe("DisputeResolverHandler", function () { ); //Set dispute resolver 2's assistant address to dispute resolver 1's assistant address - disputeResolver2.admin = other2.address; - disputeResolver2.assistant = assistant.address; + disputeResolver2.admin = await other2.getAddress(); + disputeResolver2.assistant = await assistant.getAddress(); // Attempt to update dispute resolver 1 with non-unique assistant address, expecting revert await expect(accountHandler.connect(other1).updateDisputeResolver(disputeResolver2)).to.revertedWith( @@ -1330,7 +1356,7 @@ describe("DisputeResolverHandler", function () { await configHandler.setMaxEscalationResponsePeriod(oneWeek); // New escalation period has to be different from the current escalation period - disputeResolver.escalationResponsePeriod = oneWeek + 1; + disputeResolver.escalationResponsePeriod = oneWeek + 1n; // Attempt to update a DisputeResolver, expecting revert await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)).to.revertedWith( @@ -1367,8 +1393,8 @@ describe("DisputeResolverHandler", function () { it("should emit a DisputeResolverFeesAdded event", async function () { const disputeResolverFeesToAdd = [ - new DisputeResolverFee(other4.address, "MockToken4", "0"), - new DisputeResolverFee(other5.address, "MockToken5", "0"), + new DisputeResolverFee(await other4.getAddress(), "MockToken4", "0"), + new DisputeResolverFee(await other5.getAddress(), "MockToken5", "0"), ]; const addedDisputeResolverFeeList = new DisputeResolverFeeList(disputeResolverFeesToAdd); @@ -1385,7 +1411,7 @@ describe("DisputeResolverHandler", function () { addedDisputeResolverFeeList, 1, [], - admin.address + await admin.getAddress() ); expect(valid).is.true; @@ -1393,16 +1419,16 @@ describe("DisputeResolverHandler", function () { it("should update DisputeResolverFee state only", async function () { const disputeResolverFeesToAdd = [ - new DisputeResolverFee(other4.address, "MockToken4", "0"), - new DisputeResolverFee(other5.address, "MockToken5", "0"), + new DisputeResolverFee(await other4.getAddress(), "MockToken4", "0"), + new DisputeResolverFee(await other5.getAddress(), "MockToken5", "0"), ]; const expectedDisputeResovlerFees = (disputeResolverFees = [ - new DisputeResolverFee(other1.address, "MockToken1", "0"), - new DisputeResolverFee(other2.address, "MockToken2", "0"), - new DisputeResolverFee(other3.address, "MockToken3", "0"), - new DisputeResolverFee(other4.address, "MockToken4", "0"), - new DisputeResolverFee(other5.address, "MockToken5", "0"), + new DisputeResolverFee(await other1.getAddress(), "MockToken1", "0"), + new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0"), + new DisputeResolverFee(await other3.getAddress(), "MockToken3", "0"), + new DisputeResolverFee(await other4.getAddress(), "MockToken4", "0"), + new DisputeResolverFee(await other5.getAddress(), "MockToken5", "0"), ]); const expectedDisputeResolverFeeList = new DisputeResolverFeeList(expectedDisputeResovlerFees); @@ -1437,8 +1463,8 @@ describe("DisputeResolverHandler", function () { context("💔 Revert Reasons", async function () { it("The dispute resolvers region of protocol is paused", async function () { const disputeResolverFeesToAdd = [ - new DisputeResolverFee(other4.address, "MockToken4", "400"), - new DisputeResolverFee(other5.address, "MockToken5", "500"), + new DisputeResolverFee(await other4.getAddress(), "MockToken4", "400"), + new DisputeResolverFee(await other5.getAddress(), "MockToken5", "500"), ]; // Pause the dispute resolvers region of the protocol @@ -1495,8 +1521,8 @@ describe("DisputeResolverHandler", function () { it("Duplicate dispute resolver fees", async function () { //Add to DisputeResolverFee array - disputeResolverFees.push(new DisputeResolverFee(other4.address, "MockToken4", "0")); - disputeResolverFees.push(new DisputeResolverFee(other5.address, "MockToken5", "0")); + disputeResolverFees.push(new DisputeResolverFee(await other4.getAddress(), "MockToken4", "0")); + disputeResolverFees.push(new DisputeResolverFee(await other5.getAddress(), "MockToken5", "0")); disputeResolverFeeList = new DisputeResolverFeeList(disputeResolverFees); // Attempt to add fees to the dispute resolver, expecting revert @@ -1506,7 +1532,7 @@ describe("DisputeResolverHandler", function () { }); it("Fee amount is not 0", async function () { - disputeResolverFees = [new DisputeResolverFee(other4.address, "MockToken4", "200")]; + disputeResolverFees = [new DisputeResolverFee(await other4.getAddress(), "MockToken4", "200")]; // Attempt to Create a DR, expecting revert await expect( @@ -1530,17 +1556,17 @@ describe("DisputeResolverHandler", function () { }); it("should emit a DisputeResolverFeesRemoved event", async function () { - feeTokenAddressesToRemove = [other1.address, other2.address, other3.address]; + feeTokenAddressesToRemove = [await other1.getAddress(), await other2.getAddress(), await other3.getAddress()]; await expect( accountHandler.connect(admin).removeFeesFromDisputeResolver(disputeResolver.id, feeTokenAddressesToRemove) ) .to.emit(accountHandler, "DisputeResolverFeesRemoved") - .withArgs(disputeResolver.id, feeTokenAddressesToRemove, admin.address); + .withArgs(disputeResolver.id, feeTokenAddressesToRemove, await admin.getAddress()); }); it("should update the DisputeResolverFee state only if the first DisputeResolverFee is removed", async function () { - feeTokenAddressesToRemove = [other1.address]; + feeTokenAddressesToRemove = [await other1.getAddress()]; // Remove fees from dispute resolver await accountHandler @@ -1564,8 +1590,8 @@ describe("DisputeResolverHandler", function () { } const expectedDisputeResolverFees = [ - new DisputeResolverFee(other3.address, "MockToken3", "0"), - new DisputeResolverFee(other2.address, "MockToken2", "0"), + new DisputeResolverFee(await other3.getAddress(), "MockToken3", "0"), + new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0"), ]; const expectedDisputeResolverFeeList = new DisputeResolverFeeList(expectedDisputeResolverFees); @@ -1577,7 +1603,7 @@ describe("DisputeResolverHandler", function () { }); it("should update state only if the last DisputeResolverFee is removed", async function () { - feeTokenAddressesToRemove = [other3.address]; + feeTokenAddressesToRemove = [await other3.getAddress()]; // Remove fees from dispute resolver await accountHandler @@ -1601,8 +1627,8 @@ describe("DisputeResolverHandler", function () { } const expectedDisputeResolverFees = [ - new DisputeResolverFee(other1.address, "MockToken1", "0"), - new DisputeResolverFee(other2.address, "MockToken2", "0"), + new DisputeResolverFee(await other1.getAddress(), "MockToken1", "0"), + new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0"), ]; const expectedDisputeResolverFeeList = new DisputeResolverFeeList(expectedDisputeResolverFees); @@ -1614,7 +1640,7 @@ describe("DisputeResolverHandler", function () { }); it("should update DisputeResolverFee state only if some DisputeResolverFees are removed", async function () { - feeTokenAddressesToRemove = [other1.address, other3.address]; + feeTokenAddressesToRemove = [await other1.getAddress(), await other3.getAddress()]; // Remove fees from dispute resolver await accountHandler @@ -1637,7 +1663,7 @@ describe("DisputeResolverHandler", function () { expect(JSON.stringify(returnedDisputeResolver[key]) === JSON.stringify(value)).is.true; } - const expectedisputeResolverFees = [new DisputeResolverFee(other2.address, "MockToken2", "0")]; + const expectedisputeResolverFees = [new DisputeResolverFee(await other2.getAddress(), "MockToken2", "0")]; const expectedDisputeResolverFeeList = new DisputeResolverFeeList(expectedisputeResolverFees); assert.equal( @@ -1650,7 +1676,11 @@ describe("DisputeResolverHandler", function () { }); it("should update DisputeResolverFee state only if all DisputeResolverFees are removed", async function () { - const feeTokenAddressesToRemove = [other1.address, other2.address, other3.address]; + const feeTokenAddressesToRemove = [ + await other1.getAddress(), + await other2.getAddress(), + await other3.getAddress(), + ]; // Remove fees from dispute resolver await accountHandler @@ -1687,7 +1717,7 @@ describe("DisputeResolverHandler", function () { context("💔 Revert Reasons", async function () { beforeEach(async function () { - feeTokenAddressesToRemove = [other1.address, other2.address, other3.address]; + feeTokenAddressesToRemove = [await other1.getAddress(), await other2.getAddress(), await other3.getAddress()]; }); it("The dispute resolvers region of protocol is paused", async function () { @@ -1744,7 +1774,7 @@ describe("DisputeResolverHandler", function () { }); it("DisputeResolverFee in array does not exist for Dispute Resolver", async function () { - feeTokenAddressesToRemove = [other4.address, other5.address]; + feeTokenAddressesToRemove = [await other4.getAddress(), await other5.getAddress()]; // Attempt to remove fees from the dispute resolver, expecting revert await expect( @@ -1761,7 +1791,12 @@ describe("DisputeResolverHandler", function () { .createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList); // make another seller with id = "5" - let seller4 = mockSeller(other3.address, other3.address, ethers.constants.AddressZero, other3.address); + let seller4 = mockSeller( + await other3.getAddress(), + await other3.getAddress(), + ZeroAddress, + await other3.getAddress() + ); await accountHandler.connect(other3).createSeller(seller4, emptyAuthToken, voucherInitValues); @@ -1783,7 +1818,7 @@ describe("DisputeResolverHandler", function () { // add sellers, test for event await expect(accountHandler.connect(admin).addSellersToAllowList(disputeResolver.id, allowedSellersToAdd)) .to.emit(accountHandler, "AllowedSellersAdded") - .withArgs(disputeResolver.id, allowedSellersToAdd, admin.address); + .withArgs(disputeResolver.id, allowedSellersToAdd, await admin.getAddress()); }); it("should update SellerAllowList state only", async function () { @@ -1924,7 +1959,12 @@ describe("DisputeResolverHandler", function () { .createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList); // make another seller with id = "5" - const seller4 = mockSeller(other3.address, other3.address, ethers.constants.AddressZero, other3.address); + const seller4 = mockSeller( + await other3.getAddress(), + await other3.getAddress(), + ZeroAddress, + await other3.getAddress() + ); // AuthToken emptyAuthToken = mockAuthToken(); @@ -1946,7 +1986,7 @@ describe("DisputeResolverHandler", function () { accountHandler.connect(admin).removeSellersFromAllowList(disputeResolver.id, allowedSellersToRemove) ) .to.emit(accountHandler, "AllowedSellersRemoved") - .withArgs(disputeResolver.id, allowedSellersToRemove, admin.address); + .withArgs(disputeResolver.id, allowedSellersToRemove, await admin.getAddress()); }); it("should update SellerAllowList state only if some Allowed Sellers are removed", async function () { @@ -2018,7 +2058,12 @@ describe("DisputeResolverHandler", function () { expect(returnedSellerAllowList.toString()).to.eql(expectedSellerAllowList.toString(), "Allowed list wrong"); // make another seller with id = "6" - const seller6 = mockSeller(other4.address, other4.address, ethers.constants.AddressZero, other4.address); + const seller6 = mockSeller( + await other4.getAddress(), + await other4.getAddress(), + ZeroAddress, + await other4.getAddress() + ); await accountHandler.connect(other4).createSeller(seller6, emptyAuthToken, voucherInitValues); // check that mappings of allowed selleres were updated @@ -2084,7 +2129,12 @@ describe("DisputeResolverHandler", function () { it("Seller id is not approved", async function () { // make another seller with id = "6" - const seller6 = mockSeller(other4.address, other4.address, ethers.constants.AddressZero, other4.address); + const seller6 = mockSeller( + await other4.getAddress(), + await other4.getAddress(), + ZeroAddress, + await other4.getAddress() + ); await accountHandler.connect(other4).createSeller(seller6, emptyAuthToken, voucherInitValues); // seller exists, it's not approved @@ -2117,8 +2167,8 @@ describe("DisputeResolverHandler", function () { }); it("New assistant should opt-in to update disputeResolver", async function () { - disputeResolver.assistant = other1.address; - expectedDisputeResolver.assistant = other1.address; + disputeResolver.assistant = await other1.getAddress(); + expectedDisputeResolver.assistant = await other1.getAddress(); expectedDisputeResolverStruct = expectedDisputeResolver.toStruct(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); @@ -2133,13 +2183,13 @@ describe("DisputeResolverHandler", function () { disputeResolver.id, expectedDisputeResolverStruct, disputeResolverPendingUpdateStruct, - other1.address + await other1.getAddress() ); }); it("New admin should opt-in to update disputeResolver", async function () { - disputeResolver.admin = other1.address; - expectedDisputeResolver.admin = other1.address; + disputeResolver.admin = await other1.getAddress(); + expectedDisputeResolver.admin = await other1.getAddress(); expectedDisputeResolverStruct = expectedDisputeResolver.toStruct(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); @@ -2154,14 +2204,14 @@ describe("DisputeResolverHandler", function () { disputeResolver.id, expectedDisputeResolverStruct, disputeResolverPendingUpdateStruct, - other1.address + await other1.getAddress() ); }); it("Should update admin and assistant in a single call ", async function () { - disputeResolver.clerk = expectedDisputeResolver.clerk = ethers.constants.AddressZero; - disputeResolver.admin = expectedDisputeResolver.admin = other1.address; - disputeResolver.assistant = expectedDisputeResolver.assistant = other1.address; + disputeResolver.clerk = expectedDisputeResolver.clerk = ZeroAddress; + disputeResolver.admin = expectedDisputeResolver.admin = await other1.getAddress(); + disputeResolver.assistant = expectedDisputeResolver.assistant = await other1.getAddress(); expectedDisputeResolverStruct = expectedDisputeResolver.toStruct(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); @@ -2179,28 +2229,28 @@ describe("DisputeResolverHandler", function () { disputeResolver.id, expectedDisputeResolverStruct, disputeResolverPendingUpdateStruct, - other1.address + await other1.getAddress() ); }); it("If updateDisputeResolver is called twice with no optIn in between, disputeResolverPendingUpdate is populated with the data from second call", async function () { - disputeResolver.assistant = disputeResolverPendingUpdate.assistant = other1.address; + disputeResolver.assistant = disputeResolverPendingUpdate.assistant = await other1.getAddress(); disputeResolverPendingUpdateStruct = disputeResolverPendingUpdate.toStruct(); await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)) .to.emit(accountHandler, "DisputeResolverUpdatePending") - .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, admin.address); + .withArgs(disputeResolver.id, disputeResolverPendingUpdateStruct, await admin.getAddress()); const disputeResolverPendingUpdate2 = disputeResolverPendingUpdate.clone(); disputeResolver.assistant = expectedDisputeResolver.assistant = disputeResolverPendingUpdate2.assistant = - other2.address; + await other2.getAddress(); let disputeResolverPendingUpdate2Struct = disputeResolverPendingUpdate2.toStruct(); await expect(accountHandler.connect(admin).updateDisputeResolver(disputeResolver)) .to.emit(accountHandler, "DisputeResolverUpdatePending") - .withArgs(disputeResolver.id, disputeResolverPendingUpdate2Struct, admin.address); + .withArgs(disputeResolver.id, disputeResolverPendingUpdate2Struct, await admin.getAddress()); await expect( accountHandler @@ -2208,7 +2258,7 @@ describe("DisputeResolverHandler", function () { .optInToDisputeResolverUpdate(disputeResolver.id, [DisputeResolverUpdateFields.Assistant]) ).to.revertedWith(RevertReasons.UNAUTHORIZED_CALLER_UPDATE); - disputeResolverPendingUpdate.assistant = ethers.constants.AddressZero; + disputeResolverPendingUpdate.assistant = ZeroAddress; disputeResolverPendingUpdate2Struct = disputeResolverPendingUpdate.toStruct(); expectedDisputeResolverStruct = expectedDisputeResolver.toStruct(); @@ -2223,12 +2273,12 @@ describe("DisputeResolverHandler", function () { disputeResolver.id, expectedDisputeResolverStruct, disputeResolverPendingUpdate2Struct, - other2.address + await other2.getAddress() ); }); it("Should not emit 'DisputeResolverUpdateApplied' event if caller doesn't specify any field", async function () { - disputeResolver.assistant = other1.address; + disputeResolver.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); await expect(accountHandler.connect(other1).optInToDisputeResolverUpdate(disputeResolver.id, [])).to.not.emit( @@ -2238,7 +2288,7 @@ describe("DisputeResolverHandler", function () { }); it("Should not emit 'DisputeResolverUpdateApplied'event if there is no pending update for specified field", async function () { - disputeResolver.assistant = other1.address; + disputeResolver.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); await expect( @@ -2250,9 +2300,9 @@ describe("DisputeResolverHandler", function () { context("💔 Revert Reasons", async function () { it("There are no pending updates", async function () { - disputeResolver.clerk = ethers.constants.AddressZero; - disputeResolver.admin = other1.address; - disputeResolver.assistant = other1.address; + disputeResolver.clerk = ZeroAddress; + disputeResolver.admin = await other1.getAddress(); + disputeResolver.assistant = await other1.getAddress(); expectedDisputeResolver = disputeResolver.clone(); expectedDisputeResolver.active = true; expectedDisputeResolverStruct = expectedDisputeResolver.toStruct(); @@ -2273,7 +2323,7 @@ describe("DisputeResolverHandler", function () { disputeResolver.id, expectedDisputeResolverStruct, disputeResolverPendingUpdateStruct, - other1.address + await other1.getAddress() ); await expect( @@ -2282,7 +2332,7 @@ describe("DisputeResolverHandler", function () { }); it("Caller is not the new admin", async function () { - disputeResolver.admin = other1.address; + disputeResolver.admin = await other1.getAddress(); disputeResolverStruct = disputeResolver.toStruct(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); @@ -2295,7 +2345,7 @@ describe("DisputeResolverHandler", function () { }); it("Caller is not the new assistant", async function () { - disputeResolver.assistant = other1.address; + disputeResolver.assistant = await other1.getAddress(); disputeResolverStruct = disputeResolver.toStruct(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); @@ -2308,7 +2358,7 @@ describe("DisputeResolverHandler", function () { }); it("The DisputeResolvers region of protocol is paused", async function () { - disputeResolver.assistant = other1.address; + disputeResolver.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); @@ -2322,15 +2372,15 @@ describe("DisputeResolverHandler", function () { it("Admin is not unique to this disputeResolver", async function () { // Update disputeResolver admin - disputeResolver.admin = other1.address; + disputeResolver.admin = await other1.getAddress(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); // Create disputeResolver with same admin disputeResolver2 = mockDisputeResolver( - other1.address, - other1.address, - ethers.constants.AddressZero, - other1.address + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() ); expect(disputeResolver2.isValid()).is.true; @@ -2348,15 +2398,15 @@ describe("DisputeResolverHandler", function () { it("Assistant is not unique to this disputeResolver", async function () { // Update disputeResolver assistant - disputeResolver.assistant = other1.address; + disputeResolver.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); // Create disputeResolver with same assistant disputeResolver2 = mockDisputeResolver( - other1.address, - other1.address, - ethers.constants.AddressZero, - other1.address + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() ); expect(disputeResolver2.isValid()).is.true; @@ -2373,7 +2423,7 @@ describe("DisputeResolverHandler", function () { }); it("Dispute resolver tries to update the clerk", async function () { - disputeResolver.assistant = other1.address; + disputeResolver.assistant = await other1.getAddress(); disputeResolverStruct = disputeResolver.toStruct(); await accountHandler.connect(admin).updateDisputeResolver(disputeResolver); diff --git a/test/protocol/ExchangeHandlerTest.js b/test/protocol/ExchangeHandlerTest.js index ccf8e0b8d..61b3b9d45 100644 --- a/test/protocol/ExchangeHandlerTest.js +++ b/test/protocol/ExchangeHandlerTest.js @@ -1,4 +1,16 @@ const { ethers } = require("hardhat"); +const { + ZeroAddress, + getSigners, + getContractAt, + provider, + parseUnits, + getContractFactory, + MaxUint256, + parseEther, + getImpersonatedSigner, + toBeHex, +} = ethers; const { expect, assert } = require("chai"); const Role = require("../../scripts/domain/Role"); @@ -148,12 +160,12 @@ describe("IBosonExchangeHandler", function () { diamondAddress: protocolDiamondAddress, } = await setupTestEnvironment(contracts)); - [deployer] = await ethers.getSigners(); + [deployer] = await getSigners(); // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; // Deploy the mock tokens [foreign20, foreign721, foreign1155] = await deployMockTokens(["Foreign20", "Foreign721", "Foreign1155"]); @@ -170,24 +182,24 @@ describe("IBosonExchangeHandler", function () { async function upgradeMetaTransactionsHandlerFacet() { // Upgrade the ExchangeHandlerFacet functions // DiamondCutFacet - const cutFacetViaDiamond = await ethers.getContractAt("DiamondCutFacet", protocolDiamondAddress); + const cutFacetViaDiamond = await getContractAt("DiamondCutFacet", protocolDiamondAddress); // Deploy MockMetaTransactionsHandlerFacet - const MockMetaTransactionsHandlerFacet = await ethers.getContractFactory("MockMetaTransactionsHandlerFacet"); + const MockMetaTransactionsHandlerFacet = await getContractFactory("MockMetaTransactionsHandlerFacet"); const mockMetaTransactionsHandlerFacet = await MockMetaTransactionsHandlerFacet.deploy(); - await mockMetaTransactionsHandlerFacet.deployed(); + await mockMetaTransactionsHandlerFacet.waitForDeployment(); // Define the facet cut const facetCuts = [ { - facetAddress: mockMetaTransactionsHandlerFacet.address, + facetAddress: await mockMetaTransactionsHandlerFacet.getAddress(), action: FacetCutAction.Add, functionSelectors: getSelectors(mockMetaTransactionsHandlerFacet), }, ]; // Send the DiamondCut transaction - const tx = await cutFacetViaDiamond.connect(deployer).diamondCut(facetCuts, ethers.constants.AddressZero, "0x"); + const tx = await cutFacetViaDiamond.connect(deployer).diamondCut(facetCuts, ZeroAddress, "0x"); // Wait for transaction to confirm const receipt = await tx.wait(); @@ -196,10 +208,7 @@ describe("IBosonExchangeHandler", function () { assert.equal(receipt.status, 1, `Diamond upgrade failed: ${tx.hash}`); // Cast Diamond to MockMetaTransactionsHandlerFacet - mockMetaTransactionsHandler = await ethers.getContractAt( - "MockMetaTransactionsHandlerFacet", - protocolDiamondAddress - ); + mockMetaTransactionsHandler = await getContractAt("MockMetaTransactionsHandlerFacet", protocolDiamondAddress); } // Interface support (ERC-156 provided by ProtocolDiamond, others by deployed facets) @@ -223,7 +232,12 @@ describe("IBosonExchangeHandler", function () { agentId = "0"; // agent id is optional while creating an offer // Create a valid seller - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // AuthToken @@ -237,20 +251,20 @@ describe("IBosonExchangeHandler", function () { expect(voucherInitValues.isValid()).is.true; await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); - expectedCloneAddress = calculateContractAddress(accountHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "1"); // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed - disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")]; + disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", "0")]; // Make empty seller list, so every seller is allowed const sellerAllowList = []; @@ -283,7 +297,7 @@ describe("IBosonExchangeHandler", function () { voucherRedeemableFrom = offerDates.voucherRedeemableFrom; voucherValid = offerDurations.voucherValid; disputePeriod = offerDurations.disputePeriod; - sellerPool = ethers.utils.parseUnits("15", "ether").toString(); + sellerPool = parseUnits("15", "ether").toString(); // Required voucher constructor params voucher = mockVoucher(); @@ -297,9 +311,7 @@ describe("IBosonExchangeHandler", function () { exchange.finalizedDate = "0"; // Deposit seller funds so the commit will succeed - await fundsHandler - .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerPool, { value: sellerPool }); + await fundsHandler.connect(assistant).depositFunds(seller.id, ZeroAddress, sellerPool, { value: sellerPool }); }); afterEach(async function () { @@ -310,13 +322,13 @@ describe("IBosonExchangeHandler", function () { context("👉 commitToOffer()", async function () { it("should emit a BuyerCommitted event", async function () { // Commit to offer, retrieving the event - tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + tx = await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); txReceipt = await tx.wait(); event = getEvent(txReceipt, exchangeHandler, "BuyerCommitted"); // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -342,7 +354,7 @@ describe("IBosonExchangeHandler", function () { it("should increment the next exchange id counter", async function () { // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Get the next exchange id and ensure it was incremented by the creation of the offer nextExchangeId = await exchangeHandler.connect(rando).getNextExchangeId(); @@ -351,17 +363,17 @@ describe("IBosonExchangeHandler", function () { it("should issue the voucher on the correct clone", async function () { // Cast expectedCloneAddress to IBosonVoucher (existing clone) - bosonVoucherClone = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucherClone = await getContractAt("IBosonVoucher", expectedCloneAddress); // Create a new seller to get new clone - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller(await rando.getAddress(), await rando.getAddress(), ZeroAddress, await rando.getAddress()); seller.id = "3"; // buyer is created after seller in this test expect(seller.isValid()).is.true; await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); - expectedCloneAddress = calculateContractAddress(accountHandler.address, "2"); - const bosonVoucherClone2 = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "2"); + const bosonVoucherClone2 = await getContractAt("IBosonVoucher", expectedCloneAddress); // Create an offer with new seller const { offer, offerDates, offerDurations, disputeResolverId } = await mockOffer(); @@ -370,46 +382,61 @@ describe("IBosonExchangeHandler", function () { await offerHandler.connect(rando).createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // Deposit seller funds so the commit will succeed - await fundsHandler - .connect(rando) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerPool, { value: sellerPool }); + await fundsHandler.connect(rando).depositFunds(seller.id, ZeroAddress, sellerPool, { value: sellerPool }); const buyer2 = newOwner; // Commit to offer, creating a new exchange - tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + tx = await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); const tokenId1 = deriveTokenId(offerId, "1"); - const tx2 = await exchangeHandler.connect(deployer).commitToOffer(buyer2.address, ++offerId, { value: price }); + const tx2 = await exchangeHandler + .connect(deployer) + .commitToOffer(await buyer2.getAddress(), ++offerId, { value: price }); const tokenId2 = deriveTokenId(offerId, "2"); await expect(tx) .to.emit(bosonVoucherClone, "Transfer") - .withArgs(ethers.constants.Zero, buyer.address, tokenId1); + .withArgs(0n, await buyer.getAddress(), tokenId1); await expect(tx2) .to.emit(bosonVoucherClone2, "Transfer") - .withArgs(ethers.constants.Zero, buyer2.address, tokenId2); + .withArgs(0n, await buyer2.getAddress(), tokenId2); // buyer should own 1 voucher on the clone1 address and buyer2 should own 1 voucher on clone2 - expect(await bosonVoucherClone.balanceOf(buyer.address)).to.equal("1", "Clone 1: buyer 1 balance should be 1"); - expect(await bosonVoucherClone.balanceOf(buyer2.address)).to.equal("0", "Clone 1: buyer 2 balance should be 0"); - expect(await bosonVoucherClone2.balanceOf(buyer.address)).to.equal("0", "Clone 2: buyer 1 balance should be 0"); - expect(await bosonVoucherClone2.balanceOf(buyer2.address)).to.equal( + expect(await bosonVoucherClone.balanceOf(await buyer.getAddress())).to.equal( + "1", + "Clone 1: buyer 1 balance should be 1" + ); + expect(await bosonVoucherClone.balanceOf(await buyer2.getAddress())).to.equal( + "0", + "Clone 1: buyer 2 balance should be 0" + ); + expect(await bosonVoucherClone2.balanceOf(await buyer.getAddress())).to.equal( + "0", + "Clone 2: buyer 1 balance should be 0" + ); + expect(await bosonVoucherClone2.balanceOf(await buyer2.getAddress())).to.equal( "1", "Clone 2: buyer 2 balance should be 1" ); // Make sure that vouchers belong to correct buyers and that exist on the correct clone - expect(await bosonVoucherClone.ownerOf(tokenId1)).to.equal(buyer.address, "Voucher 1: Wrong buyer address"); + expect(await bosonVoucherClone.ownerOf(tokenId1)).to.equal( + await buyer.getAddress(), + "Voucher 1: Wrong buyer address" + ); await expect(bosonVoucherClone.ownerOf(tokenId2)).to.revertedWith(RevertReasons.ERC721_NON_EXISTENT); - expect(await bosonVoucherClone2.ownerOf(tokenId2)).to.equal(buyer2.address, "Voucher 2: Wrong buyer address"); + expect(await bosonVoucherClone2.ownerOf(tokenId2)).to.equal( + await buyer2.getAddress(), + "Voucher 2: Wrong buyer address" + ); await expect(bosonVoucherClone2.ownerOf(tokenId1)).to.revertedWith(RevertReasons.ERC721_NON_EXISTENT); // reference boson voucher proxy should not have any vouchers - expect(await bosonVoucher.balanceOf(buyer.address)).to.equal( + expect(await bosonVoucher.balanceOf(await buyer.getAddress())).to.equal( "0", "Reference proxy: buyer 1 balance should be 0" ); - expect(await bosonVoucher.balanceOf(buyer2.address)).to.equal( + expect(await bosonVoucher.balanceOf(await buyer2.getAddress())).to.equal( "0", "Reference proxy: buyer 2 balance should be 0" ); @@ -419,11 +446,11 @@ describe("IBosonExchangeHandler", function () { await expect(bosonVoucher.ownerOf(tokenId2)).to.revertedWith(RevertReasons.ERC721_NON_EXISTENT); // boson voucher implementation should not have any vouchers - expect(await voucherImplementation.balanceOf(buyer.address)).to.equal( + expect(await voucherImplementation.balanceOf(await buyer.getAddress())).to.equal( "0", "Voucher implementation: buyer 1 balance should be 0" ); - expect(await voucherImplementation.balanceOf(buyer2.address)).to.equal( + expect(await voucherImplementation.balanceOf(await buyer2.getAddress())).to.equal( "0", "Voucher implementation: buyer 2 balance should be 0" ); @@ -435,10 +462,10 @@ describe("IBosonExchangeHandler", function () { it("ERC2981: issued voucher should have royalty fees", async function () { // Cast expectedCloneAddress to IBosonVoucher (existing clone) - bosonVoucherClone = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucherClone = await getContractAt("IBosonVoucher", expectedCloneAddress); // Create a new seller to get new clone - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller(await rando.getAddress(), await rando.getAddress(), ZeroAddress, await rando.getAddress()); seller.id = "3"; // buyer is created after seller in this test expect(seller.isValid()).is.true; @@ -447,8 +474,8 @@ describe("IBosonExchangeHandler", function () { expect(voucherInitValues.isValid()).is.true; await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); - expectedCloneAddress = calculateContractAddress(accountHandler.address, "2"); - const bosonVoucherClone2 = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "2"); + const bosonVoucherClone2 = await getContractAt("IBosonVoucher", expectedCloneAddress); // Create an offer with new seller const { offer, offerDates, offerDurations, disputeResolverId } = await mockOffer(); @@ -457,38 +484,53 @@ describe("IBosonExchangeHandler", function () { await offerHandler.connect(rando).createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // Deposit seller funds so the commit will succeed - await fundsHandler - .connect(rando) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerPool, { value: sellerPool }); + await fundsHandler.connect(rando).depositFunds(seller.id, ZeroAddress, sellerPool, { value: sellerPool }); const buyer2 = newOwner; // Commit to offer, creating a new exchange - tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + tx = await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); const tokenId1 = deriveTokenId(offerId, "1"); - const tx2 = await exchangeHandler.connect(deployer).commitToOffer(buyer2.address, ++offerId, { value: price }); + const tx2 = await exchangeHandler + .connect(deployer) + .commitToOffer(await buyer2.getAddress(), ++offerId, { value: price }); const tokenId2 = deriveTokenId(offerId, "2"); await expect(tx) .to.emit(bosonVoucherClone, "Transfer") - .withArgs(ethers.constants.Zero, buyer.address, tokenId1); + .withArgs(0n, await buyer.getAddress(), tokenId1); await expect(tx2) .to.emit(bosonVoucherClone2, "Transfer") - .withArgs(ethers.constants.Zero, buyer2.address, tokenId2); + .withArgs(0n, await buyer2.getAddress(), tokenId2); // buyer should own 1 voucher on the clone1 address and buyer2 should own 1 voucher on clone2 - expect(await bosonVoucherClone.balanceOf(buyer.address)).to.equal("1", "Clone 1: buyer 1 balance should be 1"); - expect(await bosonVoucherClone.balanceOf(buyer2.address)).to.equal("0", "Clone 1: buyer 2 balance should be 0"); - expect(await bosonVoucherClone2.balanceOf(buyer.address)).to.equal("0", "Clone 2: buyer 1 balance should be 0"); - expect(await bosonVoucherClone2.balanceOf(buyer2.address)).to.equal( + expect(await bosonVoucherClone.balanceOf(await buyer.getAddress())).to.equal( + "1", + "Clone 1: buyer 1 balance should be 1" + ); + expect(await bosonVoucherClone.balanceOf(await buyer2.getAddress())).to.equal( + "0", + "Clone 1: buyer 2 balance should be 0" + ); + expect(await bosonVoucherClone2.balanceOf(await buyer.getAddress())).to.equal( + "0", + "Clone 2: buyer 1 balance should be 0" + ); + expect(await bosonVoucherClone2.balanceOf(await buyer2.getAddress())).to.equal( "1", "Clone 2: buyer 2 balance should be 1" ); // Make sure that vouchers belong to correct buyers and that exist on the correct clone - expect(await bosonVoucherClone.ownerOf(tokenId1)).to.equal(buyer.address, "Voucher 1: Wrong buyer address"); + expect(await bosonVoucherClone.ownerOf(tokenId1)).to.equal( + await buyer.getAddress(), + "Voucher 1: Wrong buyer address" + ); await expect(bosonVoucherClone.ownerOf(tokenId2)).to.revertedWith(RevertReasons.ERC721_NON_EXISTENT); - expect(await bosonVoucherClone2.ownerOf(tokenId2)).to.equal(buyer2.address, "Voucher 2: Wrong buyer address"); + expect(await bosonVoucherClone2.ownerOf(tokenId2)).to.equal( + await buyer2.getAddress(), + "Voucher 2: Wrong buyer address" + ); await expect(bosonVoucherClone2.ownerOf(tokenId1)).to.revertedWith(RevertReasons.ERC721_NON_EXISTENT); // Make sure that vouchers have correct royalty fee for exchangeId 1 @@ -537,13 +579,13 @@ describe("IBosonExchangeHandler", function () { exchange.offerId = offerId = "2"; // tested against second offer // Commit to offer, retrieving the event - tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + tx = await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); txReceipt = await tx.wait(); event = getEvent(txReceipt, exchangeHandler, "BuyerCommitted"); // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -569,7 +611,7 @@ describe("IBosonExchangeHandler", function () { it("Should decrement quantityAvailable", async function () { // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Offer qunantityAvailable should be decremented const [, offer] = await offerHandler.connect(rando).getOffer(offerId); @@ -579,7 +621,7 @@ describe("IBosonExchangeHandler", function () { it("Should not decrement quantityAvailable if offer is unlimited", async function () { // Create an offer with unlimited quantity let { offer, ...details } = await mockOffer(); - offer.quantityAvailable = ethers.constants.MaxUint256.toString(); + offer.quantityAvailable = MaxUint256.toString(); // Delete unnecessary field delete details.offerFees; @@ -592,11 +634,11 @@ describe("IBosonExchangeHandler", function () { exchange.offerId = offerId = "2"; // first offer is created on beforeEach // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Offer qunantityAvailable should not be decremented [, offer] = await offerHandler.connect(rando).getOffer(offerId); - expect(offer.quantityAvailable).to.equal(ethers.constants.MaxUint256, "Quantity available should be unlimited"); + expect(offer.quantityAvailable).to.equal(MaxUint256, "Quantity available should be unlimited"); }); it("Should not decrement seller funds if offer price and sellerDeposit is 0", async function () { @@ -614,7 +656,7 @@ describe("IBosonExchangeHandler", function () { offer = mo.offer; offer.price = offer.sellerDeposit = offer.buyerCancelPenalty = "0"; // set a dummy token address otherwise protocol token (zero address) and offer token will be the same and we will get the error AGENT_FEE_AMOUNT_TOO_HIGH - offer.exchangeToken = foreign20.address; + offer.exchangeToken = await foreign20.getAddress(); disputeResolverId = agentId = "0"; exchange.offerId = offerId = "2"; // first offer is created on beforeEach @@ -627,7 +669,7 @@ describe("IBosonExchangeHandler", function () { .createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId); // Seller funds after const sellerFundsAfter = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); @@ -644,7 +686,7 @@ describe("IBosonExchangeHandler", function () { // Attempt to create an exchange, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.REGION_PAUSED); }); @@ -654,14 +696,14 @@ describe("IBosonExchangeHandler", function () { // Attempt to create a buyer, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.REGION_PAUSED); }); it("buyer address is the zero address", async function () { // Attempt to commit, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(ethers.constants.AddressZero, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(ZeroAddress, offerId, { value: price }) ).to.revertedWith(RevertReasons.INVALID_ADDRESS); }); @@ -671,7 +713,7 @@ describe("IBosonExchangeHandler", function () { // Attempt to commit, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.NO_SUCH_OFFER); }); @@ -681,21 +723,18 @@ describe("IBosonExchangeHandler", function () { // Attempt to commit to the voided offer, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.OFFER_HAS_BEEN_VOIDED); }); it("offer is not yet available for commits", async function () { // Create an offer with staring date in the future // get current block timestamp - const block = await ethers.provider.getBlock("latest"); - const now = block.timestamp.toString(); + const block = await provider.getBlock("latest"); // set validFrom date in the past - offerDates.validFrom = ethers.BigNumber.from(now) - .add(oneMonth * 6) - .toString(); // 6 months in the future - offerDates.validUntil = ethers.BigNumber.from(offerDates.validFrom).add(10).toString(); // just after the valid from so it succeeds. + offerDates.validFrom = (BigInt(block.timestamp) + oneMonth * 6n).toString(); // 6 months in the future + offerDates.validUntil = BigInt(offerDates.validFrom + 10).toString(); // just after the valid from so it succeeds. await offerHandler .connect(assistant) @@ -703,7 +742,7 @@ describe("IBosonExchangeHandler", function () { // Attempt to commit to the not availabe offer, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, ++offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), ++offerId, { value: price }) ).to.revertedWith(RevertReasons.OFFER_NOT_AVAILABLE); }); @@ -713,7 +752,7 @@ describe("IBosonExchangeHandler", function () { // Attempt to commit to the expired offer, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.OFFER_HAS_EXPIRED); }); @@ -724,11 +763,11 @@ describe("IBosonExchangeHandler", function () { .connect(assistant) .createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // Commit to offer, so it's not availble anymore - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, ++offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), ++offerId, { value: price }); // Attempt to commit to the sold out offer, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.OFFER_SOLD_OUT); }); }); @@ -738,26 +777,29 @@ describe("IBosonExchangeHandler", function () { let tokenId; beforeEach(async function () { // Reserve range - await offerHandler.connect(assistant).reserveRange(offer.id, offer.quantityAvailable, assistant.address); + await offerHandler + .connect(assistant) + .reserveRange(offer.id, offer.quantityAvailable, await assistant.getAddress()); // expected address of the first clone - const voucherCloneAddress = calculateContractAddress(accountHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherCloneAddress); + const voucherCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("BosonVoucher", voucherCloneAddress); await bosonVoucher.connect(assistant).preMint(offer.id, offer.quantityAvailable); - tokenId = "1"; tokenId = deriveTokenId(offer.id, exchangeId); }); it("should emit a BuyerCommitted event", async function () { // Commit to preminted offer, retrieving the event - tx = await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + tx = await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); txReceipt = await tx.wait(); event = getEvent(txReceipt, exchangeHandler, "BuyerCommitted"); // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -786,7 +828,9 @@ describe("IBosonExchangeHandler", function () { let nextExchangeIdBefore = await exchangeHandler.connect(rando).getNextExchangeId(); // Commit to preminted offer, creating a new exchange - await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); // Get the next exchange id and ensure it was incremented by the creation of the offer nextExchangeId = await exchangeHandler.connect(rando).getNextExchangeId(); @@ -801,7 +845,9 @@ describe("IBosonExchangeHandler", function () { await expect(bosonVoucher.ownerOf(nextExchangeId)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); // Commit to preminted offer, creating a new exchange - await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); // Voucher with nextExchangeId still should not exist await expect(bosonVoucher.ownerOf(nextExchangeId)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); @@ -814,15 +860,17 @@ describe("IBosonExchangeHandler", function () { // Before voucher is transferred, it should have zero royalty fee let [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(tokenId, offer.price); - assert.equal(receiver, ethers.constants.AddressZero, "Recipient address is incorrect"); + assert.equal(receiver, ZeroAddress, "Recipient address is incorrect"); assert.equal(royaltyAmount.toString(), "0", "Royalty amount is incorrect"); // Commit to preminted offer, creating a new exchange - await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); // After voucher is transferred, it should have royalty fee [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(tokenId, offer.price); - assert.equal(receiver, treasury.address, "Recipient address is incorrect"); + assert.equal(receiver, await treasury.getAddress(), "Recipient address is incorrect"); assert.equal( royaltyAmount.toString(), applyPercentage(offer.price, royaltyPercentage), @@ -836,7 +884,9 @@ describe("IBosonExchangeHandler", function () { const quantityAvailableBefore = offer.quantityAvailable; // Commit to preminted offer - await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); // Offer qunantityAvailable should be decremented [, offer] = await offerHandler.connect(rando).getOffer(offerId); @@ -862,14 +912,14 @@ describe("IBosonExchangeHandler", function () { // Deposit seller funds so the commit will succeed await fundsHandler .connect(rando) - .depositFunds(seller.id, ethers.constants.AddressZero, offer.sellerDeposit, { value: offer.sellerDeposit }); + .depositFunds(seller.id, ZeroAddress, offer.sellerDeposit, { value: offer.sellerDeposit }); // reserve half of the offer, so it's still possible to commit directly - await offerHandler.connect(assistant).reserveRange(offerId, rangeLength, assistant.address); + await offerHandler.connect(assistant).reserveRange(offerId, rangeLength, await assistant.getAddress()); // Commit to offer directly await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: offer.price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: offer.price }) ).to.emit(exchangeHandler, "BuyerCommitted"); }); @@ -880,7 +930,9 @@ describe("IBosonExchangeHandler", function () { // Attempt to create an exchange, expecting revert await expect( - bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId) + bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId) ).to.revertedWith(RevertReasons.REGION_PAUSED); }); @@ -890,31 +942,37 @@ describe("IBosonExchangeHandler", function () { // Attempt to create a buyer, expecting revert await expect( - bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId) + bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId) ).to.revertedWith(RevertReasons.REGION_PAUSED); }); it("Caller is not the voucher contract, owned by the seller", async function () { // Attempt to commit to preminted offer, expecting revert await expect( - exchangeHandler.connect(rando).commitToPreMintedOffer(buyer.address, offerId, tokenId) + exchangeHandler.connect(rando).commitToPreMintedOffer(await buyer.getAddress(), offerId, tokenId) ).to.revertedWith(RevertReasons.ACCESS_DENIED); }); it("Exchange exists already", async function () { // Commit to preminted offer, creating a new exchange - await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); // impersonate voucher contract and give it some funds - const impersonatedBosonVoucher = await ethers.getImpersonatedSigner(bosonVoucher.address); - await ethers.provider.send("hardhat_setBalance", [ - impersonatedBosonVoucher.address, - ethers.utils.parseEther("10").toHexString(), + const impersonatedBosonVoucher = await getImpersonatedSigner(await bosonVoucher.getAddress()); + await provider.send("hardhat_setBalance", [ + await impersonatedBosonVoucher.getAddress(), + toBeHex(parseEther("10")), ]); // Simulate a second commit with the same token id await expect( - exchangeHandler.connect(impersonatedBosonVoucher).commitToPreMintedOffer(buyer.address, offerId, exchangeId) + exchangeHandler + .connect(impersonatedBosonVoucher) + .commitToPreMintedOffer(await buyer.getAddress(), offerId, exchangeId) ).to.revertedWith(RevertReasons.EXCHANGE_ALREADY_EXISTS); }); @@ -924,23 +982,23 @@ describe("IBosonExchangeHandler", function () { // Attempt to commit to the voided offer, expecting revert await expect( - bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId) + bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId) ).to.revertedWith(RevertReasons.OFFER_HAS_BEEN_VOIDED); }); it("offer is not yet available for commits", async function () { // Create an offer with staring date in the future // get current block timestamp - const block = await ethers.provider.getBlock("latest"); + const block = await provider.getBlock("latest"); const now = block.timestamp.toString(); // Get next offer id offerId = await offerHandler.getNextOfferId(); // set validFrom date in the past - offerDates.validFrom = ethers.BigNumber.from(now) - .add(oneMonth * 6) - .toString(); // 6 months in the future - offerDates.validUntil = ethers.BigNumber.from(offerDates.validFrom).add(10).toString(); // just after the valid from so it succeeds. + offerDates.validFrom = BigInt(now + oneMonth * 6n).toString(); // 6 months in the future + offerDates.validUntil = BigInt(offerDates.validFrom + 10n).toString(); // just after the valid from so it succeeds. await offerHandler .connect(assistant) @@ -948,14 +1006,16 @@ describe("IBosonExchangeHandler", function () { // Reserve a range and premint vouchers exchangeId = await exchangeHandler.getNextExchangeId(); - await offerHandler.connect(assistant).reserveRange(offerId, "1", assistant.address); + await offerHandler.connect(assistant).reserveRange(offerId, "1", await assistant.getAddress()); await bosonVoucher.connect(assistant).preMint(offerId, "1"); tokenId = deriveTokenId(offerId, exchangeId); // Attempt to commit to the not available offer, expecting revert await expect( - bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId) + bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId) ).to.revertedWith(RevertReasons.OFFER_NOT_AVAILABLE); }); @@ -965,7 +1025,9 @@ describe("IBosonExchangeHandler", function () { // Attempt to commit to the expired offer, expecting revert await expect( - bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId) + bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId) ).to.revertedWith(RevertReasons.OFFER_HAS_EXPIRED); }); @@ -976,11 +1038,11 @@ describe("IBosonExchangeHandler", function () { .connect(assistant) .createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // Commit to offer, so it's not availble anymore - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, ++offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), ++offerId, { value: price }); // Attempt to commit to the sold out offer, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.OFFER_SOLD_OUT); }); }); @@ -994,7 +1056,7 @@ describe("IBosonExchangeHandler", function () { offerIds = [offerId]; // Create Condition - condition = mockCondition({ tokenAddress: foreign20.address, threshold: "50", maxCommits: "3" }); + condition = mockCondition({ tokenAddress: await foreign20.getAddress(), threshold: "50", maxCommits: "3" }); expect(condition.isValid()).to.be.true; // Create Group @@ -1005,25 +1067,24 @@ describe("IBosonExchangeHandler", function () { it("should emit a BuyerCommitted event if user meets condition", async function () { // mint enough tokens for the buyer - await foreign20.connect(buyer).mint(buyer.address, condition.threshold); + await foreign20.connect(buyer).mint(await buyer.getAddress(), condition.threshold); // Commit to offer. // We're only concerned that the event is emitted, indicating the condition was met - await expect(exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price })).to.emit( - exchangeHandler, - "BuyerCommitted" - ); + await expect( + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) + ).to.emit(exchangeHandler, "BuyerCommitted"); }); it("should allow buyer to commit up to the max times for the group", async function () { // mint enough tokens for the buyer - await foreign20.connect(buyer).mint(buyer.address, condition.threshold); + await foreign20.connect(buyer).mint(await buyer.getAddress(), condition.threshold); // Commit to offer the maximum number of times for (let i = 0; i < Number(condition.maxCommits); i++) { // We're only concerned that the event is emitted, indicating the commit was allowed await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.emit(exchangeHandler, "BuyerCommitted"); } }); @@ -1032,22 +1093,22 @@ describe("IBosonExchangeHandler", function () { it("buyer does not meet condition for commit", async function () { // Attempt to commit, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.CANNOT_COMMIT); }); it("buyer has exhausted allowable commits", async function () { // mint a token for the buyer - await foreign20.connect(buyer).mint(buyer.address, condition.threshold); + await foreign20.connect(buyer).mint(await buyer.getAddress(), condition.threshold); // Commit to offer the maximum number of times for (let i = 0; i < Number(condition.maxCommits); i++) { - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); } // Attempt to commit again after maximum commits has been reached await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.CANNOT_COMMIT); }); }); @@ -1061,7 +1122,7 @@ describe("IBosonExchangeHandler", function () { // Create Condition condition = mockCondition({ - tokenAddress: foreign721.address, + tokenAddress: await foreign721.getAddress(), threshold: "5", maxCommits: "3", tokenType: TokenType.NonFungibleToken, @@ -1080,10 +1141,9 @@ describe("IBosonExchangeHandler", function () { // Commit to offer. // We're only concerned that the event is emitted, indicating the condition was met - await expect(exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price })).to.emit( - exchangeHandler, - "BuyerCommitted" - ); + await expect( + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) + ).to.emit(exchangeHandler, "BuyerCommitted"); }); it("should allow buyer to commit up to the max times for the group", async function () { @@ -1094,7 +1154,7 @@ describe("IBosonExchangeHandler", function () { for (let i = 0; i < Number(condition.maxCommits); i++) { // We're only concerned that the event is emitted, indicating the commit was allowed await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.emit(exchangeHandler, "BuyerCommitted"); } }); @@ -1103,7 +1163,7 @@ describe("IBosonExchangeHandler", function () { it("buyer does not meet condition for commit", async function () { // Attempt to commit, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.CANNOT_COMMIT); }); @@ -1113,12 +1173,12 @@ describe("IBosonExchangeHandler", function () { // Commit to offer the maximum number of times for (let i = 0; i < Number(condition.maxCommits); i++) { - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); } // Attempt to commit again after maximum commits has been reached await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.CANNOT_COMMIT); }); }); @@ -1132,7 +1192,7 @@ describe("IBosonExchangeHandler", function () { // Create Condition condition = mockCondition({ - tokenAddress: foreign1155.address, + tokenAddress: await foreign1155.getAddress(), threshold: "20", maxCommits: "3", tokenType: TokenType.MultiToken, @@ -1152,10 +1212,9 @@ describe("IBosonExchangeHandler", function () { // Commit to offer. // We're only concerned that the event is emitted, indicating the condition was met - await expect(exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price })).to.emit( - exchangeHandler, - "BuyerCommitted" - ); + await expect( + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) + ).to.emit(exchangeHandler, "BuyerCommitted"); }); it("should allow buyer to commit up to the max times for the group", async function () { @@ -1166,7 +1225,7 @@ describe("IBosonExchangeHandler", function () { for (let i = 0; i < Number(condition.maxCommits); i++) { // We're only concerned that the event is emitted, indicating the commit was allowed await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.emit(exchangeHandler, "BuyerCommitted"); } }); @@ -1175,7 +1234,7 @@ describe("IBosonExchangeHandler", function () { it("buyer does not meet condition for commit", async function () { // Attempt to commit, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.CANNOT_COMMIT); }); @@ -1185,12 +1244,12 @@ describe("IBosonExchangeHandler", function () { // Commit to offer the maximum number of times for (let i = 0; i < Number(condition.maxCommits); i++) { - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); } // Attempt to commit again after maximum commits has been reached await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.CANNOT_COMMIT); }); }); @@ -1204,7 +1263,7 @@ describe("IBosonExchangeHandler", function () { // Create Condition condition = mockCondition({ - tokenAddress: foreign721.address, + tokenAddress: await foreign721.getAddress(), threshold: "0", maxCommits: "3", tokenType: TokenType.NonFungibleToken, @@ -1225,10 +1284,9 @@ describe("IBosonExchangeHandler", function () { // Commit to offer. // We're only concerned that the event is emitted, indicating the condition was met - await expect(exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price })).to.emit( - exchangeHandler, - "BuyerCommitted" - ); + await expect( + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) + ).to.emit(exchangeHandler, "BuyerCommitted"); }); it("should allow buyer to commit up to the max times for the group", async function () { @@ -1239,7 +1297,7 @@ describe("IBosonExchangeHandler", function () { for (let i = 0; i < Number(condition.maxCommits); i++) { // We're only concerned that the event is emitted, indicating the commit was allowed await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.emit(exchangeHandler, "BuyerCommitted"); } }); @@ -1248,7 +1306,7 @@ describe("IBosonExchangeHandler", function () { it("token id does not exist", async function () { // Attempt to commit, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.ERC721_NON_EXISTENT); }); @@ -1258,7 +1316,7 @@ describe("IBosonExchangeHandler", function () { // Attempt to commit, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.CANNOT_COMMIT); }); @@ -1268,12 +1326,12 @@ describe("IBosonExchangeHandler", function () { // Commit to offer the maximum number of times for (let i = 0; i < Number(condition.maxCommits); i++) { - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); } // Attempt to commit again after maximum commits has been reached await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) ).to.revertedWith(RevertReasons.CANNOT_COMMIT); }); }); @@ -1298,10 +1356,9 @@ describe("IBosonExchangeHandler", function () { it("should emit a BuyerCommitted event", async function () { // Commit to offer. // We're only concerned that the event is emitted, indicating the condition was met - await expect(exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price })).to.emit( - exchangeHandler, - "BuyerCommitted" - ); + await expect( + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }) + ).to.emit(exchangeHandler, "BuyerCommitted"); }); }); }); @@ -1309,7 +1366,7 @@ describe("IBosonExchangeHandler", function () { context("👉 completeExchange()", async function () { beforeEach(async function () { // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); }); it("should emit an ExchangeCompleted event when buyer calls", async function () { @@ -1322,7 +1379,7 @@ describe("IBosonExchangeHandler", function () { // Complete the exchange, expecting event await expect(exchangeHandler.connect(buyer).completeExchange(exchange.id)) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchange.id, buyer.address); + .withArgs(offerId, buyerId, exchange.id, await buyer.getAddress()); }); it("should update state", async function () { @@ -1350,17 +1407,17 @@ describe("IBosonExchangeHandler", function () { await exchangeHandler.connect(buyer).redeemVoucher(exchange.id); // Get the current block info - blockNumber = await ethers.provider.getBlockNumber(); - block = await ethers.provider.getBlock(blockNumber); + blockNumber = await provider.getBlockNumber(); + block = await provider.getBlock(blockNumber); // Set time forward to run out the dispute period - newTime = ethers.BigNumber.from(block.timestamp).add(disputePeriod).add(1).toNumber(); + newTime = Number(BigInt(block.timestamp) + BigInt(disputePeriod) + 1n); await setNextBlockTimestamp(newTime); // Complete exchange await expect(exchangeHandler.connect(assistant).completeExchange(exchange.id)) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchange.id, assistant.address); + .withArgs(offerId, buyerId, exchange.id, await assistant.getAddress()); }); it("should emit an ExchangeCompleted event if anyone calls after dispute period", async function () { @@ -1371,17 +1428,17 @@ describe("IBosonExchangeHandler", function () { await exchangeHandler.connect(buyer).redeemVoucher(exchange.id); // Get the current block info - blockNumber = await ethers.provider.getBlockNumber(); - block = await ethers.provider.getBlock(blockNumber); + blockNumber = await provider.getBlockNumber(); + block = await provider.getBlock(blockNumber); // Set time forward to run out the dispute period - newTime = ethers.BigNumber.from(block.timestamp).add(disputePeriod).add(1).toNumber(); + newTime = Number(BigInt(block.timestamp) + BigInt(disputePeriod) + 1n); await setNextBlockTimestamp(newTime); // Complete exchange await expect(exchangeHandler.connect(rando).completeExchange(exchange.id)) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchange.id, rando.address); + .withArgs(offerId, buyerId, exchange.id, await rando.getAddress()); }); it("should emit an ExchangeCompleted event if another buyer calls after dispute period", async function () { @@ -1392,20 +1449,20 @@ describe("IBosonExchangeHandler", function () { await exchangeHandler.connect(buyer).redeemVoucher(exchange.id); // Get the current block info - blockNumber = await ethers.provider.getBlockNumber(); - block = await ethers.provider.getBlock(blockNumber); + blockNumber = await provider.getBlockNumber(); + block = await provider.getBlock(blockNumber); // Set time forward to run out the dispute period - newTime = ethers.BigNumber.from(block.timestamp).add(disputePeriod).add(1).toNumber(); + newTime = Number(BigInt(block.timestamp) + BigInt(disputePeriod) + 1n); await setNextBlockTimestamp(newTime); // Create a rando buyer account - await accountHandler.connect(rando).createBuyer(mockBuyer(rando.address)); + await accountHandler.connect(rando).createBuyer(mockBuyer(await rando.getAddress())); // Complete exchange await expect(exchangeHandler.connect(rando).completeExchange(exchange.id)) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchange.id, rando.address); + .withArgs(offerId, buyerId, exchange.id, await rando.getAddress()); }); context("💔 Revert Reasons", async function () { @@ -1473,7 +1530,7 @@ describe("IBosonExchangeHandler", function () { await exchangeHandler.connect(buyer).redeemVoucher(exchange.id); // Create a rando buyer account - await accountHandler.connect(rando).createBuyer(mockBuyer(rando.address)); + await accountHandler.connect(rando).createBuyer(mockBuyer(await rando.getAddress())); // Attempt to complete the exchange, expecting revert await expect(exchangeHandler.connect(rando).completeExchange(exchange.id)).to.revertedWith( @@ -1503,7 +1560,7 @@ describe("IBosonExchangeHandler", function () { for (exchangeId = 1; exchangeId <= 5; exchangeId++) { // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Redeem voucher await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); @@ -1517,23 +1574,23 @@ describe("IBosonExchangeHandler", function () { const tx = await exchangeHandler.connect(buyer).completeExchangeBatch(exchangesToComplete); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[0], buyer.address); + .withArgs(offerId, buyerId, exchangesToComplete[0], await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[1], buyer.address); + .withArgs(offerId, buyerId, exchangesToComplete[1], await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[2], buyer.address); + .withArgs(offerId, buyerId, exchangesToComplete[2], await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[3], buyer.address); + .withArgs(offerId, buyerId, exchangesToComplete[3], await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[4], buyer.address); + .withArgs(offerId, buyerId, exchangesToComplete[4], await buyer.getAddress()); }); it("should update state", async function () { @@ -1551,66 +1608,66 @@ describe("IBosonExchangeHandler", function () { it("should emit an ExchangeCompleted event if assistant calls after dispute period", async function () { // Get the current block info - blockNumber = await ethers.provider.getBlockNumber(); - block = await ethers.provider.getBlock(blockNumber); + blockNumber = await provider.getBlockNumber(); + block = await provider.getBlock(blockNumber); // Set time forward to run out the dispute period - newTime = ethers.BigNumber.from(block.timestamp).add(disputePeriod).add(1).toNumber(); + newTime = Number(BigInt(block.timestamp) + BigInt(disputePeriod) + 1n); await setNextBlockTimestamp(newTime); // Complete exchange const tx = await exchangeHandler.connect(assistant).completeExchangeBatch(exchangesToComplete); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[0], assistant.address); + .withArgs(offerId, buyerId, exchangesToComplete[0], await assistant.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[1], assistant.address); + .withArgs(offerId, buyerId, exchangesToComplete[1], await assistant.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[2], assistant.address); + .withArgs(offerId, buyerId, exchangesToComplete[2], await assistant.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[3], assistant.address); + .withArgs(offerId, buyerId, exchangesToComplete[3], await assistant.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[4], assistant.address); + .withArgs(offerId, buyerId, exchangesToComplete[4], await assistant.getAddress()); }); it("should emit an ExchangeCompleted event if anyone calls after dispute period", async function () { // Get the current block info - blockNumber = await ethers.provider.getBlockNumber(); - block = await ethers.provider.getBlock(blockNumber); + blockNumber = await provider.getBlockNumber(); + block = await provider.getBlock(blockNumber); // Set time forward to run out the dispute period - newTime = ethers.BigNumber.from(block.timestamp).add(disputePeriod).add(1).toNumber(); + newTime = Number(BigInt(block.timestamp) + BigInt(disputePeriod) + 1n); await setNextBlockTimestamp(newTime); // Complete exchange const tx = await exchangeHandler.connect(rando).completeExchangeBatch(exchangesToComplete); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[0], rando.address); + .withArgs(offerId, buyerId, exchangesToComplete[0], await rando.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[1], rando.address); + .withArgs(offerId, buyerId, exchangesToComplete[1], await rando.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[2], rando.address); + .withArgs(offerId, buyerId, exchangesToComplete[2], await rando.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[3], rando.address); + .withArgs(offerId, buyerId, exchangesToComplete[3], await rando.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ExchangeCompleted") - .withArgs(offerId, buyerId, exchangesToComplete[4], rando.address); + .withArgs(offerId, buyerId, exchangesToComplete[4], await rando.getAddress()); }); context("💔 Revert Reasons", async function () { @@ -1649,7 +1706,7 @@ describe("IBosonExchangeHandler", function () { it("exchange is not in redeemed state", async function () { // Create exchange with id 6 - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); exchangeId = "6"; // Cancel the voucher for any 1 exchange @@ -1666,7 +1723,7 @@ describe("IBosonExchangeHandler", function () { it("caller is not buyer and offer dispute period has not elapsed", async function () { // Create exchange with id 6 - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); exchangeId = "6"; @@ -1684,7 +1741,7 @@ describe("IBosonExchangeHandler", function () { it("caller is seller's assistant and offer dispute period has not elapsed", async function () { // Create exchange with id 6 - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); exchangeId = "6"; @@ -1702,14 +1759,14 @@ describe("IBosonExchangeHandler", function () { context("👉 revokeVoucher()", async function () { beforeEach(async function () { // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); }); it("should emit an VoucherRevoked event when seller's assistant calls", async function () { // Revoke the voucher, expecting event await expect(exchangeHandler.connect(assistant).revokeVoucher(exchange.id)) .to.emit(exchangeHandler, "VoucherRevoked") - .withArgs(offerId, exchange.id, assistant.address); + .withArgs(offerId, exchange.id, await assistant.getAddress()); }); it("should update state", async function () { @@ -1766,27 +1823,29 @@ describe("IBosonExchangeHandler", function () { context("👉 cancelVoucher()", async function () { beforeEach(async function () { // Commit to offer, retrieving the event - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); }); it("should emit an VoucherCanceled event when original buyer calls", async function () { // Cancel the voucher, expecting event await expect(exchangeHandler.connect(buyer).cancelVoucher(exchange.id)) .to.emit(exchangeHandler, "VoucherCanceled") - .withArgs(offerId, exchange.id, buyer.address); + .withArgs(offerId, exchange.id, await buyer.getAddress()); }); it("should emit an VoucherCanceled event when new owner (not a buyer) calls", async function () { // Transfer voucher to new owner tokenId = deriveTokenId(offerId, exchange.id); - bosonVoucherCloneAddress = calculateContractAddress(exchangeHandler.address, "1"); - bosonVoucherClone = await ethers.getContractAt("IBosonVoucher", bosonVoucherCloneAddress); - await bosonVoucherClone.connect(buyer).transferFrom(buyer.address, newOwner.address, tokenId); + bosonVoucherCloneAddress = calculateContractAddress(await exchangeHandler.getAddress(), "1"); + bosonVoucherClone = await getContractAt("IBosonVoucher", bosonVoucherCloneAddress); + await bosonVoucherClone + .connect(buyer) + .transferFrom(await buyer.getAddress(), await newOwner.getAddress(), tokenId); // Cancel the voucher, expecting event await expect(exchangeHandler.connect(newOwner).cancelVoucher(exchange.id)) .to.emit(exchangeHandler, "VoucherCanceled") - .withArgs(offerId, exchange.id, newOwner.address); + .withArgs(offerId, exchange.id, await newOwner.getAddress()); }); it("should update state when buyer calls", async function () { @@ -1860,7 +1919,7 @@ describe("IBosonExchangeHandler", function () { it("getCurrentSenderAddress() returns zero address and has isMetaTransaction set to true on chain", async function () { await upgradeMetaTransactionsHandlerFacet(); - await mockMetaTransactionsHandler.setAsMetaTransactionAndCurrentSenderAs(ethers.constants.AddressZero); + await mockMetaTransactionsHandler.setAsMetaTransactionAndCurrentSenderAs(ZeroAddress); // Attempt to cancel the voucher, expecting revert await expect(exchangeHandler.connect(rando).cancelVoucher(exchange.id)).to.revertedWith( @@ -1873,7 +1932,7 @@ describe("IBosonExchangeHandler", function () { context("👉 expireVoucher()", async function () { beforeEach(async function () { // Commit to offer, retrieving the event - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); }); it("should emit an VoucherExpired event when anyone calls and voucher has expired", async function () { @@ -1883,7 +1942,7 @@ describe("IBosonExchangeHandler", function () { // Expire the voucher, expecting event await expect(exchangeHandler.connect(rando).expireVoucher(exchange.id)) .to.emit(exchangeHandler, "VoucherExpired") - .withArgs(offerId, exchange.id, rando.address); + .withArgs(offerId, exchange.id, await rando.getAddress()); }); it("should update state when anyone calls and voucher has expired", async function () { @@ -1986,7 +2045,7 @@ describe("IBosonExchangeHandler", function () { context("👉 redeemVoucher()", async function () { beforeEach(async function () { // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); }); it("should emit a VoucherRedeemed event when buyer calls", async function () { @@ -1996,7 +2055,7 @@ describe("IBosonExchangeHandler", function () { // Redeem the voucher, expecting event await expect(exchangeHandler.connect(buyer).redeemVoucher(exchange.id)) .to.emit(exchangeHandler, "VoucherRedeemed") - .withArgs(offerId, exchange.id, buyer.address); + .withArgs(offerId, exchange.id, await buyer.getAddress()); }); it("should update state", async function () { @@ -2073,7 +2132,7 @@ describe("IBosonExchangeHandler", function () { context("👉 redeemVoucher() with bundle", async function () { beforeEach(async function () { // Mint some tokens to be bundled - await foreign20.connect(assistant).mint(assistant.address, "500"); + await foreign20.connect(assistant).mint(await assistant.getAddress(), "500"); // Mint first two and last two tokens of range await foreign721.connect(assistant).mint("0", "2"); await foreign721.connect(assistant).mint("8", "2"); @@ -2085,20 +2144,20 @@ describe("IBosonExchangeHandler", function () { await foreign1155.connect(assistant).setApprovalForAll(protocolDiamondAddress, true); // Create an ERC20 twin - twin20 = mockTwin(foreign20.address); + twin20 = mockTwin(await foreign20.getAddress()); twin20.amount = "3"; twin20.supplyAvailable = "30"; expect(twin20.isValid()).is.true; // Create an ERC721 twin - twin721 = mockTwin(foreign721.address, TokenType.NonFungibleToken); + twin721 = mockTwin(await foreign721.getAddress(), TokenType.NonFungibleToken); twin721.id = "2"; twin721.amount = "0"; twin721.supplyAvailable = "10"; expect(twin721.isValid()).is.true; // Create an ERC1155 twin - twin1155 = mockTwin(foreign1155.address, TokenType.MultiToken); + twin1155 = mockTwin(await foreign1155.getAddress(), TokenType.MultiToken); twin1155.id = "3"; twin1155.tokenId = "1"; twin1155.amount = "1"; @@ -2123,7 +2182,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(voucherRedeemableFrom)); @@ -2131,16 +2190,23 @@ describe("IBosonExchangeHandler", function () { it("should transfer the twin", async function () { // Check the buyer's balance of the ERC20 - balance = await foreign20.balanceOf(buyer.address); + balance = await foreign20.balanceOf(await buyer.getAddress()); expect(balance).to.equal(0); // Redeem the voucher await expect(exchangeHandler.connect(buyer).redeemVoucher(exchange.id)) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin20.id, twin20.tokenAddress, exchange.id, twin20.tokenId, twin20.amount, buyer.address); + .withArgs( + twin20.id, + twin20.tokenAddress, + exchange.id, + twin20.tokenId, + twin20.amount, + await buyer.getAddress() + ); // Check the buyer's balance of the ERC20 - balance = await foreign20.balanceOf(buyer.address); + balance = await foreign20.balanceOf(await buyer.getAddress()); expect(balance).to.equal(3); }); @@ -2156,7 +2222,7 @@ describe("IBosonExchangeHandler", function () { it("Should not decrease twin supplyAvailable if supply is unlimited", async function () { // Change twin supply to unlimited - twin20.supplyAvailable = ethers.constants.MaxUint256.toString(); + twin20.supplyAvailable = MaxUint256.toString(); twin20.id = "4"; // Create a new twin @@ -2175,7 +2241,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom voucherRedeemableFrom = offerDates.voucherRedeemableFrom; @@ -2209,7 +2275,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom voucherRedeemableFrom = offerDates.voucherRedeemableFrom; @@ -2218,10 +2284,10 @@ describe("IBosonExchangeHandler", function () { // Redeem the second voucher await expect(exchangeHandler.connect(buyer).redeemVoucher(++exchange.id)) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin20.id, twin20.tokenAddress, exchange.id, "0", twin20.amount, buyer.address); + .withArgs(twin20.id, twin20.tokenAddress, exchange.id, "0", twin20.amount, await buyer.getAddress()); // Check the buyer's balance - balance = await foreign20.balanceOf(buyer.address); + balance = await foreign20.balanceOf(await buyer.getAddress()); expect(balance).to.equal(3); const [, twin] = await twinHandler.getTwin(twin20.id); @@ -2237,11 +2303,18 @@ describe("IBosonExchangeHandler", function () { await expect(tx) .to.emit(exchangeHandler, "VoucherRevoked") - .withArgs(exchange.offerId, exchange.id, buyer.address); + .withArgs(exchange.offerId, exchange.id, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferFailed") - .withArgs(twin20.id, twin20.tokenAddress, exchange.id, twin20.tokenId, twin20.amount, buyer.address); + .withArgs( + twin20.id, + twin20.tokenAddress, + exchange.id, + twin20.tokenId, + twin20.amount, + await buyer.getAddress() + ); // Get the exchange state [, response] = await exchangeHandler.connect(rando).getExchangeState(exchange.id); @@ -2253,11 +2326,11 @@ describe("IBosonExchangeHandler", function () { it("should revoke exchange when ERC20 contract transferFrom returns false", async function () { const [foreign20ReturnFalse] = await deployMockTokens(["Foreign20TransferFromReturnFalse"]); - await foreign20ReturnFalse.connect(assistant).mint(assistant.address, "500"); + await foreign20ReturnFalse.connect(assistant).mint(await assistant.getAddress(), "500"); await foreign20ReturnFalse.connect(assistant).approve(protocolDiamondAddress, "100"); // Create a new ERC20 twin - twin20 = mockTwin(foreign20ReturnFalse.address, TokenType.FungibleToken); + twin20 = mockTwin(await foreign20ReturnFalse.getAddress(), TokenType.FungibleToken); twin20.id = "4"; // Create a new twin @@ -2278,11 +2351,11 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(new Bundle("1", seller.id, [++offerId], [twin20.id])); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); await expect(exchangeHandler.connect(buyer).redeemVoucher(++exchange.id)) .to.emit(exchangeHandler, "TwinTransferFailed") - .withArgs(twin20.id, twin20.tokenAddress, exchange.id, "0", twin20.amount, buyer.address); + .withArgs(twin20.id, twin20.tokenAddress, exchange.id, "0", twin20.amount, await buyer.getAddress()); // Get the exchange state [, response] = await exchangeHandler.connect(rando).getExchangeState(exchange.id); @@ -2296,9 +2369,9 @@ describe("IBosonExchangeHandler", function () { await foreign20.connect(assistant).approve(protocolDiamondAddress, "0"); // Deploy contract to test redeem called by another contract - let TestProtocolFunctionsFactory = await ethers.getContractFactory("TestProtocolFunctions"); + let TestProtocolFunctionsFactory = await getContractFactory("TestProtocolFunctions"); const testProtocolFunctions = await TestProtocolFunctionsFactory.deploy(protocolDiamondAddress); - await testProtocolFunctions.deployed(); + await testProtocolFunctions.waitForDeployment(); await testProtocolFunctions.commit(offerId, { value: price }); @@ -2308,7 +2381,7 @@ describe("IBosonExchangeHandler", function () { await expect(tx) .to.emit(disputeHandler, "DisputeRaised") - .withArgs(exchangeId, ++exchange.buyerId, seller.id, testProtocolFunctions.address); + .withArgs(exchangeId, ++exchange.buyerId, seller.id, await testProtocolFunctions.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferFailed") @@ -2318,7 +2391,7 @@ describe("IBosonExchangeHandler", function () { exchangeId, twin20.tokenId, twin20.amount, - testProtocolFunctions.address + await testProtocolFunctions.getAddress() ); // Get the exchange state @@ -2338,7 +2411,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(voucherRedeemableFrom)); @@ -2349,34 +2422,34 @@ describe("IBosonExchangeHandler", function () { // Check the assistant owns the last ERC721 of twin range owner = await foreign721.ownerOf(tokenId); - expect(owner).to.equal(assistant.address); + expect(owner).to.equal(await assistant.getAddress()); [exists, response] = await exchangeHandler.connect(rando).getExchangeState(exchange.id); // Redeem the voucher await expect(exchangeHandler.connect(buyer).redeemVoucher(exchange.id)) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchange.id, tokenId, "0", buyer.address); + .withArgs(twin721.id, twin721.tokenAddress, exchange.id, tokenId, "0", await buyer.getAddress()); // Check the buyer owns the last ERC721 of twin range owner = await foreign721.ownerOf(tokenId); - expect(owner).to.equal(buyer.address); + expect(owner).to.equal(await buyer.getAddress()); tokenId = "8"; // Check the assistant owns the last ERC721 of twin range owner = await foreign721.ownerOf(tokenId); - expect(owner).to.equal(assistant.address); + expect(owner).to.equal(await assistant.getAddress()); // Commit to offer for the second time - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Redeem the second voucher for the second time / id = 2 await expect(exchangeHandler.connect(buyer).redeemVoucher(++exchange.id)) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchange.id, tokenId, "0", buyer.address); + .withArgs(twin721.id, twin721.tokenAddress, exchange.id, tokenId, "0", await buyer.getAddress()); // Check the buyer owns the last ERC721 of twin range owner = await foreign721.ownerOf(tokenId); - expect(owner).to.equal(buyer.address); + expect(owner).to.equal(await buyer.getAddress()); }); it("1 should be reduced from twin supplyAvailable", async function () { @@ -2412,7 +2485,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom voucherRedeemableFrom = offerDates.voucherRedeemableFrom; @@ -2422,11 +2495,11 @@ describe("IBosonExchangeHandler", function () { // Redeem the second voucher await expect(exchangeHandler.connect(buyer).redeemVoucher(++exchange.id)) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchange.id, tokenId, twin721.amount, buyer.address); + .withArgs(twin721.id, twin721.tokenAddress, exchange.id, tokenId, twin721.amount, await buyer.getAddress()); // Check the buyer owns the first ERC721 in twin range owner = await foreign721.ownerOf(tokenId); - expect(owner).to.equal(buyer.address); + expect(owner).to.equal(await buyer.getAddress()); const [, twin] = await twinHandler.getTwin(twin721.id); expect(twin.supplyAvailable).to.equal(0); @@ -2436,7 +2509,7 @@ describe("IBosonExchangeHandler", function () { let other721; beforeEach(async function () { // Deploy a new ERC721 token - let TokenContractFactory = await ethers.getContractFactory("Foreign721"); + let TokenContractFactory = await getContractFactory("Foreign721"); other721 = await TokenContractFactory.connect(rando).deploy(); // Mint enough tokens to cover the offer @@ -2454,8 +2527,8 @@ describe("IBosonExchangeHandler", function () { .createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // Change twin supply to unlimited and token address to the new token - twin721.supplyAvailable = ethers.constants.MaxUint256.toString(); - twin721.tokenAddress = other721.address; + twin721.supplyAvailable = MaxUint256.toString(); + twin721.tokenAddress = await other721.getAddress(); twin721.id = "4"; // Create a new twin with the new token address @@ -2466,7 +2539,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom voucherRedeemableFrom = offerDates.voucherRedeemableFrom; @@ -2491,35 +2564,35 @@ describe("IBosonExchangeHandler", function () { // Check the assistant owns the first ERC721 of twin range owner = await other721.ownerOf(expectedTokenId); - expect(owner).to.equal(assistant.address); + expect(owner).to.equal(await assistant.getAddress()); // Redeem the voucher await expect(exchangeHandler.connect(buyer).redeemVoucher(exchangeId)) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchangeId, expectedTokenId, "0", buyer.address); + .withArgs(twin721.id, twin721.tokenAddress, exchangeId, expectedTokenId, "0", await buyer.getAddress()); // Check the buyer owns the first ERC721 of twin range owner = await other721.ownerOf(expectedTokenId); - expect(owner).to.equal(buyer.address); + expect(owner).to.equal(await buyer.getAddress()); ++expectedTokenId; // Check the assistant owns the second ERC721 of twin range owner = await other721.ownerOf(expectedTokenId); - expect(owner).to.equal(assistant.address); + expect(owner).to.equal(await assistant.getAddress()); // Commit to offer for the second time - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Redeem the voucher // tokenId transferred to the buyer is 1 await expect(exchangeHandler.connect(buyer).redeemVoucher(++exchangeId)) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchangeId, expectedTokenId, "0", buyer.address); + .withArgs(twin721.id, twin721.tokenAddress, exchangeId, expectedTokenId, "0", await buyer.getAddress()); // Check the buyer owns the second ERC721 of twin range owner = await other721.ownerOf(expectedTokenId); - expect(owner).to.equal(buyer.address); + expect(owner).to.equal(await buyer.getAddress()); }); }); @@ -2532,11 +2605,11 @@ describe("IBosonExchangeHandler", function () { await expect(tx) .to.emit(exchangeHandler, "VoucherRevoked") - .withArgs(exchange.offerId, exchange.id, buyer.address); + .withArgs(exchange.offerId, exchange.id, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferFailed") - .withArgs(twin721.id, twin721.tokenAddress, exchange.id, "9", "0", buyer.address); + .withArgs(twin721.id, twin721.tokenAddress, exchange.id, "9", "0", await buyer.getAddress()); // Get the exchange state [, response] = await exchangeHandler.connect(rando).getExchangeState(exchange.id); @@ -2547,9 +2620,9 @@ describe("IBosonExchangeHandler", function () { it("should raise a dispute when buyer account is a contract", async function () { // Deploy contract to test redeem called by another contract - let TestProtocolFunctionsFactory = await ethers.getContractFactory("TestProtocolFunctions"); + let TestProtocolFunctionsFactory = await getContractFactory("TestProtocolFunctions"); const testProtocolFunctions = await TestProtocolFunctionsFactory.deploy(protocolDiamondAddress); - await testProtocolFunctions.deployed(); + await testProtocolFunctions.waitForDeployment(); await testProtocolFunctions.commit(offerId, { value: price }); @@ -2558,11 +2631,18 @@ describe("IBosonExchangeHandler", function () { await expect(tx) .to.emit(disputeHandler, "DisputeRaised") - .withArgs(exchange.id, ++exchange.buyerId, seller.id, testProtocolFunctions.address); + .withArgs(exchange.id, ++exchange.buyerId, seller.id, await testProtocolFunctions.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferFailed") - .withArgs(twin721.id, twin721.tokenAddress, exchange.id, "9", "0", testProtocolFunctions.address); + .withArgs( + twin721.id, + twin721.tokenAddress, + exchange.id, + "9", + "0", + await testProtocolFunctions.getAddress() + ); // Get the exchange state [, response] = await exchangeHandler.connect(rando).getExchangeState(exchange.id); @@ -2581,7 +2661,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(voucherRedeemableFrom)); @@ -2591,16 +2671,23 @@ describe("IBosonExchangeHandler", function () { let tokenId = "1"; // Check the buyer's balance of the ERC1155 - balance = await foreign1155.balanceOf(buyer.address, tokenId); + balance = await foreign1155.balanceOf(await buyer.getAddress(), tokenId); expect(balance).to.equal(0); // Redeem the voucher await expect(exchangeHandler.connect(buyer).redeemVoucher(exchange.id)) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin1155.id, twin1155.tokenAddress, exchange.id, tokenId, twin1155.amount, buyer.address); + .withArgs( + twin1155.id, + twin1155.tokenAddress, + exchange.id, + tokenId, + twin1155.amount, + await buyer.getAddress() + ); // Check the buyer's balance of the ERC1155 - balance = await foreign1155.balanceOf(buyer.address, tokenId); + balance = await foreign1155.balanceOf(await buyer.getAddress(), tokenId); expect(balance).to.equal(1); }); @@ -2616,7 +2703,7 @@ describe("IBosonExchangeHandler", function () { it("Should not decrease twin supplyAvailable if supply is unlimited", async function () { // Change twin supply to unlimited - twin1155.supplyAvailable = ethers.constants.MaxUint256.toString(); + twin1155.supplyAvailable = MaxUint256.toString(); twin1155.id = "4"; // Create a new twin @@ -2635,7 +2722,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom voucherRedeemableFrom = offerDates.voucherRedeemableFrom; @@ -2670,7 +2757,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom voucherRedeemableFrom = offerDates.voucherRedeemableFrom; @@ -2685,11 +2772,11 @@ describe("IBosonExchangeHandler", function () { exchange.id, twin1155.tokenId, twin1155.amount, - buyer.address + await buyer.getAddress() ); // Check the buyer's balance - balance = await foreign1155.balanceOf(buyer.address, twin1155.tokenId); + balance = await foreign1155.balanceOf(await buyer.getAddress(), twin1155.tokenId); expect(balance).to.equal(1); const [, twin] = await twinHandler.getTwin(twin1155.id); @@ -2704,7 +2791,7 @@ describe("IBosonExchangeHandler", function () { const tx = await exchangeHandler.connect(buyer).redeemVoucher(exchange.id); await expect(tx) .to.emit(exchangeHandler, "VoucherRevoked") - .withArgs(exchange.offerId, exchange.id, buyer.address); + .withArgs(exchange.offerId, exchange.id, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferFailed") @@ -2714,7 +2801,7 @@ describe("IBosonExchangeHandler", function () { exchange.id, twin1155.tokenId, twin1155.amount, - buyer.address + await buyer.getAddress() ); // Get the exchange state @@ -2726,9 +2813,9 @@ describe("IBosonExchangeHandler", function () { it("should raise a dispute when buyer account is a contract", async function () { // Deploy contract to test redeem called by another contract - let TestProtocolFunctionsFactory = await ethers.getContractFactory("TestProtocolFunctions"); + let TestProtocolFunctionsFactory = await getContractFactory("TestProtocolFunctions"); const testProtocolFunctions = await TestProtocolFunctionsFactory.deploy(protocolDiamondAddress); - await testProtocolFunctions.deployed(); + await testProtocolFunctions.waitForDeployment(); await testProtocolFunctions.commit(offerId, { value: price }); @@ -2736,7 +2823,7 @@ describe("IBosonExchangeHandler", function () { const tx = await testProtocolFunctions.redeem(++exchange.id); await expect(tx) .to.emit(disputeHandler, "DisputeRaised") - .withArgs(exchange.id, ++exchange.buyerId, seller.id, testProtocolFunctions.address); + .withArgs(exchange.id, ++exchange.buyerId, seller.id, await testProtocolFunctions.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferFailed") @@ -2746,7 +2833,7 @@ describe("IBosonExchangeHandler", function () { exchange.id, twin1155.tokenId, twin1155.amount, - testProtocolFunctions.address + await testProtocolFunctions.getAddress() ); // Get the exchange state @@ -2766,7 +2853,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(voucherRedeemableFrom)); @@ -2777,15 +2864,15 @@ describe("IBosonExchangeHandler", function () { let tokenIdMultiToken = "1"; // Check the buyer's balance of the ERC20 - balance = await foreign20.balanceOf(buyer.address); + balance = await foreign20.balanceOf(await buyer.getAddress()); expect(balance).to.equal(0); // Check the assistant owns the ERC721 owner = await foreign721.ownerOf(tokenIdNonFungible); - expect(owner).to.equal(assistant.address); + expect(owner).to.equal(await assistant.getAddress()); // Check the buyer's balance of the ERC1155 - balance = await foreign1155.balanceOf(buyer.address, tokenIdMultiToken); + balance = await foreign1155.balanceOf(await buyer.getAddress(), tokenIdMultiToken); expect(balance).to.equal(0); let exchangeId = exchange.id; @@ -2801,27 +2888,34 @@ describe("IBosonExchangeHandler", function () { exchangeId, tokenIdMultiToken, twin1155.amount, - buyer.address + await buyer.getAddress() ); await expect(tx) .and.to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin20.id, twin20.tokenAddress, exchangeId, "0", twin20.amount, buyer.address); + .withArgs(twin20.id, twin20.tokenAddress, exchangeId, "0", twin20.amount, await buyer.getAddress()); await expect(tx) .and.to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchangeId, tokenIdNonFungible, twin721.amount, buyer.address); + .withArgs( + twin721.id, + twin721.tokenAddress, + exchangeId, + tokenIdNonFungible, + twin721.amount, + await buyer.getAddress() + ); // Check the buyer's balance of the ERC20 - balance = await foreign20.balanceOf(buyer.address); + balance = await foreign20.balanceOf(await buyer.getAddress()); expect(balance).to.equal(3); // Check the buyer owns the ERC721 owner = await foreign721.ownerOf(tokenIdNonFungible); - expect(owner).to.equal(buyer.address); + expect(owner).to.equal(await buyer.getAddress()); // Check the buyer's balance of the ERC1155 - balance = await foreign1155.balanceOf(buyer.address, tokenIdMultiToken); + balance = await foreign1155.balanceOf(await buyer.getAddress(), tokenIdMultiToken); expect(balance).to.equal(1); }); @@ -2858,7 +2952,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom voucherRedeemableFrom = offerDates.voucherRedeemableFrom; @@ -2875,25 +2969,32 @@ describe("IBosonExchangeHandler", function () { exchange.id, twin1155.tokenId, twin1155.amount, - buyer.address + await buyer.getAddress() ); await expect(tx) .and.to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchange.id, twin721.tokenId, twin721.amount, buyer.address); + .withArgs( + twin721.id, + twin721.tokenAddress, + exchange.id, + twin721.tokenId, + twin721.amount, + await buyer.getAddress() + ); await expect(tx) .and.to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin20.id, twin20.tokenAddress, exchange.id, "0", twin20.amount, buyer.address); + .withArgs(twin20.id, twin20.tokenAddress, exchange.id, "0", twin20.amount, await buyer.getAddress()); // Check the buyer's balance - balance = await foreign1155.balanceOf(buyer.address, twin1155.tokenId); + balance = await foreign1155.balanceOf(await buyer.getAddress(), twin1155.tokenId); expect(balance).to.equal(1); - balance = await foreign721.balanceOf(buyer.address); + balance = await foreign721.balanceOf(await buyer.getAddress()); expect(balance).to.equal(1); - balance = await foreign20.balanceOf(buyer.address); + balance = await foreign20.balanceOf(await buyer.getAddress()); expect(balance).to.equal(3); let [, twin] = await twinHandler.getTwin(twin1155.id); @@ -2911,7 +3012,7 @@ describe("IBosonExchangeHandler", function () { beforeEach(async function () { // Deploy a new ERC721 token - let TokenContractFactory = await ethers.getContractFactory("Foreign721"); + let TokenContractFactory = await getContractFactory("Foreign721"); other721 = await TokenContractFactory.connect(rando).deploy(); // Mint enough tokens to cover the offer @@ -2929,18 +3030,18 @@ describe("IBosonExchangeHandler", function () { .createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // Change twin supply to unlimited and token address to the new token - twin721.supplyAvailable = ethers.constants.MaxUint256.toString(); - twin721.tokenAddress = other721.address; + twin721.supplyAvailable = MaxUint256.toString(); + twin721.tokenAddress = await other721.getAddress(); twin721.id = "4"; // Create a new ERC721 twin with the new token address await twinHandler.connect(assistant).createTwin(twin721.toStruct()); - twin20.supplyAvailable = ethers.constants.MaxUint256.toString(); + twin20.supplyAvailable = MaxUint256.toString(); twin20.id = "5"; // Create a new ERC20 twin with the new token address await twinHandler.connect(assistant).createTwin(twin20.toStruct()); - twin1155.supplyAvailable = ethers.constants.MaxUint256.toString(); + twin1155.supplyAvailable = MaxUint256.toString(); twin1155.id = "6"; // Create a new ERC1155 twin with the new token address await twinHandler.connect(assistant).createTwin(twin1155.toStruct()); @@ -2950,7 +3051,7 @@ describe("IBosonExchangeHandler", function () { await bundleHandler.connect(assistant).createBundle(bundle.toStruct()); // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom voucherRedeemableFrom = offerDates.voucherRedeemableFrom; @@ -2965,11 +3066,18 @@ describe("IBosonExchangeHandler", function () { await expect(tx) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchange.id, "0", twin721.amount, buyer.address); + .withArgs(twin721.id, twin721.tokenAddress, exchange.id, "0", twin721.amount, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin20.id, twin20.tokenAddress, exchange.id, twin20.tokenId, twin20.amount, buyer.address); + .withArgs( + twin20.id, + twin20.tokenAddress, + exchange.id, + twin20.tokenId, + twin20.amount, + await buyer.getAddress() + ); await expect(tx) .to.emit(exchangeHandler, "TwinTransferred") @@ -2979,7 +3087,7 @@ describe("IBosonExchangeHandler", function () { exchange.id, twin1155.tokenId, twin1155.amount, - buyer.address + await buyer.getAddress() ); // Check the supplyAvailable of each twin @@ -3000,35 +3108,35 @@ describe("IBosonExchangeHandler", function () { // Check the assistant owns the first ERC721 of twin range owner = await other721.ownerOf(expectedTokenId); - expect(owner).to.equal(assistant.address); + expect(owner).to.equal(await assistant.getAddress()); // Redeem the voucher await expect(exchangeHandler.connect(buyer).redeemVoucher(exchangeId)) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchangeId, expectedTokenId, "0", buyer.address); + .withArgs(twin721.id, twin721.tokenAddress, exchangeId, expectedTokenId, "0", await buyer.getAddress()); // Check the buyer owns the first ERC721 of twin range owner = await other721.ownerOf(expectedTokenId); - expect(owner).to.equal(buyer.address); + expect(owner).to.equal(await buyer.getAddress()); ++expectedTokenId; // Check the assistant owns the second ERC721 of twin range owner = await other721.ownerOf(expectedTokenId); - expect(owner).to.equal(assistant.address); + expect(owner).to.equal(await assistant.getAddress()); // Commit to offer for the second time - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Redeem the voucher // tokenId transferred to the buyer is 1 await expect(exchangeHandler.connect(buyer).redeemVoucher(++exchangeId)) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchangeId, expectedTokenId, "0", buyer.address); + .withArgs(twin721.id, twin721.tokenAddress, exchangeId, expectedTokenId, "0", await buyer.getAddress()); // Check the buyer owns the second ERC721 of twin range owner = await other721.ownerOf(expectedTokenId); - expect(owner).to.equal(buyer.address); + expect(owner).to.equal(await buyer.getAddress()); }); }); @@ -3042,15 +3150,15 @@ describe("IBosonExchangeHandler", function () { await expect(tx) .to.emit(exchangeHandler, "VoucherRevoked") - .withArgs(exchange.offerId, exchangeId, buyer.address); + .withArgs(exchange.offerId, exchangeId, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferFailed") - .withArgs(twin20.id, twin20.tokenAddress, exchangeId, "0", twin20.amount, buyer.address); + .withArgs(twin20.id, twin20.tokenAddress, exchangeId, "0", twin20.amount, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferred") - .withArgs(twin721.id, twin721.tokenAddress, exchangeId, "9", "0", buyer.address); + .withArgs(twin721.id, twin721.tokenAddress, exchangeId, "9", "0", await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferred") @@ -3060,7 +3168,7 @@ describe("IBosonExchangeHandler", function () { exchangeId, twin1155.tokenId, twin1155.amount, - buyer.address + await buyer.getAddress() ); // Get the exchange state @@ -3075,9 +3183,9 @@ describe("IBosonExchangeHandler", function () { await foreign20.connect(assistant).approve(protocolDiamondAddress, "0"); // Deploy contract to test redeem called by another contract - let TestProtocolFunctionsFactory = await ethers.getContractFactory("TestProtocolFunctions"); + let TestProtocolFunctionsFactory = await getContractFactory("TestProtocolFunctions"); const testProtocolFunctions = await TestProtocolFunctionsFactory.deploy(protocolDiamondAddress); - await testProtocolFunctions.deployed(); + await testProtocolFunctions.waitForDeployment(); await testProtocolFunctions.commit(offerId, { value: price }); @@ -3087,15 +3195,29 @@ describe("IBosonExchangeHandler", function () { const tx = await testProtocolFunctions.redeem(exchangeId); await expect(tx) .to.emit(disputeHandler, "DisputeRaised") - .withArgs(exchangeId, ++exchange.buyerId, seller.id, testProtocolFunctions.address); + .withArgs(exchangeId, ++exchange.buyerId, seller.id, await testProtocolFunctions.getAddress()); await expect(tx) .to.emit(exchangeHandler, "TwinTransferFailed") - .withArgs(twin20.id, twin20.tokenAddress, exchangeId, "0", twin20.amount, testProtocolFunctions.address); + .withArgs( + twin20.id, + twin20.tokenAddress, + exchangeId, + "0", + twin20.amount, + await testProtocolFunctions.getAddress() + ); await expect(tx) .to.emit(exchangeHandler, "TwinTransferFailed") - .withArgs(twin721.id, twin721.tokenAddress, exchangeId, "9", "0", testProtocolFunctions.address); + .withArgs( + twin721.id, + twin721.tokenAddress, + exchangeId, + "9", + "0", + await testProtocolFunctions.getAddress() + ); await expect(tx) .to.emit(exchangeHandler, "TwinTransferFailed") @@ -3105,7 +3227,7 @@ describe("IBosonExchangeHandler", function () { exchangeId, twin1155.tokenId, twin1155.amount, - testProtocolFunctions.address + await testProtocolFunctions.getAddress() ); // Get the exchange state @@ -3121,11 +3243,11 @@ describe("IBosonExchangeHandler", function () { context("👉 extendVoucher()", async function () { beforeEach(async function () { // Commit to offer - tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + tx = await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -3134,14 +3256,14 @@ describe("IBosonExchangeHandler", function () { voucher.validUntilDate = calculateVoucherExpiry(block, voucherRedeemableFrom, voucherValid); // New expiry date for extensions - validUntilDate = ethers.BigNumber.from(voucher.validUntilDate).add(oneMonth).toString(); + validUntilDate = BigInt(voucher.validUntilDate) + oneMonth.toString(); }); it("should emit an VoucherExtended event when seller's assistant calls", async function () { // Extend the voucher, expecting event await expect(exchangeHandler.connect(assistant).extendVoucher(exchange.id, validUntilDate)) .to.emit(exchangeHandler, "VoucherExtended") - .withArgs(offerId, exchange.id, validUntilDate, assistant.address); + .withArgs(offerId, exchange.id, validUntilDate, await assistant.getAddress()); }); it("should update state", async function () { @@ -3196,7 +3318,7 @@ describe("IBosonExchangeHandler", function () { it("new date is not later than the current one", async function () { // New expiry date is older than current - validUntilDate = ethers.BigNumber.from(voucher.validUntilDate).sub(oneMonth).toString(); + validUntilDate = BigInt(voucher.validUntilDate) - oneMonth; // Attempt to extend voucher, expecting revert await expect(exchangeHandler.connect(assistant).extendVoucher(exchange.id, validUntilDate)).to.revertedWith( @@ -3209,11 +3331,11 @@ describe("IBosonExchangeHandler", function () { context("👉 onVoucherTransferred()", async function () { beforeEach(async function () { // Commit to offer, retrieving the event - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Client used for tests - bosonVoucherCloneAddress = calculateContractAddress(exchangeHandler.address, "1"); - bosonVoucherClone = await ethers.getContractAt("IBosonVoucher", bosonVoucherCloneAddress); + bosonVoucherCloneAddress = calculateContractAddress(await exchangeHandler.getAddress(), "1"); + bosonVoucherClone = await getContractAt("IBosonVoucher", bosonVoucherCloneAddress); tokenId = deriveTokenId(offerId, exchange.id); }); @@ -3223,9 +3345,11 @@ describe("IBosonExchangeHandler", function () { nextAccountId = await accountHandler.connect(rando).getNextAccountId(); // Call onVoucherTransferred, expecting event - await expect(bosonVoucherClone.connect(buyer).transferFrom(buyer.address, newOwner.address, tokenId)) + await expect( + bosonVoucherClone.connect(buyer).transferFrom(await buyer.getAddress(), await newOwner.getAddress(), tokenId) + ) .to.emit(exchangeHandler, "VoucherTransferred") - .withArgs(offerId, exchange.id, nextAccountId, bosonVoucherClone.address); + .withArgs(offerId, exchange.id, nextAccountId, await bosonVoucherClone.getAddress()); }); it("should update exchange when new buyer (with existing, active account) is passed", async function () { @@ -3233,10 +3357,12 @@ describe("IBosonExchangeHandler", function () { nextAccountId = await accountHandler.connect(rando).getNextAccountId(); // Create a buyer account for the new owner - await accountHandler.connect(newOwner).createBuyer(mockBuyer(newOwner.address)); + await accountHandler.connect(newOwner).createBuyer(mockBuyer(await newOwner.getAddress())); // Call onVoucherTransferred - await bosonVoucherClone.connect(buyer).transferFrom(buyer.address, newOwner.address, tokenId); + await bosonVoucherClone + .connect(buyer) + .transferFrom(await buyer.getAddress(), await newOwner.getAddress(), tokenId); // Get the exchange [exists, response] = await exchangeHandler.connect(rando).getExchange(exchange.id); @@ -3254,7 +3380,9 @@ describe("IBosonExchangeHandler", function () { nextAccountId = await accountHandler.connect(rando).getNextAccountId(); // Call onVoucherTransferred - await bosonVoucherClone.connect(buyer).transferFrom(buyer.address, newOwner.address, tokenId); + await bosonVoucherClone + .connect(buyer) + .transferFrom(await buyer.getAddress(), await newOwner.getAddress(), tokenId); // Get the exchange [exists, response] = await exchangeHandler.connect(rando).getExchange(exchange.id); @@ -3269,10 +3397,9 @@ describe("IBosonExchangeHandler", function () { it("should be triggered when a voucher is transferred", async function () { // Transfer voucher, expecting event - await expect(bosonVoucherClone.connect(buyer).transferFrom(buyer.address, newOwner.address, tokenId)).to.emit( - exchangeHandler, - "VoucherTransferred" - ); + await expect( + bosonVoucherClone.connect(buyer).transferFrom(await buyer.getAddress(), await newOwner.getAddress(), tokenId) + ).to.emit(exchangeHandler, "VoucherTransferred"); }); it("should not be triggered when a voucher is issued", async function () { @@ -3280,21 +3407,20 @@ describe("IBosonExchangeHandler", function () { nextExchangeId = await exchangeHandler.getNextExchangeId(); // Create a buyer account - await accountHandler.connect(newOwner).createBuyer(mockBuyer(newOwner.address)); + await accountHandler.connect(newOwner).createBuyer(mockBuyer(await newOwner.getAddress())); // Grant PROTOCOL role to EOA address for test - await accessController.grantRole(Role.PROTOCOL, rando.address); + await accessController.grantRole(Role.PROTOCOL, await rando.getAddress()); // Issue voucher, expecting no event - await expect(bosonVoucherClone.connect(rando).issueVoucher(nextExchangeId, buyer.address)).to.not.emit( - exchangeHandler, - "VoucherTransferred" - ); + await expect( + bosonVoucherClone.connect(rando).issueVoucher(nextExchangeId, await buyer.getAddress()) + ).to.not.emit(exchangeHandler, "VoucherTransferred"); }); it("should not be triggered when a voucher is burned", async function () { // Grant PROTOCOL role to EOA address for test - await accessController.grantRole(Role.PROTOCOL, rando.address); + await accessController.grantRole(Role.PROTOCOL, await rando.getAddress()); // Burn voucher, expecting no event await expect(bosonVoucherClone.connect(rando).burnVoucher(tokenId)).to.not.emit( @@ -3305,18 +3431,16 @@ describe("IBosonExchangeHandler", function () { it("Should not be triggered when from and to addresses are the same", async function () { // Transfer voucher, expecting event - await expect(bosonVoucherClone.connect(buyer).transferFrom(buyer.address, buyer.address, tokenId)).to.not.emit( - exchangeHandler, - "VoucherTransferred" - ); + await expect( + bosonVoucherClone.connect(buyer).transferFrom(await buyer.getAddress(), await buyer.getAddress(), tokenId) + ).to.not.emit(exchangeHandler, "VoucherTransferred"); }); it("Should not be triggered when first transfer of preminted voucher happens", async function () { // Transfer voucher, expecting event - await expect(bosonVoucherClone.connect(buyer).transferFrom(buyer.address, buyer.address, tokenId)).to.not.emit( - exchangeHandler, - "VoucherTransferred" - ); + await expect( + bosonVoucherClone.connect(buyer).transferFrom(await buyer.getAddress(), await buyer.getAddress(), tokenId) + ).to.not.emit(exchangeHandler, "VoucherTransferred"); }); context("💔 Revert Reasons", async function () { @@ -3326,37 +3450,46 @@ describe("IBosonExchangeHandler", function () { // Attempt to create a buyer, expecting revert await expect( - bosonVoucherClone.connect(buyer).transferFrom(buyer.address, newOwner.address, tokenId) + bosonVoucherClone + .connect(buyer) + .transferFrom(await buyer.getAddress(), await newOwner.getAddress(), tokenId) ).to.revertedWith(RevertReasons.REGION_PAUSED); }); it("Caller is not a clone address", async function () { // Attempt to call onVoucherTransferred, expecting revert await expect( - exchangeHandler.connect(rando).onVoucherTransferred(exchange.id, newOwner.address) + exchangeHandler.connect(rando).onVoucherTransferred(exchange.id, await newOwner.getAddress()) ).to.revertedWith(RevertReasons.ACCESS_DENIED); }); it("Caller is not a clone address associated with the seller", async function () { // Create a new seller to get new clone - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); expect(seller.isValid()).is.true; await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); - expectedCloneAddress = calculateContractAddress(accountHandler.address, "2"); - const bosonVoucherClone2 = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "2"); + const bosonVoucherClone2 = await getContractAt("IBosonVoucher", expectedCloneAddress); // For the sake of test, mint token on bv2 with the id of token on bv1 // Temporarily grant PROTOCOL role to deployer account - await accessController.grantRole(Role.PROTOCOL, deployer.address); + await accessController.grantRole(Role.PROTOCOL, await deployer.getAddress()); - const newBuyer = mockBuyer(buyer.address); + const newBuyer = mockBuyer(await buyer.getAddress()); newBuyer.id = buyerId; await bosonVoucherClone2.issueVoucher(exchange.id, newBuyer.wallet); // Attempt to call onVoucherTransferred, expecting revert await expect( - bosonVoucherClone2.connect(buyer).transferFrom(buyer.address, newOwner.address, exchange.id) + bosonVoucherClone2 + .connect(buyer) + .transferFrom(await buyer.getAddress(), await newOwner.getAddress(), exchange.id) ).to.revertedWith(RevertReasons.ACCESS_DENIED); }); @@ -3366,7 +3499,7 @@ describe("IBosonExchangeHandler", function () { // Attempt to call onVoucherTransferred, expecting revert await expect( - exchangeHandler.connect(fauxClient).onVoucherTransferred(exchangeId, newOwner.address) + exchangeHandler.connect(fauxClient).onVoucherTransferred(exchangeId, await newOwner.getAddress()) ).to.revertedWith(RevertReasons.NO_SUCH_EXCHANGE); }); @@ -3376,7 +3509,7 @@ describe("IBosonExchangeHandler", function () { // Attempt to call onVoucherTransferred, expecting revert await expect( - exchangeHandler.connect(fauxClient).onVoucherTransferred(exchangeId, newOwner.address) + exchangeHandler.connect(fauxClient).onVoucherTransferred(exchangeId, await newOwner.getAddress()) ).to.revertedWith(RevertReasons.INVALID_STATE); }); @@ -3386,7 +3519,7 @@ describe("IBosonExchangeHandler", function () { // Attempt to call onVoucherTransferred, expecting revert await expect( - exchangeHandler.connect(fauxClient).onVoucherTransferred(exchangeId, newOwner.address) + exchangeHandler.connect(fauxClient).onVoucherTransferred(exchangeId, await newOwner.getAddress()) ).to.revertedWith(RevertReasons.VOUCHER_HAS_EXPIRED); }); }); @@ -3395,7 +3528,7 @@ describe("IBosonExchangeHandler", function () { context("👉 isExchangeFinalized()", async function () { beforeEach(async function () { // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); }); context("👍 undisputed exchange", async function () { @@ -3439,11 +3572,11 @@ describe("IBosonExchangeHandler", function () { await exchangeHandler.connect(buyer).redeemVoucher(exchange.id); // Get the current block info - blockNumber = await ethers.provider.getBlockNumber(); - block = await ethers.provider.getBlock(blockNumber); + blockNumber = await provider.getBlockNumber(); + block = await provider.getBlock(blockNumber); // Set time forward to run out the dispute period - newTime = ethers.BigNumber.from(voucherRedeemableFrom).add(disputePeriod).add(1).toNumber(); + newTime = Number(BigInt(voucherRedeemableFrom) + BigInt(disputePeriod) + 1n); await setNextBlockTimestamp(newTime); // Complete exchange @@ -3534,7 +3667,7 @@ describe("IBosonExchangeHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() ); // Resolve Dispute @@ -3578,7 +3711,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); const escalatedDate = block.timestamp.toString(); await setNextBlockTimestamp(Number(escalatedDate) + Number(disputeResolver.escalationResponsePeriod)); @@ -3602,7 +3735,7 @@ describe("IBosonExchangeHandler", function () { expect(nextExchangeId).to.equal(exchangeId); // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Get the next exchange id and ensure it was incremented by the creation of the offer nextExchangeId = await exchangeHandler.connect(rando).getNextExchangeId(); @@ -3623,7 +3756,7 @@ describe("IBosonExchangeHandler", function () { context("👉 getExchange()", async function () { beforeEach(async function () { // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); }); it("should return true for exists if exchange id is valid", async function () { @@ -3654,7 +3787,7 @@ describe("IBosonExchangeHandler", function () { context("👉 getExchangeState()", async function () { beforeEach(async function () { // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); }); it("should return true for exists if exchange id is valid", async function () { @@ -3685,14 +3818,14 @@ describe("IBosonExchangeHandler", function () { context("getReceipt", async function () { beforeEach(async () => { // Commit to offer - tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + tx = await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Decrease offer quantityAvailable offer.quantityAvailable = "9"; // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -3708,7 +3841,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the redeemedDate date in the expected exchange struct voucher.redeemedDate = block.timestamp.toString(); @@ -3720,7 +3853,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the finalizedDate date in the expected exchange struct exchange.finalizedDate = block.timestamp.toString(); @@ -3773,7 +3906,7 @@ describe("IBosonExchangeHandler", function () { offer.id = offerId = "2"; offer.price = offer.buyerCancelPenalty = offer.sellerDeposit = "0"; // set a dummy token address otherwise protocol token (zero address) and offer token will be the same and we will get the error AGENT_FEE_AMOUNT_TOO_HIGH - offer.exchangeToken = foreign20.address; + offer.exchangeToken = await foreign20.getAddress(); disputeResolverId = agentId = "0"; // Update voucherRedeemableFrom @@ -3790,7 +3923,7 @@ describe("IBosonExchangeHandler", function () { .createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // Commit to offer - tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId); + tx = await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId); // Decrease offer quantityAvailable offer.quantityAvailable = "0"; @@ -3799,7 +3932,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -3815,14 +3948,14 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the redeemedDate date in the expected exchange struct voucher.redeemedDate = block.timestamp.toString(); // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the redeemedDate date in the expected exchange struct voucher.redeemedDate = block.timestamp.toString(); @@ -3832,7 +3965,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the finalizedDate date in the expected exchange struct exchange.finalizedDate = block.timestamp.toString(); @@ -3880,7 +4013,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); }); @@ -3891,7 +4024,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the finalizedDate date in the expected exchange struct exchange.finalizedDate = block.timestamp.toString(); @@ -3943,7 +4076,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); const escalatedDate = block.timestamp.toString(); @@ -3952,7 +4085,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the finalizedDate date in the expected exchange struct exchange.finalizedDate = block.timestamp.toString(); @@ -4002,7 +4135,7 @@ describe("IBosonExchangeHandler", function () { context("TwinReceipt tests", async function () { beforeEach(async function () { // Mint some tokens to be bundled - await foreign20.connect(assistant).mint(assistant.address, "500"); + await foreign20.connect(assistant).mint(await assistant.getAddress(), "500"); await foreign721.connect(assistant).mint("0", "10"); // Approve the protocol diamond to transfer seller's tokens @@ -4010,14 +4143,14 @@ describe("IBosonExchangeHandler", function () { await foreign721.connect(assistant).setApprovalForAll(protocolDiamondAddress, true); // Create an ERC20 twin - twin20 = mockTwin(foreign20.address); + twin20 = mockTwin(await foreign20.getAddress()); twin20.amount = "3"; expect(twin20.isValid()).is.true; await twinHandler.connect(assistant).createTwin(twin20.toStruct()); // Create an ERC721 twin - twin721 = mockTwin(foreign721.address, TokenType.NonFungibleToken); + twin721 = mockTwin(await foreign721.getAddress(), TokenType.NonFungibleToken); twin721.amount = "0"; twin721.supplyAvailable = "10"; twin721.id = "2"; @@ -4057,11 +4190,13 @@ describe("IBosonExchangeHandler", function () { await setNextBlockTimestamp(Number(voucherRedeemableFrom)); // Commit to offer - let tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + let tx = await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -4081,7 +4216,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the redeemedDate date in the expected exchange struct voucher.redeemedDate = block.timestamp.toString(); @@ -4091,7 +4226,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the finalizedDate date in the expected exchange struct exchange.finalizedDate = block.timestamp.toString(); @@ -4155,11 +4290,13 @@ describe("IBosonExchangeHandler", function () { await setNextBlockTimestamp(Number(voucherRedeemableFrom)); // Commit to offer - let tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + let tx = await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -4179,7 +4316,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the redeemedDate date in the expected exchange struct voucher.redeemedDate = block.timestamp.toString(); @@ -4189,7 +4326,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the finalizedDate date in the expected exchange struct exchange.finalizedDate = block.timestamp.toString(); @@ -4258,7 +4395,7 @@ describe("IBosonExchangeHandler", function () { offerIds = [offerId]; // Create condition - condition = mockCondition({ tokenAddress: foreign20.address }); + condition = mockCondition({ tokenAddress: await foreign20.getAddress() }); expect(condition.isValid()).to.be.true; // Create a new group @@ -4267,10 +4404,12 @@ describe("IBosonExchangeHandler", function () { await groupHandler.connect(assistant).createGroup(group, condition); // Mint enough tokens for the buyer - await foreign20.connect(buyer).mint(buyer.address, condition.threshold); + await foreign20.connect(buyer).mint(await buyer.getAddress(), condition.threshold); // Commit to offer - let tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + let tx = await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Decrease offer quantityAvailable offer.quantityAvailable = "9"; @@ -4281,7 +4420,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -4297,7 +4436,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the redeemedDate date in the expected exchange struct voucher.redeemedDate = block.timestamp.toString(); @@ -4307,7 +4446,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the finalizedDate date in the expected exchange struct exchange.finalizedDate = block.timestamp.toString(); @@ -4349,7 +4488,7 @@ describe("IBosonExchangeHandler", function () { it("Receipt should contain agentId and agentAddress if agent for offer exists", async function () { // Create a valid agent - agent = mockAgent(rando.address); + agent = mockAgent(await rando.getAddress()); // Set new agentId agentId = agent.id = "4"; expect(agent.isValid()).is.true; @@ -4358,7 +4497,7 @@ describe("IBosonExchangeHandler", function () { await accountHandler.connect(rando).createAgent(agent); // Update agentFee - const agentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + const agentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = agentFee; // Create a new offer @@ -4382,7 +4521,9 @@ describe("IBosonExchangeHandler", function () { .createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // Commit to offer - let tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + let tx = await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerId, { value: price }); // Decrease offer quantityAvailable offer.quantityAvailable = "0"; @@ -4393,7 +4534,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the committed date in the expected exchange struct with the block timestamp of the tx voucher.committedDate = block.timestamp.toString(); @@ -4409,7 +4550,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the redeemedDate date in the expected exchange struct voucher.redeemedDate = block.timestamp.toString(); @@ -4419,7 +4560,7 @@ describe("IBosonExchangeHandler", function () { // Get the block timestamp of the confirmed tx blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); // Update the finalizedDate date in the expected exchange struct exchange.finalizedDate = block.timestamp.toString(); diff --git a/test/protocol/FundsHandlerTest.js b/test/protocol/FundsHandlerTest.js index 9212ed4cf..9bcf55105 100644 --- a/test/protocol/FundsHandlerTest.js +++ b/test/protocol/FundsHandlerTest.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, getSigners, provider, parseUnits, getContractAt, getContractFactory } = ethers; const { expect, assert } = require("chai"); const Role = require("../../scripts/domain/Role"); const { Funds, FundsList } = require("../../scripts/domain/Funds"); @@ -135,9 +136,9 @@ describe("IBosonFundsHandler", function () { // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; - [deployer, protocolTreasury] = await ethers.getSigners(); + [deployer, protocolTreasury] = await getSigners(); // Deploy the mock token [mockToken] = await deployMockTokens(["Foreign20"]); @@ -168,7 +169,12 @@ describe("IBosonFundsHandler", function () { context("📋 Funds Handler Methods", async function () { beforeEach(async function () { // Create a valid seller, then set fields in tests directly - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -182,13 +188,13 @@ describe("IBosonFundsHandler", function () { await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); // top up assistants account - await mockToken.mint(assistant.address, "1000000"); + await mockToken.mint(await assistant.getAddress(), "1000000"); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, "1000000"); // set the deposit amount - depositAmount = "100"; + depositAmount = 100n; // Set agent id as zero as it is optional for createOffer(). agentId = "0"; @@ -203,63 +209,67 @@ describe("IBosonFundsHandler", function () { it("should emit a FundsDeposited event", async function () { // Deposit funds, testing for the event // Deposit token - await expect(fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, depositAmount)) + await expect( + fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), depositAmount) + ) .to.emit(fundsHandler, "FundsDeposited") - .withArgs(seller.id, assistant.address, mockToken.address, depositAmount); + .withArgs(seller.id, await assistant.getAddress(), await mockToken.getAddress(), depositAmount); // Deposit native currency await expect( - fundsHandler - .connect(rando) - .depositFunds(seller.id, ethers.constants.AddressZero, depositAmount, { value: depositAmount }) + fundsHandler.connect(rando).depositFunds(seller.id, ZeroAddress, depositAmount, { value: depositAmount }) ) .to.emit(fundsHandler, "FundsDeposited") - .withArgs(seller.id, rando.address, ethers.constants.AddressZero, depositAmount); + .withArgs(seller.id, await rando.getAddress(), ZeroAddress, depositAmount); }); it("should update state", async function () { // Deposit token - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, depositAmount); + await fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), depositAmount); // Read on chain state let returnedAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // Chain state should match the expected available funds - let expectedAvailableFunds = new FundsList([new Funds(mockToken.address, "Foreign20", depositAmount)]); + let expectedAvailableFunds = new FundsList([ + new Funds(await mockToken.getAddress(), "Foreign20", depositAmount.toString()), + ]); expect(returnedAvailableFunds).to.eql(expectedAvailableFunds); // Deposit native currency to the same seller id - await fundsHandler - .connect(rando) - .depositFunds(seller.id, ethers.constants.AddressZero, depositAmount, { value: depositAmount }); + await fundsHandler.connect(rando).depositFunds(seller.id, ZeroAddress, depositAmount, { value: depositAmount }); // Get new on chain state returnedAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // Chain state should match the expected available funds - expectedAvailableFunds.funds.push(new Funds(ethers.constants.AddressZero, "Native currency", depositAmount)); + expectedAvailableFunds.funds.push(new Funds(ZeroAddress, "Native currency", depositAmount.toString())); expect(returnedAvailableFunds).to.eql(expectedAvailableFunds); }); it("should be possible to top up the account", async function () { // Deposit token - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, depositAmount); + await fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), depositAmount); // Read on chain state let returnedAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // Chain state should match the expected available funds - let expectedAvailableFunds = new FundsList([new Funds(mockToken.address, "Foreign20", depositAmount)]); + let expectedAvailableFunds = new FundsList([ + new Funds(await mockToken.getAddress(), "Foreign20", depositAmount.toString()), + ]); expect(returnedAvailableFunds).to.eql(expectedAvailableFunds); // Deposit the same token again - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, 2 * depositAmount); + await fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), 2n * depositAmount); // Get new on chain state returnedAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // Chain state should match the expected available funds - expectedAvailableFunds = new FundsList([new Funds(mockToken.address, "Foreign20", `${3 * depositAmount}`)]); + expectedAvailableFunds = new FundsList([ + new Funds(await mockToken.getAddress(), "Foreign20", (3n * depositAmount).toString()), + ]); expect(returnedAvailableFunds).to.eql(expectedAvailableFunds); }); @@ -270,7 +280,7 @@ describe("IBosonFundsHandler", function () { // Attempt to deposit funds, expecting revert await expect( - fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, depositAmount) + fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), depositAmount) ).to.revertedWith(RevertReasons.REGION_PAUSED); }); @@ -278,7 +288,7 @@ describe("IBosonFundsHandler", function () { // Attempt to deposit the funds, expecting revert seller.id = "555"; await expect( - fundsHandler.connect(rando).depositFunds(seller.id, mockToken.address, depositAmount) + fundsHandler.connect(rando).depositFunds(seller.id, await mockToken.getAddress(), depositAmount) ).to.revertedWith(RevertReasons.NO_SUCH_SELLER); }); @@ -287,7 +297,7 @@ describe("IBosonFundsHandler", function () { await expect( fundsHandler .connect(rando) - .depositFunds(seller.id, mockToken.address, depositAmount, { value: depositAmount }) + .depositFunds(seller.id, await mockToken.getAddress(), depositAmount, { value: depositAmount }) ).to.revertedWith(RevertReasons.NATIVE_WRONG_ADDRESS); }); @@ -296,7 +306,7 @@ describe("IBosonFundsHandler", function () { await expect( fundsHandler .connect(rando) - .depositFunds(seller.id, ethers.constants.AddressZero, depositAmount * 2, { value: depositAmount }) + .depositFunds(seller.id, ZeroAddress, depositAmount * 2n, { value: depositAmount }) ).to.revertedWith(RevertReasons.NATIVE_WRONG_AMOUNT); }); @@ -306,14 +316,14 @@ describe("IBosonFundsHandler", function () { // Attempt to deposit the funds, expecting revert await expect( - fundsHandler.connect(rando).depositFunds(seller.id, bosonToken.address, depositAmount) + fundsHandler.connect(rando).depositFunds(seller.id, await bosonToken.getAddress(), depositAmount) ).to.revertedWith(RevertReasons.SAFE_ERC20_LOW_LEVEL_CALL); }); it("Token address is not a contract", async function () { // Attempt to deposit the funds, expecting revert await expect( - fundsHandler.connect(rando).depositFunds(seller.id, admin.address, depositAmount) + fundsHandler.connect(rando).depositFunds(seller.id, await admin.getAddress(), depositAmount) ).to.revertedWithoutReason(); }); @@ -323,13 +333,13 @@ describe("IBosonFundsHandler", function () { await mockToken.connect(rando).approve(protocolDiamondAddress, depositAmount); // Attempt to deposit the funds, expecting revert await expect( - fundsHandler.connect(rando).depositFunds(seller.id, mockToken.address, depositAmount) + fundsHandler.connect(rando).depositFunds(seller.id, await mockToken.getAddress(), depositAmount) ).to.revertedWith(RevertReasons.ERC20_EXCEEDS_BALANCE); // not approved - depositAmount = "10000000"; + depositAmount = 10000000n; await expect( - fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, depositAmount) + fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), depositAmount) ).to.revertedWith(RevertReasons.ERC20_INSUFFICIENT_ALLOWANCE); }); @@ -338,23 +348,25 @@ describe("IBosonFundsHandler", function () { const [Foreign20WithFee] = await deployMockTokens(["Foreign20WithFee"]); // mint tokens and approve - await Foreign20WithFee.mint(assistant.address, depositAmount); + await Foreign20WithFee.mint(await assistant.getAddress(), depositAmount); await Foreign20WithFee.connect(assistant).approve(protocolDiamondAddress, depositAmount); // Attempt to deposit funds, expecting revert await expect( - fundsHandler.connect(assistant).depositFunds(seller.id, Foreign20WithFee.address, depositAmount) + fundsHandler.connect(assistant).depositFunds(seller.id, await Foreign20WithFee.getAddress(), depositAmount) ).to.revertedWith(RevertReasons.INSUFFICIENT_VALUE_RECEIVED); }); it("ERC20 transferFrom returns false", async function () { const [foreign20ReturnFalse] = await deployMockTokens(["Foreign20TransferFromReturnFalse"]); - await foreign20ReturnFalse.connect(assistant).mint(assistant.address, depositAmount); + await foreign20ReturnFalse.connect(assistant).mint(await assistant.getAddress(), depositAmount); await foreign20ReturnFalse.connect(assistant).approve(protocolDiamondAddress, depositAmount); await expect( - fundsHandler.connect(assistant).depositFunds(seller.id, foreign20ReturnFalse.address, depositAmount) + fundsHandler + .connect(assistant) + .depositFunds(seller.id, await foreign20ReturnFalse.getAddress(), depositAmount) ).to.revertedWith(RevertReasons.SAFE_ERC20_NOT_SUCCEEDED); }); }); @@ -367,18 +379,18 @@ describe("IBosonFundsHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0"), - new DisputeResolverFee(mockToken.address, "mockToken", "0"), + new DisputeResolverFee(ZeroAddress, "Native", "0"), + new DisputeResolverFee(await mockToken.getAddress(), "mockToken", "0"), ]; // Make empty seller list, so every seller is allowed @@ -397,7 +409,7 @@ describe("IBosonFundsHandler", function () { offerToken = offer.clone(); offerToken.id = "2"; - offerToken.exchangeToken = mockToken.address; + offerToken.exchangeToken = await mockToken.getAddress(); // Check if domais are valid expect(offerNative.isValid()).is.true; @@ -424,7 +436,10 @@ describe("IBosonFundsHandler", function () { offerTokenProtocolFee = offerNativeProtocolFee = offerFees.protocolFee; // top up seller's and buyer's account - await Promise.all([mockToken.mint(assistant.address, sellerDeposit), mockToken.mint(buyer.address, price)]); + await Promise.all([ + mockToken.mint(await assistant.getAddress(), sellerDeposit), + mockToken.mint(await buyer.getAddress(), price), + ]); // approve protocol to transfer the tokens await Promise.all([ @@ -434,15 +449,15 @@ describe("IBosonFundsHandler", function () { // deposit to seller's pool await Promise.all([ - fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, sellerDeposit), - fundsHandler - .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerDeposit, { value: sellerDeposit }), + fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), sellerDeposit), + fundsHandler.connect(assistant).depositFunds(seller.id, ZeroAddress, sellerDeposit, { value: sellerDeposit }), ]); // commit to both offers - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerNative.id, { value: offerNative.price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); + await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerNative.id, { value: offerNative.price }); buyerId = accountId.next().value; }); @@ -460,21 +475,21 @@ describe("IBosonFundsHandler", function () { // expected payoffs - they are the same for token and native currency // buyer: price - buyerCancelPenalty - buyerPayoff = ethers.BigNumber.from(offerToken.price).sub(offerToken.buyerCancelPenalty).toString(); + buyerPayoff = BigInt(offerToken.price) - BigInt(offerToken.buyerCancelPenalty); // seller: sellerDeposit + buyerCancelPenalty - sellerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit).add(offerToken.buyerCancelPenalty).toString(); + sellerPayoff = BigInt(offerToken.sellerDeposit) + BigInt(offerToken.buyerCancelPenalty); }); it("should emit a FundsWithdrawn event", async function () { // Withdraw funds, testing for the event // Withdraw tokens - tokenListSeller = [mockToken.address, ethers.constants.AddressZero]; - tokenListBuyer = [ethers.constants.AddressZero, mockToken.address]; + tokenListSeller = [await mockToken.getAddress(), ZeroAddress]; + tokenListBuyer = [ZeroAddress, await mockToken.getAddress()]; // Withdraw amounts - tokenAmountsSeller = [sellerPayoff, ethers.BigNumber.from(sellerPayoff).div("2").toString()]; - tokenAmountsBuyer = [buyerPayoff, ethers.BigNumber.from(buyerPayoff).div("5").toString()]; + tokenAmountsSeller = [sellerPayoff, (BigInt(sellerPayoff) / 2n).toString()]; + tokenAmountsBuyer = [buyerPayoff, (BigInt(buyerPayoff) / 5n).toString()]; // seller withdrawal const tx = await fundsHandler @@ -482,33 +497,39 @@ describe("IBosonFundsHandler", function () { .withdrawFunds(seller.id, tokenListSeller, tokenAmountsSeller); await expect(tx) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(seller.id, treasury.address, mockToken.address, sellerPayoff, assistant.address); + .withArgs( + seller.id, + await treasury.getAddress(), + await mockToken.getAddress(), + sellerPayoff, + await assistant.getAddress() + ); await expect(tx) .to.emit(fundsHandler, "FundsWithdrawn") .withArgs( seller.id, - treasury.address, - ethers.constants.Zero, - ethers.BigNumber.from(sellerPayoff).div("2"), - assistant.address + await treasury.getAddress(), + 0n, + BigInt(sellerPayoff) / 2n, + await assistant.getAddress() ); // buyer withdrawal const tx2 = await fundsHandler.connect(buyer).withdrawFunds(buyerId, tokenListBuyer, tokenAmountsBuyer); await expect(tx2) - .to.emit(fundsHandler, "FundsWithdrawn", buyer.address) + .to.emit(fundsHandler, "FundsWithdrawn", await buyer.getAddress()) .withArgs( buyerId, - buyer.address, - mockToken.address, - ethers.BigNumber.from(buyerPayoff).div("5"), - buyer.address + await buyer.getAddress(), + await mockToken.getAddress(), + BigInt(buyerPayoff) / 5n, + await buyer.getAddress() ); await expect(tx2) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(buyerId, buyer.address, ethers.constants.Zero, buyerPayoff, buyer.address); + .withArgs(buyerId, await buyer.getAddress(), 0n, buyerPayoff, await buyer.getAddress()); }); it("should update state", async function () { @@ -516,12 +537,12 @@ describe("IBosonFundsHandler", function () { // Read on chain state sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - const treasuryBalanceBefore = await ethers.provider.getBalance(treasury.address); + const treasuryBalanceBefore = await provider.getBalance(await treasury.getAddress()); // Chain state should match the expected available funds before the withdrawal expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerPayoff), - new Funds(ethers.constants.AddressZero, "Native currency", sellerPayoff), + new Funds(await mockToken.getAddress(), "Foreign20", sellerPayoff), + new Funds(ZeroAddress, "Native currency", sellerPayoff), ]); expect(sellersAvailableFunds).to.eql( expectedSellerAvailableFunds, @@ -529,31 +550,28 @@ describe("IBosonFundsHandler", function () { ); // withdraw funds - const withdrawAmount = ethers.BigNumber.from(sellerPayoff) - .sub(ethers.utils.parseUnits("0.1", "ether")) - .toString(); - await fundsHandler - .connect(assistant) - .withdrawFunds(seller.id, [ethers.constants.AddressZero], [withdrawAmount]); + const withdrawAmount = BigInt(sellerPayoff) - parseUnits("0.1", "ether"); + await fundsHandler.connect(assistant).withdrawFunds(seller.id, [ZeroAddress], [withdrawAmount]); // Read on chain state sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - const treasuryBalanceAfter = await ethers.provider.getBalance(treasury.address); + const treasuryBalanceAfter = await provider.getBalance(await treasury.getAddress()); // Chain state should match the expected available funds after the withdrawal // Native currency available funds are reduced for the withdrawal amount expectedSellerAvailableFunds.funds[1] = new Funds( - ethers.constants.AddressZero, + ZeroAddress, "Native currency", - ethers.BigNumber.from(sellerPayoff).sub(withdrawAmount).toString() + BigInt(sellerPayoff) - BigInt(withdrawAmount) ); expect(sellersAvailableFunds).to.eql( expectedSellerAvailableFunds, "Seller available funds mismatch after withdrawal" ); + // Native currency balance is increased for the withdrawAmount expect(treasuryBalanceAfter).to.eql( - treasuryBalanceBefore.add(withdrawAmount), + treasuryBalanceBefore + withdrawAmount, "Treasury token balance mismatch" ); @@ -561,12 +579,12 @@ describe("IBosonFundsHandler", function () { // Read on chain state buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); - const buyerBalanceBefore = await mockToken.balanceOf(buyer.address); + const buyerBalanceBefore = await mockToken.balanceOf(await buyer.getAddress()); // Chain state should match the expected available funds before the withdrawal expectedBuyerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", buyerPayoff), - new Funds(ethers.constants.AddressZero, "Native currency", buyerPayoff), + new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff), + new Funds(ZeroAddress, "Native currency", buyerPayoff), ]); expect(buyerAvailableFunds).to.eql( expectedBuyerAvailableFunds, @@ -574,35 +592,33 @@ describe("IBosonFundsHandler", function () { ); // withdraw funds - await fundsHandler.connect(buyer).withdrawFunds(buyerId, [mockToken.address], [buyerPayoff]); + await fundsHandler.connect(buyer).withdrawFunds(buyerId, [await mockToken.getAddress()], [buyerPayoff]); // Read on chain state buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); - const buyerBalanceAfter = await mockToken.balanceOf(buyer.address); + const buyerBalanceAfter = await mockToken.balanceOf(await buyer.getAddress()); // Chain state should match the expected available funds after the withdrawal // Since all tokens are withdrawn, token should be removed from the list - expectedBuyerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", buyerPayoff), - ]); + expectedBuyerAvailableFunds = new FundsList([new Funds(ZeroAddress, "Native currency", buyerPayoff)]); expect(buyerAvailableFunds).to.eql( expectedBuyerAvailableFunds, "Buyer available funds mismatch after withdrawal" ); // Token balance is increased for the buyer payoff - expect(buyerBalanceAfter).to.eql(buyerBalanceBefore.add(buyerPayoff), "Buyer token balance mismatch"); + expect(buyerBalanceAfter).to.eql(buyerBalanceBefore + buyerPayoff, "Buyer token balance mismatch"); }); it("should allow to withdraw all funds at once", async function () { // Read on chain state sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - const treasuryNativeBalanceBefore = await ethers.provider.getBalance(treasury.address); - const treasuryTokenBalanceBefore = await mockToken.balanceOf(treasury.address); + const treasuryNativeBalanceBefore = await provider.getBalance(await treasury.getAddress()); + const treasuryTokenBalanceBefore = await mockToken.balanceOf(await treasury.getAddress()); // Chain state should match the expected available funds before the withdrawal expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerPayoff), - new Funds(ethers.constants.AddressZero, "Native currency", sellerPayoff), + new Funds(await mockToken.getAddress(), "Foreign20", sellerPayoff), + new Funds(ZeroAddress, "Native currency", sellerPayoff), ]); expect(sellersAvailableFunds).to.eql( expectedSellerAvailableFunds, @@ -614,8 +630,8 @@ describe("IBosonFundsHandler", function () { // Read on chain state sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - const treasuryNativeBalanceAfter = await ethers.provider.getBalance(treasury.address); - const treasuryTokenBalanceAfter = await mockToken.balanceOf(treasury.address); + const treasuryNativeBalanceAfter = await provider.getBalance(await treasury.getAddress()); + const treasuryTokenBalanceAfter = await mockToken.balanceOf(await treasury.getAddress()); // Chain state should match the expected available funds after the withdrawal // Funds available should be an empty list @@ -626,11 +642,11 @@ describe("IBosonFundsHandler", function () { ); // Native currency balance is increased for the withdrawAmount expect(treasuryNativeBalanceAfter).to.eql( - treasuryNativeBalanceBefore.add(sellerPayoff), + treasuryNativeBalanceBefore + sellerPayoff, "Treasury native currency balance mismatch" ); expect(treasuryTokenBalanceAfter).to.eql( - treasuryTokenBalanceBefore.add(sellerPayoff), + treasuryTokenBalanceBefore + sellerPayoff, "Treasury token balance mismatch" ); }); @@ -641,13 +657,13 @@ describe("IBosonFundsHandler", function () { // Read on chain state sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - const treasuryNativeBalanceBefore = await ethers.provider.getBalance(treasury.address); - const treasuryTokenBalanceBefore = await mockToken.balanceOf(treasury.address); + const treasuryNativeBalanceBefore = await provider.getBalance(await treasury.getAddress()); + const treasuryTokenBalanceBefore = await mockToken.balanceOf(await treasury.getAddress()); // Chain state should match the expected available funds before the withdrawal expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerPayoff), - new Funds(ethers.constants.AddressZero, "Native currency", sellerPayoff), + new Funds(await mockToken.getAddress(), "Foreign20", sellerPayoff), + new Funds(ZeroAddress, "Native currency", sellerPayoff), ]); expect(sellersAvailableFunds).to.eql( expectedSellerAvailableFunds, @@ -659,14 +675,12 @@ describe("IBosonFundsHandler", function () { // Read on chain state sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - let treasuryNativeBalanceAfter = await ethers.provider.getBalance(treasury.address); - const treasuryTokenBalanceAfter = await mockToken.balanceOf(treasury.address); + let treasuryNativeBalanceAfter = await provider.getBalance(await treasury.getAddress()); + const treasuryTokenBalanceAfter = await mockToken.balanceOf(await treasury.getAddress()); // Chain state should match the expected available funds after the withdrawal // Funds available should still have the entries from above the threshold - expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", sellerPayoff), - ]); + expectedSellerAvailableFunds = new FundsList([new Funds(ZeroAddress, "Native currency", sellerPayoff)]); expect(sellersAvailableFunds).to.eql( expectedSellerAvailableFunds, "Seller available funds mismatch after first withdrawal" @@ -677,7 +691,7 @@ describe("IBosonFundsHandler", function () { "Treasury native currency balance mismatch after first withdrawal" ); expect(treasuryTokenBalanceAfter).to.eql( - treasuryTokenBalanceBefore.add(sellerPayoff), + treasuryTokenBalanceBefore + sellerPayoff, "Treasury token balance mismatch after first withdrawal" ); @@ -686,7 +700,7 @@ describe("IBosonFundsHandler", function () { // Read on chain state sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - treasuryNativeBalanceAfter = await ethers.provider.getBalance(treasury.address); + treasuryNativeBalanceAfter = await provider.getBalance(await treasury.getAddress()); // Chain state should match the expected available funds after the withdrawal // Funds available should now be an empty list @@ -697,16 +711,16 @@ describe("IBosonFundsHandler", function () { ); // Native currency balance is increased for the withdrawAmount expect(treasuryNativeBalanceAfter).to.eql( - treasuryNativeBalanceBefore.add(sellerPayoff), + treasuryNativeBalanceBefore + sellerPayoff, "Treasury native currency balance mismatch after second withdrawal" ); }); it("It's possible to withdraw same toke twice if in total enough available funds", async function () { - let reduction = ethers.utils.parseUnits("0.1", "ether").toString(); + let reduction = parseUnits("0.1", "ether"); // Withdraw token - tokenListSeller = [mockToken.address, mockToken.address]; - tokenAmountsSeller = [ethers.BigNumber.from(sellerPayoff).sub(reduction).toString(), reduction]; + tokenListSeller = [await mockToken.getAddress(), await mockToken.getAddress()]; + tokenAmountsSeller = [BigInt(sellerPayoff) - BigInt(reduction), reduction]; // seller withdrawal const tx = await fundsHandler @@ -716,22 +730,28 @@ describe("IBosonFundsHandler", function () { .to.emit(fundsHandler, "FundsWithdrawn") .withArgs( seller.id, - treasury.address, - mockToken.address, - ethers.BigNumber.from(sellerPayoff).sub(reduction).toString(), - assistant.address + await treasury.getAddress(), + await mockToken.getAddress(), + BigInt(sellerPayoff) - BigInt(reduction), + await assistant.getAddress() ); await expect(tx) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(seller.id, treasury.address, mockToken.address, reduction, assistant.address); + .withArgs( + seller.id, + await treasury.getAddress(), + await mockToken.getAddress(), + reduction, + await assistant.getAddress() + ); }); context("Agent Withdraws funds", async function () { beforeEach(async function () { // Create a valid agent, agentId = "4"; - agent = mockAgent(other.address); + agent = mockAgent(await other.getAddress()); agent.id = agentId; expect(agent.isValid()).is.true; @@ -743,7 +763,7 @@ describe("IBosonFundsHandler", function () { agentOffer = offer.clone(); agentOffer.id = "3"; exchangeId = "3"; - agentOffer.exchangeToken = mockToken.address; + agentOffer.exchangeToken = await mockToken.getAddress(); // Create offer with agent await offerHandler @@ -756,18 +776,18 @@ describe("IBosonFundsHandler", function () { voucherRedeemableFrom = offerDates.voucherRedeemableFrom; // top up seller's and buyer's account - await mockToken.mint(assistant.address, sellerDeposit); - await mockToken.mint(buyer.address, price); + await mockToken.mint(await assistant.getAddress(), sellerDeposit); + await mockToken.mint(await buyer.getAddress(), price); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, sellerDeposit); await mockToken.connect(buyer).approve(protocolDiamondAddress, price); // deposit to seller's pool - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, sellerDeposit); + await fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), sellerDeposit); // commit to agent offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(voucherRedeemableFrom)); @@ -785,17 +805,18 @@ describe("IBosonFundsHandler", function () { // Check the balance BEFORE withdrawFunds() const feeCollectorNativeBalanceBefore = await mockToken.balanceOf(agent.wallet); - await expect(fundsHandler.connect(other).withdrawFunds(agentId, [mockToken.address], [agentPayoff])) + await expect( + fundsHandler.connect(other).withdrawFunds(agentId, [await mockToken.getAddress()], [agentPayoff]) + ) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(agentId, agent.wallet, mockToken.address, agentPayoff, agent.wallet); + .withArgs(agentId, agent.wallet, await mockToken.getAddress(), agentPayoff, agent.wallet); // Check the balance AFTER withdrawFunds() const feeCollectorNativeBalanceAfter = await mockToken.balanceOf(agent.wallet); // Expected balance - const expectedFeeCollectorNativeBalanceAfter = ethers.BigNumber.from(feeCollectorNativeBalanceBefore).add( - agentPayoff - ); + const expectedFeeCollectorNativeBalanceAfter = + BigInt(feeCollectorNativeBalanceBefore) + BigInt(agentPayoff); // Check agent wallet balance and verify the transfer really happened. expect(feeCollectorNativeBalanceAfter).to.eql( @@ -811,22 +832,23 @@ describe("IBosonFundsHandler", function () { // retract from the dispute await disputeHandler.connect(buyer).retractDispute(exchangeId); - agentPayoff = ethers.BigNumber.from(agentOffer.price).mul(agent.feePercentage).div("10000").toString(); + agentPayoff = ((BigInt(agentOffer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); // Check the balance BEFORE withdrawFunds() const feeCollectorNativeBalanceBefore = await mockToken.balanceOf(agent.wallet); - await expect(fundsHandler.connect(other).withdrawFunds(agentId, [mockToken.address], [agentPayoff])) + await expect( + fundsHandler.connect(other).withdrawFunds(agentId, [await mockToken.getAddress()], [agentPayoff]) + ) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(agentId, agent.wallet, mockToken.address, agentPayoff, agent.wallet); + .withArgs(agentId, agent.wallet, await mockToken.getAddress(), agentPayoff, agent.wallet); // Check the balance AFTER withdrawFunds() const feeCollectorNativeBalanceAfter = await mockToken.balanceOf(agent.wallet); // Expected balance - const expectedFeeCollectorNativeBalanceAfter = ethers.BigNumber.from(feeCollectorNativeBalanceBefore).add( - agentPayoff - ); + const expectedFeeCollectorNativeBalanceAfter = + BigInt(feeCollectorNativeBalanceBefore) + BigInt(agentPayoff); // Check agent wallet balance and verify the transfer really happened. expect(feeCollectorNativeBalanceAfter).to.eql( @@ -839,10 +861,10 @@ describe("IBosonFundsHandler", function () { context("💔 Revert Reasons", async function () { it("The funds region of protocol is paused", async function () { // Withdraw tokens - tokenListBuyer = [ethers.constants.AddressZero, mockToken.address]; + tokenListBuyer = [ZeroAddress, await mockToken.getAddress()]; // Withdraw amounts - tokenAmountsBuyer = [buyerPayoff, ethers.BigNumber.from(buyerPayoff).div("5").toString()]; + tokenAmountsBuyer = [BigInt(buyerPayoff), BigInt(buyerPayoff) / 5n]; // Pause the funds region of the protocol await pauseHandler.connect(pauser).pause([PausableRegion.Funds]); @@ -872,7 +894,7 @@ describe("IBosonFundsHandler", function () { it("Token list address does not match token amount address", async function () { // Withdraw token - tokenList = [mockToken.address, ethers.constants.AddressZero]; + tokenList = [await mockToken.getAddress(), ZeroAddress]; tokenAmounts = [sellerPayoff]; // Attempt to withdraw the funds, expecting revert @@ -882,7 +904,7 @@ describe("IBosonFundsHandler", function () { }); it("Caller wants to withdraw more different tokens than allowed", async function () { - tokenList = new Array(101).fill(ethers.constants.AddressZero); + tokenList = new Array(101).fill(ZeroAddress); tokenAmounts = new Array(101).fill("1"); // Attempt to withdraw the funds, expecting revert @@ -893,8 +915,8 @@ describe("IBosonFundsHandler", function () { it("Caller tries to withdraw more than they have in the available funds", async function () { // Withdraw token - tokenList = [mockToken.address]; - tokenAmounts = [ethers.BigNumber.from(sellerPayoff).mul("2")]; + tokenList = [await mockToken.getAddress()]; + tokenAmounts = [BigInt(sellerPayoff) * 2n]; // Attempt to withdraw the funds, expecting revert await expect( @@ -904,7 +926,7 @@ describe("IBosonFundsHandler", function () { it("Caller tries to withdraw the same token twice", async function () { // Withdraw token - tokenList = [mockToken.address, mockToken.address]; + tokenList = [await mockToken.getAddress(), await mockToken.getAddress()]; tokenAmounts = [sellerPayoff, sellerPayoff]; // Attempt to withdraw the funds, expecting revert @@ -915,7 +937,7 @@ describe("IBosonFundsHandler", function () { it("Nothing to withdraw", async function () { // Withdraw token - tokenList = [mockToken.address]; + tokenList = [await mockToken.getAddress()]; tokenAmounts = ["0"]; await expect( @@ -938,7 +960,7 @@ describe("IBosonFundsHandler", function () { // commit to offer on behalf of some contract tx = await exchangeHandler .connect(buyer) - .commitToOffer(fallbackErrorContract.address, offerNative.id, { value: price }); + .commitToOffer(await fallbackErrorContract.getAddress(), offerNative.id, { value: price }); txReceipt = await tx.wait(); event = getEvent(txReceipt, exchangeHandler, "BuyerCommitted"); exchangeId = event.exchangeId; @@ -950,9 +972,9 @@ describe("IBosonFundsHandler", function () { // we call a fallbackContract which calls fundsHandler.withdraw, which should revert await expect( fallbackErrorContract.withdrawFunds( - fundsHandler.address, + await fundsHandler.getAddress(), fallbackContractBuyerId, - [ethers.constants.AddressZero], + [ZeroAddress], [offerNative.price] ) ).to.revertedWith(RevertReasons.TOKEN_TRANSFER_FAILED); @@ -965,7 +987,7 @@ describe("IBosonFundsHandler", function () { // commit to offer on behalf of some contract tx = await exchangeHandler .connect(buyer) - .commitToOffer(fallbackErrorContract.address, offerNative.id, { value: price }); + .commitToOffer(await fallbackErrorContract.getAddress(), offerNative.id, { value: price }); txReceipt = await tx.wait(); event = getEvent(txReceipt, exchangeHandler, "BuyerCommitted"); exchangeId = event.exchangeId; @@ -977,9 +999,9 @@ describe("IBosonFundsHandler", function () { // we call a fallbackContract which calls fundsHandler.withdraw, which should revert await expect( fallbackErrorContract.withdrawFunds( - fundsHandler.address, + await fundsHandler.getAddress(), fallbackContractBuyerId, - [ethers.constants.AddressZero], + [ZeroAddress], [offerNative.price] ) ).to.revertedWith(RevertReasons.TOKEN_TRANSFER_FAILED); @@ -1006,13 +1028,17 @@ describe("IBosonFundsHandler", function () { it("Transfer of funds failed - ERC20 transfer returns false", async function () { const [foreign20ReturnFalse] = await deployMockTokens(["Foreign20TransferReturnFalse"]); - await foreign20ReturnFalse.connect(assistant).mint(assistant.address, sellerDeposit); + await foreign20ReturnFalse.connect(assistant).mint(await assistant.getAddress(), sellerDeposit); await foreign20ReturnFalse.connect(assistant).approve(protocolDiamondAddress, sellerDeposit); - await fundsHandler.connect(assistant).depositFunds(seller.id, foreign20ReturnFalse.address, sellerDeposit); + await fundsHandler + .connect(assistant) + .depositFunds(seller.id, await foreign20ReturnFalse.getAddress(), sellerDeposit); await expect( - fundsHandler.connect(assistant).withdrawFunds(seller.id, [foreign20ReturnFalse.address], [sellerDeposit]) + fundsHandler + .connect(assistant) + .withdrawFunds(seller.id, [await foreign20ReturnFalse.getAddress()], [sellerDeposit]) ).to.revertedWith(RevertReasons.SAFE_ERC20_NOT_SUCCEEDED); }); }); @@ -1035,13 +1061,13 @@ describe("IBosonFundsHandler", function () { buyerPayoff = 0; // seller: sellerDeposit + offerToken.price - sellerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit).add(offerToken.price).toString(); + sellerPayoff = BigInt(offerToken.sellerDeposit) + BigInt(offerToken.price); // protocol: protocolFee - protocolPayoff = offerTokenProtocolFee; + protocolPayoff = BigInt(offerTokenProtocolFee); // grant fee collecor role - await accessController.grantRole(Role.FEE_COLLECTOR, feeCollector.address); + await accessController.grantRole(Role.FEE_COLLECTOR, await feeCollector.getAddress()); // set the protocol id protocolId = "0"; @@ -1049,72 +1075,73 @@ describe("IBosonFundsHandler", function () { it("should emit a FundsWithdrawn event", async function () { // Withdraw funds, testing for the event - tokenList = [mockToken.address, ethers.constants.AddressZero]; + tokenList = [await mockToken.getAddress(), ZeroAddress]; tokenAmounts = [protocolPayoff, protocolPayoff]; // protocol fee withdrawal const tx = await fundsHandler.connect(feeCollector).withdrawProtocolFees(tokenList, tokenAmounts); await expect(tx) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(protocolId, protocolTreasury.address, mockToken.address, protocolPayoff, feeCollector.address); + .withArgs( + protocolId, + await protocolTreasury.getAddress(), + await mockToken.getAddress(), + protocolPayoff, + await feeCollector.getAddress() + ); await expect(tx) .to.emit(fundsHandler, "FundsWithdrawn") .withArgs( protocolId, - protocolTreasury.address, - ethers.constants.Zero, + await protocolTreasury.getAddress(), + 0n, protocolPayoff, - feeCollector.address + await feeCollector.getAddress() ); }); it("should update state", async function () { // Read on chain state protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); - const protocolTreasuryNativeBalanceBefore = await ethers.provider.getBalance(protocolTreasury.address); - const protocolTreasuryTokenBalanceBefore = await mockToken.balanceOf(protocolTreasury.address); + const protocolTreasuryNativeBalanceBefore = await provider.getBalance(await protocolTreasury.getAddress()); + const protocolTreasuryTokenBalanceBefore = await mockToken.balanceOf(await protocolTreasury.getAddress()); // Chain state should match the expected available funds before the withdrawal expectedProtocolAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", protocolPayoff), - new Funds(ethers.constants.AddressZero, "Native currency", protocolPayoff), + new Funds(await mockToken.getAddress(), "Foreign20", protocolPayoff.toString()), + new Funds(ZeroAddress, "Native currency", protocolPayoff.toString()), ]); + expect(protocolAvailableFunds).to.eql( expectedProtocolAvailableFunds, "Protocol available funds mismatch before withdrawal" ); // withdraw funds - const partialFeeWithdrawAmount = ethers.BigNumber.from(protocolPayoff) - .sub(ethers.utils.parseUnits("0.01", "ether")) - .toString(); + const partialFeeWithdrawAmount = BigInt(protocolPayoff) - parseUnits("0.01", "ether"); tx = await fundsHandler .connect(feeCollector) .withdrawProtocolFees( - [mockToken.address, ethers.constants.AddressZero], + [await mockToken.getAddress(), ZeroAddress], [protocolPayoff, partialFeeWithdrawAmount] ); // calcualte tx costs txReceipt = await tx.wait(); - txCost = tx.gasPrice.mul(txReceipt.gasUsed); + txCost = tx.gasPrice * txReceipt.gasUsed; // Read on chain state protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); - const protocolTreasuryNativeBalanceAfter = await ethers.provider.getBalance(protocolTreasury.address); - const protocolTreasuryTokenBalanceAfter = await mockToken.balanceOf(protocolTreasury.address); + const protocolTreasuryNativeBalanceAfter = await provider.getBalance(await protocolTreasury.getAddress()); + const protocolTreasuryTokenBalanceAfter = await mockToken.balanceOf(await protocolTreasury.getAddress()); // Chain state should match the expected available funds after the withdrawal // Native currency available funds are reduced for the withdrawal amount // Mock token is fully withdrawn expectedProtocolAvailableFunds = new FundsList([ - new Funds( - ethers.constants.AddressZero, - "Native currency", - ethers.BigNumber.from(protocolPayoff).sub(partialFeeWithdrawAmount).toString() - ), + new Funds(ZeroAddress, "Native currency", (BigInt(protocolPayoff) - partialFeeWithdrawAmount).toString()), ]); expect(protocolAvailableFunds).to.eql( @@ -1123,12 +1150,12 @@ describe("IBosonFundsHandler", function () { ); // Native currency balance is increased for the partialFeeWithdrawAmount expect(protocolTreasuryNativeBalanceAfter).to.eql( - protocolTreasuryNativeBalanceBefore.add(partialFeeWithdrawAmount), + protocolTreasuryNativeBalanceBefore + partialFeeWithdrawAmount, "Fee collector token balance mismatch" ); // Token balance is increased for the protocol fee expect(protocolTreasuryTokenBalanceAfter).to.eql( - protocolTreasuryTokenBalanceBefore.add(protocolPayoff), + protocolTreasuryTokenBalanceBefore + BigInt(protocolPayoff), "Fee collector token balance mismatch" ); }); @@ -1136,14 +1163,15 @@ describe("IBosonFundsHandler", function () { it("should allow to withdraw all funds at once", async function () { // Read on chain state protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); - const protocolTreasuryNativeBalanceBefore = await ethers.provider.getBalance(protocolTreasury.address); - const protocolTreasuryTokenBalanceBefore = await mockToken.balanceOf(protocolTreasury.address); + const protocolTreasuryNativeBalanceBefore = await provider.getBalance(await protocolTreasury.getAddress()); + const protocolTreasuryTokenBalanceBefore = await mockToken.balanceOf(await protocolTreasury.getAddress()); // Chain state should match the expected available funds before the withdrawal expectedProtocolAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", protocolPayoff), - new Funds(ethers.constants.AddressZero, "Native currency", protocolPayoff), + new Funds(await mockToken.getAddress(), "Foreign20", protocolPayoff.toString()), + new Funds(ZeroAddress, "Native currency", protocolPayoff.toString()), ]); + expect(protocolAvailableFunds).to.eql( expectedProtocolAvailableFunds, "Protocol available funds mismatch before withdrawal" @@ -1154,12 +1182,12 @@ describe("IBosonFundsHandler", function () { // calcualte tx costs txReceipt = await tx.wait(); - txCost = tx.gasPrice.mul(txReceipt.gasUsed); + txCost = tx.gasPrice * txReceipt.gasUsed; // Read on chain state protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); - const protocolTreasuryNativeBalanceAfter = await ethers.provider.getBalance(protocolTreasury.address); - const protocolTreasuryTokenBalanceAfter = await mockToken.balanceOf(protocolTreasury.address); + const protocolTreasuryNativeBalanceAfter = await provider.getBalance(await protocolTreasury.getAddress()); + const protocolTreasuryTokenBalanceAfter = await mockToken.balanceOf(await protocolTreasury.getAddress()); // Chain state should match the expected available funds after the withdrawal // Funds available should be an empty list @@ -1170,12 +1198,12 @@ describe("IBosonFundsHandler", function () { ); // Native currency balance is increased for the partialFeeWithdrawAmount expect(protocolTreasuryNativeBalanceAfter).to.eql( - protocolTreasuryNativeBalanceBefore.add(protocolPayoff), + protocolTreasuryNativeBalanceBefore + protocolPayoff, "Fee collector native currency balance mismatch" ); // Token balance is increased for the protocol fee expect(protocolTreasuryTokenBalanceAfter).to.eql( - protocolTreasuryTokenBalanceBefore.add(protocolPayoff), + protocolTreasuryTokenBalanceBefore + protocolPayoff, "Fee collector token balance mismatch" ); }); @@ -1186,13 +1214,13 @@ describe("IBosonFundsHandler", function () { // Read on chain state protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); - let protocolTreasuryNativeBalanceBefore = await ethers.provider.getBalance(protocolTreasury.address); - const protocolTreasuryTokenBalanceBefore = await mockToken.balanceOf(protocolTreasury.address); + let protocolTreasuryNativeBalanceBefore = await provider.getBalance(await protocolTreasury.getAddress()); + const protocolTreasuryTokenBalanceBefore = await mockToken.balanceOf(await protocolTreasury.getAddress()); // Chain state should match the expected available funds before the withdrawal expectedProtocolAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", protocolPayoff), - new Funds(ethers.constants.AddressZero, "Native currency", protocolPayoff), + new Funds(await mockToken.getAddress(), "Foreign20", protocolPayoff.toString()), + new Funds(ZeroAddress, "Native currency", protocolPayoff.toString()), ]); expect(protocolAvailableFunds).to.eql( expectedProtocolAvailableFunds, @@ -1204,17 +1232,17 @@ describe("IBosonFundsHandler", function () { // calcualte tx costs txReceipt = await tx.wait(); - txCost = tx.gasPrice.mul(txReceipt.gasUsed); + txCost = tx.gasPrice * txReceipt.gasUsed; // Read on chain state protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); - let protocolTreasuryNativeBalanceAfter = await ethers.provider.getBalance(protocolTreasury.address); - const protocolTreasuryTokenBalanceAfter = await mockToken.balanceOf(protocolTreasury.address); + let protocolTreasuryNativeBalanceAfter = await provider.getBalance(await protocolTreasury.getAddress()); + const protocolTreasuryTokenBalanceAfter = await mockToken.balanceOf(await protocolTreasury.getAddress()); // Chain state should match the expected available funds after the withdrawal // Funds available should still have the entries from above the threshold expectedProtocolAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", protocolPayoff), + new Funds(ZeroAddress, "Native currency", protocolPayoff.toString()), ]); expect(protocolAvailableFunds).to.eql( expectedProtocolAvailableFunds, @@ -1226,7 +1254,7 @@ describe("IBosonFundsHandler", function () { "Fee collector native currency balance mismatch after first withdrawal" ); expect(protocolTreasuryTokenBalanceAfter).to.eql( - protocolTreasuryTokenBalanceBefore.add(protocolPayoff), + protocolTreasuryTokenBalanceBefore + protocolPayoff, "Fee collector token balance mismatch after first withdrawal" ); @@ -1235,11 +1263,11 @@ describe("IBosonFundsHandler", function () { // calcualte tx costs txReceipt = await tx.wait(); - txCost = tx.gasPrice.mul(txReceipt.gasUsed); + txCost = tx.gasPrice * txReceipt.gasUsed; // Read on chain state protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); - protocolTreasuryNativeBalanceAfter = await ethers.provider.getBalance(protocolTreasury.address); + protocolTreasuryNativeBalanceAfter = await provider.getBalance(await protocolTreasury.getAddress()); // Chain state should match the expected available funds after the withdrawal // Funds available should now be an empty list @@ -1250,16 +1278,16 @@ describe("IBosonFundsHandler", function () { ); // Native currency balance is increased for the protocol fee expect(protocolTreasuryNativeBalanceAfter).to.eql( - protocolTreasuryNativeBalanceBefore.add(offerTokenProtocolFee), + protocolTreasuryNativeBalanceBefore + BigInt(offerTokenProtocolFee), "Fee collector native currency balance mismatch after second withdrawal" ); }); it("It's possible to withdraw same token twice if in total enough available funds", async function () { - let reduction = ethers.utils.parseUnits("0.01", "ether").toString(); + let reduction = parseUnits("0.01", "ether"); // Withdraw token - tokenList = [mockToken.address, mockToken.address]; - tokenAmounts = [ethers.BigNumber.from(protocolPayoff).sub(reduction).toString(), reduction]; + tokenList = [await mockToken.getAddress(), await mockToken.getAddress()]; + tokenAmounts = [BigInt(protocolPayoff) - reduction, reduction]; // protocol fee withdrawal const tx = await fundsHandler.connect(feeCollector).withdrawProtocolFees(tokenList, tokenAmounts); @@ -1267,21 +1295,27 @@ describe("IBosonFundsHandler", function () { .to.emit(fundsHandler, "FundsWithdrawn") .withArgs( protocolId, - protocolTreasury.address, - mockToken.address, - ethers.BigNumber.from(protocolPayoff).sub(reduction).toString(), - feeCollector.address + await protocolTreasury.getAddress(), + await mockToken.getAddress(), + BigInt(protocolPayoff) - reduction, + await feeCollector.getAddress() ); await expect(tx) .to.emit(fundsHandler, "FundsWithdrawn") - .withArgs(protocolId, protocolTreasury.address, mockToken.address, reduction, feeCollector.address); + .withArgs( + protocolId, + await protocolTreasury.getAddress(), + await mockToken.getAddress(), + reduction, + await feeCollector.getAddress() + ); }); context("💔 Revert Reasons", async function () { it("The funds region of protocol is paused", async function () { // Withdraw funds, testing for the event - tokenList = [mockToken.address, ethers.constants.AddressZero]; + tokenList = [await mockToken.getAddress(), ZeroAddress]; tokenAmounts = [protocolPayoff, protocolPayoff]; // Pause the funds region of the protocol @@ -1302,7 +1336,7 @@ describe("IBosonFundsHandler", function () { it("Token list address does not match token amount address", async function () { // Withdraw token - tokenList = [mockToken.address, ethers.constants.AddressZero]; + tokenList = [await mockToken.getAddress(), ZeroAddress]; tokenAmounts = [sellerPayoff]; // Attempt to withdraw the funds, expecting revert @@ -1312,7 +1346,7 @@ describe("IBosonFundsHandler", function () { }); it("Caller wants to withdraw more different tokens than allowed", async function () { - tokenList = new Array(101).fill(ethers.constants.AddressZero); + tokenList = new Array(101).fill(ZeroAddress); tokenAmounts = new Array(101).fill("1"); // Attempt to withdraw the funds, expecting revert @@ -1323,8 +1357,8 @@ describe("IBosonFundsHandler", function () { it("Caller tries to withdraw more than they have in the available funds", async function () { // Withdraw token - tokenList = [mockToken.address]; - tokenAmounts = [ethers.BigNumber.from(offerTokenProtocolFee).mul("2")]; + tokenList = [await mockToken.getAddress()]; + tokenAmounts = [BigInt(offerTokenProtocolFee) * 2n]; // Attempt to withdraw the funds, expecting revert await expect( @@ -1334,7 +1368,7 @@ describe("IBosonFundsHandler", function () { it("Caller tries to withdraw the same token twice", async function () { // Withdraw token - tokenList = [mockToken.address, mockToken.address]; + tokenList = [await mockToken.getAddress(), await mockToken.getAddress()]; tokenAmounts = [offerTokenProtocolFee, offerTokenProtocolFee]; // Attempt to withdraw the funds, expecting revert @@ -1345,7 +1379,7 @@ describe("IBosonFundsHandler", function () { it("Nothing to withdraw", async function () { // Withdraw token - tokenList = [mockToken.address]; + tokenList = [await mockToken.getAddress()]; tokenAmounts = ["0"]; await expect( @@ -1366,16 +1400,14 @@ describe("IBosonFundsHandler", function () { const [fallbackErrorContract] = await deployMockTokens(["FallbackError"]); // temporarily grant ADMIN role to deployer account - await accessController.grantRole(Role.ADMIN, deployer.address); + await accessController.grantRole(Role.ADMIN, await deployer.getAddress()); // set treasury to this contract - await configHandler.connect(deployer).setTreasuryAddress(fallbackErrorContract.address); + await configHandler.connect(deployer).setTreasuryAddress(await fallbackErrorContract.getAddress()); // attempt to withdraw the funds, expecting revert await expect( - fundsHandler - .connect(feeCollector) - .withdrawProtocolFees([ethers.constants.AddressZero], [offerNativeProtocolFee]) + fundsHandler.connect(feeCollector).withdrawProtocolFees([ZeroAddress], [offerNativeProtocolFee]) ).to.revertedWith(RevertReasons.TOKEN_TRANSFER_FAILED); }); @@ -1384,16 +1416,14 @@ describe("IBosonFundsHandler", function () { const [fallbackErrorContract] = await deployMockTokens(["WithoutFallbackError"]); // temporarily grant ADMIN role to deployer account - await accessController.grantRole(Role.ADMIN, deployer.address); + await accessController.grantRole(Role.ADMIN, await deployer.getAddress()); // set treasury to this contract - await configHandler.connect(deployer).setTreasuryAddress(fallbackErrorContract.address); + await configHandler.connect(deployer).setTreasuryAddress(await fallbackErrorContract.getAddress()); // attempt to withdraw the funds, expecting revert await expect( - fundsHandler - .connect(feeCollector) - .withdrawProtocolFees([ethers.constants.AddressZero], [offerNativeProtocolFee]) + fundsHandler.connect(feeCollector).withdrawProtocolFees([ZeroAddress], [offerNativeProtocolFee]) ).to.revertedWith(RevertReasons.TOKEN_TRANSFER_FAILED); }); @@ -1423,19 +1453,19 @@ describe("IBosonFundsHandler", function () { // Deploy the mock token with no name const [mockToken] = await deployMockTokens(["Foreign20NoName"]); // top up assistants account - await mockToken.mint(assistant.address, "1000000"); + await mockToken.mint(await assistant.getAddress(), "1000000"); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, "1000000"); // Deposit token - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, depositAmount); + await fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), depositAmount); // Read on chain state let returnedAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // Chain state should match the expected available funds let expectedAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Token name unspecified", depositAmount), + new Funds(await mockToken.getAddress(), "Token name unspecified", depositAmount.toString()), ]); expect(returnedAvailableFunds).to.eql(expectedAvailableFunds); }); @@ -1447,7 +1477,12 @@ describe("IBosonFundsHandler", function () { context("📋 FundsLib Methods", async function () { beforeEach(async function () { // Create a valid seller - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -1462,19 +1497,19 @@ describe("IBosonFundsHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed - DRFee = ethers.utils.parseUnits("0", "ether").toString(); + DRFee = parseUnits("0", "ether").toString(); disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0"), - new DisputeResolverFee(mockToken.address, "mockToken", DRFee), + new DisputeResolverFee(ZeroAddress, "Native", "0"), + new DisputeResolverFee(await mockToken.getAddress(), "mockToken", DRFee), ]; // Make empty seller list, so every seller is allowed @@ -1493,7 +1528,7 @@ describe("IBosonFundsHandler", function () { offerToken = offerNative.clone(); offerToken.id = "2"; - offerToken.exchangeToken = mockToken.address; + offerToken.exchangeToken = await mockToken.getAddress(); offerDates = mo.offerDates; expect(offerDates.isValid()).is.true; @@ -1520,26 +1555,26 @@ describe("IBosonFundsHandler", function () { resolutionPeriod = offerDurations.resolutionPeriod; // top up seller's and buyer's account - await mockToken.mint(assistant.address, `${2 * sellerDeposit}`); - await mockToken.mint(buyer.address, `${2 * price}`); + await mockToken.mint(await assistant.getAddress(), `${2 * sellerDeposit}`); + await mockToken.mint(await buyer.getAddress(), `${2 * price}`); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, `${2 * sellerDeposit}`); await mockToken.connect(buyer).approve(protocolDiamondAddress, `${2 * price}`); // deposit to seller's pool - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, `${2 * sellerDeposit}`); await fundsHandler .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, `${2 * sellerDeposit}`, { - value: `${2 * sellerDeposit}`, - }); + .depositFunds(seller.id, await mockToken.getAddress(), `${2 * sellerDeposit}`); + await fundsHandler.connect(assistant).depositFunds(seller.id, ZeroAddress, `${2 * sellerDeposit}`, { + value: `${2 * sellerDeposit}`, + }); // Agents // Create a valid agent, agentId = "3"; agentFeePercentage = "500"; //5% - agent = mockAgent(other.address); + agent = mockAgent(await other.getAddress()); expect(agent.isValid()).is.true; @@ -1563,43 +1598,45 @@ describe("IBosonFundsHandler", function () { let buyerId = "4"; // 1: seller, 2: disputeResolver, 3: agent, 4: buyer // Commit to an offer with erc20 token, test for FundsEncumbered event - const tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); + const tx = await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); await expect(tx) .to.emit(exchangeHandler, "FundsEncumbered") - .withArgs(buyerId, mockToken.address, price, buyer.address); + .withArgs(buyerId, await mockToken.getAddress(), price, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "FundsEncumbered") - .withArgs(seller.id, mockToken.address, sellerDeposit, buyer.address); + .withArgs(seller.id, await mockToken.getAddress(), sellerDeposit, await buyer.getAddress()); // Commit to an offer with native currency, test for FundsEncumbered event - const tx2 = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerNative.id, { value: price }); + const tx2 = await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerNative.id, { value: price }); await expect(tx2) .to.emit(exchangeHandler, "FundsEncumbered") - .withArgs(buyerId, ethers.constants.AddressZero, price, buyer.address); + .withArgs(buyerId, ZeroAddress, price, await buyer.getAddress()); await expect(tx2) .to.emit(exchangeHandler, "FundsEncumbered") - .withArgs(seller.id, ethers.constants.AddressZero, sellerDeposit, buyer.address); + .withArgs(seller.id, ZeroAddress, sellerDeposit, await buyer.getAddress()); }); it("should update state", async function () { // contract token value const contractTokenBalanceBefore = await mockToken.balanceOf(protocolDiamondAddress); // contract native token balance - const contractNativeBalanceBefore = await ethers.provider.getBalance(protocolDiamondAddress); + const contractNativeBalanceBefore = await provider.getBalance(protocolDiamondAddress); // seller's available funds const sellersAvailableFundsBefore = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // Commit to an offer with erc20 token - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); // Check that token balance increased const contractTokenBalanceAfter = await mockToken.balanceOf(protocolDiamondAddress); // contract token balance should increase for the incoming price // seller's deposit was already held in the contract's pool before - expect(contractTokenBalanceAfter.sub(contractTokenBalanceBefore).toString()).to.eql( - price, + expect(contractTokenBalanceAfter - contractTokenBalanceBefore).to.eql( + BigInt(price), "Token wrong balance increase" ); @@ -1607,20 +1644,19 @@ describe("IBosonFundsHandler", function () { let sellersAvailableFundsAfter = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // token is the first on the list of the available funds and the amount should be decreased for the sellerDeposit expect( - ethers.BigNumber.from(sellersAvailableFundsBefore.funds[0].availableAmount) - .sub(ethers.BigNumber.from(sellersAvailableFundsAfter.funds[0].availableAmount)) - .toString() - ).to.eql(sellerDeposit, "Token seller available funds mismatch"); + BigInt(sellersAvailableFundsBefore.funds[0].availableAmount) - + BigInt(sellersAvailableFundsAfter.funds[0].availableAmount) + ).to.eql(BigInt(sellerDeposit), "Token seller available funds mismatch"); // Commit to an offer with native currency - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerNative.id, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerNative.id, { value: price }); // check that native currency balance increased - const contractNativeBalanceAfter = await ethers.provider.getBalance(protocolDiamondAddress); + const contractNativeBalanceAfter = await provider.getBalance(protocolDiamondAddress); // contract token balance should increase for the incoming price // seller's deposit was already held in the contract's pool before - expect(contractNativeBalanceAfter.sub(contractNativeBalanceBefore).toString()).to.eql( - price, + expect(contractNativeBalanceAfter - contractNativeBalanceBefore).to.eql( + BigInt(price), "Native currency wrong balance increase" ); @@ -1628,10 +1664,9 @@ describe("IBosonFundsHandler", function () { sellersAvailableFundsAfter = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // native currency is the second on the list of the available funds and the amount should be decreased for the sellerDeposit expect( - ethers.BigNumber.from(sellersAvailableFundsBefore.funds[1].availableAmount) - .sub(ethers.BigNumber.from(sellersAvailableFundsAfter.funds[1].availableAmount)) - .toString() - ).to.eql(sellerDeposit, "Native currency seller available funds mismatch"); + BigInt(sellersAvailableFundsBefore.funds[1].availableAmount) - + BigInt(sellersAvailableFundsAfter.funds[1].availableAmount) + ).to.eql(BigInt(sellerDeposit), "Native currency seller available funds mismatch"); }); context("seller's available funds drop to 0", async function () { @@ -1640,29 +1675,27 @@ describe("IBosonFundsHandler", function () { let sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); expect(sellersAvailableFunds.funds.length).to.eql(2, "Funds length mismatch"); expect(sellersAvailableFunds.funds[0].tokenAddress).to.eql( - mockToken.address, + await mockToken.getAddress(), "Token contract address mismatch" ); - expect(sellersAvailableFunds.funds[1].tokenAddress).to.eql( - ethers.constants.AddressZero, - "Native currency address mismatch" - ); + expect(sellersAvailableFunds.funds[1].tokenAddress).to.eql(ZeroAddress, "Native currency address mismatch"); // Commit to offer with token twice to empty the seller's pool - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); // Token address should be removed and have only native currency in the list sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); expect(sellersAvailableFunds.funds.length).to.eql(1, "Funds length mismatch"); - expect(sellersAvailableFunds.funds[0].tokenAddress).to.eql( - ethers.constants.AddressZero, - "Native currency address mismatch" - ); + expect(sellersAvailableFunds.funds[0].tokenAddress).to.eql(ZeroAddress, "Native currency address mismatch"); // Commit to offer with token twice to empty the seller's pool - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerNative.id, { value: price }); - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerNative.id, { value: price }); + await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerNative.id, { value: price }); + await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerNative.id, { value: price }); // Seller available funds must be empty sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); @@ -1672,55 +1705,56 @@ describe("IBosonFundsHandler", function () { it("token should be removed from the token list even when list length - 1 is different from index", async function () { // length - 1 is different from index when index isn't the first or last element in the list // Deploy a new mock token - let TokenContractFactory = await ethers.getContractFactory("Foreign20"); + let TokenContractFactory = await getContractFactory("Foreign20"); const otherToken = await TokenContractFactory.deploy(); - await otherToken.deployed(); + await otherToken.waitForDeployment(); // Add otherToken to DR fees await accountHandler .connect(adminDR) .addFeesToDisputeResolver(disputeResolver.id, [ - new DisputeResolverFee(otherToken.address, "Other Token", "0"), + new DisputeResolverFee(await otherToken.getAddress(), "Other Token", "0"), ]); // top up seller's and buyer's account - await otherToken.mint(assistant.address, sellerDeposit); + await otherToken.mint(await assistant.getAddress(), sellerDeposit); // approve protocol to transfer the tokens await otherToken.connect(assistant).approve(protocolDiamondAddress, sellerDeposit); // deposit to seller's pool - await fundsHandler.connect(assistant).depositFunds(seller.id, otherToken.address, sellerDeposit); + await fundsHandler.connect(assistant).depositFunds(seller.id, await otherToken.getAddress(), sellerDeposit); // seller's available funds let sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); expect(sellersAvailableFunds.funds.length).to.eql(3, "Funds length mismatch"); expect(sellersAvailableFunds.funds[0].tokenAddress).to.eql( - mockToken.address, + await mockToken.getAddress(), "Token contract address mismatch" ); - expect(sellersAvailableFunds.funds[1].tokenAddress).to.eql( - ethers.constants.AddressZero, - "Native currency address mismatch" - ); + expect(sellersAvailableFunds.funds[1].tokenAddress).to.eql(ZeroAddress, "Native currency address mismatch"); expect(sellersAvailableFunds.funds[2].tokenAddress).to.eql( - otherToken.address, + await otherToken.getAddress(), "Boson token address mismatch" ); // Commit to offer with token twice to empty the seller's pool - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerNative.id, { value: price }); - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerNative.id, { value: price }); + await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerNative.id, { value: price }); + await exchangeHandler + .connect(buyer) + .commitToOffer(await buyer.getAddress(), offerNative.id, { value: price }); // Native currency address should be removed and have only mock token and other token in the list sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); expect(sellersAvailableFunds.funds.length).to.eql(2, "Funds length mismatch"); expect(sellersAvailableFunds.funds[0].tokenAddress).to.eql( - mockToken.address, + await mockToken.getAddress(), "Token contract address mismatch" ); expect(sellersAvailableFunds.funds[1].tokenAddress).to.eql( - otherToken.address, + await otherToken.getAddress(), "Other token address mismatch" ); }); @@ -1729,46 +1763,45 @@ describe("IBosonFundsHandler", function () { it("when someone else deposits on buyer's behalf, callers funds are transferred", async function () { // buyer will commit to an offer on rando's behalf // get token balance before the commit - const buyerTokenBalanceBefore = await mockToken.balanceOf(buyer.address); - const randoTokenBalanceBefore = await mockToken.balanceOf(rando.address); + const buyerTokenBalanceBefore = await mockToken.balanceOf(await buyer.getAddress()); + const randoTokenBalanceBefore = await mockToken.balanceOf(await rando.getAddress()); // commit to an offer with token on rando's behalf - await exchangeHandler.connect(buyer).commitToOffer(rando.address, offerToken.id); + await exchangeHandler.connect(buyer).commitToOffer(await rando.getAddress(), offerToken.id); // get token balance after the commit - const buyerTokenBalanceAfter = await mockToken.balanceOf(buyer.address); - const randoTokenBalanceAfter = await mockToken.balanceOf(rando.address); + const buyerTokenBalanceAfter = await mockToken.balanceOf(await buyer.getAddress()); + const randoTokenBalanceAfter = await mockToken.balanceOf(await rando.getAddress()); // buyer's balance should decrease, rando's should remain - expect(buyerTokenBalanceBefore.sub(buyerTokenBalanceAfter).toString()).to.eql( - price, + expect(buyerTokenBalanceBefore - buyerTokenBalanceAfter).to.eql( + BigInt(price), "Buyer's token balance should decrease for a price" ); - expect(randoTokenBalanceAfter.toString()).to.eql( - randoTokenBalanceBefore.toString(), - "Rando's token balance should remain the same" - ); + expect(randoTokenBalanceAfter).to.eql(randoTokenBalanceBefore, "Rando's token balance should remain the same"); // make sure that rando is actually the buyer of the exchange let exchange; [, exchange] = await exchangeHandler.getExchange("1"); expect(exchange.buyerId.toString()).to.eql(randoBuyerId, "Wrong buyer id"); // get native currency balance before the commit - const buyerNativeBalanceBefore = await ethers.provider.getBalance(buyer.address); - const randoNativeBalanceBefore = await ethers.provider.getBalance(rando.address); + const buyerNativeBalanceBefore = await provider.getBalance(await buyer.getAddress()); + const randoNativeBalanceBefore = await provider.getBalance(await rando.getAddress()); // commit to an offer with native currency on rando's behalf - tx = await exchangeHandler.connect(buyer).commitToOffer(rando.address, offerNative.id, { value: price }); + tx = await exchangeHandler + .connect(buyer) + .commitToOffer(await rando.getAddress(), offerNative.id, { value: price }); txReceipt = await tx.wait(); - txCost = tx.gasPrice.mul(txReceipt.gasUsed); + txCost = tx.gasPrice * txReceipt.gasUsed; // get token balance after the commit - const buyerNativeBalanceAfter = await ethers.provider.getBalance(buyer.address); - const randoNativeBalanceAfter = await ethers.provider.getBalance(rando.address); + const buyerNativeBalanceAfter = await provider.getBalance(await buyer.getAddress()); + const randoNativeBalanceAfter = await provider.getBalance(await rando.getAddress()); // buyer's balance should decrease, rando's should remain - expect(buyerNativeBalanceBefore.sub(buyerNativeBalanceAfter).sub(txCost).toString()).to.eql( - price, + expect(buyerNativeBalanceBefore - buyerNativeBalanceAfter - txCost).to.eql( + BigInt(price), "Buyer's native balance should decrease for a price" ); expect(randoNativeBalanceAfter.toString()).to.eql( @@ -1781,54 +1814,55 @@ describe("IBosonFundsHandler", function () { // make sure that randoBuyerId actually belongs to rando address let [, buyerStruct] = await accountHandler.getBuyer(randoBuyerId); - expect(buyerStruct.wallet).to.eql(rando.address, "Wrong buyer address"); + expect(buyerStruct.wallet).to.eql(await rando.getAddress(), "Wrong buyer address"); }); it("if offer is preminted, only sellers funds are encumbered", async function () { // deposit to seller's pool to cover for the price const buyerId = mockBuyer().id; - await mockToken.mint(assistant.address, `${2 * price}`); + await mockToken.mint(await assistant.getAddress(), `${2 * price}`); await mockToken.connect(assistant).approve(protocolDiamondAddress, `${2 * price}`); - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, `${2 * price}`); - await fundsHandler.connect(assistant).depositFunds(seller.id, ethers.constants.AddressZero, `${2 * price}`, { + await fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), `${2 * price}`); + await fundsHandler.connect(assistant).depositFunds(seller.id, ZeroAddress, `${2 * price}`, { value: `${2 * price}`, }); // get token balance before the commit - const buyerTokenBalanceBefore = await mockToken.balanceOf(buyer.address); + const buyerTokenBalanceBefore = await mockToken.balanceOf(await buyer.getAddress()); const sellersAvailableFundsBefore = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // reserve a range and premint vouchers await offerHandler .connect(assistant) - .reserveRange(offerToken.id, offerToken.quantityAvailable, assistant.address); - const voucherCloneAddress = calculateContractAddress(accountHandler.address, "1"); - const bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherCloneAddress); + .reserveRange(offerToken.id, offerToken.quantityAvailable, await assistant.getAddress()); + const voucherCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "1"); + const bosonVoucher = await getContractAt("BosonVoucher", voucherCloneAddress); await bosonVoucher.connect(assistant).preMint(offerToken.id, offerToken.quantityAvailable); // commit to an offer via preminted voucher let exchangeId = "1"; let tokenId = deriveTokenId(offerToken.id, exchangeId); - tx = await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + tx = await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); // it should emit FundsEncumbered event with amount equal to sellerDeposit + price - let encumberedFunds = ethers.BigNumber.from(sellerDeposit).add(price); + let encumberedFunds = BigInt(sellerDeposit) + BigInt(price); await expect(tx) .to.emit(exchangeHandler, "FundsEncumbered") - .withArgs(seller.id, mockToken.address, encumberedFunds, bosonVoucher.address); + .withArgs(seller.id, await mockToken.getAddress(), encumberedFunds, await bosonVoucher.getAddress()); // Check that seller's pool balance was reduced let sellersAvailableFundsAfter = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // token is the first on the list of the available funds and the amount should be decreased for the sellerDeposit and price expect( - ethers.BigNumber.from(sellersAvailableFundsBefore.funds[0].availableAmount) - .sub(ethers.BigNumber.from(sellersAvailableFundsAfter.funds[0].availableAmount)) - .toString() - ).to.eql(encumberedFunds.toString(), "Token seller available funds mismatch"); + BigInt(sellersAvailableFundsBefore.funds[0].availableAmount) - + BigInt(sellersAvailableFundsAfter.funds[0].availableAmount) + ).to.eql(encumberedFunds, "Token seller available funds mismatch"); // buyer's token balance should stay the same - const buyerTokenBalanceAfter = await mockToken.balanceOf(buyer.address); + const buyerTokenBalanceAfter = await mockToken.balanceOf(await buyer.getAddress()); expect(buyerTokenBalanceBefore.toString()).to.eql( buyerTokenBalanceAfter.toString(), "Buyer's token balance should remain the same" @@ -1840,27 +1874,29 @@ describe("IBosonFundsHandler", function () { expect(exchange.buyerId.toString()).to.eql(buyerId, "Wrong buyer id"); // get native currency balance before the commit - const buyerNativeBalanceBefore = await ethers.provider.getBalance(buyer.address); + const buyerNativeBalanceBefore = await provider.getBalance(await buyer.getAddress()); // reserve a range and premint vouchers exchangeId = await exchangeHandler.getNextExchangeId(); tokenId = deriveTokenId(offerNative.id, exchangeId); await offerHandler .connect(assistant) - .reserveRange(offerNative.id, offerNative.quantityAvailable, assistant.address); + .reserveRange(offerNative.id, offerNative.quantityAvailable, await assistant.getAddress()); await bosonVoucher.connect(assistant).preMint(offerNative.id, offerNative.quantityAvailable); // commit to an offer via preminted voucher - tx = await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + tx = await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); // it should emit FundsEncumbered event with amount equal to sellerDeposit + price - encumberedFunds = ethers.BigNumber.from(sellerDeposit).add(price); + encumberedFunds = BigInt(sellerDeposit) + BigInt(price); await expect(tx) .to.emit(exchangeHandler, "FundsEncumbered") - .withArgs(seller.id, ethers.constants.AddressZero, encumberedFunds, bosonVoucher.address); + .withArgs(seller.id, ZeroAddress, encumberedFunds, await bosonVoucher.getAddress()); // buyer's balance should remain the same - const buyerNativeBalanceAfter = await ethers.provider.getBalance(buyer.address); + const buyerNativeBalanceAfter = await provider.getBalance(await buyer.getAddress()); expect(buyerNativeBalanceBefore.toString()).to.eql( buyerNativeBalanceAfter.toString(), "Buyer's native balance should remain the same" @@ -1870,10 +1906,9 @@ describe("IBosonFundsHandler", function () { sellersAvailableFundsAfter = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); // native currency the second on the list of the available funds and the amount should be decreased for the sellerDeposit and price expect( - ethers.BigNumber.from(sellersAvailableFundsBefore.funds[1].availableAmount) - .sub(ethers.BigNumber.from(sellersAvailableFundsAfter.funds[1].availableAmount)) - .toString() - ).to.eql(encumberedFunds.toString(), "Native currency seller available funds mismatch"); + BigInt(sellersAvailableFundsBefore.funds[1].availableAmount) - + BigInt(sellersAvailableFundsAfter.funds[1].availableAmount) + ).to.eql(encumberedFunds, "Native currency seller available funds mismatch"); // make sure that buyer is actually the buyer of the exchange [, exchange] = await exchangeHandler.getExchange(exchangeId); @@ -1886,14 +1921,14 @@ describe("IBosonFundsHandler", function () { await expect( exchangeHandler .connect(buyer) - .commitToOffer(buyer.address, offerNative.id, { value: ethers.BigNumber.from(price).sub("1").toString() }) + .commitToOffer(await buyer.getAddress(), offerNative.id, { value: BigInt(price) - 1n }) ).to.revertedWith(RevertReasons.INSUFFICIENT_VALUE_RECEIVED); }); it("Native currency sent together with ERC20 token transfer", async function () { // Attempt to commit to an offer, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id, { value: price }) ).to.revertedWith(RevertReasons.NATIVE_NOT_ALLOWED); }); @@ -1902,7 +1937,7 @@ describe("IBosonFundsHandler", function () { [bosonToken] = await deployMockTokens(["BosonToken"]); // create an offer with a bad token contrat - offerToken.exchangeToken = bosonToken.address; + offerToken.exchangeToken = await bosonToken.getAddress(); offerToken.id = "3"; // add to DR fees @@ -1916,14 +1951,14 @@ describe("IBosonFundsHandler", function () { .createOffer(offerToken, offerDates, offerDurations, disputeResolverId, agentId); // Attempt to commit to an offer, expecting revert - await expect(exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id)).to.revertedWith( - RevertReasons.SAFE_ERC20_LOW_LEVEL_CALL - ); + await expect( + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id) + ).to.revertedWith(RevertReasons.SAFE_ERC20_LOW_LEVEL_CALL); }); it("Token address is not a contract", async function () { // create an offer with a bad token contrat - offerToken.exchangeToken = admin.address; + offerToken.exchangeToken = await admin.getAddress(); offerToken.id = "3"; // add to DR fees @@ -1939,7 +1974,7 @@ describe("IBosonFundsHandler", function () { // Attempt to commit to an offer, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id) ).to.revertedWithoutReason(); }); @@ -1948,35 +1983,33 @@ describe("IBosonFundsHandler", function () { // approve more than account actually have await mockToken.connect(rando).approve(protocolDiamondAddress, price); // Attempt to commit to an offer, expecting revert - await expect(exchangeHandler.connect(rando).commitToOffer(rando.address, offerToken.id)).to.revertedWith( - RevertReasons.ERC20_EXCEEDS_BALANCE - ); + await expect( + exchangeHandler.connect(rando).commitToOffer(await rando.getAddress(), offerToken.id) + ).to.revertedWith(RevertReasons.ERC20_EXCEEDS_BALANCE); // not approved - await mockToken - .connect(rando) - .approve(protocolDiamondAddress, ethers.BigNumber.from(price).sub("1").toString()); + await mockToken.connect(rando).approve(protocolDiamondAddress, BigInt(price) - 1n); // Attempt to commit to an offer, expecting revert - await expect(exchangeHandler.connect(rando).commitToOffer(rando.address, offerToken.id)).to.revertedWith( - RevertReasons.ERC20_INSUFFICIENT_ALLOWANCE - ); + await expect( + exchangeHandler.connect(rando).commitToOffer(await rando.getAddress(), offerToken.id) + ).to.revertedWith(RevertReasons.ERC20_INSUFFICIENT_ALLOWANCE); }); it("Seller'a availableFunds is less than the required sellerDeposit", async function () { // create an offer with token with higher seller deposit - offerToken.sellerDeposit = ethers.BigNumber.from(offerToken.sellerDeposit).mul("4"); + offerToken.sellerDeposit = BigInt(offerToken.sellerDeposit) * 4n; offerToken.id = "3"; await offerHandler .connect(assistant) .createOffer(offerToken, offerDates, offerDurations, disputeResolverId, agentId); // Attempt to commit to an offer, expecting revert - await expect(exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id)).to.revertedWith( - RevertReasons.INSUFFICIENT_AVAILABLE_FUNDS - ); + await expect( + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id) + ).to.revertedWith(RevertReasons.INSUFFICIENT_AVAILABLE_FUNDS); // create an offer with native currency with higher seller deposit - offerNative.sellerDeposit = ethers.BigNumber.from(offerNative.sellerDeposit).mul("4"); + offerNative.sellerDeposit = BigInt(offerNative.sellerDeposit) * 4n; offerNative.id = "4"; await offerHandler .connect(assistant) @@ -1984,7 +2017,7 @@ describe("IBosonFundsHandler", function () { // Attempt to commit to an offer, expecting revert await expect( - exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerNative.id, { value: price }) + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerNative.id, { value: price }) ).to.revertedWith(RevertReasons.INSUFFICIENT_AVAILABLE_FUNDS); }); @@ -1992,9 +2025,9 @@ describe("IBosonFundsHandler", function () { // reserve a range and premint vouchers for offer in tokens await offerHandler .connect(assistant) - .reserveRange(offerToken.id, offerToken.quantityAvailable, assistant.address); - const voucherCloneAddress = calculateContractAddress(accountHandler.address, "1"); - const bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherCloneAddress); + .reserveRange(offerToken.id, offerToken.quantityAvailable, await assistant.getAddress()); + const voucherCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "1"); + const bosonVoucher = await getContractAt("BosonVoucher", voucherCloneAddress); await bosonVoucher.connect(assistant).preMint(offerToken.id, offerToken.quantityAvailable); // Seller's availableFunds is 2*sellerDeposit which is less than sellerDeposit + price. @@ -2003,7 +2036,9 @@ describe("IBosonFundsHandler", function () { // Attempt to commit to an offer via preminted voucher, expecting revert let tokenId = deriveTokenId(offerToken.id, "1"); await expect( - bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId) + bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId) ).to.revertedWith(RevertReasons.INSUFFICIENT_AVAILABLE_FUNDS); // reserve a range and premint vouchers for offer in native currency @@ -2011,12 +2046,14 @@ describe("IBosonFundsHandler", function () { tokenId = deriveTokenId(offerNative.id, exchangeId); await offerHandler .connect(assistant) - .reserveRange(offerNative.id, offerNative.quantityAvailable, assistant.address); + .reserveRange(offerNative.id, offerNative.quantityAvailable, await assistant.getAddress()); await bosonVoucher.connect(assistant).preMint(offerNative.id, offerNative.quantityAvailable); // Attempt to commit to an offer, expecting revert await expect( - bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId) + bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId) ).to.revertedWith(RevertReasons.INSUFFICIENT_AVAILABLE_FUNDS); }); @@ -2025,16 +2062,16 @@ describe("IBosonFundsHandler", function () { const [Foreign20WithFee] = await deployMockTokens(["Foreign20WithFee"]); // add to DR fees - DRFee = ethers.utils.parseUnits("0", "ether").toString(); + DRFee = parseUnits("0", "ether").toString(); await accountHandler .connect(adminDR) .addFeesToDisputeResolver(disputeResolverId, [ - new DisputeResolverFee(Foreign20WithFee.address, "Foreign20WithFee", DRFee), + new DisputeResolverFee(await Foreign20WithFee.getAddress(), "Foreign20WithFee", DRFee), ]); // Create an offer with ERC20 with fees // Prepare an absolute zero offer - offerToken.exchangeToken = Foreign20WithFee.address; + offerToken.exchangeToken = await Foreign20WithFee.getAddress(); offerToken.sellerDeposit = "0"; offerToken.id++; @@ -2044,13 +2081,13 @@ describe("IBosonFundsHandler", function () { .createOffer(offerToken, offerDates, offerDurations, disputeResolverId, agentId); // mint tokens and approve - await Foreign20WithFee.mint(buyer.address, offerToken.price); + await Foreign20WithFee.mint(await buyer.getAddress(), offerToken.price); await Foreign20WithFee.connect(buyer).approve(protocolDiamondAddress, offerToken.price); // Attempt to commit to offer, expecting revert - await expect(exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id)).to.revertedWith( - RevertReasons.INSUFFICIENT_VALUE_RECEIVED - ); + await expect( + exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id) + ).to.revertedWith(RevertReasons.INSUFFICIENT_VALUE_RECEIVED); }); }); }); @@ -2063,7 +2100,7 @@ describe("IBosonFundsHandler", function () { exchangeId = "1"; // commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); }); context("Final state COMPLETED", async function () { @@ -2079,10 +2116,11 @@ describe("IBosonFundsHandler", function () { buyerPayoff = 0; // seller: sellerDeposit + price - protocolFee - sellerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit) - .add(offerToken.price) - .sub(offerTokenProtocolFee) - .toString(); + sellerPayoff = ( + BigInt(offerToken.sellerDeposit) + + BigInt(offerToken.price) - + BigInt(offerTokenProtocolFee) + ).toString(); // protocol: protocolFee protocolPayoff = offerTokenProtocolFee; @@ -2094,16 +2132,16 @@ describe("IBosonFundsHandler", function () { await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, buyer.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, offerToken.exchangeToken, protocolPayoff, buyer.address); + .withArgs(exchangeId, offerToken.exchangeToken, protocolPayoff, await buyer.getAddress()); }); it("should update state", async function () { // commit again, so seller has nothing in available funds - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); // Read on chain state sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); @@ -2113,7 +2151,7 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -2131,8 +2169,10 @@ describe("IBosonFundsHandler", function () { // seller: sellerDeposit + price - protocolFee - agentFee // protocol: protocolFee // agent: 0 - expectedSellerAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", sellerPayoff)); - expectedProtocolAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", offerTokenProtocolFee)); + expectedSellerAvailableFunds.funds.push(new Funds(await mockToken.getAddress(), "Foreign20", sellerPayoff)); + expectedProtocolAvailableFunds.funds.push( + new Funds(await mockToken.getAddress(), "Foreign20", offerTokenProtocolFee) + ); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -2151,14 +2191,14 @@ describe("IBosonFundsHandler", function () { protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); agentAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(agentId)); expectedSellerAvailableFunds.funds[1] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerPayoff).mul(2).toString() + BigInt(sellerPayoff) * 2n ); expectedProtocolAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(protocolPayoff).mul(2).toString() + BigInt(protocolPayoff) * 2n ); expect(sellersAvailableFunds).to.eql(expectedSellerAvailableFunds); expect(buyerAvailableFunds).to.eql(expectedBuyerAvailableFunds); @@ -2174,7 +2214,7 @@ describe("IBosonFundsHandler", function () { .createOffer(agentOffer, offerDates, offerDurations, disputeResolverId, agent.id); // Commit to Offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); // succesfully redeem exchange exchangeId = "2"; @@ -2185,15 +2225,16 @@ describe("IBosonFundsHandler", function () { buyerPayoff = 0; // agentPayoff: agentFee - agentFee = ethers.BigNumber.from(agentOffer.price).mul(agentFeePercentage).div("10000").toString(); + agentFee = (BigInt(agentOffer.price) * BigInt(agentFeePercentage)) / 10000n; agentPayoff = agentFee; // seller: sellerDeposit + price - protocolFee - agentFee - sellerPayoff = ethers.BigNumber.from(agentOffer.sellerDeposit) - .add(agentOffer.price) - .sub(agentOfferProtocolFee) - .sub(agentFee) - .toString(); + sellerPayoff = ( + BigInt(agentOffer.sellerDeposit) + + BigInt(agentOffer.price) - + BigInt(agentOfferProtocolFee) - + BigInt(agentFee) + ).toString(); // protocol: protocolFee protocolPayoff = agentOfferProtocolFee; @@ -2206,15 +2247,15 @@ describe("IBosonFundsHandler", function () { // Complete the exchange, expecting event await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, agentOffer.exchangeToken, sellerPayoff, buyer.address); + .withArgs(exchangeId, seller.id, agentOffer.exchangeToken, sellerPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, agentOffer.exchangeToken, protocolPayoff, buyer.address); + .withArgs(exchangeId, agentOffer.exchangeToken, protocolPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, agentId, agentOffer.exchangeToken, agentPayoff, buyer.address); + .withArgs(exchangeId, agentId, agentOffer.exchangeToken, agentPayoff, await buyer.getAddress()); }); it("should update state", async function () { @@ -2226,7 +2267,7 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -2244,9 +2285,11 @@ describe("IBosonFundsHandler", function () { // seller: sellerDeposit + price - protocolFee - agentFee // protocol: protocolFee // agent: agentFee - expectedSellerAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", sellerPayoff)); - expectedProtocolAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", agentOfferProtocolFee)); - expectedAgentAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", agentPayoff)); + expectedSellerAvailableFunds.funds.push(new Funds(await mockToken.getAddress(), "Foreign20", sellerPayoff)); + expectedProtocolAvailableFunds.funds.push( + new Funds(await mockToken.getAddress(), "Foreign20", agentOfferProtocolFee) + ); + expectedAgentAvailableFunds.funds.push(new Funds(await mockToken.getAddress(), "Foreign20", agentPayoff)); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -2263,7 +2306,7 @@ describe("IBosonFundsHandler", function () { beforeEach(async function () { // expected payoffs // buyer: sellerDeposit + price - buyerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit).add(offerToken.price).toString(); + buyerPayoff = BigInt(offerToken.sellerDeposit) + BigInt(offerToken.price); // seller: 0 sellerPayoff = 0; @@ -2276,7 +2319,7 @@ describe("IBosonFundsHandler", function () { // Revoke the voucher, expecting event await expect(exchangeHandler.connect(assistant).revokeVoucher(exchangeId)) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, assistant.address); + .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, await assistant.getAddress()); }); it("should update state", async function () { @@ -2288,8 +2331,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", (2n * BigInt(sellerDeposit)).toString()), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -2307,7 +2350,7 @@ describe("IBosonFundsHandler", function () { // seller: 0 // protocol: 0 // agent: 0 - expectedBuyerAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", buyerPayoff)); + expectedBuyerAvailableFunds.funds.push(new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff)); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -2319,7 +2362,7 @@ describe("IBosonFundsHandler", function () { // Test that if buyer has some funds available, and gets more, the funds are only updated // Commit again - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); // Revoke another voucher await exchangeHandler.connect(assistant).revokeVoucher(++exchangeId); @@ -2330,12 +2373,12 @@ describe("IBosonFundsHandler", function () { // protocol: 0 // agent: 0 expectedBuyerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(buyerPayoff).mul(2).toString() + BigInt(buyerPayoff) * 2n ); expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); @@ -2355,22 +2398,24 @@ describe("IBosonFundsHandler", function () { .createOffer(agentOffer, offerDates, offerDurations, disputeResolverId, agent.id); // top up seller's and buyer's account - await mockToken.mint(assistant.address, `${2 * sellerDeposit}`); - await mockToken.mint(buyer.address, `${2 * price}`); + await mockToken.mint(await assistant.getAddress(), `${2 * sellerDeposit}`); + await mockToken.mint(await buyer.getAddress(), `${2 * price}`); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, `${2 * sellerDeposit}`); await mockToken.connect(buyer).approve(protocolDiamondAddress, `${2 * price}`); // deposit to seller's pool - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, `${2 * sellerDeposit}`); + await fundsHandler + .connect(assistant) + .depositFunds(seller.id, await mockToken.getAddress(), `${2 * sellerDeposit}`); // Commit to Offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); // expected payoffs // buyer: sellerDeposit + price - buyerPayoff = ethers.BigNumber.from(agentOffer.sellerDeposit).add(agentOffer.price).toString(); + buyerPayoff = BigInt(agentOffer.sellerDeposit) + BigInt(agentOffer.price); // seller: 0 sellerPayoff = 0; @@ -2393,8 +2438,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", `${2 * sellerDeposit}`), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -2412,7 +2457,7 @@ describe("IBosonFundsHandler", function () { // seller: 0 // protocol: 0 // agent: 0 - expectedBuyerAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", buyerPayoff)); + expectedBuyerAvailableFunds.funds.push(new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff)); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -2424,7 +2469,7 @@ describe("IBosonFundsHandler", function () { // Test that if buyer has some funds available, and gets more, the funds are only updated // Commit again - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); // Revoke another voucher await exchangeHandler.connect(assistant).revokeVoucher(++exchangeId); @@ -2435,13 +2480,13 @@ describe("IBosonFundsHandler", function () { // protocol: 0 // agent: 0 expectedBuyerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(buyerPayoff).mul(2).toString() + BigInt(buyerPayoff) * 2n ); expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", `${sellerDeposit}`), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", `${sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); @@ -2459,10 +2504,10 @@ describe("IBosonFundsHandler", function () { beforeEach(async function () { // expected payoffs // buyer: price - buyerCancelPenalty - buyerPayoff = ethers.BigNumber.from(offerToken.price).sub(offerToken.buyerCancelPenalty).toString(); + buyerPayoff = BigInt(offerToken.price) - BigInt(offerToken.buyerCancelPenalty); // seller: sellerDeposit + buyerCancelPenalty - sellerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit).add(offerToken.buyerCancelPenalty).toString(); + sellerPayoff = BigInt(offerToken.sellerDeposit) + BigInt(offerToken.buyerCancelPenalty); // protocol: 0 protocolPayoff = 0; @@ -2473,11 +2518,11 @@ describe("IBosonFundsHandler", function () { const tx = await exchangeHandler.connect(buyer).cancelVoucher(exchangeId); await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, buyer.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, buyer.address); + .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, await buyer.getAddress()); await expect(tx).to.not.emit(exchangeHandler, "ProtocolFeeCollected"); }); @@ -2491,8 +2536,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -2511,11 +2556,11 @@ describe("IBosonFundsHandler", function () { // protocol: 0 // agent: 0 expectedSellerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerDeposit).add(sellerPayoff).toString() + BigInt(sellerDeposit) + BigInt(sellerPayoff) ); - expectedBuyerAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", buyerPayoff)); + expectedBuyerAvailableFunds.funds.push(new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff)); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -2534,27 +2579,27 @@ describe("IBosonFundsHandler", function () { .createOffer(agentOffer, offerDates, offerDurations, disputeResolverId, agent.id); // top up seller's and buyer's account - await mockToken.mint(assistant.address, `${2 * sellerDeposit}`); - await mockToken.mint(buyer.address, `${2 * price}`); + await mockToken.mint(await assistant.getAddress(), `${2 * sellerDeposit}`); + await mockToken.mint(await buyer.getAddress(), `${2 * price}`); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, `${2 * sellerDeposit}`); await mockToken.connect(buyer).approve(protocolDiamondAddress, `${2 * price}`); // deposit to seller's pool - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, `${sellerDeposit}`); + await fundsHandler + .connect(assistant) + .depositFunds(seller.id, await mockToken.getAddress(), `${sellerDeposit}`); // Commit to Offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); // expected payoffs // buyer: price - buyerCancelPenalty - buyerPayoff = ethers.BigNumber.from(agentOffer.price).sub(agentOffer.buyerCancelPenalty).toString(); + buyerPayoff = BigInt(agentOffer.price) - BigInt(agentOffer.buyerCancelPenalty); // seller: sellerDeposit + buyerCancelPenalty - sellerPayoff = ethers.BigNumber.from(agentOffer.sellerDeposit) - .add(agentOffer.buyerCancelPenalty) - .toString(); + sellerPayoff = BigInt(agentOffer.sellerDeposit) + BigInt(agentOffer.buyerCancelPenalty); // protocol: 0 protocolPayoff = 0; @@ -2574,8 +2619,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -2594,11 +2639,11 @@ describe("IBosonFundsHandler", function () { // protocol: 0 // agent: 0 expectedSellerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerDeposit).add(sellerPayoff).toString() + BigInt(sellerDeposit) + BigInt(sellerPayoff) ); - expectedBuyerAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", buyerPayoff)); + expectedBuyerAvailableFunds.funds.push(new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff)); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -2624,9 +2669,9 @@ describe("IBosonFundsHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = BigInt(disputedDate) + BigInt(resolutionPeriod); }); context("Final state DISPUTED - RETRACTED", async function () { @@ -2636,10 +2681,7 @@ describe("IBosonFundsHandler", function () { buyerPayoff = 0; // seller: sellerDeposit + price - protocolFee - sellerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit) - .add(offerToken.price) - .sub(offerTokenProtocolFee) - .toString(); + sellerPayoff = BigInt(offerToken.sellerDeposit) + BigInt(offerToken.price) - BigInt(offerTokenProtocolFee); // protocol: 0 protocolPayoff = offerTokenProtocolFee; @@ -2651,11 +2693,11 @@ describe("IBosonFundsHandler", function () { await expect(tx) .to.emit(disputeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, offerToken.exchangeToken, protocolPayoff, buyer.address); + .withArgs(exchangeId, offerToken.exchangeToken, protocolPayoff, await buyer.getAddress()); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, buyer.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await buyer.getAddress()); //check that FundsReleased event was NOT emitted with buyer Id const txReceipt = await tx.wait(); @@ -2664,7 +2706,7 @@ describe("IBosonFundsHandler", function () { buyerId, offerToken.exchangeToken, buyerPayoff, - buyer.address, + await buyer.getAddress(), ]); expect(match).to.be.false; }); @@ -2678,8 +2720,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -2698,11 +2740,15 @@ describe("IBosonFundsHandler", function () { // protocol: protocolFee // agent: 0 expectedSellerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), + "Foreign20", + (BigInt(sellerDeposit) + BigInt(sellerPayoff)).toString() + ); + expectedProtocolAvailableFunds.funds[0] = new Funds( + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerDeposit).add(sellerPayoff).toString() + protocolPayoff ); - expectedProtocolAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", protocolPayoff); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -2720,15 +2766,16 @@ describe("IBosonFundsHandler", function () { buyerPayoff = 0; // agentPayoff: agentFee - agentFee = ethers.BigNumber.from(agentOffer.price).mul(agentFeePercentage).div("10000").toString(); + agentFee = ((BigInt(agentOffer.price) * BigInt(agentFeePercentage)) / 10000n).toString(); agentPayoff = agentFee; // seller: sellerDeposit + price - protocolFee - agentFee - sellerPayoff = ethers.BigNumber.from(agentOffer.sellerDeposit) - .add(agentOffer.price) - .sub(agentOfferProtocolFee) - .sub(agentFee) - .toString(); + sellerPayoff = ( + BigInt(agentOffer.sellerDeposit) + + BigInt(agentOffer.price) - + BigInt(agentOfferProtocolFee) - + BigInt(agentFee) + ).toString(); // protocol: 0 protocolPayoff = agentOfferProtocolFee; @@ -2738,7 +2785,7 @@ describe("IBosonFundsHandler", function () { await offerHandler .connect(assistant) .createOffer(agentOffer, offerDates, offerDurations, disputeResolverId, agent.id); - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); // succesfully redeem exchange await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); @@ -2753,15 +2800,15 @@ describe("IBosonFundsHandler", function () { await expect(tx) .to.emit(disputeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, offerToken.exchangeToken, protocolPayoff, buyer.address); + .withArgs(exchangeId, offerToken.exchangeToken, protocolPayoff, await buyer.getAddress()); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, buyer.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, agentId, agentOffer.exchangeToken, agentPayoff, buyer.address); + .withArgs(exchangeId, agentId, agentOffer.exchangeToken, agentPayoff, await buyer.getAddress()); }); it("should update state", async function () { @@ -2773,7 +2820,7 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -2792,10 +2839,14 @@ describe("IBosonFundsHandler", function () { // protocol: protocolFee // agent: agentFee expectedSellerAvailableFunds.funds.push( - new Funds(mockToken.address, "Foreign20", ethers.BigNumber.from(sellerPayoff).toString()) + new Funds(await mockToken.getAddress(), "Foreign20", BigInt(sellerPayoff).toString()) + ); + expectedProtocolAvailableFunds.funds[0] = new Funds( + await mockToken.getAddress(), + "Foreign20", + protocolPayoff ); - expectedProtocolAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", protocolPayoff); - expectedAgentAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", agentPayoff)); + expectedAgentAvailableFunds.funds.push(new Funds(await mockToken.getAddress(), "Foreign20", agentPayoff)); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -2815,10 +2866,11 @@ describe("IBosonFundsHandler", function () { buyerPayoff = 0; // seller: sellerDeposit + price - protocolFee - sellerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit) - .add(offerToken.price) - .sub(offerTokenProtocolFee) - .toString(); + sellerPayoff = ( + BigInt(offerToken.sellerDeposit) + + BigInt(offerToken.price) - + BigInt(offerTokenProtocolFee) + ).toString(); // protocol: protocolFee protocolPayoff = offerTokenProtocolFee; @@ -2831,11 +2883,11 @@ describe("IBosonFundsHandler", function () { const tx = await disputeHandler.connect(rando).expireDispute(exchangeId); await expect(tx) .to.emit(disputeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, offerToken.exchangeToken, protocolPayoff, rando.address); + .withArgs(exchangeId, offerToken.exchangeToken, protocolPayoff, await rando.getAddress()); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, rando.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await rando.getAddress()); //check that FundsReleased event was NOT emitted with buyer Id const txReceipt = await tx.wait(); @@ -2844,7 +2896,7 @@ describe("IBosonFundsHandler", function () { buyerId, offerToken.exchangeToken, buyerPayoff, - rando.address, + await rando.getAddress(), ]); expect(match).to.be.false; }); @@ -2858,8 +2910,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -2878,11 +2930,15 @@ describe("IBosonFundsHandler", function () { // protocol: protocolFee // agent: 0 expectedSellerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerDeposit).add(sellerPayoff).toString() + (BigInt(sellerDeposit) + BigInt(sellerPayoff)).toString() + ); + expectedProtocolAvailableFunds.funds[0] = new Funds( + await mockToken.getAddress(), + "Foreign20", + protocolPayoff ); - expectedProtocolAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", protocolPayoff); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -2901,22 +2957,23 @@ describe("IBosonFundsHandler", function () { .createOffer(agentOffer, offerDates, offerDurations, disputeResolverId, agent.id); // Commit to Offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); // expected payoffs // buyer: 0 buyerPayoff = 0; // agentPayoff: agentFee - agentFee = ethers.BigNumber.from(agentOffer.price).mul(agentFeePercentage).div("10000").toString(); + agentFee = ((BigInt(agentOffer.price) * BigInt(agentFeePercentage)) / 10000n).toString(); agentPayoff = agentFee; // seller: sellerDeposit + price - protocolFee - agent fee - sellerPayoff = ethers.BigNumber.from(agentOffer.sellerDeposit) - .add(agentOffer.price) - .sub(agentOfferProtocolFee) - .sub(agentFee) - .toString(); + sellerPayoff = ( + BigInt(agentOffer.sellerDeposit) + + BigInt(agentOffer.price) - + BigInt(agentOfferProtocolFee) - + BigInt(agentFee) + ).toString(); // protocol: protocolFee protocolPayoff = agentOfferProtocolFee; @@ -2932,9 +2989,9 @@ describe("IBosonFundsHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = BigInt(disputedDate) + resolutionPeriod.toString(); await setNextBlockTimestamp(Number(timeout)); }); @@ -2946,15 +3003,15 @@ describe("IBosonFundsHandler", function () { // Complete the exchange, expecting event await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, agentId, agentOffer.exchangeToken, agentPayoff, rando.address); + .withArgs(exchangeId, agentId, agentOffer.exchangeToken, agentPayoff, await rando.getAddress()); await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, agentOffer.exchangeToken, sellerPayoff, rando.address); + .withArgs(exchangeId, seller.id, agentOffer.exchangeToken, sellerPayoff, await rando.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, agentOffer.exchangeToken, protocolPayoff, rando.address); + .withArgs(exchangeId, agentOffer.exchangeToken, protocolPayoff, await rando.getAddress()); }); it("should update state", async function () { @@ -2966,7 +3023,7 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -2985,12 +3042,16 @@ describe("IBosonFundsHandler", function () { // protocol: protocolFee // agent: agent fee expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), - new Funds(mockToken.address, "Foreign20", sellerPayoff), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerPayoff), ]); - expectedProtocolAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", protocolPayoff); - expectedAgentAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", agentPayoff); + expectedProtocolAvailableFunds.funds[0] = new Funds( + await mockToken.getAddress(), + "Foreign20", + protocolPayoff + ); + expectedAgentAvailableFunds.funds[0] = new Funds(await mockToken.getAddress(), "Foreign20", agentPayoff); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -3009,17 +3070,12 @@ describe("IBosonFundsHandler", function () { // expected payoffs // buyer: (price + sellerDeposit)*buyerPercentage - buyerPayoff = ethers.BigNumber.from(offerToken.price) - .add(offerToken.sellerDeposit) - .mul(buyerPercentBasisPoints) - .div("10000") - .toString(); + buyerPayoff = + ((BigInt(offerToken.price) + BigInt(offerToken.sellerDeposit)) * BigInt(buyerPercentBasisPoints)) / + 10000n; // seller: (price + sellerDeposit)*(1-buyerPercentage) - sellerPayoff = ethers.BigNumber.from(offerToken.price) - .add(offerToken.sellerDeposit) - .sub(buyerPayoff) - .toString(); + sellerPayoff = BigInt(offerToken.price) + BigInt(offerToken.sellerDeposit) - buyerPayoff; // protocol: 0 protocolPayoff = 0; @@ -3045,7 +3101,7 @@ describe("IBosonFundsHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() )); }); @@ -3056,11 +3112,11 @@ describe("IBosonFundsHandler", function () { .resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, assistant.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await assistant.getAddress()); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, assistant.address); + .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, await assistant.getAddress()); await expect(tx).to.not.emit(disputeHandler, "ProtocolFeeCollected"); }); @@ -3074,8 +3130,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", (2n * BigInt(sellerDeposit)).toString()), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -3094,11 +3150,13 @@ describe("IBosonFundsHandler", function () { // protocol: 0 // agent: 0 expectedSellerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerDeposit).add(sellerPayoff).toString() + (BigInt(sellerDeposit) + BigInt(sellerPayoff)).toString() ); - expectedBuyerAvailableFunds = new FundsList([new Funds(mockToken.address, "Foreign20", buyerPayoff)]); + expectedBuyerAvailableFunds = new FundsList([ + new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff), + ]); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -3118,7 +3176,7 @@ describe("IBosonFundsHandler", function () { .createOffer(agentOffer, offerDates, offerDurations, disputeResolverId, agent.id); // Commit to Offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); exchangeId = "2"; @@ -3132,17 +3190,17 @@ describe("IBosonFundsHandler", function () { // expected payoffs // buyer: (price + sellerDeposit)*buyerPercentage - buyerPayoff = ethers.BigNumber.from(agentOffer.price) - .add(agentOffer.sellerDeposit) - .mul(buyerPercentBasisPoints) - .div("10000") - .toString(); + buyerPayoff = ( + ((BigInt(agentOffer.price) + BigInt(agentOffer.sellerDeposit)) * BigInt(buyerPercentBasisPoints)) / + 10000n + ).toString(); // seller: (price + sellerDeposit)*(1-buyerPercentage) - sellerPayoff = ethers.BigNumber.from(agentOffer.price) - .add(agentOffer.sellerDeposit) - .sub(buyerPayoff) - .toString(); + sellerPayoff = ( + BigInt(agentOffer.price) + + BigInt(agentOffer.sellerDeposit) - + BigInt(buyerPayoff) + ).toString(); // protocol: 0 protocolPayoff = 0; @@ -3168,7 +3226,7 @@ describe("IBosonFundsHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() )); }); @@ -3181,7 +3239,7 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -3200,9 +3258,11 @@ describe("IBosonFundsHandler", function () { // protocol: 0 // agent: 0 expectedSellerAvailableFunds.funds.push( - new Funds(mockToken.address, "Foreign20", ethers.BigNumber.from(sellerPayoff).toString()) + new Funds(await mockToken.getAddress(), "Foreign20", sellerPayoff.toString()) ); - expectedBuyerAvailableFunds = new FundsList([new Funds(mockToken.address, "Foreign20", buyerPayoff)]); + expectedBuyerAvailableFunds = new FundsList([ + new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff), + ]); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -3223,11 +3283,12 @@ describe("IBosonFundsHandler", function () { buyerPayoff = 0; // seller: sellerDeposit + price - protocolFee + buyerEscalationDeposit - sellerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit) - .add(offerToken.price) - .sub(offerTokenProtocolFee) - .add(buyerEscalationDeposit) - .toString(); + sellerPayoff = ( + BigInt(offerToken.sellerDeposit) + + BigInt(offerToken.price) - + BigInt(offerTokenProtocolFee) + + BigInt(buyerEscalationDeposit) + ).toString(); // protocol: 0 protocolPayoff = offerTokenProtocolFee; @@ -3242,11 +3303,11 @@ describe("IBosonFundsHandler", function () { await expect(tx) .to.emit(disputeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, offerToken.exchangeToken, protocolPayoff, buyer.address); + .withArgs(exchangeId, offerToken.exchangeToken, protocolPayoff, await buyer.getAddress()); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, buyer.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await buyer.getAddress()); //check that FundsReleased event was NOT emitted with buyer Id const txReceipt = await tx.wait(); @@ -3255,7 +3316,7 @@ describe("IBosonFundsHandler", function () { buyerId, offerToken.exchangeToken, buyerPayoff, - buyer.address, + await buyer.getAddress(), ]); expect(match).to.be.false; }); @@ -3269,8 +3330,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -3289,11 +3350,15 @@ describe("IBosonFundsHandler", function () { // protocol: protocolFee // agent: 0 expectedSellerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerDeposit).add(sellerPayoff).toString() + (BigInt(sellerDeposit) + BigInt(sellerPayoff)).toString() + ); + expectedProtocolAvailableFunds.funds[0] = new Funds( + await mockToken.getAddress(), + "Foreign20", + protocolPayoff ); - expectedProtocolAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", protocolPayoff); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -3311,16 +3376,17 @@ describe("IBosonFundsHandler", function () { buyerPayoff = 0; // agentPayoff: agentFee - agentFee = ethers.BigNumber.from(agentOffer.price).mul(agentFeePercentage).div("10000").toString(); + agentFee = ((BigInt(agentOffer.price) * BigInt(agentFeePercentage)) / 10000n).toString(); agentPayoff = agentFee; // seller: sellerDeposit + price - protocolFee - agentFee + buyerEscalationDeposit - sellerPayoff = ethers.BigNumber.from(agentOffer.sellerDeposit) - .add(agentOffer.price) - .sub(agentOfferProtocolFee) - .sub(agentFee) - .add(buyerEscalationDeposit) - .toString(); + sellerPayoff = ( + BigInt(agentOffer.sellerDeposit) + + BigInt(agentOffer.price) - + BigInt(agentOfferProtocolFee) - + BigInt(agentFee) + + BigInt(buyerEscalationDeposit) + ).toString(); // protocol: 0 protocolPayoff = agentOfferProtocolFee; @@ -3333,8 +3399,8 @@ describe("IBosonFundsHandler", function () { // approve protocol to transfer the tokens await mockToken.connect(buyer).approve(protocolDiamondAddress, agentOffer.price); - await mockToken.mint(buyer.address, agentOffer.price); - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await mockToken.mint(await buyer.getAddress(), agentOffer.price); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); // succesfully redeem exchange await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); @@ -3343,7 +3409,7 @@ describe("IBosonFundsHandler", function () { await disputeHandler.connect(buyer).raiseDispute(exchangeId); // escalate the dispute - await mockToken.mint(buyer.address, buyerEscalationDeposit); + await mockToken.mint(await buyer.getAddress(), buyerEscalationDeposit); await mockToken.connect(buyer).approve(protocolDiamondAddress, buyerEscalationDeposit); await disputeHandler.connect(buyer).escalateDispute(exchangeId); }); @@ -3357,7 +3423,7 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -3376,10 +3442,14 @@ describe("IBosonFundsHandler", function () { // protocol: protocolFee // agent: agentFee expectedSellerAvailableFunds.funds.push( - new Funds(mockToken.address, "Foreign20", ethers.BigNumber.from(sellerPayoff).toString()) + new Funds(await mockToken.getAddress(), "Foreign20", BigInt(sellerPayoff).toString()) + ); + expectedProtocolAvailableFunds.funds[0] = new Funds( + await mockToken.getAddress(), + "Foreign20", + protocolPayoff ); - expectedProtocolAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", protocolPayoff); - expectedAgentAvailableFunds.funds.push(new Funds(mockToken.address, "Foreign20", agentPayoff)); + expectedAgentAvailableFunds.funds.push(new Funds(await mockToken.getAddress(), "Foreign20", agentPayoff)); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -3398,19 +3468,19 @@ describe("IBosonFundsHandler", function () { // expected payoffs // buyer: (price + sellerDeposit + buyerEscalationDeposit)*buyerPercentage - buyerPayoff = ethers.BigNumber.from(offerToken.price) - .add(offerToken.sellerDeposit) - .add(buyerEscalationDeposit) - .mul(buyerPercentBasisPoints) - .div("10000") - .toString(); + buyerPayoff = ( + ((BigInt(offerToken.price) + BigInt(offerToken.sellerDeposit) + BigInt(buyerEscalationDeposit)) * + BigInt(buyerPercentBasisPoints)) / + 10000n + ).toString(); // seller: (price + sellerDeposit + buyerEscalationDeposit)*(1-buyerPercentage) - sellerPayoff = ethers.BigNumber.from(offerToken.price) - .add(offerToken.sellerDeposit) - .add(buyerEscalationDeposit) - .sub(buyerPayoff) - .toString(); + sellerPayoff = ( + BigInt(offerToken.price) + + BigInt(offerToken.sellerDeposit) + + BigInt(buyerEscalationDeposit) - + BigInt(buyerPayoff) + ).toString(); // protocol: 0 protocolPayoff = 0; @@ -3436,7 +3506,7 @@ describe("IBosonFundsHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() )); // Escalate the dispute @@ -3450,11 +3520,11 @@ describe("IBosonFundsHandler", function () { .resolveDispute(exchangeId, buyerPercentBasisPoints, r, s, v); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, assistant.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await assistant.getAddress()); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, assistant.address); + .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, await assistant.getAddress()); await expect(tx).to.not.emit(disputeHandler, "ProtocolFeeCollected"); }); @@ -3468,8 +3538,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -3487,11 +3557,11 @@ describe("IBosonFundsHandler", function () { // seller: (price + sellerDeposit + buyerEscalationDeposit)*(1-buyerPercentage); note that seller has sellerDeposit in availableFunds from before // protocol: 0 // agent: 0 - expectedBuyerAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", buyerPayoff); + expectedBuyerAvailableFunds.funds[0] = new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff); expectedSellerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerDeposit).add(sellerPayoff).toString() + (BigInt(sellerDeposit) + BigInt(sellerPayoff)).toString() ); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); @@ -3512,10 +3582,10 @@ describe("IBosonFundsHandler", function () { // approve protocol to transfer the tokens await mockToken.connect(buyer).approve(protocolDiamondAddress, agentOffer.price); - await mockToken.mint(buyer.address, agentOffer.price); + await mockToken.mint(await buyer.getAddress(), agentOffer.price); // Commit to Offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); exchangeId = "2"; @@ -3529,19 +3599,19 @@ describe("IBosonFundsHandler", function () { // expected payoffs // buyer: (price + sellerDeposit + buyerEscalationDeposit)*buyerPercentage - buyerPayoff = ethers.BigNumber.from(agentOffer.price) - .add(agentOffer.sellerDeposit) - .add(buyerEscalationDeposit) - .mul(buyerPercentBasisPoints) - .div("10000") - .toString(); + buyerPayoff = ( + ((BigInt(agentOffer.price) + BigInt(agentOffer.sellerDeposit) + BigInt(buyerEscalationDeposit)) * + BigInt(buyerPercentBasisPoints)) / + 10000n + ).toString(); // seller: (price + sellerDeposit + buyerEscalationDeposit)*(1-buyerPercentage) - sellerPayoff = ethers.BigNumber.from(agentOffer.price) - .add(agentOffer.sellerDeposit) - .add(buyerEscalationDeposit) - .sub(buyerPayoff) - .toString(); + sellerPayoff = ( + BigInt(agentOffer.price) + + BigInt(agentOffer.sellerDeposit) + + BigInt(buyerEscalationDeposit) - + BigInt(buyerPayoff) + ).toString(); // protocol: 0 protocolPayoff = 0; @@ -3567,11 +3637,11 @@ describe("IBosonFundsHandler", function () { customSignatureType, "Resolution", message, - disputeHandler.address + await disputeHandler.getAddress() )); // escalate the dispute - await mockToken.mint(buyer.address, buyerEscalationDeposit); + await mockToken.mint(await buyer.getAddress(), buyerEscalationDeposit); await mockToken.connect(buyer).approve(protocolDiamondAddress, buyerEscalationDeposit); await disputeHandler.connect(buyer).escalateDispute(exchangeId); }); @@ -3585,7 +3655,7 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -3604,9 +3674,11 @@ describe("IBosonFundsHandler", function () { // protocol: 0 // agent: 0 expectedSellerAvailableFunds.funds.push( - new Funds(mockToken.address, "Foreign20", ethers.BigNumber.from(sellerPayoff).toString()) + new Funds(await mockToken.getAddress(), "Foreign20", BigInt(sellerPayoff).toString()) ); - expectedBuyerAvailableFunds = new FundsList([new Funds(mockToken.address, "Foreign20", buyerPayoff)]); + expectedBuyerAvailableFunds = new FundsList([ + new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff), + ]); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -3626,19 +3698,19 @@ describe("IBosonFundsHandler", function () { // expected payoffs // buyer: (price + sellerDeposit + buyerEscalationDeposit)*buyerPercentage - buyerPayoff = ethers.BigNumber.from(offerToken.price) - .add(offerToken.sellerDeposit) - .add(buyerEscalationDeposit) - .mul(buyerPercentBasisPoints) - .div("10000") - .toString(); + buyerPayoff = ( + ((BigInt(offerToken.price) + BigInt(offerToken.sellerDeposit) + BigInt(buyerEscalationDeposit)) * + BigInt(buyerPercentBasisPoints)) / + 10000n + ).toString(); // seller: (price + sellerDeposit + buyerEscalationDeposit)*(1-buyerPercentage) - sellerPayoff = ethers.BigNumber.from(offerToken.price) - .add(offerToken.sellerDeposit) - .add(buyerEscalationDeposit) - .sub(buyerPayoff) - .toString(); + sellerPayoff = ( + BigInt(offerToken.price) + + BigInt(offerToken.sellerDeposit) + + BigInt(buyerEscalationDeposit) - + BigInt(buyerPayoff) + ).toString(); // protocol: 0 protocolPayoff = 0; @@ -3652,11 +3724,11 @@ describe("IBosonFundsHandler", function () { const tx = await disputeHandler.connect(assistantDR).decideDispute(exchangeId, buyerPercentBasisPoints); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, assistantDR.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await assistantDR.getAddress()); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, assistantDR.address); + .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, await assistantDR.getAddress()); await expect(tx).to.not.emit(disputeHandler, "ProtocolFeeCollected"); }); @@ -3670,8 +3742,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -3689,11 +3761,11 @@ describe("IBosonFundsHandler", function () { // seller: (price + sellerDeposit + buyerEscalationDeposit)*(1-buyerPercentage); note that seller has sellerDeposit in availableFunds from before // protocol: 0 // agent: 0 - expectedBuyerAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", buyerPayoff); + expectedBuyerAvailableFunds.funds[0] = new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff); expectedSellerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerDeposit).add(sellerPayoff).toString() + (BigInt(sellerDeposit) + BigInt(sellerPayoff)).toString() ); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); @@ -3714,10 +3786,10 @@ describe("IBosonFundsHandler", function () { // approve protocol to transfer the tokens await mockToken.connect(buyer).approve(protocolDiamondAddress, agentOffer.price); - await mockToken.mint(buyer.address, agentOffer.price); + await mockToken.mint(await buyer.getAddress(), agentOffer.price); // Commit to Offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); exchangeId = "2"; @@ -3729,33 +3801,33 @@ describe("IBosonFundsHandler", function () { // Get the block timestamp of the confirmed tx and set disputedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(disputedDate).add(resolutionPeriod).toString(); + timeout = (BigInt(disputedDate) + BigInt(resolutionPeriod)).toString(); buyerPercentBasisPoints = "5566"; // 55.66% // expected payoffs // buyer: (price + sellerDeposit + buyerEscalationDeposit)*buyerPercentage - buyerPayoff = ethers.BigNumber.from(agentOffer.price) - .add(agentOffer.sellerDeposit) - .add(buyerEscalationDeposit) - .mul(buyerPercentBasisPoints) - .div("10000") - .toString(); + buyerPayoff = ( + ((BigInt(agentOffer.price) + BigInt(agentOffer.sellerDeposit) + BigInt(buyerEscalationDeposit)) * + BigInt(buyerPercentBasisPoints)) / + 10000n + ).toString(); // seller: (price + sellerDeposit + buyerEscalationDeposit)*(1-buyerPercentage) - sellerPayoff = ethers.BigNumber.from(agentOffer.price) - .add(agentOffer.sellerDeposit) - .add(buyerEscalationDeposit) - .sub(buyerPayoff) - .toString(); + sellerPayoff = ( + BigInt(agentOffer.price) + + BigInt(agentOffer.sellerDeposit) + + BigInt(buyerEscalationDeposit) - + BigInt(buyerPayoff) + ).toString(); // protocol: 0 protocolPayoff = 0; // escalate the dispute - await mockToken.mint(buyer.address, buyerEscalationDeposit); + await mockToken.mint(await buyer.getAddress(), buyerEscalationDeposit); await mockToken.connect(buyer).approve(protocolDiamondAddress, buyerEscalationDeposit); await disputeHandler.connect(buyer).escalateDispute(exchangeId); }); @@ -3769,7 +3841,7 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -3788,9 +3860,11 @@ describe("IBosonFundsHandler", function () { // protocol: 0 // agent: 0 expectedSellerAvailableFunds.funds.push( - new Funds(mockToken.address, "Foreign20", ethers.BigNumber.from(sellerPayoff).toString()) + new Funds(await mockToken.getAddress(), "Foreign20", sellerPayoff) ); - expectedBuyerAvailableFunds = new FundsList([new Funds(mockToken.address, "Foreign20", buyerPayoff)]); + expectedBuyerAvailableFunds = new FundsList([ + new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff), + ]); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); protocolAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(protocolId)); @@ -3809,7 +3883,7 @@ describe("IBosonFundsHandler", function () { beforeEach(async function () { // expected payoffs // buyer: price + buyerEscalationDeposit - buyerPayoff = ethers.BigNumber.from(offerToken.price).add(buyerEscalationDeposit).toString(); + buyerPayoff = (BigInt(offerToken.price) + BigInt(buyerEscalationDeposit)).toString(); // seller: sellerDeposit sellerPayoff = offerToken.sellerDeposit; @@ -3822,7 +3896,7 @@ describe("IBosonFundsHandler", function () { // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); escalatedDate = block.timestamp.toString(); await setNextBlockTimestamp(Number(escalatedDate) + Number(disputeResolver.escalationResponsePeriod)); @@ -3833,10 +3907,10 @@ describe("IBosonFundsHandler", function () { const tx = await disputeHandler.connect(rando).expireEscalatedDispute(exchangeId); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, rando.address); + .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, await rando.getAddress()); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, rando.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await rando.getAddress()); await expect(tx).to.not.emit(disputeHandler, "ProtocolFeeCollected"); }); @@ -3850,8 +3924,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -3869,11 +3943,11 @@ describe("IBosonFundsHandler", function () { // seller: sellerDeposit; note that seller has sellerDeposit in availableFunds from before // protocol: 0 // agent: 0 - expectedBuyerAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", buyerPayoff); + expectedBuyerAvailableFunds.funds[0] = new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff); expectedSellerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerDeposit).add(sellerPayoff).toString() + (BigInt(sellerDeposit) + BigInt(sellerPayoff)).toString() ); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); @@ -3894,10 +3968,10 @@ describe("IBosonFundsHandler", function () { // approve protocol to transfer the tokens await mockToken.connect(buyer).approve(protocolDiamondAddress, agentOffer.price); - await mockToken.mint(buyer.address, agentOffer.price); + await mockToken.mint(await buyer.getAddress(), agentOffer.price); // Commit to Offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); exchangeId = "2"; @@ -3909,7 +3983,7 @@ describe("IBosonFundsHandler", function () { // expected payoffs // buyer: price + buyerEscalationDeposit - buyerPayoff = ethers.BigNumber.from(offerToken.price).add(buyerEscalationDeposit).toString(); + buyerPayoff = (BigInt(offerToken.price) + BigInt(buyerEscalationDeposit)).toString(); // seller: sellerDeposit sellerPayoff = offerToken.sellerDeposit; @@ -3918,13 +3992,13 @@ describe("IBosonFundsHandler", function () { protocolPayoff = 0; // Escalate the dispute - await mockToken.mint(buyer.address, buyerEscalationDeposit); + await mockToken.mint(await buyer.getAddress(), buyerEscalationDeposit); await mockToken.connect(buyer).approve(protocolDiamondAddress, buyerEscalationDeposit); tx = await disputeHandler.connect(buyer).escalateDispute(exchangeId); // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); escalatedDate = block.timestamp.toString(); await setNextBlockTimestamp(Number(escalatedDate) + Number(disputeResolver.escalationResponsePeriod)); @@ -3939,7 +4013,7 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -3957,9 +4031,13 @@ describe("IBosonFundsHandler", function () { // seller: sellerDeposit; // protocol: 0 // agent: 0 - expectedBuyerAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", buyerPayoff); + expectedBuyerAvailableFunds.funds[0] = new Funds( + await mockToken.getAddress(), + "Foreign20", + buyerPayoff + ); expectedSellerAvailableFunds.funds.push( - new Funds(mockToken.address, "Foreign20", ethers.BigNumber.from(sellerPayoff).toString()) + new Funds(await mockToken.getAddress(), "Foreign20", BigInt(sellerPayoff).toString()) ); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); @@ -3980,7 +4058,7 @@ describe("IBosonFundsHandler", function () { beforeEach(async function () { // expected payoffs // buyer: price + buyerEscalationDeposit - buyerPayoff = ethers.BigNumber.from(offerToken.price).add(buyerEscalationDeposit).toString(); + buyerPayoff = (BigInt(offerToken.price) + BigInt(buyerEscalationDeposit)).toString(); // seller: sellerDeposit sellerPayoff = offerToken.sellerDeposit; @@ -3998,11 +4076,17 @@ describe("IBosonFundsHandler", function () { await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, assistantDR.address); + .withArgs( + exchangeId, + seller.id, + offerToken.exchangeToken, + sellerPayoff, + await assistantDR.getAddress() + ); await expect(tx) .to.emit(disputeHandler, "FundsReleased") - .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, assistantDR.address); + .withArgs(exchangeId, buyerId, offerToken.exchangeToken, buyerPayoff, await assistantDR.getAddress()); await expect(tx).to.not.emit(disputeHandler, "ProtocolFeeCollected"); @@ -4013,7 +4097,7 @@ describe("IBosonFundsHandler", function () { seller.id, offerToken.exchangeToken, sellerPayoff, - rando.address, + await rando.getAddress(), ]); expect(match).to.be.false; }); @@ -4027,8 +4111,8 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", sellerDeposit), - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(await mockToken.getAddress(), "Foreign20", sellerDeposit), + new Funds(ZeroAddress, "Native currency", (2n * BigInt(sellerDeposit)).toString()), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -4046,11 +4130,11 @@ describe("IBosonFundsHandler", function () { // seller: sellerDeposit; note that seller has sellerDeposit in availableFunds from before // protocol: 0 // agent: 0 - expectedBuyerAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", buyerPayoff); + expectedBuyerAvailableFunds.funds[0] = new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff); expectedSellerAvailableFunds.funds[0] = new Funds( - mockToken.address, + await mockToken.getAddress(), "Foreign20", - ethers.BigNumber.from(sellerDeposit).add(sellerPayoff).toString() + (BigInt(sellerDeposit) + BigInt(sellerPayoff)).toString() ); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); @@ -4071,10 +4155,10 @@ describe("IBosonFundsHandler", function () { // approve protocol to transfer the tokens await mockToken.connect(buyer).approve(protocolDiamondAddress, agentOffer.price); - await mockToken.mint(buyer.address, agentOffer.price); + await mockToken.mint(await buyer.getAddress(), agentOffer.price); // Commit to Offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); exchangeId = "2"; @@ -4086,7 +4170,7 @@ describe("IBosonFundsHandler", function () { // expected payoffs // buyer: price + buyerEscalationDeposit - buyerPayoff = ethers.BigNumber.from(offerToken.price).add(buyerEscalationDeposit).toString(); + buyerPayoff = (BigInt(offerToken.price) + BigInt(buyerEscalationDeposit)).toString(); // seller: sellerDeposit sellerPayoff = offerToken.sellerDeposit; @@ -4095,7 +4179,7 @@ describe("IBosonFundsHandler", function () { protocolPayoff = 0; // Escalate the dispute - await mockToken.mint(buyer.address, buyerEscalationDeposit); + await mockToken.mint(await buyer.getAddress(), buyerEscalationDeposit); await mockToken.connect(buyer).approve(protocolDiamondAddress, buyerEscalationDeposit); await disputeHandler.connect(buyer).escalateDispute(exchangeId); }); @@ -4109,7 +4193,7 @@ describe("IBosonFundsHandler", function () { // Chain state should match the expected available funds expectedSellerAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", `${2 * sellerDeposit}`), + new Funds(ZeroAddress, "Native currency", `${2 * sellerDeposit}`), ]); expectedBuyerAvailableFunds = new FundsList([]); expectedProtocolAvailableFunds = new FundsList([]); @@ -4127,9 +4211,13 @@ describe("IBosonFundsHandler", function () { // seller: sellerDeposit; // protocol: 0 // agent: 0 - expectedBuyerAvailableFunds.funds[0] = new Funds(mockToken.address, "Foreign20", buyerPayoff); + expectedBuyerAvailableFunds.funds[0] = new Funds( + await mockToken.getAddress(), + "Foreign20", + buyerPayoff + ); expectedSellerAvailableFunds.funds.push( - new Funds(mockToken.address, "Foreign20", ethers.BigNumber.from(sellerPayoff).toString()) + new Funds(await mockToken.getAddress(), "Foreign20", BigInt(sellerPayoff).toString()) ); sellersAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); @@ -4148,17 +4236,14 @@ describe("IBosonFundsHandler", function () { context("Changing the protocol fee", async function () { beforeEach(async function () { // Cast Diamond to IBosonConfigHandler - configHandler = await ethers.getContractAt("IBosonConfigHandler", protocolDiamondAddress); + configHandler = await getContractAt("IBosonConfigHandler", protocolDiamondAddress); // expected payoffs // buyer: 0 buyerPayoff = 0; // seller: sellerDeposit + price - protocolFee - sellerPayoff = ethers.BigNumber.from(offerToken.sellerDeposit) - .add(offerToken.price) - .sub(offerTokenProtocolFee) - .toString(); + sellerPayoff = BigInt(offerToken.sellerDeposit) + BigInt(offerToken.price) - BigInt(offerTokenProtocolFee); }); it("Protocol fee for existing exchanges should be the same as at the offer creation", async function () { @@ -4176,11 +4261,11 @@ describe("IBosonFundsHandler", function () { const tx = await exchangeHandler.connect(buyer).completeExchange(exchangeId); await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, buyer.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, offerToken.exchangeToken, offerTokenProtocolFee, buyer.address); + .withArgs(exchangeId, offerToken.exchangeToken, offerTokenProtocolFee, await buyer.getAddress()); }); it("Protocol fee for new exchanges should be the same as at the offer creation", async function () { @@ -4191,7 +4276,7 @@ describe("IBosonFundsHandler", function () { // similar as teste before, excpet the commit to offer is done after the procol fee change // commit to offer and get the correct exchangeId - tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); + tx = await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); txReceipt = await tx.wait(); event = getEvent(txReceipt, exchangeHandler, "BuyerCommitted"); exchangeId = event.exchangeId.toString(); @@ -4206,11 +4291,11 @@ describe("IBosonFundsHandler", function () { tx = await exchangeHandler.connect(buyer).completeExchange(exchangeId); await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, buyer.address); + .withArgs(exchangeId, seller.id, offerToken.exchangeToken, sellerPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, offerToken.exchangeToken, offerTokenProtocolFee, buyer.address); + .withArgs(exchangeId, offerToken.exchangeToken, offerTokenProtocolFee, await buyer.getAddress()); }); context("Offer has an agent", async function () { @@ -4218,22 +4303,22 @@ describe("IBosonFundsHandler", function () { exchangeId = "2"; // Cast Diamond to IBosonConfigHandler - configHandler = await ethers.getContractAt("IBosonConfigHandler", protocolDiamondAddress); + configHandler = await getContractAt("IBosonConfigHandler", protocolDiamondAddress); // expected payoffs // buyer: 0 buyerPayoff = 0; // agentPayoff: agentFee - agentFee = ethers.BigNumber.from(agentOffer.price).mul(agentFeePercentage).div("10000").toString(); + agentFee = ((BigInt(agentOffer.price) * BigInt(agentFeePercentage)) / 10000n).toString(); agentPayoff = agentFee; // seller: sellerDeposit + price - protocolFee - agentFee - sellerPayoff = ethers.BigNumber.from(agentOffer.sellerDeposit) - .add(agentOffer.price) - .sub(agentOfferProtocolFee) - .sub(agentFee) - .toString(); + sellerPayoff = + BigInt(agentOffer.sellerDeposit) + + BigInt(agentOffer.price) - + BigInt(agentOfferProtocolFee) - + BigInt(agentFee); // protocol: protocolFee protocolPayoff = agentOfferProtocolFee; @@ -4244,7 +4329,7 @@ describe("IBosonFundsHandler", function () { .createOffer(agentOffer, offerDates, offerDurations, disputeResolverId, agent.id); // Commit to Agent Offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); // set the new procol fee protocolFeePercentage = "300"; // 3% @@ -4263,33 +4348,33 @@ describe("IBosonFundsHandler", function () { await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, agentOffer.exchangeToken, sellerPayoff, buyer.address); + .withArgs(exchangeId, seller.id, agentOffer.exchangeToken, sellerPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, agentOffer.exchangeToken, protocolPayoff, buyer.address); + .withArgs(exchangeId, agentOffer.exchangeToken, protocolPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, agentId, agentOffer.exchangeToken, agentPayoff, buyer.address); + .withArgs(exchangeId, agentId, agentOffer.exchangeToken, agentPayoff, await buyer.getAddress()); }); it("Protocol fee for new exchanges should be the same as at the agent offer creation", async function () { // similar as tests before, excpet the commit to offer is done after the protocol fee change // top up seller's and buyer's account - await mockToken.mint(assistant.address, sellerDeposit); - await mockToken.mint(buyer.address, price); + await mockToken.mint(await assistant.getAddress(), sellerDeposit); + await mockToken.mint(await buyer.getAddress(), price); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, sellerDeposit); await mockToken.connect(buyer).approve(protocolDiamondAddress, price); // deposit to seller's pool - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, sellerDeposit); + await fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), sellerDeposit); // commit to offer and get the correct exchangeId - tx = await exchangeHandler.connect(buyer).commitToOffer(buyer.address, agentOffer.id); + tx = await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), agentOffer.id); txReceipt = await tx.wait(); event = getEvent(txReceipt, exchangeHandler, "BuyerCommitted"); exchangeId = event.exchangeId.toString(); @@ -4306,15 +4391,15 @@ describe("IBosonFundsHandler", function () { // Complete the exchange, expecting event await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, seller.id, agentOffer.exchangeToken, sellerPayoff, buyer.address); + .withArgs(exchangeId, seller.id, agentOffer.exchangeToken, sellerPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "ProtocolFeeCollected") - .withArgs(exchangeId, agentOffer.exchangeToken, protocolPayoff, buyer.address); + .withArgs(exchangeId, agentOffer.exchangeToken, protocolPayoff, await buyer.getAddress()); await expect(tx) .to.emit(exchangeHandler, "FundsReleased") - .withArgs(exchangeId, agentId, agentOffer.exchangeToken, agentPayoff, buyer.address); + .withArgs(exchangeId, agentId, agentOffer.exchangeToken, agentPayoff, await buyer.getAddress()); }); }); }); diff --git a/test/protocol/GroupHandlerTest.js b/test/protocol/GroupHandlerTest.js index 466c6f017..2044504b7 100644 --- a/test/protocol/GroupHandlerTest.js +++ b/test/protocol/GroupHandlerTest.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, getSigners, parseUnits, getContractFactory } = ethers; const { assert, expect } = require("chai"); const Group = require("../../scripts/domain/Group"); @@ -68,9 +69,9 @@ describe("IBosonGroupHandler", function () { // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; - accounts = await ethers.getSigners(); + accounts = await getSigners(); // Get snapshot id snapshotId = await getSnapshot(); @@ -103,7 +104,12 @@ describe("IBosonGroupHandler", function () { agentId = "0"; // agent id is optional while creating an offer // Create a valid seller, then set fields in tests directly - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -118,16 +124,16 @@ describe("IBosonGroupHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed - disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")]; + disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", "0")]; // Make empty seller list, so every seller is allowed const sellerAllowList = []; @@ -147,12 +153,12 @@ describe("IBosonGroupHandler", function () { // Set unique offer properties based on index offer.id = `${i + 1}`; - offer.price = ethers.utils.parseUnits(`${1.5 + i * 1}`, "ether").toString(); - offer.sellerDeposit = ethers.utils.parseUnits(`${0.25 + i * 0.1}`, "ether").toString(); - offer.buyerCancelPenalty = ethers.utils.parseUnits(`${0.05 + i * 0.1}`, "ether").toString(); + offer.price = parseUnits(`${1.5 + i * 1}`, "ether").toString(); + offer.sellerDeposit = parseUnits(`${0.25 + i * 0.1}`, "ether").toString(); + offer.buyerCancelPenalty = parseUnits(`${0.05 + i * 0.1}`, "ether").toString(); offer.quantityAvailable = `${(i + 1) * 2}`; - offerDates.validFrom = ethers.BigNumber.from(Date.now() + oneMonth * i).toString(); - offerDates.validUntil = ethers.BigNumber.from(Date.now() + oneMonth * 6 * (i + 1)).toString(); + offerDates.validFrom = (BigInt(Date.now()) + oneMonth * BigInt(i)).toString(); + offerDates.validUntil = (BigInt(Date.now()) + oneMonth * 6n * BigInt(i + 1)).toString(); // Check if domains are valid expect(offer.isValid()).is.true; @@ -183,7 +189,7 @@ describe("IBosonGroupHandler", function () { groupStruct = group.toStruct(); // initialize groupHandler - groupHandlerFacet_Factory = await ethers.getContractFactory("GroupHandlerFacet"); + groupHandlerFacet_Factory = await getContractFactory("GroupHandlerFacet"); }); afterEach(async function () { @@ -205,7 +211,7 @@ describe("IBosonGroupHandler", function () { assert.equal(event.groupId.toString(), group.id, "Group Id is incorrect"); assert.equal(event.sellerId.toString(), group.sellerId, "Seller Id is incorrect"); - assert.equal(event.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal(event.executedBy.toString(), await assistant.getAddress(), "Executed by is incorrect"); assert.equal(groupInstance.toString(), group.toString(), "Group struct is incorrect"); }); @@ -240,7 +246,7 @@ describe("IBosonGroupHandler", function () { assert.equal(event.groupId.toString(), groupId, "Group Id is incorrect"); assert.equal(event.sellerId.toString(), group.sellerId, "Seller Id is incorrect"); - assert.equal(event.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal(event.executedBy.toString(), await assistant.getAddress(), "Executed by is incorrect"); assert.equal(groupInstance.toStruct().toString(), groupStruct.toString(), "Group struct is incorrect"); // wrong group id should not exist @@ -280,7 +286,7 @@ describe("IBosonGroupHandler", function () { assert.equal(event.groupId.toString(), groupId, "Group Id is incorrect"); assert.equal(event.sellerId.toString(), seller.id, "Seller Id is incorrect"); - assert.equal(event.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal(event.executedBy.toString(), await assistant.getAddress(), "Executed by is incorrect"); assert.equal(groupInstance.toStruct().toString(), groupStruct.toString(), "Group struct is incorrect"); }); @@ -304,7 +310,12 @@ describe("IBosonGroupHandler", function () { it("Caller is not the seller of all offers", async function () { // create another seller and an offer - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); await offerHandler.connect(rando).createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // creates an offer with id 6 @@ -375,7 +386,7 @@ describe("IBosonGroupHandler", function () { }); it("Token address is not zero", async function () { - condition.tokenAddress = rando.address; + condition.tokenAddress = await rando.getAddress(); // Attempt to create the group, expecting revert await expect(groupHandler.connect(assistant).createGroup(group, condition)).to.revertedWith( @@ -415,14 +426,14 @@ describe("IBosonGroupHandler", function () { beforeEach(async function () { condition = mockCondition({ method: EvaluationMethod.Threshold, - tokenAddress: rando.address, + tokenAddress: await rando.getAddress(), maxCommits: "10", threshold: "200", }); }); it("Condition 'Threshold' has zero token contract address", async function () { - condition.tokenAddress = ethers.constants.AddressZero; + condition.tokenAddress = ZeroAddress; // Attempt to create the group, expecting revert await expect(groupHandler.connect(assistant).createGroup(group, condition)).to.revertedWith( @@ -453,14 +464,14 @@ describe("IBosonGroupHandler", function () { beforeEach(async function () { condition = mockCondition({ method: EvaluationMethod.SpecificToken, - tokenAddress: rando.address, + tokenAddress: await rando.getAddress(), threshold: "0", maxCommits: "5", }); }); it("Condition 'SpecificToken' has zero token contract address", async function () { - condition.tokenAddress = ethers.constants.AddressZero; + condition.tokenAddress = ZeroAddress; // Attempt to create the group, expecting revert await expect(groupHandler.connect(assistant).createGroup(group, condition)).to.revertedWith( @@ -514,7 +525,7 @@ describe("IBosonGroupHandler", function () { assert.equal(event.groupId.toString(), group.id, "Group Id is incorrect"); assert.equal(event.sellerId.toString(), group.sellerId, "Seller Id is incorrect"); - assert.equal(event.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal(event.executedBy.toString(), await assistant.getAddress(), "Executed by is incorrect"); assert.equal(groupInstance.toString(), group.toString(), "Group struct is incorrect"); }); @@ -572,7 +583,12 @@ describe("IBosonGroupHandler", function () { it("Caller is not the seller of all offers", async function () { // create another seller and an offer - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); await offerHandler.connect(rando).createOffer(offer, offerDates, offerDurations, disputeResolverId, agentId); // creates an offer with id 6 @@ -682,7 +698,7 @@ describe("IBosonGroupHandler", function () { expect(groupInstance.isValid()).to.be.true; assert.equal(event.groupId.toString(), group.id, "Group Id is incorrect"); - assert.equal(event.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal(event.executedBy.toString(), await assistant.getAddress(), "Executed by is incorrect"); assert.equal(groupInstance.toString(), group.toString(), "Group struct is incorrect"); }); @@ -856,7 +872,7 @@ describe("IBosonGroupHandler", function () { assert.equal(event.groupId.toString(), group.id, "Group Id is incorrect"); assert.equal(event.sellerId.toString(), group.sellerId, "Seller Id is incorrect"); - assert.equal(event.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal(event.executedBy.toString(), await assistant.getAddress(), "Executed by is incorrect"); assert.equal(groupInstance.toString(), group.toString(), "Group struct is incorrect"); }); @@ -918,7 +934,7 @@ describe("IBosonGroupHandler", function () { it("Condition 'Threshold' has zero token contract address", async function () { condition.method = EvaluationMethod.Threshold; - condition.tokenAddress = ethers.constants.AddressZero; + condition.tokenAddress = ZeroAddress; // Attempt to update the group, expecting revert await expect(groupHandler.connect(assistant).setGroupCondition(group.id, condition)).to.revertedWith( @@ -938,7 +954,7 @@ describe("IBosonGroupHandler", function () { it("Condition 'SpecificToken' has zero token contract address", async function () { condition.method = EvaluationMethod.SpecificToken; - condition.tokenAddress = ethers.constants.AddressZero; + condition.tokenAddress = ZeroAddress; // Attempt to update the group, expecting revert await expect(groupHandler.connect(assistant).setGroupCondition(group.id, condition)).to.revertedWith( diff --git a/test/protocol/MetaTransactionsHandlerTest.js b/test/protocol/MetaTransactionsHandlerTest.js index 9287b79e2..0289ef260 100644 --- a/test/protocol/MetaTransactionsHandlerTest.js +++ b/test/protocol/MetaTransactionsHandlerTest.js @@ -1,6 +1,15 @@ const { ethers } = require("hardhat"); const { - utils: { keccak256, toUtf8Bytes }, + keccak256, + toUtf8Bytes, + ZeroAddress, + getContractAt, + getContractFactory, + getSigners, + randomBytes, + zeroPadBytes, + ZeroHash, + MaxUint256, } = ethers; const { expect, assert } = require("chai"); @@ -14,6 +23,7 @@ const { DisputeResolverFee } = require("../../scripts/domain/DisputeResolverFee" const { getInterfaceIds } = require("../../scripts/config/supported-interfaces.js"); const { RevertReasons } = require("../../scripts/config/revert-reasons.js"); const { deployMockTokens } = require("../../scripts/util/deploy-mock-tokens"); +const { toHexString } = require("../../scripts/util/utils.js"); const { prepareDataSignatureParameters, setNextBlockTimestamp, @@ -152,9 +162,9 @@ describe("IBosonMetaTransactionsHandler", function () { // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; - [deployer] = await ethers.getSigners(); + [deployer] = await getSigners(); // Deploy the mock tokens [bosonToken, mockToken] = await deployMockTokens(["BosonToken", "Foreign20"]); @@ -174,24 +184,24 @@ describe("IBosonMetaTransactionsHandler", function () { async function upgradeMetaTransactionsHandlerFacet() { // Upgrade the ExchangeHandlerFacet functions // DiamondCutFacet - const cutFacetViaDiamond = await ethers.getContractAt("DiamondCutFacet", protocolDiamondAddress); + const cutFacetViaDiamond = await getContractAt("DiamondCutFacet", protocolDiamondAddress); // Deploy MockMetaTransactionsHandlerFacet - const MockMetaTransactionsHandlerFacet = await ethers.getContractFactory("MockMetaTransactionsHandlerFacet"); + const MockMetaTransactionsHandlerFacet = await getContractFactory("MockMetaTransactionsHandlerFacet"); const mockMetaTransactionsHandlerFacet = await MockMetaTransactionsHandlerFacet.deploy(); - await mockMetaTransactionsHandlerFacet.deployed(); + await mockMetaTransactionsHandlerFacet.waitForDeployment(); // Define the facet cut const facetCuts = [ { - facetAddress: mockMetaTransactionsHandlerFacet.address, + facetAddress: await mockMetaTransactionsHandlerFacet.getAddress(), action: FacetCutAction.Add, functionSelectors: getSelectors(mockMetaTransactionsHandlerFacet), }, ]; // Send the DiamondCut transaction - const tx = await cutFacetViaDiamond.connect(deployer).diamondCut(facetCuts, ethers.constants.AddressZero, "0x"); + const tx = await cutFacetViaDiamond.connect(deployer).diamondCut(facetCuts, ZeroAddress, "0x"); // Wait for transaction to confirm const receipt = await tx.wait(); @@ -200,10 +210,7 @@ describe("IBosonMetaTransactionsHandler", function () { assert.equal(receipt.status, 1, `Diamond upgrade failed: ${tx.hash}`); // Cast Diamond to MockMetaTransactionsHandlerFacet - mockMetaTransactionsHandler = await ethers.getContractAt( - "MockMetaTransactionsHandlerFacet", - protocolDiamondAddress - ); + mockMetaTransactionsHandler = await getContractAt("MockMetaTransactionsHandlerFacet", protocolDiamondAddress); } // Interface support (ERC-156 provided by ProtocolDiamond, others by deployed facets) @@ -222,7 +229,7 @@ describe("IBosonMetaTransactionsHandler", function () { // All supported methods context("📋 Meta Transactions Handler Methods", async function () { beforeEach(async function () { - nonce = parseInt(ethers.utils.randomBytes(8)); + nonce = parseInt(randomBytes(8)); }); context("👉 isUsedNonce()", async function () { @@ -233,20 +240,25 @@ describe("IBosonMetaTransactionsHandler", function () { it("should return false if nonce is not used", async function () { // Check if nonce is used before - result = await metaTransactionsHandler.connect(assistant).isUsedNonce(rando.address, nonce); + result = await metaTransactionsHandler.connect(assistant).isUsedNonce(await rando.getAddress(), nonce); // Verify the expectation assert.equal(result, expectedResult, "Nonce is used"); }); it("should be true after executing a meta transaction with nonce", async function () { - result = await metaTransactionsHandler.connect(assistant).isUsedNonce(assistant.address, nonce); + result = await metaTransactionsHandler.connect(assistant).isUsedNonce(await assistant.getAddress(), nonce); // Verify the expectation assert.equal(result, expectedResult, "Nonce is used"); // Create a valid seller for meta transaction - seller = mockSeller(assistant.address, assistant.address, ethers.constants.AddressZero, assistant.address); + seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + ZeroAddress, + await assistant.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -280,8 +292,8 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message let message = {}; message.nonce = parseInt(nonce); - message.from = assistant.address; - message.contractAddress = accountHandler.address; + message.from = await assistant.getAddress(); + message.contractAddress = await accountHandler.getAddress(); message.functionName = "createSeller((uint256,address,address,address,address,bool,string),(uint256,uint8),(string,uint256))"; message.functionSignature = functionSignature; @@ -292,12 +304,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Send as meta transaction await metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -308,13 +320,13 @@ describe("IBosonMetaTransactionsHandler", function () { // We expect that the nonce is used now. Hence expecting to return true. expectedResult = true; - result = await metaTransactionsHandler.connect(assistant).isUsedNonce(assistant.address, nonce); + result = await metaTransactionsHandler.connect(assistant).isUsedNonce(await assistant.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is not used"); //Verify that another nonce value is unused. expectedResult = false; nonce = nonce + 1; - result = await metaTransactionsHandler.connect(rando).isUsedNonce(assistant.address, nonce); + result = await metaTransactionsHandler.connect(rando).isUsedNonce(await assistant.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is used"); }); }); @@ -333,19 +345,19 @@ describe("IBosonMetaTransactionsHandler", function () { functionHashList = functionList.map((func) => keccak256(toUtf8Bytes(func))); // Grant UPGRADER role to admin account - await accessController.grantRole(Role.ADMIN, admin.address); + await accessController.grantRole(Role.ADMIN, await admin.getAddress()); }); it("should emit a FunctionsAllowlisted event", async function () { // Enable functions await expect(metaTransactionsHandler.connect(admin).setAllowlistedFunctions(functionHashList, true)) .to.emit(metaTransactionsHandler, "FunctionsAllowlisted") - .withArgs(functionHashList, true, admin.address); + .withArgs(functionHashList, true, await admin.getAddress()); // Disable functions await expect(metaTransactionsHandler.connect(admin).setAllowlistedFunctions(functionHashList, false)) .to.emit(metaTransactionsHandler, "FunctionsAllowlisted") - .withArgs(functionHashList, false, admin.address); + .withArgs(functionHashList, false, await admin.getAddress()); }); it("should update state", async function () { @@ -395,13 +407,11 @@ describe("IBosonMetaTransactionsHandler", function () { functionHashList = functionList.map((func) => keccak256(toUtf8Bytes(func))); // Grant UPGRADER role to admin account - await accessController.grantRole(Role.ADMIN, admin.address); + await accessController.grantRole(Role.ADMIN, await admin.getAddress()); }); it("after initialization all state modifying functions should be allowlisted", async function () { - const stateModifyingFunctionsClosure = getStateModifyingFunctionsHashes(facetNames, [ - "executeMetaTransaction(address,string,bytes,uint256,bytes32,bytes32,uint8)", - ]); + const stateModifyingFunctionsClosure = getStateModifyingFunctionsHashes(facetNames, ["executeMetaTransaction"]); const stateModifyingFunctionsHashes = await stateModifyingFunctionsClosure(); // Functions should be enabled @@ -448,14 +458,14 @@ describe("IBosonMetaTransactionsHandler", function () { functionHashList = functionList.map((func) => keccak256(toUtf8Bytes(func))); // Grant UPGRADER role to admin account - await accessController.grantRole(Role.ADMIN, admin.address); + await accessController.grantRole(Role.ADMIN, await admin.getAddress()); }); it("after initialization all state modifying functions should be allowlisted", async function () { // Get list of state modifying functions const stateModifyingFunctions = await getStateModifyingFunctions(facetNames, [ - "executeMetaTransaction(address,string,bytes,uint256,bytes32,bytes32,uint8)", - "initialize()", + "executeMetaTransaction", + "initialize", ]); for (const func of stateModifyingFunctions) { @@ -511,7 +521,12 @@ describe("IBosonMetaTransactionsHandler", function () { context("👉 AccountHandlerFacet 👉 createSeller()", async function () { beforeEach(async function () { // Create a valid seller for meta transaction - seller = mockSeller(assistant.address, assistant.address, ethers.constants.AddressZero, assistant.address); + seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + ZeroAddress, + await assistant.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -525,8 +540,8 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message message = {}; message.nonce = parseInt(nonce); - message.from = assistant.address; - message.contractAddress = accountHandler.address; + message.from = await assistant.getAddress(); + message.contractAddress = await accountHandler.getAddress(); message.functionName = "createSeller((uint256,address,address,address,address,bool,string),(uint256,uint8),(string,uint256))"; }); @@ -547,21 +562,29 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // send a meta transaction, check for event await expect( metaTransactionsHandler .connect(deployer) - .executeMetaTransaction(assistant.address, message.functionName, functionSignature, nonce, r, s, v) + .executeMetaTransaction( + await assistant.getAddress(), + message.functionName, + functionSignature, + nonce, + r, + s, + v + ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(assistant.address, deployer.address, message.functionName, nonce); + .withArgs(await assistant.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(assistant).isUsedNonce(assistant.address, nonce); + result = await metaTransactionsHandler.connect(assistant).isUsedNonce(await assistant.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -586,21 +609,29 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // send a meta transaction, does not revert await expect( metaTransactionsHandler .connect(deployer) - .executeMetaTransaction(assistant.address, message.functionName, functionSignature, nonce, r, s, v) + .executeMetaTransaction( + await assistant.getAddress(), + message.functionName, + functionSignature, + nonce, + r, + s, + v + ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(assistant.address, deployer.address, message.functionName, nonce); + .withArgs(await assistant.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(assistant).isUsedNonce(assistant.address, nonce); + result = await metaTransactionsHandler.connect(assistant).isUsedNonce(await assistant.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -623,13 +654,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // send a meta transaction, expecting revert await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -658,30 +689,38 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() )); // send a meta transaction, check for event await expect( metaTransactionsHandler .connect(deployer) - .executeMetaTransaction(assistant.address, message.functionName, functionSignature, nonce, r, s, v) + .executeMetaTransaction( + await assistant.getAddress(), + message.functionName, + functionSignature, + nonce, + r, + s, + v + ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(assistant.address, deployer.address, message.functionName, nonce); + .withArgs(await assistant.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(assistant).isUsedNonce(assistant.address, nonce); + result = await metaTransactionsHandler.connect(assistant).isUsedNonce(await assistant.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); // send a meta transaction again, check for event - seller.assistant = assistantDR.address; - seller.admin = adminDR.address; + seller.assistant = await assistantDR.getAddress(); + seller.admin = await adminDR.getAddress(); seller.clerk = clerkDR.address; - seller.treasury = treasuryDR.address; + seller.treasury = await treasuryDR.getAddress(); - message.from = adminDR.address; + message.from = await adminDR.getAddress(); // Prepare the function signature for the facet function. functionSignature = accountHandler.interface.encodeFunctionData("createSeller", [ @@ -698,20 +737,30 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() )); await expect( metaTransactionsHandler .connect(rando) - .executeMetaTransaction(adminDR.address, message.functionName, functionSignature, nonce, r, s, v) + .executeMetaTransaction( + await adminDR.getAddress(), + message.functionName, + functionSignature, + nonce, + r, + s, + v + ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(adminDR.address, rando.address, message.functionName, nonce); + .withArgs(await adminDR.getAddress(), await rando.getAddress(), message.functionName, nonce); // Verify that nonce is used. Expect true. expectedResult = true; - result = await metaTransactionsHandler.connect(assistantDR).isUsedNonce(assistantDR.address, nonce); + result = await metaTransactionsHandler + .connect(assistantDR) + .isUsedNonce(await assistantDR.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -734,7 +783,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Pause the metatx region of the protocol @@ -744,7 +793,15 @@ describe("IBosonMetaTransactionsHandler", function () { await expect( metaTransactionsHandler .connect(deployer) - .executeMetaTransaction(assistant.address, message.functionName, functionSignature, nonce, r, s, v) + .executeMetaTransaction( + await assistant.getAddress(), + message.functionName, + functionSignature, + nonce, + r, + s, + v + ) ).to.revertedWith(RevertReasons.REGION_PAUSED); }); @@ -771,13 +828,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -808,13 +865,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -845,13 +902,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -866,11 +923,11 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare a function, which selector collide with another funtion selector // In this case certain bytes are appended to redeemVoucher so it gets the same selector as cancelVoucher const fn = `redeemVoucher(uint256)`; - const fnBytes = ethers.utils.toUtf8Bytes(fn); + const fnBytes = toUtf8Bytes(fn); const collisionBytes = "0a7f0f031e"; const collisionBytesBuffer = Buffer.from(collisionBytes, "hex"); const fnCollision = Buffer.concat([fnBytes, collisionBytesBuffer]); - const sigCollision = ethers.utils.keccak256(fnCollision).slice(0, 10); + const sigCollision = keccak256(fnCollision).slice(0, 10); // Prepare the function signature for the facet function. functionSignature = exchangeHandler.interface.encodeFunctionData("cancelVoucher", [1]); @@ -888,13 +945,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -921,12 +978,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -938,7 +995,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -958,7 +1015,7 @@ describe("IBosonMetaTransactionsHandler", function () { ]); // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); message.functionSignature = functionSignature; // Collect the signature components @@ -967,13 +1024,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -1001,13 +1058,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -1020,12 +1077,12 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, r, - ethers.constants.MaxUint256, // invalid s signature component + toHexString(MaxUint256), // invalid s signature component v ) ).to.revertedWith(RevertReasons.INVALID_SIGNATURE); @@ -1033,12 +1090,12 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, r, - ethers.utils.hexZeroPad("0x", 32), // invalid s signature component + zeroPadBytes("0x", 32), // invalid s signature component v ) ).to.revertedWith(RevertReasons.INVALID_SIGNATURE); @@ -1046,11 +1103,11 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, - ethers.utils.hexZeroPad("0x", 32), // invalid r signature component + zeroPadBytes("0x", 32), // invalid r signature component s, v ) @@ -1062,7 +1119,12 @@ describe("IBosonMetaTransactionsHandler", function () { context("👉TwinHandler 👉 removeTwin()", async function () { beforeEach(async function () { // Create a valid seller for meta transaction - seller = mockSeller(assistant.address, assistant.address, ethers.constants.AddressZero, assistant.address); + seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + ZeroAddress, + await assistant.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -1076,13 +1138,13 @@ describe("IBosonMetaTransactionsHandler", function () { await accountHandler.connect(assistant).createSeller(seller, emptyAuthToken, voucherInitValues); // Create a valid twin, then set fields in tests directly - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); twin.id = "1"; twin.sellerId = "1"; expect(twin.isValid()).is.true; // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // Create a twin await twinHandler.connect(assistant).createTwin(twin); @@ -1090,8 +1152,8 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message message = {}; message.nonce = parseInt(nonce); - message.from = assistant.address; - message.contractAddress = twinHandler.address; + message.from = await assistant.getAddress(); + message.contractAddress = await twinHandler.getAddress(); }); it("removeTwin() can remove a twin", async function () { @@ -1112,12 +1174,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Remove the twin. Send as meta transaction. await metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -1137,24 +1199,24 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message message = {}; message.nonce = parseInt(nonce); - message.from = assistant.address; - message.contractAddress = metaTransactionsHandler.address; + message.from = await assistant.getAddress(); + message.contractAddress = await metaTransactionsHandler.getAddress(); }); it("Should fail when try to call executeMetaTransaction method itself", async function () { // Function signature for executeMetaTransaction function. functionSignature = metaTransactionsHandler.interface.encodeFunctionData("executeMetaTransaction", [ - assistant.address, + await assistant.getAddress(), "executeMetaTransaction", - ethers.constants.HashZero, // hash of zero + ZeroHash, // hash of zero nonce, - ethers.utils.randomBytes(32), // random bytes32 - ethers.utils.randomBytes(32), // random bytes32 - parseInt(ethers.utils.randomBytes(8)), // random uint8 + randomBytes(32), // random bytes32 + randomBytes(32), // random bytes32 + parseInt(randomBytes(8)), // random uint8 ]); // Prepare the message - message.contractAddress = metaTransactionsHandler.address; + message.contractAddress = await metaTransactionsHandler.getAddress(); message.functionName = "executeMetaTransaction(address,string,bytes,uint256,bytes32,bytes32,uint8)"; message.functionSignature = functionSignature; @@ -1164,13 +1226,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // send a meta transaction, expecting revert await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -1183,7 +1245,12 @@ describe("IBosonMetaTransactionsHandler", function () { it("Returns default revert reason if called function reverts without a reason", async function () { // Create a valid seller for meta transaction - seller = mockSeller(assistant.address, assistant.address, ethers.constants.AddressZero, assistant.address); + seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + ZeroAddress, + await assistant.getAddress() + ); voucherInitValues = mockVoucherInitValues(); emptyAuthToken = mockAuthToken(); await accountHandler.connect(assistant).createSeller(seller, emptyAuthToken, voucherInitValues); @@ -1191,7 +1258,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Depositing funds, where token address is not a contract address reverts without a reason. functionSignature = fundsHandler.interface.encodeFunctionData("depositFunds", [ seller.id, - rando.address, + await rando.getAddress(), "10", ]); @@ -1205,13 +1272,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // send a meta transaction, expecting revert await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -1225,7 +1292,12 @@ describe("IBosonMetaTransactionsHandler", function () { context("Reentrancy guard", async function () { beforeEach(async function () { // Create a valid seller for meta transaction - seller = mockSeller(assistant.address, assistant.address, ethers.constants.AddressZero, assistant.address); + seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + ZeroAddress, + await assistant.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -1250,10 +1322,10 @@ describe("IBosonMetaTransactionsHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; @@ -1261,7 +1333,7 @@ describe("IBosonMetaTransactionsHandler", function () { buyerId = accountId.next().value; //Create DisputeResolverFee array so offer creation will succeed - disputeResolverFees = [new DisputeResolverFee(maliciousToken.address, "maliciousToken", "0")]; + disputeResolverFees = [new DisputeResolverFee(await maliciousToken.getAddress(), "maliciousToken", "0")]; // Make empty seller list, so every seller is allowed sellerAllowList = []; @@ -1274,7 +1346,7 @@ describe("IBosonMetaTransactionsHandler", function () { const { offer, ...mo } = await mockOffer(); ({ offerDates, offerDurations } = mo); offerToken = offer; - offerToken.exchangeToken = maliciousToken.address; + offerToken.exchangeToken = await maliciousToken.getAddress(); price = offer.price; sellerDeposit = offer.sellerDeposit; @@ -1290,28 +1362,30 @@ describe("IBosonMetaTransactionsHandler", function () { .createOffer(offerToken, offerDates, offerDurations, disputeResolver.id, agentId); // top up seller's and buyer's account - await maliciousToken.mint(assistant.address, sellerDeposit); - await maliciousToken.mint(buyer.address, price); + await maliciousToken.mint(await assistant.getAddress(), sellerDeposit); + await maliciousToken.mint(await buyer.getAddress(), price); // Approve protocol to transfer the tokens await maliciousToken.connect(assistant).approve(protocolDiamondAddress, sellerDeposit); await maliciousToken.connect(buyer).approve(protocolDiamondAddress, price); // Deposit to seller's pool - await fundsHandler.connect(assistant).depositFunds(seller.id, maliciousToken.address, sellerDeposit); + await fundsHandler + .connect(assistant) + .depositFunds(seller.id, await maliciousToken.getAddress(), sellerDeposit); // Commit to the offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); // Cancel the voucher, so both seller and buyer have something to withdraw await exchangeHandler.connect(buyer).cancelVoucher(exchangeId); // canceling the voucher in tokens // Expected payoffs - they are the same for token and native currency // Buyer: price - buyerCancelPenalty - buyerPayoff = ethers.BigNumber.from(offerToken.price).sub(offerToken.buyerCancelPenalty).toString(); + buyerPayoff = (BigInt(offerToken.price) - BigInt(offerToken.buyerCancelPenalty)).toString(); // Prepare validFundDetails - tokenListBuyer = [maliciousToken.address]; + tokenListBuyer = [await maliciousToken.getAddress()]; tokenAmountsBuyer = [buyerPayoff]; validFundDetails = { entityId: buyerId, @@ -1322,10 +1396,10 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message message = {}; message.nonce = parseInt(nonce); - message.contractAddress = fundsHandler.address; + message.contractAddress = await fundsHandler.getAddress(); message.functionName = "withdrawFunds(uint256,address[],uint256[])"; message.fundDetails = validFundDetails; - message.from = buyer.address; + message.from = await buyer.getAddress(); // Set the fund Type fundType = [ @@ -1361,7 +1435,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxFund", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); let [, buyerStruct] = await accountHandler.getBuyer(buyerId); @@ -1370,7 +1444,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute the meta transaction. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1391,7 +1465,7 @@ describe("IBosonMetaTransactionsHandler", function () { await maliciousToken.setProtocolAddress(protocolDiamondAddress); // Mint and approve protocol to transfer the tokens - await maliciousToken.mint(rando.address, "1"); + await maliciousToken.mint(await rando.getAddress(), "1"); await maliciousToken.connect(rando).approve(protocolDiamondAddress, "1"); // Just make a random metaTx signature to some view function that will delete "currentSender" @@ -1400,8 +1474,8 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message message.nonce = "0"; - message.from = rando.address; - message.contractAddress = accountHandler.address; + message.from = await rando.getAddress(); + message.contractAddress = await accountHandler.getAddress(); message.functionName = "getNextExchangeId()"; message.functionSignature = functionSignature; @@ -1411,22 +1485,22 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); - await maliciousToken.setMetaTxBytes(rando.address, functionSignature, r, s, v); + await maliciousToken.setMetaTxBytes(await rando.getAddress(), functionSignature, r, s, v); // Prepare the function signature for the facet function. functionSignature = fundsHandler.interface.encodeFunctionData("depositFunds", [ seller.id, - maliciousToken.address, + await maliciousToken.getAddress(), "1", ]); // Prepare the message message.nonce = nonce; - message.from = rando.address; - message.contractAddress = accountHandler.address; + message.from = await rando.getAddress(); + message.contractAddress = await accountHandler.getAddress(); message.functionName = "depositFunds(uint256,address,uint256)"; message.functionSignature = functionSignature; @@ -1436,14 +1510,22 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() )); // send a meta transaction, expect revert await expect( metaTransactionsHandler .connect(deployer) - .executeMetaTransaction(rando.address, message.functionName, functionSignature, nonce, r, s, v) + .executeMetaTransaction( + await rando.getAddress(), + message.functionName, + functionSignature, + nonce, + r, + s, + v + ) ).to.revertedWith(RevertReasons.REENTRANCY_GUARD); }); }); @@ -1454,7 +1536,12 @@ describe("IBosonMetaTransactionsHandler", function () { offerId = "1"; // Create a valid seller - seller = mockSeller(assistant.address, assistant.address, ethers.constants.AddressZero, assistant.address); + seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + ZeroAddress, + await assistant.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -1468,18 +1555,18 @@ describe("IBosonMetaTransactionsHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0"), - new DisputeResolverFee(mockToken.address, "BosonToken", "0"), + new DisputeResolverFee(ZeroAddress, "Native", "0"), + new DisputeResolverFee(await mockToken.getAddress(), "BosonToken", "0"), ]; // Make empty seller list, so every seller is allowed @@ -1513,14 +1600,14 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message message = {}; message.nonce = parseInt(nonce); - message.contractAddress = exchangeHandler.address; - message.from = buyer.address; + message.contractAddress = await exchangeHandler.getAddress(); + message.from = await buyer.getAddress(); message.functionName = "commitToOffer(address,uint256)"; // Deposit native currency to the same seller id await fundsHandler .connect(rando) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerDeposit, { value: sellerDeposit }); + .depositFunds(seller.id, ZeroAddress, sellerDeposit, { value: sellerDeposit }); }); afterEach(async function () { @@ -1530,7 +1617,7 @@ describe("IBosonMetaTransactionsHandler", function () { context("👉 ExchangeHandlerFacet 👉 commitToOffer()", async function () { beforeEach(async function () { - offer.exchangeToken = mockToken.address; + offer.exchangeToken = await mockToken.getAddress(); // Check if domains are valid expect(offer.isValid()).is.true; @@ -1538,15 +1625,15 @@ describe("IBosonMetaTransactionsHandler", function () { expect(offerDurations.isValid()).is.true; // top up seller's and buyer's account - await mockToken.mint(assistant.address, sellerDeposit); - await mockToken.mint(buyer.address, price); + await mockToken.mint(await assistant.getAddress(), sellerDeposit); + await mockToken.mint(await buyer.getAddress(), price); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, sellerDeposit); await mockToken.connect(buyer).approve(protocolDiamondAddress, price); // deposit to seller's pool - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, sellerDeposit); + await fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), sellerDeposit); // Create the offer await offerHandler @@ -1576,7 +1663,7 @@ describe("IBosonMetaTransactionsHandler", function () { // prepare validOfferDetails validOfferDetails = { - buyer: buyer.address, + buyer: await buyer.getAddress(), offerId: offer.id, }; @@ -1586,7 +1673,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Deposit native currency to the same seller id await fundsHandler .connect(rando) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerDeposit, { value: sellerDeposit }); + .depositFunds(seller.id, ZeroAddress, sellerDeposit, { value: sellerDeposit }); }); it("Should emit MetaTransactionExecuted event and update state", async () => { @@ -1596,7 +1683,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxCommitToOffer", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -1606,13 +1693,13 @@ describe("IBosonMetaTransactionsHandler", function () { ); // Expect that buyer has token balance matching the offer price. - const buyerBalanceBefore = await mockToken.balanceOf(buyer.address); + const buyerBalanceBefore = await mockToken.balanceOf(await buyer.getAddress()); assert.equal(buyerBalanceBefore, price, "Buyer initial token balance mismatch"); // send a meta transaction, check for event await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1622,15 +1709,15 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(buyer.address, deployer.address, message.functionName, nonce); + .withArgs(await buyer.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Expect that buyer (meta tx signer) has paid the tokens to commit to an offer. - const buyerBalanceAfter = await mockToken.balanceOf(buyer.address); + const buyerBalanceAfter = await mockToken.balanceOf(await buyer.getAddress()); assert.equal(buyerBalanceAfter, "0", "Buyer final token balance mismatch"); // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(buyer).isUsedNonce(buyer.address, nonce); + result = await metaTransactionsHandler.connect(buyer).isUsedNonce(await buyer.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -1650,7 +1737,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxCommitToOffer", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -1662,7 +1749,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1689,12 +1776,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxCommitToOffer", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1706,7 +1793,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1719,7 +1806,7 @@ describe("IBosonMetaTransactionsHandler", function () { it("Should fail when Signer and Signature do not match", async function () { // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); // Collect the signature components let { r, s, v } = await prepareDataSignatureParameters( @@ -1727,13 +1814,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxCommitToOffer", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1773,7 +1860,7 @@ describe("IBosonMetaTransactionsHandler", function () { message.exchangeDetails = validExchangeDetails; // Commit to offer - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: price }); }); context("👉 ExchangeHandlerFacet 👉 cancelVoucher()", async function () { @@ -1789,7 +1876,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -1800,7 +1887,7 @@ describe("IBosonMetaTransactionsHandler", function () { // send a meta transaction, check for event await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1810,11 +1897,11 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(buyer.address, deployer.address, message.functionName, nonce); + .withArgs(await buyer.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(buyer).isUsedNonce(buyer.address, nonce); + result = await metaTransactionsHandler.connect(buyer).isUsedNonce(await buyer.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -1833,7 +1920,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -1844,7 +1931,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1870,12 +1957,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1887,7 +1974,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1900,7 +1987,7 @@ describe("IBosonMetaTransactionsHandler", function () { it("Should fail when Signer and Signature do not match", async function () { // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); // Collect the signature components let { r, s, v } = await prepareDataSignatureParameters( @@ -1908,13 +1995,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1943,7 +2030,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -1954,7 +2041,7 @@ describe("IBosonMetaTransactionsHandler", function () { // send a meta transaction, check for event await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -1964,11 +2051,11 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(buyer.address, deployer.address, message.functionName, nonce); + .withArgs(await buyer.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(buyer).isUsedNonce(buyer.address, nonce); + result = await metaTransactionsHandler.connect(buyer).isUsedNonce(await buyer.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -1987,7 +2074,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -1998,7 +2085,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2024,12 +2111,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2041,7 +2128,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2054,7 +2141,7 @@ describe("IBosonMetaTransactionsHandler", function () { it("Should fail when Signer and Signature do not match", async function () { // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); // Collect the signature components let { r, s, v } = await prepareDataSignatureParameters( @@ -2062,13 +2149,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2100,7 +2187,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -2111,7 +2198,7 @@ describe("IBosonMetaTransactionsHandler", function () { // send a meta transaction, check for event await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2121,7 +2208,7 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(buyer.address, deployer.address, message.functionName, nonce); + .withArgs(await buyer.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Get the exchange state let response; @@ -2131,7 +2218,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(buyer).isUsedNonce(buyer.address, nonce); + result = await metaTransactionsHandler.connect(buyer).isUsedNonce(await buyer.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -2150,7 +2237,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -2161,7 +2248,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2187,12 +2274,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2204,7 +2291,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2217,7 +2304,7 @@ describe("IBosonMetaTransactionsHandler", function () { it("Should fail when Signer and Signature do not match", async function () { // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); // Collect the signature components let { r, s, v } = await prepareDataSignatureParameters( @@ -2225,13 +2312,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2265,7 +2352,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -2276,7 +2363,7 @@ describe("IBosonMetaTransactionsHandler", function () { // send a meta transaction, check for event await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2286,7 +2373,7 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(buyer.address, deployer.address, message.functionName, nonce); + .withArgs(await buyer.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Get the dispute state let response; @@ -2296,7 +2383,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(buyer).isUsedNonce(buyer.address, nonce); + result = await metaTransactionsHandler.connect(buyer).isUsedNonce(await buyer.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -2315,7 +2402,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -2326,7 +2413,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2352,12 +2439,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2369,7 +2456,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2382,7 +2469,7 @@ describe("IBosonMetaTransactionsHandler", function () { it("Should fail when Signer and Signature do not match", async function () { // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); // Collect the signature components let { r, s, v } = await prepareDataSignatureParameters( @@ -2390,13 +2477,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2436,7 +2523,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message message.functionName = "raiseDispute(uint256)"; message.exchangeDetails = validExchangeDetails; - message.from = buyer.address; + message.from = await buyer.getAddress(); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(voucherRedeemableFrom)); @@ -2452,7 +2539,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -2463,7 +2550,7 @@ describe("IBosonMetaTransactionsHandler", function () { // send a meta transaction, check for event await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2473,7 +2560,7 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(buyer.address, deployer.address, message.functionName, nonce); + .withArgs(await buyer.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Get the exchange state let response; @@ -2483,7 +2570,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(buyer).isUsedNonce(buyer.address, nonce); + result = await metaTransactionsHandler.connect(buyer).isUsedNonce(await buyer.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -2502,7 +2589,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -2513,7 +2600,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2539,12 +2626,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2556,7 +2643,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2569,7 +2656,7 @@ describe("IBosonMetaTransactionsHandler", function () { it("Should fail when Signer and Signature do not match", async function () { // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); // Collect the signature components let { r, s, v } = await prepareDataSignatureParameters( @@ -2577,13 +2664,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2617,7 +2704,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -2628,7 +2715,7 @@ describe("IBosonMetaTransactionsHandler", function () { // send a meta transaction, check for event await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2638,7 +2725,7 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(buyer.address, deployer.address, message.functionName, nonce); + .withArgs(await buyer.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Get the dispute state let response; @@ -2648,7 +2735,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(buyer).isUsedNonce(buyer.address, nonce); + result = await metaTransactionsHandler.connect(buyer).isUsedNonce(await buyer.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -2667,7 +2754,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -2678,7 +2765,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2704,12 +2791,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2721,7 +2808,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2734,7 +2821,7 @@ describe("IBosonMetaTransactionsHandler", function () { it("Should fail when Signer and Signature do not match", async function () { // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); // Collect the signature components let { r, s, v } = await prepareDataSignatureParameters( @@ -2742,13 +2829,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxExchange", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2794,7 +2881,7 @@ describe("IBosonMetaTransactionsHandler", function () { customSignatureType2, "Resolution", message2, - disputeHandler.address + await disputeHandler.getAddress() ); // prepare validDisputeResolutionDetails @@ -2832,7 +2919,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message message.functionName = "resolveDispute(uint256,uint256,bytes32,bytes32,uint8)"; message.disputeResolutionDetails = validDisputeResolutionDetails; - message.from = buyer.address; + message.from = await buyer.getAddress(); }); it("Should emit MetaTransactionExecuted event and update state", async () => { @@ -2842,7 +2929,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxDisputeResolution", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -2857,7 +2944,7 @@ describe("IBosonMetaTransactionsHandler", function () { // send a meta transaction, check for event await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2867,7 +2954,7 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(buyer.address, deployer.address, message.functionName, nonce); + .withArgs(await buyer.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Get the dispute state let response; @@ -2877,7 +2964,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(buyer).isUsedNonce(buyer.address, nonce); + result = await metaTransactionsHandler.connect(buyer).isUsedNonce(await buyer.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -2903,7 +2990,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxDisputeResolution", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -2918,7 +3005,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2948,12 +3035,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxDisputeResolution", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2965,7 +3052,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -2978,7 +3065,7 @@ describe("IBosonMetaTransactionsHandler", function () { it("Should fail when Signer and Signature do not match", async function () { // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); // Collect the signature components let { r, s, v } = await prepareDataSignatureParameters( @@ -2986,13 +3073,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxDisputeResolution", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -3013,7 +3100,12 @@ describe("IBosonMetaTransactionsHandler", function () { offerId = "1"; // Create a valid seller - seller = mockSeller(assistant.address, assistant.address, ethers.constants.AddressZero, assistant.address); + seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + ZeroAddress, + await assistant.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -3028,16 +3120,16 @@ describe("IBosonMetaTransactionsHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed - disputeResolverFees = [new DisputeResolverFee(mockToken.address, "mockToken", "0")]; + disputeResolverFees = [new DisputeResolverFee(await mockToken.getAddress(), "mockToken", "0")]; // Make empty seller list, so every seller is allowed sellerAllowList = []; @@ -3049,7 +3141,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Valid offer domains ({ offer, offerDates, offerDurations } = await mockOffer()); - offer.exchangeToken = mockToken.address; + offer.exchangeToken = await mockToken.getAddress(); // Check if domains are valid expect(offer.isValid()).is.true; @@ -3062,15 +3154,15 @@ describe("IBosonMetaTransactionsHandler", function () { voucherRedeemableFrom = offerDates.voucherRedeemableFrom; // top up seller's and buyer's account - await mockToken.mint(assistant.address, sellerDeposit); - await mockToken.mint(buyer.address, price); + await mockToken.mint(await assistant.getAddress(), sellerDeposit); + await mockToken.mint(await buyer.getAddress(), price); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, sellerDeposit); await mockToken.connect(buyer).approve(protocolDiamondAddress, price); // deposit to seller's pool - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, sellerDeposit); + await fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), sellerDeposit); // Prepare the function signature for the facet function. functionSignature = offerHandler.interface.encodeFunctionData("createOffer", [ @@ -3097,8 +3189,8 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message message = {}; message.nonce = parseInt(nonce); - message.from = assistant.address; - message.contractAddress = offerHandler.address; + message.from = await assistant.getAddress(); + message.contractAddress = await offerHandler.getAddress(); message.functionName = "createOffer((uint256,uint256,uint256,uint256,uint256,uint256,address,string,string,bool),(uint256,uint256,uint256,uint256),(uint256,uint256,uint256),uint256,uint256)"; message.functionSignature = functionSignature; @@ -3116,13 +3208,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // send a meta transaction, check for event await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -3132,18 +3224,18 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(assistant.address, deployer.address, message.functionName, nonce); + .withArgs(await assistant.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(assistant).isUsedNonce(assistant.address, nonce); + result = await metaTransactionsHandler.connect(assistant).isUsedNonce(await assistant.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); it("does not modify revert reasons", async function () { // Reverse the from and until dates - offerDates.validFrom = ethers.BigNumber.from(Date.now() + oneMonth * 6).toString(); // 6 months from now - offerDates.validUntil = ethers.BigNumber.from(Date.now()).toString(); // now + offerDates.validFrom = (BigInt(Date.now()) + oneMonth * 6n).toString(); // 6 months from now + offerDates.validUntil = BigInt(Date.now()).toString(); // now // Prepare the function signature for the facet function. functionSignature = offerHandler.interface.encodeFunctionData("createOffer", [ @@ -3163,13 +3255,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -3188,12 +3280,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -3205,7 +3297,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -3218,7 +3310,7 @@ describe("IBosonMetaTransactionsHandler", function () { it("Should fail when Signer and Signature do not match", async function () { // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); // Collect the signature components let { r, s, v } = await prepareDataSignatureParameters( @@ -3226,13 +3318,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - assistant.address, + await assistant.getAddress(), message.functionName, functionSignature, nonce, @@ -3251,7 +3343,12 @@ describe("IBosonMetaTransactionsHandler", function () { exchangeId = "1"; // Create a valid seller - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -3265,18 +3362,18 @@ describe("IBosonMetaTransactionsHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; //Create DisputeResolverFee array so offer creation will succeed disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0"), - new DisputeResolverFee(mockToken.address, "mockToken", "0"), + new DisputeResolverFee(ZeroAddress, "Native", "0"), + new DisputeResolverFee(await mockToken.getAddress(), "mockToken", "0"), ]; buyerId = accountId.next().value; @@ -3294,7 +3391,7 @@ describe("IBosonMetaTransactionsHandler", function () { offerNative = offer; offerToken = offerNative.clone(); offerToken.id = "2"; - offerToken.exchangeToken = mockToken.address; + offerToken.exchangeToken = await mockToken.getAddress(); price = offer.price; sellerDeposit = offer.sellerDeposit; @@ -3315,24 +3412,24 @@ describe("IBosonMetaTransactionsHandler", function () { ]); // top up seller's and buyer's account - await mockToken.mint(assistant.address, sellerDeposit); - await mockToken.mint(buyer.address, price); + await mockToken.mint(await assistant.getAddress(), sellerDeposit); + await mockToken.mint(await buyer.getAddress(), price); // approve protocol to transfer the tokens await mockToken.connect(assistant).approve(protocolDiamondAddress, sellerDeposit); await mockToken.connect(buyer).approve(protocolDiamondAddress, price); // deposit to seller's pool - await fundsHandler.connect(assistant).depositFunds(seller.id, mockToken.address, sellerDeposit); - await fundsHandler.connect(assistant).depositFunds(seller.id, ethers.constants.AddressZero, sellerDeposit, { + await fundsHandler.connect(assistant).depositFunds(seller.id, await mockToken.getAddress(), sellerDeposit); + await fundsHandler.connect(assistant).depositFunds(seller.id, ZeroAddress, sellerDeposit, { value: sellerDeposit, }); // commit to both offers - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerToken.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerToken.id); await exchangeHandler .connect(buyer) - .commitToOffer(buyer.address, offerNative.id, { value: offerNative.price }); + .commitToOffer(await buyer.getAddress(), offerNative.id, { value: offerNative.price }); // cancel the voucher, so both seller and buyer have something to withdraw await exchangeHandler.connect(buyer).cancelVoucher(exchangeId); // canceling the voucher in tokens @@ -3340,11 +3437,11 @@ describe("IBosonMetaTransactionsHandler", function () { // expected payoffs - they are the same for token and native currency // buyer: price - buyerCancelPenalty - buyerPayoff = ethers.BigNumber.from(offerToken.price).sub(offerToken.buyerCancelPenalty).toString(); + buyerPayoff = (BigInt(offerToken.price) - BigInt(offerToken.buyerCancelPenalty)).toString(); // prepare validFundDetails - tokenListBuyer = [mockToken.address, ethers.constants.AddressZero]; - tokenAmountsBuyer = [buyerPayoff, ethers.BigNumber.from(buyerPayoff).div("2").toString()]; + tokenListBuyer = [await mockToken.getAddress(), ZeroAddress]; + tokenAmountsBuyer = [buyerPayoff.toString(), (BigInt(buyerPayoff) / 2n).toString()]; validFundDetails = { entityId: buyerId, tokenList: tokenListBuyer, @@ -3354,10 +3451,10 @@ describe("IBosonMetaTransactionsHandler", function () { // Prepare the message message = {}; message.nonce = parseInt(nonce); - message.contractAddress = fundsHandler.address; + message.contractAddress = await fundsHandler.getAddress(); message.functionName = "withdrawFunds(uint256,address[],uint256[])"; message.fundDetails = validFundDetails; - message.from = buyer.address; + message.from = await buyer.getAddress(); // Set the fund Type fundType = [ @@ -3390,12 +3487,12 @@ describe("IBosonMetaTransactionsHandler", function () { beforeEach(async function () { // Read on chain state buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); - buyerBalanceBefore = await mockToken.balanceOf(buyer.address); + buyerBalanceBefore = await mockToken.balanceOf(await buyer.getAddress()); // Chain state should match the expected available funds before the withdrawal expectedBuyerAvailableFunds = new FundsList([ - new Funds(mockToken.address, "Foreign20", buyerPayoff), - new Funds(ethers.constants.AddressZero, "Native currency", buyerPayoff), + new Funds(await mockToken.getAddress(), "Foreign20", buyerPayoff), + new Funds(ZeroAddress, "Native currency", buyerPayoff), ]); expect(buyerAvailableFunds).to.eql( expectedBuyerAvailableFunds, @@ -3410,7 +3507,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxFund", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -3423,7 +3520,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Withdraw funds. Send a meta transaction, check for event. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -3433,20 +3530,16 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(buyer.address, deployer.address, message.functionName, nonce); + .withArgs(await buyer.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Read on chain state buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); - buyerBalanceAfter = await mockToken.balanceOf(buyer.address); + buyerBalanceAfter = await mockToken.balanceOf(await buyer.getAddress()); // Chain state should match the expected available funds after the withdrawal // Since all tokens are withdrawn, token should be removed from the list expectedBuyerAvailableFunds = new FundsList([ - new Funds( - ethers.constants.AddressZero, - "Native currency", - ethers.BigNumber.from(buyerPayoff).div("2").toString() - ), + new Funds(ZeroAddress, "Native currency", (BigInt(buyerPayoff) / 2n).toString()), ]); expect(buyerAvailableFunds).to.eql( expectedBuyerAvailableFunds, @@ -3454,11 +3547,11 @@ describe("IBosonMetaTransactionsHandler", function () { ); // Token balance is increased for the buyer payoff - expect(buyerBalanceAfter).to.eql(buyerBalanceBefore.add(buyerPayoff), "Buyer token balance mismatch"); + expect(buyerBalanceAfter).to.eql(buyerBalanceBefore + BigInt(buyerPayoff), "Buyer token balance mismatch"); // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(buyer).isUsedNonce(buyer.address, nonce); + result = await metaTransactionsHandler.connect(buyer).isUsedNonce(await buyer.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -3478,7 +3571,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxFund", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -3491,7 +3584,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Withdraw funds. Send a meta transaction, check for event. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -3501,11 +3594,11 @@ describe("IBosonMetaTransactionsHandler", function () { ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(buyer.address, deployer.address, message.functionName, nonce); + .withArgs(await buyer.getAddress(), await deployer.getAddress(), message.functionName, nonce); // Read on chain state buyerAvailableFunds = FundsList.fromStruct(await fundsHandler.getAvailableFunds(buyerId)); - buyerBalanceAfter = await mockToken.balanceOf(buyer.address); + buyerBalanceAfter = await mockToken.balanceOf(await buyer.getAddress()); // Chain state should match the expected available funds after the withdrawal // Since all tokens are withdrawn, funds list should be empty. @@ -3516,11 +3609,11 @@ describe("IBosonMetaTransactionsHandler", function () { ); // Token balance is increased for the buyer payoff - expect(buyerBalanceAfter).to.eql(buyerBalanceBefore.add(buyerPayoff), "Buyer token balance mismatch"); + expect(buyerBalanceAfter).to.eql(buyerBalanceBefore + BigInt(buyerPayoff), "Buyer token balance mismatch"); // Verify that nonce is used. Expect true. let expectedResult = true; - result = await metaTransactionsHandler.connect(buyer).isUsedNonce(buyer.address, nonce); + result = await metaTransactionsHandler.connect(buyer).isUsedNonce(await buyer.getAddress(), nonce); assert.equal(result, expectedResult, "Nonce is unused"); }); @@ -3528,7 +3621,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Set token address to boson token validFundDetails = { entityId: buyerId, - tokenList: [bosonToken.address], + tokenList: [await bosonToken.getAddress()], tokenAmounts: [buyerPayoff], }; @@ -3541,7 +3634,7 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxFund", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Prepare the function signature @@ -3554,7 +3647,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -3583,12 +3676,12 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxFund", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute the meta transaction. await metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -3600,7 +3693,7 @@ describe("IBosonMetaTransactionsHandler", function () { // Execute meta transaction again with the same nonce, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, @@ -3613,7 +3706,7 @@ describe("IBosonMetaTransactionsHandler", function () { it("Should fail when Signer and Signature do not match", async function () { // Prepare the message - message.from = rando.address; + message.from = await rando.getAddress(); // Collect the signature components let { r, s, v } = await prepareDataSignatureParameters( @@ -3621,13 +3714,13 @@ describe("IBosonMetaTransactionsHandler", function () { customTransactionType, "MetaTxFund", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler.executeMetaTransaction( - buyer.address, + await buyer.getAddress(), message.functionName, functionSignature, nonce, diff --git a/test/protocol/OfferHandlerTest.js b/test/protocol/OfferHandlerTest.js index f182e0441..e6b418496 100644 --- a/test/protocol/OfferHandlerTest.js +++ b/test/protocol/OfferHandlerTest.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractAt, ZeroAddress, getSigners, MaxUint256, provider, parseUnits } = hre.ethers; const { assert, expect } = require("chai"); const Offer = require("../../scripts/domain/Offer"); @@ -125,13 +125,13 @@ describe("IBosonOfferHandler", function () { , { percentage: protocolFeePercentage, flatBoson: protocolFeeFlatBoson, buyerEscalationDepositPercentage }, ], - } = await setupTestEnvironment(contracts, { bosonTokenAddress: bosonToken.address })); + } = await setupTestEnvironment(contracts, { bosonTokenAddress: await bosonToken.getAddress() })); // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; - [deployer] = await ethers.getSigners(); + clerk = clerkDR = { address: ZeroAddress }; + [deployer] = await getSigners(); // Get snapshot id snapshotId = await getSnapshot(); @@ -163,7 +163,12 @@ describe("IBosonOfferHandler", function () { id = nextAccountId = "1"; // argument sent to contract for createSeller will be ignored // Create a valid seller, then set fields in tests directly - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -177,10 +182,10 @@ describe("IBosonOfferHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; @@ -189,8 +194,8 @@ describe("IBosonOfferHandler", function () { DRFeeNative = "0"; DRFeeToken = "0"; disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", DRFeeNative), - new DisputeResolverFee(bosonToken.address, "Boson", DRFeeToken), + new DisputeResolverFee(ZeroAddress, "Native", DRFeeNative), + new DisputeResolverFee(await bosonToken.getAddress(), "Boson", DRFeeToken), ]; // Make empty seller list, so every seller is allowed @@ -258,7 +263,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -317,7 +322,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // wrong offer id should not exist @@ -347,7 +352,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -375,13 +380,13 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); it("If exchange token is $BOSON, fee should be flat boson fee", async function () { // Prepare an offer with $BOSON as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); disputeResolutionTerms = new DisputeResolutionTerms( disputeResolver.id, disputeResolver.escalationResponsePeriod, @@ -405,7 +410,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTerms.toStruct(), offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -430,13 +435,13 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); it("Should allow creation of an offer with unlimited supply", async function () { // Prepare an absolute zero offer - offer.quantityAvailable = ethers.constants.MaxUint256.toString(); + offer.quantityAvailable = MaxUint256.toString(); // Create a new offer await expect( @@ -452,7 +457,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -471,11 +476,11 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // create another offer, now with bosonToken as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); offer.id = "2"; disputeResolutionTermsStruct = new DisputeResolutionTerms( disputeResolver.id, @@ -500,13 +505,13 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); it("Should allow creation of an offer if DR has a sellerAllowList and seller is on it", async function () { // Create new seller so sellerAllowList can have an entry - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller(await rando.getAddress(), await rando.getAddress(), ZeroAddress, await rando.getAddress()); await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); @@ -548,8 +553,8 @@ describe("IBosonOfferHandler", function () { it("Valid from date is greater than valid until date", async function () { // Reverse the from and until dates - offerDates.validFrom = ethers.BigNumber.from(Date.now() + oneMonth * 6).toString(); // 6 months from now - offerDates.validUntil = ethers.BigNumber.from(Date.now()).toString(); // now + offerDates.validFrom = (BigInt(Date.now()) + oneMonth * 6n).toString(); // 6 months from now + offerDates.validUntil = BigInt(Date.now()).toString(); // now // Attempt to Create an offer, expecting revert await expect( @@ -559,14 +564,14 @@ describe("IBosonOfferHandler", function () { it("Valid until date is not in the future", async function () { // get current block timestamp - const block = await ethers.provider.getBlock("latest"); + const block = await provider.getBlock("latest"); const now = block.timestamp.toString(); // set validFrom date in the past - offerDates.validFrom = ethers.BigNumber.from(now - oneMonth * 6).toString(); // 6 months ago + offerDates.validFrom = (BigInt(now) - oneMonth * 6n).toString(); // 6 months ago // set valid until > valid from - offerDates.validUntil = ethers.BigNumber.from(now - oneMonth).toString(); // 1 month ago + offerDates.validUntil = (BigInt(now) - oneMonth).toString(); // 1 month ago // Attempt to Create an offer, expecting revert await expect( @@ -576,7 +581,7 @@ describe("IBosonOfferHandler", function () { it("Buyer cancel penalty is greater than price", async function () { // Set buyer cancel penalty higher than offer price - offer.buyerCancelPenalty = ethers.BigNumber.from(offer.price).add("10").toString(); + offer.buyerCancelPenalty = (BigInt(offer.price) + 10n).toString(); // Attempt to Create an offer, expecting revert await expect( @@ -596,7 +601,7 @@ describe("IBosonOfferHandler", function () { it("Both voucher expiration date and voucher expiration period are defined", async function () { // Set both voucherRedeemableUntil and voucherValid - offerDates.voucherRedeemableUntil = (Number(offerDates.voucherRedeemableFrom) + oneMonth).toString(); + offerDates.voucherRedeemableUntil = (BigInt(offerDates.voucherRedeemableFrom) + oneMonth).toString(); offerDurations.voucherValid = oneMonth.toString(); // Attempt to Create an offer, expecting revert @@ -641,7 +646,7 @@ describe("IBosonOfferHandler", function () { it("Dispute period is less than minimum dispute period", async function () { // Set dispute period to less than minDisputePeriod (oneWeek) - offerDurations.disputePeriod = ethers.BigNumber.from(oneWeek).sub(1000).toString(); + offerDurations.disputePeriod = (oneWeek - 1000n).toString(); // Attempt to Create an offer, expecting revert await expect( @@ -704,10 +709,10 @@ describe("IBosonOfferHandler", function () { it.skip("Dispute resolver is not active", async function () { // create another dispute resolver, but don't activate it disputeResolver = mockDisputeResolver( - rando.address, - rando.address, - ethers.constants.AddressZero, - rando.address, + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress(), false ); await accountHandler @@ -743,10 +748,10 @@ describe("IBosonOfferHandler", function () { it.skip("For absolute zero offer, specified dispute resolver is not active", async function () { // create another dispute resolver, but don't activate it disputeResolver = mockDisputeResolver( - rando.address, - rando.address, - ethers.constants.AddressZero, - rando.address, + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress(), false ); await accountHandler @@ -772,7 +777,12 @@ describe("IBosonOfferHandler", function () { it("Seller is not on dispute resolver's seller allow list", async function () { // Create new seller so sellerAllowList can have an entry - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); @@ -787,7 +797,7 @@ describe("IBosonOfferHandler", function () { it("Dispute resolver does not accept fees in the exchange token", async function () { // Set some address that is not part of dispute resolver fees - offer.exchangeToken = rando.address; + offer.exchangeToken = await rando.getAddress(); // Attempt to Create an offer, expecting revert await expect( @@ -799,7 +809,7 @@ describe("IBosonOfferHandler", function () { context("When offer has non zero agent id", async function () { beforeEach(async function () { // Create a valid agent, then set fields in tests directly - agent = mockAgent(other.address); + agent = mockAgent(await other.getAddress()); agent.id = "3"; agentId = agent.id; expect(agent.isValid()).is.true; @@ -807,7 +817,7 @@ describe("IBosonOfferHandler", function () { // Create an agent await accountHandler.connect(rando).createAgent(agent); - agentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + agentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = agentFee; offerFeesStruct = offerFees.toStruct(); }); @@ -827,7 +837,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Check that mapping between agent and offer is correct @@ -845,7 +855,7 @@ describe("IBosonOfferHandler", function () { offerFees.protocolFee = protocolFee; // Calculate the new agent fee amount. - let newOfferAgentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + let newOfferAgentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = newOfferAgentFee; offerFeesStruct = offerFees.toStruct(); @@ -863,7 +873,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); //Check offer agent fee for New offer. @@ -876,7 +886,7 @@ describe("IBosonOfferHandler", function () { let oldOfferId = await offerHandler.getNextOfferId(); // Calculate the new agent fee amount. - let oldOfferAgentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + let oldOfferAgentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); // Create a new offer await offerHandler @@ -889,7 +899,7 @@ describe("IBosonOfferHandler", function () { // Creating 2nd offer // Calculate the new agent fee amount. - let newOfferAgentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + let newOfferAgentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); let newOfferId = await offerHandler.getNextOfferId(); @@ -922,7 +932,7 @@ describe("IBosonOfferHandler", function () { it("Sum of agent fee amount and protocol fee amount should be <= than the offer fee limit", async function () { // Create a valid agent, then set fields in tests directly - agent = mockAgent(assistant.address); + agent = mockAgent(await assistant.getAddress()); agent.id = "4"; agent.feePercentage = "3000"; //30% expect(agent.isValid()).is.true; @@ -962,7 +972,7 @@ describe("IBosonOfferHandler", function () { // Void the offer, testing for the event await expect(offerHandler.connect(assistant).voidOffer(id)) .to.emit(offerHandler, "OfferVoided") - .withArgs(id, offerStruct.sellerId, assistant.address); + .withArgs(id, offerStruct.sellerId, await assistant.getAddress()); }); it("should update state", async function () { @@ -1016,7 +1026,12 @@ describe("IBosonOfferHandler", function () { // caller is an assistant of another seller // Create a valid seller, then set fields in tests directly - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); // AuthToken emptyAuthToken = mockAuthToken(); @@ -1051,7 +1066,7 @@ describe("IBosonOfferHandler", function () { id = nextOfferId++; // update the values - offerDates.validUntil = ethers.BigNumber.from(offerDates.validUntil).add("10000").toString(); + offerDates.validUntil = (BigInt(offerDates.validUntil) + 10000n).toString(); offerStruct = offer.toStruct(); }); @@ -1059,7 +1074,7 @@ describe("IBosonOfferHandler", function () { // Extend the valid until date, testing for the event await expect(offerHandler.connect(assistant).extendOffer(offer.id, offerDates.validUntil)) .to.emit(offerHandler, "OfferExtended") - .withArgs(id, offer.sellerId, offerDates.validUntil, assistant.address); + .withArgs(id, offer.sellerId, offerDates.validUntil, await assistant.getAddress()); }); it("should update state", async function () { @@ -1116,7 +1131,12 @@ describe("IBosonOfferHandler", function () { // caller is an assistant of another seller // Create a valid seller, then set fields in tests directly - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); // AuthToken emptyAuthToken = mockAuthToken(); @@ -1141,14 +1161,14 @@ describe("IBosonOfferHandler", function () { it("New valid until date is lower than the existing valid until date", async function () { // Make the valid until date the same as the existing offer - offerDates.validUntil = ethers.BigNumber.from(offerDates.validUntil).sub("10000").toString(); + offerDates.validUntil = (BigInt(offerDates.validUntil) - 10000n).toString(); await expect(offerHandler.connect(assistant).extendOffer(offer.id, offerDates.validUntil)).to.revertedWith( RevertReasons.OFFER_PERIOD_INVALID ); // Make new the valid until date less than existing one - offerDates.validUntil = ethers.BigNumber.from(offerDates.validUntil).sub("1").toString(); + offerDates.validUntil = (BigInt(offerDates.validUntil) - 1n).toString(); // Attempt to update an offer, expecting revert await expect(offerHandler.connect(assistant).extendOffer(offer.id, offerDates.validUntil)).to.revertedWith( @@ -1158,7 +1178,7 @@ describe("IBosonOfferHandler", function () { it("Valid until date is not in the future", async function () { // Set until date in the past - offerDates.validUntil = ethers.BigNumber.from(offerDates.validFrom - oneMonth * 6).toString(); // 6 months ago + offerDates.validUntil = (BigInt(offerDates.validFrom) - oneMonth * 6n).toString(); // 6 months ago // Attempt to update an offer, expecting revert await expect(offerHandler.connect(assistant).extendOffer(offer.id, offerDates.validUntil)).to.revertedWith( @@ -1170,7 +1190,7 @@ describe("IBosonOfferHandler", function () { context("Offers with fixed voucher expiration date", async function () { beforeEach(async function () { - offerDates.voucherRedeemableUntil = ethers.BigNumber.from(offerDates.validUntil).add(oneMonth).toString(); + offerDates.voucherRedeemableUntil = (BigInt(offerDates.validUntil) + oneMonth).toString(); offerDurations.voucherValid = "0"; // only one of voucherRedeemableUntil and voucherValid can be non zero // Create an offer @@ -1182,7 +1202,7 @@ describe("IBosonOfferHandler", function () { id = nextOfferId++; // update the values - offerDates.validUntil = ethers.BigNumber.from(offerDates.validUntil).add("10000").toString(); + offerDates.validUntil = (BigInt(offerDates.validUntil) + 10000n).toString(); offerStruct = offer.toStruct(); }); @@ -1190,7 +1210,7 @@ describe("IBosonOfferHandler", function () { // Extend the valid until date, testing for the event await expect(offerHandler.connect(assistant).extendOffer(offer.id, offerDates.validUntil)) .to.emit(offerHandler, "OfferExtended") - .withArgs(id, offer.sellerId, offerDates.validUntil, assistant.address); + .withArgs(id, offer.sellerId, offerDates.validUntil, await assistant.getAddress()); }); it("should update state", async function () { @@ -1212,7 +1232,7 @@ describe("IBosonOfferHandler", function () { context("💔 Revert Reasons", async function () { it("Offer has voucherRedeemableUntil set and new valid until date is greater than that", async function () { // Set until date in the before offerDates.voucherRedeemableUntil - offerDates.validUntil = ethers.BigNumber.from(offerDates.voucherRedeemableUntil).add(oneWeek).toString(); // one week after voucherRedeemableUntil + offerDates.validUntil = BigInt(offerDates.voucherRedeemableUntil) + oneWeek.toString(); // one week after voucherRedeemableUntil // Attempt to update an offer, expecting revert await expect(offerHandler.connect(assistant).extendOffer(offer.id, offerDates.validUntil)).to.revertedWith( @@ -1238,23 +1258,30 @@ describe("IBosonOfferHandler", function () { id = nextOfferId++; // expected address of the first clone - const voucherCloneAddress = calculateContractAddress(accountHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherCloneAddress); + const voucherCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("BosonVoucher", voucherCloneAddress); length = 100; firstTokenId = 1; lastTokenId = firstTokenId + length - 1; const tokenIdStart = deriveTokenId(offer.id, firstTokenId); - range = new Range(tokenIdStart.toString(), length.toString(), "0", "0", assistant.address); + range = new Range(tokenIdStart.toString(), length.toString(), "0", "0", await assistant.getAddress()); }); it("should emit an RangeReserved event", async function () { // Reserve a range, testing for the event - const tx = await offerHandler.connect(assistant).reserveRange(id, length, assistant.address); + const tx = await offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()); await expect(tx) .to.emit(offerHandler, "RangeReserved") - .withArgs(id, offer.sellerId, firstTokenId, lastTokenId, assistant.address, assistant.address); + .withArgs( + id, + offer.sellerId, + firstTokenId, + lastTokenId, + await assistant.getAddress(), + await assistant.getAddress() + ); await expect(tx).to.emit(bosonVoucher, "RangeReserved").withArgs(id, range.toStruct()); }); @@ -1266,20 +1293,16 @@ describe("IBosonOfferHandler", function () { const nextExchangeIdBefore = await exchangeHandler.getNextExchangeId(); // Reserve a range - await offerHandler.connect(assistant).reserveRange(id, length, assistant.address); + await offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()); // Quantity available should be updated [, offerStruct] = await offerHandler.connect(rando).getOffer(id); const quantityAvailableAfter = offerStruct.quantityAvailable; - assert.equal( - quantityAvailableBefore.sub(quantityAvailableAfter).toNumber(), - length, - "Quantity available mismatch" - ); + assert.equal(quantityAvailableBefore - quantityAvailableAfter, length, "Quantity available mismatch"); // nextExchangeId should be updated const nextExchangeIdAfter = await exchangeHandler.getNextExchangeId(); - assert.equal(nextExchangeIdAfter.sub(nextExchangeIdBefore).toNumber(), length, "nextExchangeId mismatch"); + assert.equal(nextExchangeIdAfter - nextExchangeIdBefore, length, "nextExchangeId mismatch"); // Get range object from the voucher contract const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(id)); @@ -1288,39 +1311,43 @@ describe("IBosonOfferHandler", function () { it("it's possible to reserve range even if somebody already committed to", async function () { // Deposit seller funds so the commit will succeed - const sellerPool = ethers.BigNumber.from(offer.sellerDeposit).mul(2); - await fundsHandler - .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, sellerPool, { value: sellerPool }); + const sellerPool = BigInt(offer.sellerDeposit) * 2n; + await fundsHandler.connect(assistant).depositFunds(seller.id, ZeroAddress, sellerPool, { value: sellerPool }); // Commit to the offer twice - await exchangeHandler.connect(rando).commitToOffer(rando.address, id, { value: price }); - await exchangeHandler.connect(rando).commitToOffer(rando.address, id, { value: price }); + await exchangeHandler.connect(rando).commitToOffer(await rando.getAddress(), id, { value: price }); + await exchangeHandler.connect(rando).commitToOffer(await rando.getAddress(), id, { value: price }); // Reserve a range, testing for the event - await expect(offerHandler.connect(assistant).reserveRange(id, length, assistant.address)) + await expect(offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress())) .to.emit(offerHandler, "RangeReserved") - .withArgs(id, offer.sellerId, firstTokenId + 2, lastTokenId + 2, assistant.address, assistant.address); + .withArgs( + id, + offer.sellerId, + firstTokenId + 2, + lastTokenId + 2, + await assistant.getAddress(), + await assistant.getAddress() + ); }); it("It's possible to reserve a range with maximum allowed length", async function () { // Create an unlimited offer - offer.quantityAvailable = ethers.constants.MaxUint256.toString(); + offer.quantityAvailable = MaxUint256.toString(); await offerHandler .connect(assistant) .createOffer(offer, offerDates, offerDurations, disputeResolver.id, agentId); // Set maximum allowed length - length = ethers.BigNumber.from(2).pow(64).sub(1); - await expect(offerHandler.connect(assistant).reserveRange(nextOfferId, length, assistant.address)).to.emit( - offerHandler, - "RangeReserved" - ); + length = 2n ** 64n - 1n; + await expect( + offerHandler.connect(assistant).reserveRange(nextOfferId, length, await assistant.getAddress()) + ).to.emit(offerHandler, "RangeReserved"); }); it("Reserving range of unlimited offer does not decrease quantity available", async function () { // Create an unlimited offer - offer.quantityAvailable = ethers.constants.MaxUint256.toString(); + offer.quantityAvailable = MaxUint256.toString(); await offerHandler .connect(assistant) .createOffer(offer, offerDates, offerDurations, disputeResolver.id, agentId); @@ -1330,7 +1357,7 @@ describe("IBosonOfferHandler", function () { const quantityAvailableBefore = offerStruct.quantityAvailable; // Reserve a range - await offerHandler.connect(assistant).reserveRange(nextOfferId, length, assistant.address); + await offerHandler.connect(assistant).reserveRange(nextOfferId, length, await assistant.getAddress()); // Quantity available should not change [, offerStruct] = await offerHandler.connect(rando).getOffer(nextOfferId); @@ -1344,16 +1371,23 @@ describe("IBosonOfferHandler", function () { context("Owner range is contract", async function () { beforeEach(async function () { - range.owner = bosonVoucher.address; + range.owner = await bosonVoucher.getAddress(); }); it("should emit an RangeReserved event", async function () { // Reserve a range, testing for the event - const tx = await offerHandler.connect(assistant).reserveRange(id, length, bosonVoucher.address); + const tx = await offerHandler.connect(assistant).reserveRange(id, length, await bosonVoucher.getAddress()); await expect(tx) .to.emit(offerHandler, "RangeReserved") - .withArgs(id, offer.sellerId, firstTokenId, lastTokenId, bosonVoucher.address, assistant.address); + .withArgs( + id, + offer.sellerId, + firstTokenId, + lastTokenId, + await bosonVoucher.getAddress(), + await assistant.getAddress() + ); await expect(tx).to.emit(bosonVoucher, "RangeReserved").withArgs(id, range.toStruct()); }); @@ -1365,20 +1399,16 @@ describe("IBosonOfferHandler", function () { const nextExchangeIdBefore = await exchangeHandler.getNextExchangeId(); // Reserve a range - await offerHandler.connect(assistant).reserveRange(id, length, bosonVoucher.address); + await offerHandler.connect(assistant).reserveRange(id, length, await bosonVoucher.getAddress()); // Quantity available should be updated [, offerStruct] = await offerHandler.connect(rando).getOffer(id); const quantityAvailableAfter = offerStruct.quantityAvailable; - assert.equal( - quantityAvailableBefore.sub(quantityAvailableAfter).toNumber(), - length, - "Quantity available mismatch" - ); + assert.equal(quantityAvailableBefore - quantityAvailableAfter, length, "Quantity available mismatch"); // nextExchangeId should be updated const nextExchangeIdAfter = await exchangeHandler.getNextExchangeId(); - assert.equal(nextExchangeIdAfter.sub(nextExchangeIdBefore).toNumber(), length, "nextExchangeId mismatch"); + assert.equal(nextExchangeIdAfter - nextExchangeIdBefore, length, "nextExchangeId mismatch"); // Get range object from the voucher contract const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(id)); @@ -1392,9 +1422,9 @@ describe("IBosonOfferHandler", function () { await pauseHandler.connect(pauser).pause([PausableRegion.Offers]); // Attempt to reserve a range, expecting revert - await expect(offerHandler.connect(assistant).reserveRange(id, length, assistant.address)).to.revertedWith( - RevertReasons.REGION_PAUSED - ); + await expect( + offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()) + ).to.revertedWith(RevertReasons.REGION_PAUSED); }); it("The exchanges region of protocol is paused", async function () { @@ -1402,9 +1432,9 @@ describe("IBosonOfferHandler", function () { await pauseHandler.connect(pauser).pause([PausableRegion.Exchanges]); // Attempt to reserve a range, expecting revert - await expect(offerHandler.connect(assistant).reserveRange(id, length, assistant.address)).to.revertedWith( - RevertReasons.REGION_PAUSED - ); + await expect( + offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()) + ).to.revertedWith(RevertReasons.REGION_PAUSED); }); it("Offer does not exist", async function () { @@ -1412,17 +1442,17 @@ describe("IBosonOfferHandler", function () { id = "444"; // Attempt to reserve a range, expecting revert - await expect(offerHandler.connect(assistant).reserveRange(id, length, assistant.address)).to.revertedWith( - RevertReasons.NO_SUCH_OFFER - ); + await expect( + offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()) + ).to.revertedWith(RevertReasons.NO_SUCH_OFFER); // Set invalid id id = "0"; // Attempt to reserve a range, expecting revert - await expect(offerHandler.connect(assistant).reserveRange(id, length, assistant.address)).to.revertedWith( - RevertReasons.NO_SUCH_OFFER - ); + await expect( + offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()) + ).to.revertedWith(RevertReasons.NO_SUCH_OFFER); }); it("Offer already voided", async function () { @@ -1430,21 +1460,26 @@ describe("IBosonOfferHandler", function () { await offerHandler.connect(assistant).voidOffer(id); // Attempt to reserve a range, expecting revert - await expect(offerHandler.connect(assistant).reserveRange(id, length, assistant.address)).to.revertedWith( - RevertReasons.OFFER_HAS_BEEN_VOIDED - ); + await expect( + offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()) + ).to.revertedWith(RevertReasons.OFFER_HAS_BEEN_VOIDED); }); it("Caller is not seller", async function () { // caller is not the assistant of any seller // Attempt to reserve a range, expecting revert - await expect(offerHandler.connect(rando).reserveRange(id, length, assistant.address)).to.revertedWith( - RevertReasons.NOT_ASSISTANT - ); + await expect( + offerHandler.connect(rando).reserveRange(id, length, await assistant.getAddress()) + ).to.revertedWith(RevertReasons.NOT_ASSISTANT); // caller is an assistant of another seller // Create a valid seller, then set fields in tests directly - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); // AuthToken emptyAuthToken = mockAuthToken(); @@ -1452,9 +1487,9 @@ describe("IBosonOfferHandler", function () { await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); // Attempt to reserve a range, expecting revert - await expect(offerHandler.connect(rando).reserveRange(id, length, assistant.address)).to.revertedWith( - RevertReasons.NOT_ASSISTANT - ); + await expect( + offerHandler.connect(rando).reserveRange(id, length, await assistant.getAddress()) + ).to.revertedWith(RevertReasons.NOT_ASSISTANT); }); it("Range length is zero", async function () { @@ -1462,9 +1497,9 @@ describe("IBosonOfferHandler", function () { length = 0; // Attempt to reserve a range, expecting revert - await expect(offerHandler.connect(assistant).reserveRange(id, length, assistant.address)).to.revertedWith( - RevertReasons.INVALID_RANGE_LENGTH - ); + await expect( + offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()) + ).to.revertedWith(RevertReasons.INVALID_RANGE_LENGTH); }); it("Range length is greater than quantity available", async function () { @@ -1472,42 +1507,42 @@ describe("IBosonOfferHandler", function () { length = Number(offer.quantityAvailable) + 1; // Attempt to reserve a range, expecting revert - await expect(offerHandler.connect(assistant).reserveRange(id, length, assistant.address)).to.revertedWith( - RevertReasons.INVALID_RANGE_LENGTH - ); + await expect( + offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()) + ).to.revertedWith(RevertReasons.INVALID_RANGE_LENGTH); }); it("Range length is greater than maximum allowed range length", async function () { // Create an unlimited offer - offer.quantityAvailable = ethers.constants.MaxUint256.toString(); + offer.quantityAvailable = MaxUint256.toString(); await offerHandler .connect(assistant) .createOffer(offer, offerDates, offerDurations, disputeResolver.id, agentId); // Set length to more than maximum allowed range length - length = ethers.BigNumber.from(2).pow(64); + length = 2n ** 64n; // Attempt to reserve a range, expecting revert await expect( - offerHandler.connect(assistant).reserveRange(nextOfferId, length, assistant.address) + offerHandler.connect(assistant).reserveRange(nextOfferId, length, await assistant.getAddress()) ).to.revertedWith(RevertReasons.INVALID_RANGE_LENGTH); }); it("Call to BosonVoucher.reserveRange() reverts", async function () { // Reserve a range - await offerHandler.connect(assistant).reserveRange(id, length, assistant.address); + await offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()); // Attempt to reserve the same range again, expecting revert - await expect(offerHandler.connect(assistant).reserveRange(id, length, assistant.address)).to.revertedWith( - RevertReasons.OFFER_RANGE_ALREADY_RESERVED - ); + await expect( + offerHandler.connect(assistant).reserveRange(id, length, await assistant.getAddress()) + ).to.revertedWith(RevertReasons.OFFER_RANGE_ALREADY_RESERVED); }); it("_to address isn't contract address or contract owner address", async function () { // Try to reserve range for rando address, it should fail - await expect(offerHandler.connect(assistant).reserveRange(id, length, rando.address)).to.be.revertedWith( - RevertReasons.INVALID_TO_ADDRESS - ); + await expect( + offerHandler.connect(assistant).reserveRange(id, length, await rando.getAddress()) + ).to.be.revertedWith(RevertReasons.INVALID_TO_ADDRESS); }); }); }); @@ -1677,7 +1712,12 @@ describe("IBosonOfferHandler", function () { id = sellerId = nextAccountId = "1"; // argument sent to contract for createSeller will be ignored // Create a valid seller, then set fields in tests directly - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -1691,10 +1731,10 @@ describe("IBosonOfferHandler", function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; @@ -1706,8 +1746,8 @@ describe("IBosonOfferHandler", function () { DRFeeNative = "0"; DRFeeToken = "0"; disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", DRFeeNative), - new DisputeResolverFee(bosonToken.address, "Boson", DRFeeToken), + new DisputeResolverFee(ZeroAddress, "Native", DRFeeNative), + new DisputeResolverFee(await bosonToken.getAddress(), "Boson", DRFeeToken), ]; // Register the dispute resolver @@ -1716,7 +1756,7 @@ describe("IBosonOfferHandler", function () { .createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList); // Necessary to cover all offers resolution periods - await configHandler.setMaxResolutionPeriod(oneWeek * 5); + await configHandler.setMaxResolutionPeriod(oneWeek * 5n); // create 5 offers offers = []; @@ -1737,22 +1777,18 @@ describe("IBosonOfferHandler", function () { // Set unique offer properties based on index offer.id = `${i + 1}`; - offer.price = ethers.utils.parseUnits(`${1.5 + i * 1}`, "ether").toString(); - offer.sellerDeposit = ethers.utils.parseUnits(`${0.25 + i * 0.1}`, "ether").toString(); - offer.buyerCancelPenalty = ethers.utils.parseUnits(`${0.05 + i * 0.1}`, "ether").toString(); + offer.price = parseUnits(`${1.5 + i * 1}`, "ether").toString(); + offer.sellerDeposit = parseUnits(`${0.25 + i * 0.1}`, "ether").toString(); + offer.buyerCancelPenalty = parseUnits(`${0.05 + i * 0.1}`, "ether").toString(); offer.quantityAvailable = `${(i + 1) * 2}`; let now = offerDates.validFrom; - offerDates.validFrom = validFrom = ethers.BigNumber.from(now) - .add(oneMonth * i) - .toString(); - offerDates.validUntil = validUntil = ethers.BigNumber.from(now) - .add(oneMonth * 6 * (i + 1)) - .toString(); + offerDates.validFrom = validFrom = (BigInt(now) + oneMonth * BigInt(i)).toString(); + offerDates.validUntil = validUntil = (BigInt(now) + oneMonth * 6n * BigInt(i + 1)).toString(); - offerDurations.disputePeriod = disputePeriod = `${(i + 1) * oneMonth}`; - offerDurations.voucherValid = voucherValid = `${(i + 1) * oneMonth}`; - offerDurations.resolutionPeriod = resolutionPeriod = `${(i + 1) * oneWeek}`; + offerDurations.disputePeriod = disputePeriod = `${BigInt(i + 1) * oneMonth}`; + offerDurations.voucherValid = voucherValid = `${BigInt(i + 1) * oneMonth}`; + offerDurations.resolutionPeriod = resolutionPeriod = `${BigInt(i + 1) * oneWeek}`; offerFees.protocolFee = applyPercentage(offer.price, protocolFeePercentage); @@ -1791,10 +1827,10 @@ describe("IBosonOfferHandler", function () { // change some offers to test different cases // offer with boson as an exchange token and unlimited supply - offers[2].exchangeToken = bosonToken.address; + offers[2].exchangeToken = await bosonToken.getAddress(); offerFeesList[2].protocolFee = protocolFeeFlatBoson; offerFeesStructs[2] = offerFeesList[2].toStruct(); - offers[2].quantityAvailable = ethers.constants.MaxUint256.toString(); + offers[2].quantityAvailable = MaxUint256.toString(); offerStructs[2] = offers[2].toStruct(); disputeResolutionTermsList[2] = new DisputeResolutionTerms( disputeResolver.id, @@ -1841,7 +1877,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[0], offerFeesStructs[0], agentIds[0], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -1855,7 +1891,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[1], offerFeesStructs[1], agentIds[1], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -1869,7 +1905,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[2], offerFeesStructs[2], agentIds[2], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -1883,7 +1919,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[3], offerFeesStructs[3], agentIds[3], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -1897,7 +1933,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[4], offerFeesStructs[4], agentIds[4], - assistant.address + await assistant.getAddress() ); }); @@ -1961,7 +1997,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[0], offerFeesStructs[0], agentIds[0], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -1975,7 +2011,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[1], offerFeesStructs[1], agentIds[1], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -1989,7 +2025,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[2], offerFeesStructs[2], agentIds[2], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2003,7 +2039,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[3], offerFeesStructs[3], agentIds[3], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2017,7 +2053,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[4], offerFeesStructs[4], agentIds[4], - assistant.address + await assistant.getAddress() ); for (let i = 0; i < 5; i++) { @@ -2055,7 +2091,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[0], offerFeesStructs[0], agentIds[0], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2069,7 +2105,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[1], offerFeesStructs[1], agentIds[1], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2083,7 +2119,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[2], offerFeesStructs[2], agentIds[2], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2097,7 +2133,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[3], offerFeesStructs[3], agentIds[3], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2111,13 +2147,13 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[4], offerFeesStructs[4], agentIds[4], - assistant.address + await assistant.getAddress() ); }); it("Should allow creation of an offer if DR has a sellerAllowList and seller is on it", async function () { // Create new seller so sellerAllowList can have an entry - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller(await rando.getAddress(), await rando.getAddress(), ZeroAddress, await rando.getAddress()); await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); @@ -2167,8 +2203,8 @@ describe("IBosonOfferHandler", function () { it("Valid from date is greater than valid until date in some offer", async function () { // Reverse the from and until dates - offerDatesList[4].validFrom = ethers.BigNumber.from(Date.now() + oneMonth * 6).toString(); // 6 months from now - offerDatesList[4].validUntil = ethers.BigNumber.from(Date.now()).toString(); // now + offerDatesList[4].validFrom = (BigInt(Date.now()) + oneMonth * 6n).toString(); // 6 months from now + offerDatesList[4].validUntil = BigInt(Date.now()).toString(); // now // Attempt to Create an offer, expecting revert await expect( @@ -2182,10 +2218,10 @@ describe("IBosonOfferHandler", function () { let now = offerDatesList[0].validFrom; // set validFrom date in the past - offerDatesList[0].validFrom = ethers.BigNumber.from(now - oneMonth * 6).toString(); // 6 months ago + offerDatesList[0].validFrom = (BigInt(now) - oneMonth * 6n).toString(); // 6 months ago // set valid until > valid from - offerDatesList[0].validUntil = ethers.BigNumber.from(now - oneMonth).toString(); // 1 month ago + offerDatesList[0].validUntil = (BigInt(now) - oneMonth).toString(); // 1 month ago // Attempt to Create an offer, expecting revert await expect( @@ -2197,7 +2233,7 @@ describe("IBosonOfferHandler", function () { it("Buyer cancel penalty is greater than price", async function () { // Set buyer cancel penalty higher than offer price - offers[0].buyerCancelPenalty = ethers.BigNumber.from(offers[0].price).add("10").toString(); + offers[0].buyerCancelPenalty = (BigInt(offers[0].price) + 10n).toString(); // Attempt to Create an offer, expecting revert await expect( @@ -2247,9 +2283,8 @@ describe("IBosonOfferHandler", function () { it("For some offer, both voucher expiration date and voucher expiration period are defined", async function () { // Set both voucherRedeemableUntil and voucherValid - offerDatesList[2].voucherRedeemableUntil = ethers.BigNumber.from(offerDatesList[2].voucherRedeemableFrom) - .add(oneMonth) - .toString(); + offerDatesList[2].voucherRedeemableUntil = + BigInt(offerDatesList[2].voucherRedeemableFrom) + oneMonth.toString(); offerDurationsList[2].voucherValid = oneMonth.toString(); // Attempt to Create an offer, expecting revert @@ -2275,9 +2310,7 @@ describe("IBosonOfferHandler", function () { it("For some offer, voucher redeemable period is fixed, but it ends before it starts", async function () { // Set both voucherRedeemableUntil that is less than voucherRedeemableFrom - offerDatesList[0].voucherRedeemableUntil = ethers.BigNumber.from(offerDatesList[0].voucherRedeemableFrom) - .sub(10) - .toString(); + offerDatesList[0].voucherRedeemableUntil = (BigInt(offerDatesList[0].voucherRedeemableFrom) - 10n).toString(); offerDurationsList[0].voucherValid = "0"; // Attempt to Create an offer, expecting revert @@ -2304,7 +2337,7 @@ describe("IBosonOfferHandler", function () { it("For some offer, Dispute period is less than minimum dispute period", async function () { // Set dispute period to less than minDisputePeriod (oneWeek) - offerDurationsList[1].disputePeriod = ethers.BigNumber.from(oneWeek).sub(1000).toString(); + offerDurationsList[1].disputePeriod = BigInt(oneWeek - 1000n).toString(); // Attempt to Create an offer, expecting revert await expect( @@ -2354,10 +2387,10 @@ describe("IBosonOfferHandler", function () { it.skip("For some offer, dispute resolver is not active", async function () { // create another dispute resolver, but don't activate it disputeResolver = mockDisputeResolver( - rando.address, - rando.address, - ethers.constants.AddressZero, - rando.address, + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress(), false ); await accountHandler @@ -2402,10 +2435,10 @@ describe("IBosonOfferHandler", function () { it.skip("For some absolute zero offer, specified dispute resolver is not active", async function () { // create another dispute resolver, but don't activate it disputeResolver = mockDisputeResolver( - rando.address, - rando.address, - ethers.constants.AddressZero, - rando.address, + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress(), false ); await accountHandler @@ -2436,7 +2469,12 @@ describe("IBosonOfferHandler", function () { it("For some offer seller is not on dispute resolver's seller allow list", async function () { // Create new seller so sellerAllowList can have an entry - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); @@ -2453,7 +2491,7 @@ describe("IBosonOfferHandler", function () { it("For some offer, dispute resolver does not accept fees in the exchange token", async function () { // Set some address that is not part of dispute resolver fees - offers[3].exchangeToken = rando.address; + offers[3].exchangeToken = await rando.getAddress(); // Attempt to Create offers, expecting revert await expect( @@ -2538,7 +2576,7 @@ describe("IBosonOfferHandler", function () { offerFeesStructs = []; // Create an agent: Required constructor params - agent = mockAgent(other.address); + agent = mockAgent(await other.getAddress()); agent.id = agentId; expect(agent.isValid()).is.true; // Create a valid agent @@ -2550,12 +2588,12 @@ describe("IBosonOfferHandler", function () { // Set updated offerFees let protocolFee; - if (offers[i].exchangeToken == bosonToken.address) { + if (offers[i].exchangeToken == (await bosonToken.getAddress())) { protocolFee = protocolFeeFlatBoson; } else { protocolFee = applyPercentage(offers[i].price, protocolFeePercentage); } - let agentFee = ethers.BigNumber.from(offers[i].price).mul(agent.feePercentage).div("10000").toString(); + let agentFee = ((BigInt(offers[i].price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees = new OfferFees(protocolFee, agentFee); offerFeesList.push(offerFees); @@ -2580,7 +2618,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[0], offerFeesStructs[0], nonZeroAgentIds[0], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2594,7 +2632,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[1], offerFeesStructs[1], nonZeroAgentIds[1], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2608,7 +2646,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[2], offerFeesStructs[2], nonZeroAgentIds[2], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2622,7 +2660,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[3], offerFeesStructs[3], nonZeroAgentIds[3], - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2636,7 +2674,7 @@ describe("IBosonOfferHandler", function () { disputeResolutionTermsStructs[4], offerFeesStructs[4], nonZeroAgentIds[4], - assistant.address + await assistant.getAddress() ); }); @@ -2672,7 +2710,7 @@ describe("IBosonOfferHandler", function () { let id = "4"; // argument sent to contract for createAgent will be ignored // Create a valid agent, then set fields in tests directly - agent = mockAgent(assistant.address); + agent = mockAgent(await assistant.getAddress()); agent.id = id; agent.feePercentage = "3000"; // 30% expect(agent.isValid()).is.true; @@ -2717,15 +2755,15 @@ describe("IBosonOfferHandler", function () { const tx = await offerHandler.connect(assistant).voidOfferBatch(offersToVoid); await expect(tx) .to.emit(offerHandler, "OfferVoided") - .withArgs(offersToVoid[0], offerStruct.sellerId, assistant.address); + .withArgs(offersToVoid[0], offerStruct.sellerId, await assistant.getAddress()); await expect(tx) .to.emit(offerHandler, "OfferVoided") - .withArgs(offersToVoid[1], offerStruct.sellerId, assistant.address); + .withArgs(offersToVoid[1], offerStruct.sellerId, await assistant.getAddress()); await expect(tx) .to.emit(offerHandler, "OfferVoided") - .withArgs(offersToVoid[2], offerStruct.sellerId, assistant.address); + .withArgs(offersToVoid[2], offerStruct.sellerId, await assistant.getAddress()); }); it("should update state", async function () { @@ -2790,7 +2828,12 @@ describe("IBosonOfferHandler", function () { ); // caller is an assistant of another seller - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); // AuthToken emptyAuthToken = mockAuthToken(); @@ -2843,7 +2886,7 @@ describe("IBosonOfferHandler", function () { .createOfferBatch(offers, offerDatesList, offerDurationsList, disputeResolverIds, agentIds); offersToExtend = ["1", "3", "5"]; - newValidUntilDate = ethers.BigNumber.from(offerDatesList[4].validUntil).add("10000").toString(); // offer "5" has the highest validUntilDate so we need to set something greater + newValidUntilDate = (BigInt(offerDatesList[4].validUntil) + 10000n).toString(); // offer "5" has the highest validUntilDate so we need to set something greater for (const offerToExtend of offersToExtend) { let i = offerToExtend - 1; @@ -2856,15 +2899,15 @@ describe("IBosonOfferHandler", function () { const tx = await offerHandler.connect(assistant).extendOfferBatch(offersToExtend, newValidUntilDate); await expect(tx) .to.emit(offerHandler, "OfferExtended") - .withArgs(offersToExtend[0], offer.sellerId, newValidUntilDate, assistant.address); + .withArgs(offersToExtend[0], offer.sellerId, newValidUntilDate, await assistant.getAddress()); await expect(tx) .to.emit(offerHandler, "OfferExtended") - .withArgs(offersToExtend[1], offer.sellerId, newValidUntilDate, assistant.address); + .withArgs(offersToExtend[1], offer.sellerId, newValidUntilDate, await assistant.getAddress()); await expect(tx) .to.emit(offerHandler, "OfferExtended") - .withArgs(offersToExtend[2], offer.sellerId, newValidUntilDate, assistant.address); + .withArgs(offersToExtend[2], offer.sellerId, newValidUntilDate, await assistant.getAddress()); }); it("should update state", async function () { @@ -2921,7 +2964,12 @@ describe("IBosonOfferHandler", function () { ); // caller is an assistant of another seller - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); // AuthToken emptyAuthToken = mockAuthToken(); @@ -2946,14 +2994,14 @@ describe("IBosonOfferHandler", function () { it("New valid until date is lower than the existing valid until date", async function () { // Make the valid until date the same as the existing offer - newValidUntilDate = ethers.BigNumber.from(offers[4].validUntilDate).sub("10000").toString(); // same as that validUntilDate of offer 5 + newValidUntilDate = (BigInt(offers[4].validUntilDate) - 10000n).toString(); // same as that validUntilDate of offer 5 await expect( offerHandler.connect(assistant).extendOfferBatch(offersToExtend, newValidUntilDate) ).to.revertedWith(RevertReasons.OFFER_PERIOD_INVALID); // Make new the valid until date less than existing one - newValidUntilDate = ethers.BigNumber.from(newValidUntilDate).sub("1").toString(); // less that validUntilDate of offer 5 + newValidUntilDate = (BigInt(newValidUntilDate) - 1n).toString(); // less that validUntilDate of offer 5 // Attempt to extend the offers, expecting revert await expect( @@ -2963,7 +3011,7 @@ describe("IBosonOfferHandler", function () { it("Valid until date is not in the future", async function () { // Set until date in the past - newValidUntilDate = ethers.BigNumber.from(offerDatesList[0].validFrom - oneMonth * 6).toString(); // 6 months ago + newValidUntilDate = (BigInt(offerDatesList[0].validFrom) - oneMonth * 6n).toString(); // 6 months ago // Attempt to extend the offers, expecting revert await expect( @@ -2974,7 +3022,7 @@ describe("IBosonOfferHandler", function () { it("Offer has voucherRedeemableUntil set and new valid until date is greater than that", async function () { // create a new offer with vouchers with fix expiration date offer.id++; - offerDates.voucherRedeemableUntil = ethers.BigNumber.from(offerDates.validUntil).add(oneMonth).toString(); + offerDates.voucherRedeemableUntil = BigInt(offerDates.validUntil) + oneMonth.toString(); offerDurations.voucherValid = "0"; // only one of voucherRedeemableUntil and voucherValid can be non zero await offerHandler .connect(assistant) @@ -2982,7 +3030,7 @@ describe("IBosonOfferHandler", function () { offersToExtend.push(offer.id); // Set until date in after the offerDates.voucherRedeemableUntil - newValidUntilDate = ethers.BigNumber.from(offerDates.voucherRedeemableUntil).add(oneWeek).toString(); // one week after voucherRedeemableUntil + newValidUntilDate = BigInt(offerDates.voucherRedeemableUntil) + oneWeek.toString(); // one week after voucherRedeemableUntil // Attempt to extend the offers, expecting revert await expect( diff --git a/test/protocol/OrchestrationHandlerTest.js b/test/protocol/OrchestrationHandlerTest.js index a13413570..b1689c190 100644 --- a/test/protocol/OrchestrationHandlerTest.js +++ b/test/protocol/OrchestrationHandlerTest.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, getSigners, provider, getContractAt, MaxUint256, parseUnits } = ethers; const { assert, expect } = require("chai"); const Seller = require("../../scripts/domain/Seller"); @@ -160,14 +161,14 @@ describe("IBosonOrchestrationHandler", function () { { percentage: protocolFeePercentage, flatBoson: protocolFeeFlatBoson, buyerEscalationDepositPercentage }, ], diamondAddress: protocolDiamondAddress, - } = await setupTestEnvironment(contracts, { bosonTokenAddress: bosonToken.address })); + } = await setupTestEnvironment(contracts, { bosonTokenAddress: await bosonToken.getAddress() })); // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; + clerk = clerkDR = { address: ZeroAddress }; - [deployer] = await ethers.getSigners(); + [deployer] = await getSigners(); // Get snapshot id snapshotId = await getSnapshot(); @@ -196,10 +197,10 @@ describe("IBosonOrchestrationHandler", function () { beforeEach(async function () { // Create a valid dispute resolver disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, + await assistantDR.getAddress(), + await adminDR.getAddress(), clerkDR.address, - treasuryDR.address, + await treasuryDR.getAddress(), true ); expect(disputeResolver.isValid()).is.true; @@ -209,8 +210,8 @@ describe("IBosonOrchestrationHandler", function () { DRFeeNative = "0"; DRFeeToken = "0"; disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", DRFeeNative), - new DisputeResolverFee(bosonToken.address, "Boson", DRFeeToken), + new DisputeResolverFee(ZeroAddress, "Native", DRFeeNative), + new DisputeResolverFee(await bosonToken.getAddress(), "Boson", DRFeeToken), ]; // Make empty seller list, so every seller is allowed @@ -222,7 +223,12 @@ describe("IBosonOrchestrationHandler", function () { .createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList); // Create a valid seller, then set fields in tests directly - seller = mockSeller(assistant.address, assistant.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // How that seller looks as a returned struct @@ -244,7 +250,9 @@ describe("IBosonOrchestrationHandler", function () { // deploy mock auth token and mint one to assistant const [mockAuthERC721Contract] = await deployMockTokens(["Foreign721"]); - await configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.Lens, mockAuthERC721Contract.address); + await configHandler + .connect(deployer) + .setAuthTokenContract(AuthTokenType.Lens, await mockAuthERC721Contract.getAddress()); await mockAuthERC721Contract.connect(assistant).mint(authToken.tokenId, 1); // The first offer id @@ -296,11 +304,11 @@ describe("IBosonOrchestrationHandler", function () { await accountHandler .connect(adminDR) .addFeesToDisputeResolver(disputeResolverId, [ - new DisputeResolverFee(mockToken.address, "MockToken", DRFeeToken), + new DisputeResolverFee(await mockToken.getAddress(), "MockToken", DRFeeToken), ]); // create an offer with a mock token contract - offer.exchangeToken = mockToken.address; + offer.exchangeToken = await mockToken.getAddress(); offer.sellerDeposit = offer.price = offer.buyerCancelPenalty = "0"; offer.id++; @@ -311,11 +319,11 @@ describe("IBosonOrchestrationHandler", function () { // mint tokens to buyer and approve the protocol buyerEscalationDepositToken = applyPercentage(DRFeeToken, buyerEscalationDepositPercentage); - await mockToken.mint(buyer.address, buyerEscalationDepositToken); + await mockToken.mint(await buyer.getAddress(), buyerEscalationDepositToken); await mockToken.connect(buyer).approve(protocolDiamondAddress, buyerEscalationDepositToken); // Commit to offer and put exchange all the way to dispute - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offer.id); await exchangeHandler.connect(buyer).redeemVoucher(++exchangeId); return mockToken; @@ -348,17 +356,17 @@ describe("IBosonOrchestrationHandler", function () { escalationPeriod = disputeResolver.escalationResponsePeriod; // Deposit seller funds so the commit will succeed - const fundsToDeposit = ethers.BigNumber.from(sellerDeposit).mul(quantityAvailable); + const fundsToDeposit = BigInt(sellerDeposit) * BigInt(quantityAvailable); await fundsHandler .connect(assistant) - .depositFunds(seller.id, ethers.constants.AddressZero, fundsToDeposit, { value: fundsToDeposit }); + .depositFunds(seller.id, ZeroAddress, fundsToDeposit, { value: fundsToDeposit }); buyerId = accountId.next().value; exchangeId = "1"; // Commit to offer, creating a new exchange - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, nextOfferId, { value: price }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), nextOfferId, { value: price }); // Set time forward to the offer's voucherRedeemableFrom await setNextBlockTimestamp(Number(voucherRedeemableFrom)); @@ -375,7 +383,7 @@ describe("IBosonOrchestrationHandler", function () { .raiseAndEscalateDispute(exchangeId, { value: buyerEscalationDepositNative }) ) .to.emit(disputeHandler, "DisputeRaised") - .withArgs(exchangeId, buyerId, seller.id, buyer.address); + .withArgs(exchangeId, buyerId, seller.id, await buyer.getAddress()); }); it("should emit a DisputeEscalated event", async function () { @@ -386,12 +394,12 @@ describe("IBosonOrchestrationHandler", function () { .raiseAndEscalateDispute(exchangeId, { value: buyerEscalationDepositNative }) ) .to.emit(disputeHandler, "DisputeEscalated") - .withArgs(exchangeId, disputeResolverId, buyer.address); + .withArgs(exchangeId, disputeResolverId, await buyer.getAddress()); }); it("should update state", async function () { // Protocol balance before - const escrowBalanceBefore = await ethers.provider.getBalance(protocolDiamondAddress); + const escrowBalanceBefore = await provider.getBalance(protocolDiamondAddress); // Raise and escalate the dispute tx = await orchestrationHandler @@ -400,9 +408,9 @@ describe("IBosonOrchestrationHandler", function () { // Get the block timestamp of the confirmed tx and set escalatedDate blockNumber = tx.blockNumber; - block = await ethers.provider.getBlock(blockNumber); + block = await provider.getBlock(blockNumber); disputedDate = escalatedDate = block.timestamp.toString(); - timeout = ethers.BigNumber.from(escalatedDate).add(escalationPeriod).toString(); + timeout = (BigInt(escalatedDate) + BigInt(escalationPeriod)).toString(); dispute = new Dispute(exchangeId, DisputeState.Escalated, "0"); disputeDates = new DisputeDates(disputedDate, escalatedDate, "0", timeout); @@ -430,8 +438,8 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(response, DisputeState.Escalated, "Dispute state is incorrect"); // Protocol balance should increase for buyer escalation deposit - const escrowBalanceAfter = await ethers.provider.getBalance(protocolDiamondAddress); - expect(escrowBalanceAfter.sub(escrowBalanceBefore)).to.equal( + const escrowBalanceAfter = await provider.getBalance(protocolDiamondAddress); + expect(escrowBalanceAfter - escrowBalanceBefore).to.equal( buyerEscalationDepositNative, "Escrow balance mismatch" ); @@ -446,11 +454,11 @@ describe("IBosonOrchestrationHandler", function () { // Escalate the dispute, testing for the event await expect(orchestrationHandler.connect(buyer).raiseAndEscalateDispute(exchangeId)) .to.emit(disputeHandler, "DisputeEscalated") - .withArgs(exchangeId, disputeResolverId, buyer.address); + .withArgs(exchangeId, disputeResolverId, await buyer.getAddress()); // Protocol balance should increase for buyer escalation deposit const escrowBalanceAfter = await mockToken.balanceOf(protocolDiamondAddress); - expect(escrowBalanceAfter.sub(escrowBalanceBefore)).to.equal( + expect(escrowBalanceAfter - escrowBalanceBefore).to.equal( buyerEscalationDepositToken, "Escrow balance mismatch" ); @@ -517,8 +525,8 @@ describe("IBosonOrchestrationHandler", function () { }); it("exchange is not in a redeemed state - completed", async function () { - const blockNumber = await ethers.provider.getBlockNumber(); - const block = await ethers.provider.getBlock(blockNumber); + const blockNumber = await provider.getBlockNumber(); + const block = await provider.getBlock(blockNumber); const currentTime = block.timestamp; // Set time forward to run out the dispute period @@ -559,7 +567,7 @@ describe("IBosonOrchestrationHandler", function () { const voucherRedeemedDate = voucherStruct.redeemedDate; // Set time forward past the dispute period - await setNextBlockTimestamp(voucherRedeemedDate.add(disputePeriod).add(1).toNumber()); + await setNextBlockTimestamp(Number(voucherRedeemedDate + BigInt(disputePeriod) + 1n)); // Attempt to raise a dispute, expecting revert await expect( @@ -587,11 +595,11 @@ describe("IBosonOrchestrationHandler", function () { agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); await expect(tx) .to.emit(orchestrationHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, assistant.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await assistant.getAddress()); await expect(tx) .to.emit(orchestrationHandler, "OfferCreated") .withArgs( @@ -603,26 +611,26 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); await expect(tx) .to.emit(bosonVoucher, "RoyaltyPercentageChanged") .withArgs(voucherInitValues.royaltyPercentage); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should emit a SellerCreated and OfferCreated events with auth token", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; sellerStruct = seller.toStruct(); // Create a seller and an offer, testing for the event @@ -639,11 +647,11 @@ describe("IBosonOrchestrationHandler", function () { agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); await expect(tx) .to.emit(orchestrationHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, assistant.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, await assistant.getAddress()); await expect(tx) .to.emit(orchestrationHandler, "OfferCreated") @@ -656,26 +664,26 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); await expect(tx) .to.emit(bosonVoucher, "RoyaltyPercentageChanged") .withArgs(voucherInitValues.royaltyPercentage); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should update state", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; sellerStruct = seller.toStruct(); // Create a seller and an offer @@ -735,19 +743,19 @@ describe("IBosonOrchestrationHandler", function () { } // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); - expect(await bosonVoucher.owner()).to.equal(assistant.address, "Wrong voucher clone owner"); + expect(await bosonVoucher.owner()).to.equal(await assistant.getAddress(), "Wrong voucher clone owner"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); }); it("should update state when voucherInitValues has zero royaltyPercentage and exchangeId does not exist", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // ERC2981 Royalty fee is 0% voucherInitValues.royaltyPercentage = "0"; //0% @@ -767,8 +775,8 @@ describe("IBosonOrchestrationHandler", function () { agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -787,7 +795,7 @@ describe("IBosonOrchestrationHandler", function () { [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); // Expectations - let expectedRecipient = ethers.constants.AddressZero; //expect zero address when exchange id does not exist + let expectedRecipient = ZeroAddress; //expect zero address when exchange id does not exist let expectedRoyaltyAmount = "0"; // Zero Fee when exchange id does not exist assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); @@ -795,7 +803,7 @@ describe("IBosonOrchestrationHandler", function () { }); it("should update state when voucherInitValues has non zero royaltyPercentage and exchangeId does not exist", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // ERC2981 Royalty fee is 10% voucherInitValues.royaltyPercentage = "1000"; //10% @@ -815,8 +823,8 @@ describe("IBosonOrchestrationHandler", function () { agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -835,7 +843,7 @@ describe("IBosonOrchestrationHandler", function () { [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); // Expectations - let expectedRecipient = ethers.constants.AddressZero; //expect zero address when exchange id does not exist + let expectedRecipient = ZeroAddress; //expect zero address when exchange id does not exist let expectedRoyaltyAmount = "0"; // Zero Fee when exchange id does not exist assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); @@ -866,9 +874,9 @@ describe("IBosonOrchestrationHandler", function () { .withArgs( sellerId, sellerStruct, - calculateContractAddress(orchestrationHandler.address, "1"), + calculateContractAddress(await orchestrationHandler.getAddress(), "1"), emptyAuthTokenStruct, - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -882,7 +890,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // wrong seller id should not exist @@ -931,7 +939,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -964,13 +972,13 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); it("If exchange token is $BOSON, fee should be flat boson fee", async function () { // Prepare an offer with $BOSON as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); disputeResolutionTermsStruct = new DisputeResolutionTerms( disputeResolver.id, disputeResolver.escalationResponsePeriod, @@ -1005,7 +1013,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -1041,13 +1049,13 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); it("Should allow creation of an offer with unlimited supply", async function () { // Prepare an offer with unlimited supply - offer.quantityAvailable = ethers.constants.MaxUint256.toString(); + offer.quantityAvailable = MaxUint256.toString(); // Create a seller and an offer, testing for the event await expect( @@ -1074,7 +1082,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -1104,13 +1112,13 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // create another offer, now with bosonToken as exchange token - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller(await rando.getAddress(), await rando.getAddress(), ZeroAddress, await rando.getAddress()); contractURI = `https://ipfs.io/ipfs/QmW2WQi7j6c7UgJTarActp7tDNikE4B2qXtFCfLPdsgaTQ`; - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); offer.id = "2"; offer.sellerId = seller.id; disputeResolutionTermsStruct = new DisputeResolutionTerms( @@ -1147,7 +1155,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - rando.address + await rando.getAddress() ); }); @@ -1160,11 +1168,17 @@ describe("IBosonOrchestrationHandler", function () { firstTokenId = 1; lastTokenId = firstTokenId + reservedRangeLength - 1; const tokenIdStart = deriveTokenId(offer.id, firstTokenId); - range = new Range(tokenIdStart.toString(), reservedRangeLength.toString(), "0", "0", assistant.address); + range = new Range( + tokenIdStart.toString(), + reservedRangeLength.toString(), + "0", + "0", + await assistant.getAddress() + ); }); it("should emit a SellerCreated, OfferCreated and RangeReserved events with auth token", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; sellerStruct = seller.toStruct(); // Create a seller and a preminted offer, testing for the event @@ -1177,17 +1191,17 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), authToken, voucherInitValues, agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); await expect(tx) .to.emit(orchestrationHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, assistant.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, await assistant.getAddress()); await expect(tx) .to.emit(orchestrationHandler, "OfferCreated") @@ -1200,15 +1214,22 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); await expect(tx) .to.emit(orchestrationHandler, "RangeReserved") - .withArgs(nextOfferId, offer.sellerId, firstTokenId, lastTokenId, assistant.address, assistant.address); + .withArgs( + nextOfferId, + offer.sellerId, + firstTokenId, + lastTokenId, + await assistant.getAddress(), + await assistant.getAddress() + ); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); await expect(tx) @@ -1217,15 +1238,15 @@ describe("IBosonOrchestrationHandler", function () { await expect(tx).to.emit(bosonVoucher, "RangeReserved").withArgs(nextOfferId, range.toStruct()); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should update state", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; sellerStruct = seller.toStruct(); // Create a seller and a preminted offer @@ -1238,7 +1259,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), authToken, voucherInitValues, agentId @@ -1290,12 +1311,12 @@ describe("IBosonOrchestrationHandler", function () { } // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); - expect(await bosonVoucher.owner()).to.equal(assistant.address, "Wrong voucher clone owner"); + expect(await bosonVoucher.owner()).to.equal(await assistant.getAddress(), "Wrong voucher clone owner"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -1386,7 +1407,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), emptyAuthToken, voucherInitValues, agentId @@ -1437,7 +1458,7 @@ describe("IBosonOrchestrationHandler", function () { }); it("Caller is not the supplied admin", async function () { - seller.assistant = rando.address; + seller.assistant = await rando.getAddress(); // Attempt to create a seller and an offer, expecting revert await expect( @@ -1457,8 +1478,8 @@ describe("IBosonOrchestrationHandler", function () { }); it("Caller does not own supplied auth token", async function () { - seller.admin = ethers.constants.AddressZero; - seller.assistant = rando.address; + seller.admin = ZeroAddress; + seller.assistant = await rando.getAddress(); // Attempt to create a seller and an offer, expecting revert await expect( @@ -1478,7 +1499,7 @@ describe("IBosonOrchestrationHandler", function () { }); it("Caller is not the supplied assistant", async function () { - seller.admin = rando.address; + seller.admin = await rando.getAddress(); // Attempt to create a seller and an offer, expecting revert await expect( @@ -1498,9 +1519,9 @@ describe("IBosonOrchestrationHandler", function () { }); it("Clerk is not a zero address", async function () { - seller.admin = rando.address; - seller.assistant = rando.address; - seller.clerk = rando.address; + seller.admin = await rando.getAddress(); + seller.assistant = await rando.getAddress(); + seller.clerk = await rando.getAddress(); // Attempt to create a seller and an offer, expecting revert await expect( @@ -1538,7 +1559,7 @@ describe("IBosonOrchestrationHandler", function () { }); it("admin address is zero address and AuthTokenType is None", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Attempt to create a seller and an offer, expecting revert await expect( @@ -1559,7 +1580,7 @@ describe("IBosonOrchestrationHandler", function () { it("authToken is not unique to this seller", async function () { // Set admin == zero address because seller will be created with auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Create a seller await accountHandler.connect(assistant).createSeller(seller, authToken, voucherInitValues); @@ -1583,8 +1604,8 @@ describe("IBosonOrchestrationHandler", function () { it("Valid from date is greater than valid until date", async function () { // Reverse the from and until dates - offerDates.validFrom = ethers.BigNumber.from(Date.now() + oneMonth * 6).toString(); // 6 months from now - offerDates.validUntil = ethers.BigNumber.from(Date.now()).toString(); // now + offerDates.validFrom = (BigInt(Date.now()) + oneMonth * 6n).toString(); // 6 months from now + offerDates.validUntil = BigInt(Date.now()).toString(); // now // Attempt to create a seller and an offer, expecting revert await expect( @@ -1605,13 +1626,11 @@ describe("IBosonOrchestrationHandler", function () { it("Valid until date is not in the future", async function () { // Get the current block info - const blockNumber = await ethers.provider.getBlockNumber(); - const block = await ethers.provider.getBlock(blockNumber); + const blockNumber = await provider.getBlockNumber(); + const block = await provider.getBlock(blockNumber); // Set until date in the past - offerDates.validUntil = ethers.BigNumber.from(block.timestamp) - .sub(oneMonth * 6) - .toString(); // 6 months ago + offerDates.validUntil = (BigInt(block.timestamp) - oneMonth * 6n).toString(); // 6 months ago // Attempt to create a seller and an offer, expecting revert await expect( @@ -1632,7 +1651,7 @@ describe("IBosonOrchestrationHandler", function () { it("Buyer cancel penalty is less than item price", async function () { // Set buyer cancel penalty higher than offer price - offer.buyerCancelPenalty = ethers.BigNumber.from(offer.price).add(10).toString(); + offer.buyerCancelPenalty = BigInt(offer.price + 10).toString(); // Attempt to create a seller and an offer, expecting revert await expect( @@ -1674,7 +1693,7 @@ describe("IBosonOrchestrationHandler", function () { it("Both voucher expiration date and voucher expiration period are defined", async function () { // Set both voucherRedeemableUntil and voucherValid - offerDates.voucherRedeemableUntil = (Number(offerDates.voucherRedeemableFrom) + oneMonth).toString(); + offerDates.voucherRedeemableUntil = (BigInt(offerDates.voucherRedeemableFrom) + oneMonth).toString(); offerDurations.voucherValid = oneMonth.toString(); // Attempt to create a seller and an offer, expecting revert @@ -1763,7 +1782,7 @@ describe("IBosonOrchestrationHandler", function () { it("Dispute period is less than minimum dispute period", async function () { // Set dispute period to less than minDisputePeriod (oneWeek) - offerDurations.disputePeriod = ethers.BigNumber.from(oneWeek).sub(1000).toString(); + offerDurations.disputePeriod = (oneWeek - 1000n).toString(); // Attempt to create a seller and an offer, expecting revert await expect( @@ -1805,7 +1824,7 @@ describe("IBosonOrchestrationHandler", function () { it("Resolution period is set above the maximum resolution period", async function () { // Set dispute duration period to 0 - offerDurations.resolutionPeriod = oneMonth + 1; + offerDurations.resolutionPeriod = oneMonth + 1n; // Attempt to create a seller and an offer, expecting revert await expect( @@ -1870,10 +1889,10 @@ describe("IBosonOrchestrationHandler", function () { it.skip("Dispute resolver is not active", async function () { // create another dispute resolver, but don't activate it disputeResolver = mockDisputeResolver( - rando.address, - rando.address, - ethers.constants.AddressZero, - rando.address, + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress(), false ); disputeResolver.id = "2"; // mock id is 3 because seller was mocked first but here we are creating dispute resolver first @@ -1925,10 +1944,10 @@ describe("IBosonOrchestrationHandler", function () { it.skip("For absolute zero offer, specified dispute resolver is not active", async function () { // create another dispute resolver, but don't activate it disputeResolver = mockDisputeResolver( - rando.address, - rando.address, - ethers.constants.AddressZero, - rando.address, + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress(), false ); disputeResolver.id = "2"; // mock id is 3 because seller was mocked first but here we are creating dispute resolver first @@ -1960,7 +1979,12 @@ describe("IBosonOrchestrationHandler", function () { it("Seller is not on dispute resolver's seller allow list", async function () { // Create new seller so sellerAllowList can have an entry - const newSeller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + const newSeller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); await accountHandler.connect(rando).createSeller(newSeller, emptyAuthToken, voucherInitValues); @@ -1986,7 +2010,7 @@ describe("IBosonOrchestrationHandler", function () { it("Dispute resolver does not accept fees in the exchange token", async function () { // Set some address that is not part of dispute resolver fees - offer.exchangeToken = rando.address; + offer.exchangeToken = await rando.getAddress(); // Attempt to create a seller and an offer, expecting revert await expect( @@ -2020,7 +2044,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), emptyAuthToken, voucherInitValues, agentId @@ -2043,7 +2067,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), emptyAuthToken, voucherInitValues, agentId @@ -2053,7 +2077,7 @@ describe("IBosonOrchestrationHandler", function () { it("Reserved range length is greater than maximum allowed range length", async function () { // Set reserved range length to more than maximum allowed range length - let reservedRangeLength = ethers.BigNumber.from(2).pow(64).sub(1); + let reservedRangeLength = 2n ** 64n - 1n; // Attempt to create a seller and an offer, expecting revert await expect( @@ -2066,7 +2090,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), emptyAuthToken, voucherInitValues, agentId @@ -2086,14 +2110,14 @@ describe("IBosonOrchestrationHandler", function () { agentId = "2"; // argument sent to contract for createAgent will be ignored // Create a valid agent, then set fields in tests directly - agent = mockAgent(other1.address); + agent = mockAgent(await other1.getAddress()); agent.id = agentId; expect(agent.isValid()).is.true; // Create an agent await accountHandler.connect(rando).createAgent(agent); - agentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + agentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = agentFee; offerFeesStruct = offerFees.toStruct(); }); @@ -2118,9 +2142,9 @@ describe("IBosonOrchestrationHandler", function () { .withArgs( seller.id, sellerStruct, - calculateContractAddress(orchestrationHandler.address, "1"), + calculateContractAddress(await orchestrationHandler.getAddress(), "1"), emptyAuthTokenStruct, - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -2134,7 +2158,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -2144,7 +2168,7 @@ describe("IBosonOrchestrationHandler", function () { let agentId = "16"; // Seller can have admin address OR auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Attempt to Create an offer, expecting revert await expect( @@ -2168,7 +2192,7 @@ describe("IBosonOrchestrationHandler", function () { let id = "3"; // argument sent to contract for createAgent will be ignored // Create a valid agent, then set fields in tests directly - agent = mockAgent(assistant.address); + agent = mockAgent(await assistant.getAddress()); agent.id = id; agent.feePercentage = "3000"; // 30% expect(agent.isValid()).is.true; @@ -2210,7 +2234,11 @@ describe("IBosonOrchestrationHandler", function () { seller.id = "2"; // "1" is dispute resolver offerIds = ["1"]; - condition = mockCondition({ tokenAddress: other2.address, tokenType: TokenType.MultiToken, tokenId: "5150" }); + condition = mockCondition({ + tokenAddress: await other2.getAddress(), + tokenType: TokenType.MultiToken, + tokenId: "5150", + }); expect(condition.isValid()).to.be.true; group = new Group(nextGroupId, seller.id, offerIds); @@ -2242,7 +2270,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -2256,7 +2284,7 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(eventGroupCreated.groupId.toString(), group.id, "Group Id is incorrect"); assert.equal(eventGroupCreated.sellerId.toString(), group.sellerId, "Seller Id is incorrect"); - assert.equal(eventGroupCreated.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal(eventGroupCreated.executedBy.toString(), await assistant.getAddress(), "Executed by is incorrect"); assert.equal(groupInstance.toString(), group.toString(), "Group struct is incorrect"); }); @@ -2331,7 +2359,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -2369,7 +2397,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -2388,7 +2416,7 @@ describe("IBosonOrchestrationHandler", function () { it("If exchange token is $BOSON, fee should be flat boson fee", async function () { // Prepare an offer with $BOSON as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); disputeResolutionTermsStruct = new DisputeResolutionTerms( disputeResolver.id, disputeResolver.escalationResponsePeriod, @@ -2414,7 +2442,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -2441,13 +2469,13 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); it("Should allow creation of an offer with unlimited supply", async function () { // Prepare an absolute zero offer - offer.quantityAvailable = ethers.constants.MaxUint256.toString(); + offer.quantityAvailable = MaxUint256.toString(); // Create an offer with condition, testing for the events await expect( @@ -2465,7 +2493,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -2486,11 +2514,11 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // create another offer, now with bosonToken as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); offer.id = "2"; disputeResolutionTermsStruct = new DisputeResolutionTerms( disputeResolver.id, @@ -2517,7 +2545,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -2540,14 +2568,14 @@ describe("IBosonOrchestrationHandler", function () { agentId = "3"; // argument sent to contract for createAgent will be ignored // Create a valid agent, then set fields in tests directly - agent = mockAgent(other1.address); + agent = mockAgent(await other1.getAddress()); agent.id = agentId; expect(agent.isValid()).is.true; // Create an agent await accountHandler.connect(rando).createAgent(agent); - agentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + agentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = agentFee; offerFeesStruct = offerFees.toStruct(); }); @@ -2570,7 +2598,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -2584,7 +2612,11 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(eventGroupCreated.groupId.toString(), group.id, "Group Id is incorrect"); assert.equal(eventGroupCreated.sellerId.toString(), group.sellerId, "Seller Id is incorrect"); - assert.equal(eventGroupCreated.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal( + eventGroupCreated.executedBy.toString(), + await assistant.getAddress(), + "Executed by is incorrect" + ); assert.equal(groupInstance.toString(), group.toString(), "Group struct is incorrect"); }); }); @@ -2599,11 +2631,17 @@ describe("IBosonOrchestrationHandler", function () { lastTokenId = firstTokenId + reservedRangeLength - 1; // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); const tokenIdStart = deriveTokenId(offer.id, firstTokenId); - range = new Range(tokenIdStart.toString(), reservedRangeLength.toString(), "0", "0", bosonVoucher.address); + range = new Range( + tokenIdStart.toString(), + reservedRangeLength.toString(), + "0", + "0", + await bosonVoucher.getAddress() + ); }); it("should emit an OfferCreated, a GroupCreated and a RangeReserved events", async function () { @@ -2617,7 +2655,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - bosonVoucher.address, + await bosonVoucher.getAddress(), condition, agentId ); @@ -2634,13 +2672,20 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // RangeReserved event (on protocol contract) await expect(tx) .to.emit(orchestrationHandler, "RangeReserved") - .withArgs(nextOfferId, offer.sellerId, firstTokenId, lastTokenId, bosonVoucher.address, assistant.address); + .withArgs( + nextOfferId, + offer.sellerId, + firstTokenId, + lastTokenId, + await bosonVoucher.getAddress(), + await assistant.getAddress() + ); // Events with structs that contain arrays must be tested differently const txReceipt = await tx.wait(); @@ -2653,7 +2698,11 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(eventGroupCreated.groupId.toString(), group.id, "Group Id is incorrect"); assert.equal(eventGroupCreated.sellerId.toString(), group.sellerId, "Seller Id is incorrect"); - assert.equal(eventGroupCreated.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal( + eventGroupCreated.executedBy.toString(), + await assistant.getAddress(), + "Executed by is incorrect" + ); assert.equal(groupInstance.toString(), group.toString(), "Group struct is incorrect"); // RangeReserved event (on voucher contract) @@ -2670,7 +2719,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - bosonVoucher.address, + await bosonVoucher.getAddress(), condition, agentId ); @@ -2779,7 +2828,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - bosonVoucher.address, + await bosonVoucher.getAddress(), condition, agentId ) @@ -2820,7 +2869,7 @@ describe("IBosonOrchestrationHandler", function () { it("Condition 'Threshold' has zero token contract address", async function () { condition.method = EvaluationMethod.Threshold; - condition.tokenAddress = ethers.constants.AddressZero; + condition.tokenAddress = ZeroAddress; // Attempt to create an offer with condition, expecting revert await expect( @@ -2832,7 +2881,7 @@ describe("IBosonOrchestrationHandler", function () { it("Condition 'SpecificToken' has has zero token contract address", async function () { condition.method = EvaluationMethod.SpecificToken; - condition.tokenAddress = ethers.constants.AddressZero; + condition.tokenAddress = ZeroAddress; // Attempt to create an offer with condition, expecting revert await expect( @@ -2857,14 +2906,14 @@ describe("IBosonOrchestrationHandler", function () { // Mock offer, offerDates and offerDurations ({ offer, offerDates, offerDurations } = await mockOffer()); offer.id = `${i + 1}`; - offer.price = ethers.utils.parseUnits(`${1.5 + i * 1}`, "ether").toString(); - offer.sellerDeposit = ethers.utils.parseUnits(`${0.25 + i * 0.1}`, "ether").toString(); - offer.buyerCancelPenalty = ethers.utils.parseUnits(`${0.05 + i * 0.1}`, "ether").toString(); + offer.price = parseUnits(`${1.5 + i * 1}`, "ether").toString(); + offer.sellerDeposit = parseUnits(`${0.25 + i * 0.1}`, "ether").toString(); + offer.buyerCancelPenalty = parseUnits(`${0.05 + i * 0.1}`, "ether").toString(); offer.quantityAvailable = `${(i + 1) * 2}`; offer.sellerId = seller.id; // "2" is dispute resolver - offerDates.validFrom = ethers.BigNumber.from(Date.now() + oneMonth * i).toString(); - offerDates.validUntil = ethers.BigNumber.from(Date.now() + oneMonth * 6 * (i + 1)).toString(); + offerDates.validFrom = (BigInt(Date.now()) + oneMonth * BigInt(i)).toString(); + offerDates.validUntil = (BigInt(Date.now()) + oneMonth * 6n * BigInt(i + 1)).toString(); disputeResolver.id = "1"; agentId = "0"; @@ -2889,7 +2938,7 @@ describe("IBosonOrchestrationHandler", function () { condition = mockCondition({ tokenType: TokenType.MultiToken, - tokenAddress: other2.address, + tokenAddress: await other2.getAddress(), tokenId: "5150", maxCommits: "3", }); @@ -2933,7 +2982,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -3021,7 +3070,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -3059,7 +3108,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -3078,7 +3127,7 @@ describe("IBosonOrchestrationHandler", function () { it("If exchange token is $BOSON, fee should be flat boson fee", async function () { // Prepare an offer with $BOSON as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); disputeResolutionTermsStruct = new DisputeResolutionTerms( disputeResolver.id, disputeResolver.escalationResponsePeriod, @@ -3104,7 +3153,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -3131,13 +3180,13 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); it("Should allow creation of an offer with unlimited supply", async function () { // Prepare an absolute zero offer - offer.quantityAvailable = ethers.constants.MaxUint256.toString(); + offer.quantityAvailable = MaxUint256.toString(); // Create an offer, add it to the group, testing for the events await expect( @@ -3155,7 +3204,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -3176,11 +3225,11 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // create another offer, now with bosonToken as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); offer.id++; disputeResolutionTermsStruct = new DisputeResolutionTerms( disputeResolver.id, @@ -3207,7 +3256,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -3230,14 +3279,14 @@ describe("IBosonOrchestrationHandler", function () { agentId = "3"; // argument sent to contract for createAgent will be ignored // Create a valid agent, then set fields in tests directly - agent = mockAgent(other1.address); + agent = mockAgent(await other1.getAddress()); agent.id = agentId; expect(agent.isValid()).is.true; // Create an agent await accountHandler.connect(rando).createAgent(agent); - agentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + agentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = agentFee; offerFeesStruct = offerFees.toStruct(); }); @@ -3260,7 +3309,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -3287,11 +3336,17 @@ describe("IBosonOrchestrationHandler", function () { firstTokenId = 1; lastTokenId = firstTokenId + reservedRangeLength - 1; const tokenIdStart = deriveTokenId(offer.id, firstTokenId); - range = new Range(tokenIdStart.toString(), reservedRangeLength.toString(), "0", "0", assistant.address); + range = new Range( + tokenIdStart.toString(), + reservedRangeLength.toString(), + "0", + "0", + await assistant.getAddress() + ); // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); }); it("should emit an OfferCreated, a GroupUpdated and a RangeReserved events", async function () { @@ -3304,7 +3359,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), nextGroupId, agentId ); @@ -3321,13 +3376,20 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // RangeReserved event (on protocol contract) await expect(tx) .to.emit(orchestrationHandler, "RangeReserved") - .withArgs(nextOfferId, offer.sellerId, firstTokenId, lastTokenId, assistant.address, assistant.address); + .withArgs( + nextOfferId, + offer.sellerId, + firstTokenId, + lastTokenId, + await assistant.getAddress(), + await assistant.getAddress() + ); // Events with structs that contain arrays must be tested differently const txReceipt = await tx.wait(); @@ -3356,7 +3418,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), nextGroupId, agentId ); @@ -3456,7 +3518,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), nextGroupId, agentId ) @@ -3529,7 +3591,7 @@ describe("IBosonOrchestrationHandler", function () { nextTwinId = "1"; // Create a valid twin. - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); twin.sellerId = seller.id; // How that twin looks as a returned struct twinStruct = twin.toStruct(); @@ -3538,7 +3600,7 @@ describe("IBosonOrchestrationHandler", function () { await accountHandler.connect(assistant).createSeller(seller, emptyAuthToken, voucherInitValues); // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler }); it("should emit an OfferCreated, a TwinCreated and a BundleCreated events", async function () { @@ -3559,7 +3621,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -3661,7 +3723,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -3714,7 +3776,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -3747,7 +3809,7 @@ describe("IBosonOrchestrationHandler", function () { it("If exchange token is $BOSON, fee should be flat boson fee", async function () { // Prepare an offer with $BOSON as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); disputeResolutionTermsStruct = new DisputeResolutionTerms( disputeResolver.id, disputeResolver.escalationResponsePeriod, @@ -3773,7 +3835,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -3800,15 +3862,15 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); it("Should allow creation of an offer with unlimited supply", async function () { // Prepare an offer with unlimited supply - offer.quantityAvailable = ethers.constants.MaxUint256.toString(); + offer.quantityAvailable = MaxUint256.toString(); // Twin supply should be unlimited as well - twin.supplyAvailable = ethers.constants.MaxUint256.toString(); + twin.supplyAvailable = MaxUint256.toString(); // Create an offer, a twin and a bundle, testing for the events await expect( @@ -3826,7 +3888,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -3847,11 +3909,11 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // create another offer, now with bosonToken as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); offer.id = "2"; disputeResolutionTermsStruct = new DisputeResolutionTerms( disputeResolver.id, @@ -3878,7 +3940,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -3901,14 +3963,14 @@ describe("IBosonOrchestrationHandler", function () { agentId = "3"; // argument sent to contract for createAgent will be ignored // Create a valid agent, then set fields in tests directly - agent = mockAgent(other1.address); + agent = mockAgent(await other1.getAddress()); agent.id = agentId; expect(agent.isValid()).is.true; // Create an agent await accountHandler.connect(rando).createAgent(agent); - agentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + agentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = agentFee; offerFeesStruct = offerFees.toStruct(); }); @@ -3931,7 +3993,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -3969,11 +4031,17 @@ describe("IBosonOrchestrationHandler", function () { lastTokenId = firstTokenId + reservedRangeLength - 1; // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); const tokenIdStart = deriveTokenId(offer.id, firstTokenId); - range = new Range(tokenIdStart.toString(), reservedRangeLength.toString(), "0", "0", bosonVoucher.address); + range = new Range( + tokenIdStart.toString(), + reservedRangeLength.toString(), + "0", + "0", + await bosonVoucher.getAddress() + ); }); it("should emit an OfferCreated, a TwinCreated, a BundleCreated and a RangeReserved events", async function () { @@ -3986,7 +4054,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - bosonVoucher.address, + await bosonVoucher.getAddress(), twin, agentId ); @@ -4003,13 +4071,20 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // RangeReserved event (on protocol contract) await expect(tx) .to.emit(orchestrationHandler, "RangeReserved") - .withArgs(nextOfferId, offer.sellerId, firstTokenId, lastTokenId, bosonVoucher.address, assistant.address); + .withArgs( + nextOfferId, + offer.sellerId, + firstTokenId, + lastTokenId, + await bosonVoucher.getAddress(), + await assistant.getAddress() + ); // Events with structs that contain arrays must be tested differently const txReceipt = await tx.wait(); @@ -4048,7 +4123,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - bosonVoucher.address, + await bosonVoucher.getAddress(), twin, agentId ); @@ -4175,7 +4250,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - bosonVoucher.address, + await bosonVoucher.getAddress(), twin, agentId ) @@ -4184,10 +4259,10 @@ describe("IBosonOrchestrationHandler", function () { it("should revert if protocol is not approved to transfer the ERC20 token", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 0); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 0); // approving the twin handler //ERC20 token address - twin.tokenAddress = bosonToken.address; + twin.tokenAddress = await bosonToken.getAddress(); await expect( orchestrationHandler @@ -4198,7 +4273,7 @@ describe("IBosonOrchestrationHandler", function () { it("should revert if protocol is not approved to transfer the ERC721 token", async function () { //ERC721 token address - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); await expect( orchestrationHandler @@ -4209,7 +4284,7 @@ describe("IBosonOrchestrationHandler", function () { it("should revert if protocol is not approved to transfer the ERC1155 token", async function () { //ERC1155 token address - twin.tokenAddress = foreign1155.address; + twin.tokenAddress = await foreign1155.getAddress(); await expect( orchestrationHandler @@ -4220,7 +4295,7 @@ describe("IBosonOrchestrationHandler", function () { context("Token address is unsupported", async function () { it("Token address is a zero address", async function () { - twin.tokenAddress = ethers.constants.AddressZero; + twin.tokenAddress = ZeroAddress; await expect( orchestrationHandler @@ -4230,7 +4305,7 @@ describe("IBosonOrchestrationHandler", function () { }); it("Token address is a contract address that does not support the isApprovedForAll", async function () { - twin.tokenAddress = twinHandler.address; + twin.tokenAddress = await twinHandler.getAddress(); await expect( orchestrationHandler @@ -4240,7 +4315,7 @@ describe("IBosonOrchestrationHandler", function () { }); it("Token address is a contract that reverts from a fallback method", async function () { - twin.tokenAddress = fallbackError.address; + twin.tokenAddress = await fallbackError.getAddress(); await expect( orchestrationHandler @@ -4261,7 +4336,11 @@ describe("IBosonOrchestrationHandler", function () { // Required constructor params for Group offerIds = ["1"]; - condition = mockCondition({ tokenType: TokenType.MultiToken, tokenAddress: other2.address, tokenId: "5150" }); + condition = mockCondition({ + tokenType: TokenType.MultiToken, + tokenAddress: await other2.getAddress(), + tokenId: "5150", + }); expect(condition.isValid()).to.be.true; group = new Group(nextGroupId, seller.id, offerIds); @@ -4288,7 +4367,7 @@ describe("IBosonOrchestrationHandler", function () { nextTwinId = "1"; // Create a valid twin. - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); twin.sellerId = seller.id; // How that twin looks as a returned struct @@ -4298,7 +4377,7 @@ describe("IBosonOrchestrationHandler", function () { await accountHandler.connect(assistant).createSeller(seller, emptyAuthToken, voucherInitValues); // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler }); it("should emit an OfferCreated, a GroupCreated, a TwinCreated and a BundleCreated events", async function () { @@ -4327,7 +4406,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -4474,7 +4553,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -4545,7 +4624,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -4588,7 +4667,7 @@ describe("IBosonOrchestrationHandler", function () { it("If exchange token is $BOSON, fee should be flat boson fee", async function () { // Prepare an offer with $BOSON as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); disputeResolutionTermsStruct = new DisputeResolutionTerms( disputeResolver.id, disputeResolver.escalationResponsePeriod, @@ -4622,7 +4701,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -4657,15 +4736,15 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); it("Should allow creation of an offer with unlimited supply", async function () { // Prepare an offer with unlimited supply - offer.quantityAvailable = ethers.constants.MaxUint256.toString(); + offer.quantityAvailable = MaxUint256.toString(); // Twin supply should be unlimited as well - twin.supplyAvailable = ethers.constants.MaxUint256.toString(); + twin.supplyAvailable = MaxUint256.toString(); // Create an offer with condition, twin and bundle testing for the events await expect( @@ -4691,7 +4770,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -4720,11 +4799,11 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // create another offer, now with bosonToken as exchange token - offer.exchangeToken = bosonToken.address; + offer.exchangeToken = await bosonToken.getAddress(); offer.id = "2"; disputeResolutionTermsStruct = new DisputeResolutionTerms( disputeResolver.id, @@ -4759,7 +4838,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); }); @@ -4790,7 +4869,7 @@ describe("IBosonOrchestrationHandler", function () { agentId = "3"; // argument sent to contract for createAgent will be ignored // Create a valid agent, then set fields in tests directly - agent = mockAgent(other1.address); + agent = mockAgent(await other1.getAddress()); agent.id = agentId; agent.feePercentage = "3000"; // 30% expect(agent.isValid()).is.true; @@ -4798,7 +4877,7 @@ describe("IBosonOrchestrationHandler", function () { // Create an agent await accountHandler.connect(rando).createAgent(agent); - agentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + agentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = agentFee; offerFeesStruct = offerFees.toStruct(); }); @@ -4829,7 +4908,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -4876,11 +4955,17 @@ describe("IBosonOrchestrationHandler", function () { firstTokenId = 1; lastTokenId = firstTokenId + reservedRangeLength - 1; const tokenIdStart = deriveTokenId(offer.id, firstTokenId); - range = new Range(tokenIdStart.toString(), reservedRangeLength.toString(), "0", "0", assistant.address); + range = new Range( + tokenIdStart.toString(), + reservedRangeLength.toString(), + "0", + "0", + await assistant.getAddress() + ); // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); }); it("should emit an OfferCreated, a GroupCreated, a TwinCreated, a BundleCreated and a RangeReserved events", async function () { @@ -4893,7 +4978,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), condition, twin, agentId @@ -4911,13 +4996,20 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // RangeReserved event (on protocol contract) await expect(tx) .to.emit(orchestrationHandler, "RangeReserved") - .withArgs(nextOfferId, offer.sellerId, firstTokenId, lastTokenId, assistant.address, assistant.address); + .withArgs( + nextOfferId, + offer.sellerId, + firstTokenId, + lastTokenId, + await assistant.getAddress(), + await assistant.getAddress() + ); // Events with structs that contain arrays must be tested differently const txReceipt = await tx.wait(); @@ -4966,7 +5058,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), condition, twin, agentId @@ -5165,7 +5257,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), condition, twin, agentId @@ -5185,7 +5277,11 @@ describe("IBosonOrchestrationHandler", function () { // Required constructor params for Group offerIds = ["1"]; - condition = mockCondition({ tokenType: TokenType.MultiToken, tokenAddress: other2.address, tokenId: "5150" }); + condition = mockCondition({ + tokenType: TokenType.MultiToken, + tokenAddress: await other2.getAddress(), + tokenId: "5150", + }); expect(condition.isValid()).to.be.true; group = new Group(nextGroupId, seller.id, offerIds); @@ -5212,12 +5308,12 @@ describe("IBosonOrchestrationHandler", function () { agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); // SellerCreated and OfferCreated events await expect(tx) .to.emit(orchestrationHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, assistant.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await assistant.getAddress()); await expect(tx) .to.emit(orchestrationHandler, "OfferCreated") @@ -5230,7 +5326,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -5247,18 +5343,18 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(groupInstance.toString(), group.toString(), "Group struct is incorrect"); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); await expect(tx) .to.emit(bosonVoucher, "RoyaltyPercentageChanged") .withArgs(voucherInitValues.royaltyPercentage); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should update state", async function () { @@ -5339,12 +5435,12 @@ describe("IBosonOrchestrationHandler", function () { } // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); - expect(await bosonVoucher.owner()).to.equal(assistant.address, "Wrong voucher clone owner"); + expect(await bosonVoucher.owner()).to.equal(await assistant.getAddress(), "Wrong voucher clone owner"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -5371,8 +5467,8 @@ describe("IBosonOrchestrationHandler", function () { ); // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -5391,7 +5487,7 @@ describe("IBosonOrchestrationHandler", function () { [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); // Expectations - let expectedRecipient = ethers.constants.AddressZero; //expect zero address when exchange id does not exist + let expectedRecipient = ZeroAddress; //expect zero address when exchange id does not exist let expectedRoyaltyAmount = "0"; // Zero Fee when exchange id does not exist assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); @@ -5419,8 +5515,8 @@ describe("IBosonOrchestrationHandler", function () { ); // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -5439,7 +5535,7 @@ describe("IBosonOrchestrationHandler", function () { [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); // Expectations - let expectedRecipient = ethers.constants.AddressZero; //expect zero address when exchange id does not exist + let expectedRecipient = ZeroAddress; //expect zero address when exchange id does not exist let expectedRoyaltyAmount = "0"; // Zero Fee when exchange id does not exist assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); @@ -5472,9 +5568,9 @@ describe("IBosonOrchestrationHandler", function () { .withArgs( sellerId, sellerStruct, - calculateContractAddress(orchestrationHandler.address, "1"), + calculateContractAddress(await orchestrationHandler.getAddress(), "1"), emptyAuthTokenStruct, - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -5488,7 +5584,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -5517,14 +5613,14 @@ describe("IBosonOrchestrationHandler", function () { agentId = "2"; // argument sent to contract for createAgent will be ignored // Create a valid agent, then set fields in tests directly - agent = mockAgent(other1.address); + agent = mockAgent(await other1.getAddress()); agent.id = agentId; expect(agent.isValid()).is.true; // Create an agent await accountHandler.connect(rando).createAgent(agent); - agentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + agentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = agentFee; offerFeesStruct = offerFees.toStruct(); }); @@ -5551,9 +5647,9 @@ describe("IBosonOrchestrationHandler", function () { .withArgs( seller.id, sellerStruct, - calculateContractAddress(orchestrationHandler.address, "1"), + calculateContractAddress(await orchestrationHandler.getAddress(), "1"), emptyAuthTokenStruct, - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -5567,7 +5663,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -5594,7 +5690,13 @@ describe("IBosonOrchestrationHandler", function () { firstTokenId = 1; lastTokenId = firstTokenId + reservedRangeLength - 1; const tokenIdStart = deriveTokenId(offer.id, firstTokenId); - range = new Range(tokenIdStart.toString(), reservedRangeLength.toString(), "0", "0", assistant.address); + range = new Range( + tokenIdStart.toString(), + reservedRangeLength.toString(), + "0", + "0", + await assistant.getAddress() + ); }); it("should emit a SellerCreated, an OfferCreated, a GroupCreated and a RangeReserved event", async function () { @@ -5608,19 +5710,25 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), condition, emptyAuthToken, voucherInitValues, agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); // SellerCreated and OfferCreated RangeReserved events await expect(tx) .to.emit(orchestrationHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, assistant.address); + .withArgs( + seller.id, + sellerStruct, + expectedCloneAddress, + emptyAuthTokenStruct, + await assistant.getAddress() + ); await expect(tx) .to.emit(orchestrationHandler, "OfferCreated") @@ -5633,12 +5741,19 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); await expect(tx) .to.emit(orchestrationHandler, "RangeReserved") - .withArgs(nextOfferId, offer.sellerId, firstTokenId, lastTokenId, assistant.address, assistant.address); + .withArgs( + nextOfferId, + offer.sellerId, + firstTokenId, + lastTokenId, + await assistant.getAddress(), + await assistant.getAddress() + ); // Events with structs that contain arrays must be tested differently const txReceipt = await tx.wait(); @@ -5654,7 +5769,7 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(groupInstance.toString(), group.toString(), "Group struct is incorrect"); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); await expect(tx) @@ -5663,11 +5778,11 @@ describe("IBosonOrchestrationHandler", function () { await expect(tx).to.emit(bosonVoucher, "RangeReserved").withArgs(nextOfferId, range.toStruct()); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should update state", async function () { @@ -5681,7 +5796,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), condition, emptyAuthToken, voucherInitValues, @@ -5753,12 +5868,12 @@ describe("IBosonOrchestrationHandler", function () { } // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); - expect(await bosonVoucher.owner()).to.equal(assistant.address, "Wrong voucher clone owner"); + expect(await bosonVoucher.owner()).to.equal(await assistant.getAddress(), "Wrong voucher clone owner"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -5874,7 +5989,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), condition, emptyAuthToken, voucherInitValues, @@ -5906,7 +6021,7 @@ describe("IBosonOrchestrationHandler", function () { nextTwinId = "1"; // Create a valid twin. - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); twin.sellerId = seller.id; // How that twin looks as a returned struct @@ -5915,7 +6030,7 @@ describe("IBosonOrchestrationHandler", function () { it("should emit a SellerCreated, an OfferCreated, a TwinCreated and a BundleCreated event", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, an offer with condition and a twin with bundle, testing for the events const tx = await orchestrationHandler @@ -5932,12 +6047,12 @@ describe("IBosonOrchestrationHandler", function () { agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); // SellerCreated and OfferCreated events await expect(tx) .to.emit(orchestrationHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, assistant.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await assistant.getAddress()); await expect(tx) .to.emit(orchestrationHandler, "OfferCreated") @@ -5950,7 +6065,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -5964,7 +6079,7 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(eventTwinCreated.twinId.toString(), twin.id, "Twin Id is incorrect"); assert.equal(eventTwinCreated.sellerId.toString(), twin.sellerId, "Seller Id is incorrect"); - assert.equal(eventTwinCreated.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal(eventTwinCreated.executedBy.toString(), await assistant.getAddress(), "Executed by is incorrect"); assert.equal(twinInstance.toString(), twin.toString(), "Twin struct is incorrect"); // BundleCreated event @@ -5975,27 +6090,31 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(eventBundleCreated.bundleId.toString(), bundle.id, "Bundle Id is incorrect"); assert.equal(eventBundleCreated.sellerId.toString(), bundle.sellerId, "Seller Id is incorrect"); - assert.equal(eventBundleCreated.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal( + eventBundleCreated.executedBy.toString(), + await assistant.getAddress(), + "Executed by is incorrect" + ); assert.equal(bundleInstance.toString(), bundle.toString(), "Bundle struct is incorrect"); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); await expect(tx) .to.emit(bosonVoucher, "RoyaltyPercentageChanged") .withArgs(voucherInitValues.royaltyPercentage); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should update state", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, an offer with condition and a twin with bundle, testing for the events await orchestrationHandler @@ -6077,12 +6196,12 @@ describe("IBosonOrchestrationHandler", function () { } // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); - expect(await bosonVoucher.owner()).to.equal(assistant.address, "Wrong voucher clone owner"); + expect(await bosonVoucher.owner()).to.equal(await assistant.getAddress(), "Wrong voucher clone owner"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -6094,7 +6213,7 @@ describe("IBosonOrchestrationHandler", function () { expect(voucherInitValues.isValid()).is.true; // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, an offer with condition and a twin with bundle, testing for the events await orchestrationHandler @@ -6112,8 +6231,8 @@ describe("IBosonOrchestrationHandler", function () { ); // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -6132,7 +6251,7 @@ describe("IBosonOrchestrationHandler", function () { [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); // Expectations - let expectedRecipient = ethers.constants.AddressZero; //expect zero address when exchange id does not exist + let expectedRecipient = ZeroAddress; //expect zero address when exchange id does not exist let expectedRoyaltyAmount = "0"; // Zero Fee when exchange id does not exist assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); @@ -6145,7 +6264,7 @@ describe("IBosonOrchestrationHandler", function () { expect(voucherInitValues.isValid()).is.true; // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, an offer with condition and a twin with bundle, testing for the events await orchestrationHandler @@ -6163,8 +6282,8 @@ describe("IBosonOrchestrationHandler", function () { ); // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -6183,7 +6302,7 @@ describe("IBosonOrchestrationHandler", function () { [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); // Expectations - let expectedRecipient = ethers.constants.AddressZero; //expect zero address when exchange id does not exist + let expectedRecipient = ZeroAddress; //expect zero address when exchange id does not exist let expectedRoyaltyAmount = "0"; // Zero Fee when exchange id does not exist assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); @@ -6192,7 +6311,7 @@ describe("IBosonOrchestrationHandler", function () { it("should ignore any provided ids and assign the next available", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler const sellerId = seller.id; seller.id = "333"; @@ -6220,9 +6339,9 @@ describe("IBosonOrchestrationHandler", function () { .withArgs( sellerId, sellerStruct, - calculateContractAddress(orchestrationHandler.address, "1"), + calculateContractAddress(await orchestrationHandler.getAddress(), "1"), emptyAuthTokenStruct, - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -6236,7 +6355,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -6280,21 +6399,21 @@ describe("IBosonOrchestrationHandler", function () { agentId = "2"; // argument sent to contract for createAgent will be ignored // Create a valid agent, then set fields in tests directly - agent = mockAgent(other1.address); + agent = mockAgent(await other1.getAddress()); agent.id = agentId; expect(agent.isValid()).is.true; // Create an agent await accountHandler.connect(rando).createAgent(agent); - agentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + agentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = agentFee; offerFeesStruct = offerFees.toStruct(); }); it("should emit a SellerCreated, an OfferCreated, a TwinCreated and a BundleCreated event", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, an offer with condition and a twin with bundle, testing for the events const tx = await orchestrationHandler @@ -6317,9 +6436,9 @@ describe("IBosonOrchestrationHandler", function () { .withArgs( seller.id, sellerStruct, - calculateContractAddress(orchestrationHandler.address, "1"), + calculateContractAddress(await orchestrationHandler.getAddress(), "1"), emptyAuthTokenStruct, - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -6333,7 +6452,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -6347,7 +6466,11 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(eventTwinCreated.twinId.toString(), twin.id, "Twin Id is incorrect"); assert.equal(eventTwinCreated.sellerId.toString(), twin.sellerId, "Seller Id is incorrect"); - assert.equal(eventTwinCreated.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal( + eventTwinCreated.executedBy.toString(), + await assistant.getAddress(), + "Executed by is incorrect" + ); assert.equal(twinInstance.toString(), twin.toString(), "Twin struct is incorrect"); // BundleCreated event @@ -6358,7 +6481,11 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(eventBundleCreated.bundleId.toString(), bundle.id, "Bundle Id is incorrect"); assert.equal(eventBundleCreated.sellerId.toString(), bundle.sellerId, "Seller Id is incorrect"); - assert.equal(eventBundleCreated.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal( + eventBundleCreated.executedBy.toString(), + await assistant.getAddress(), + "Executed by is incorrect" + ); assert.equal(bundleInstance.toString(), bundle.toString(), "Bundle struct is incorrect"); }); }); @@ -6372,12 +6499,18 @@ describe("IBosonOrchestrationHandler", function () { firstTokenId = 1; lastTokenId = firstTokenId + reservedRangeLength - 1; const tokenIdStart = deriveTokenId(offer.id, firstTokenId); - range = new Range(tokenIdStart.toString(), reservedRangeLength.toString(), "0", "0", assistant.address); + range = new Range( + tokenIdStart.toString(), + reservedRangeLength.toString(), + "0", + "0", + await assistant.getAddress() + ); }); it("should emit a SellerCreated, an OfferCreated, a TwinCreated, a BundleCreated and RangeReserved event", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, a preminted offer with condition and a twin with bundle, testing for the events const tx = await orchestrationHandler @@ -6389,19 +6522,25 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), twin, emptyAuthToken, voucherInitValues, agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); // SellerCreated, OfferCreated and RangeReserved events await expect(tx) .to.emit(orchestrationHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, assistant.address); + .withArgs( + seller.id, + sellerStruct, + expectedCloneAddress, + emptyAuthTokenStruct, + await assistant.getAddress() + ); await expect(tx) .to.emit(orchestrationHandler, "OfferCreated") @@ -6414,12 +6553,19 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); await expect(tx) .to.emit(orchestrationHandler, "RangeReserved") - .withArgs(nextOfferId, offer.sellerId, firstTokenId, lastTokenId, assistant.address, assistant.address); + .withArgs( + nextOfferId, + offer.sellerId, + firstTokenId, + lastTokenId, + await assistant.getAddress(), + await assistant.getAddress() + ); // Events with structs that contain arrays must be tested differently const txReceipt = await tx.wait(); @@ -6432,7 +6578,11 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(eventTwinCreated.twinId.toString(), twin.id, "Twin Id is incorrect"); assert.equal(eventTwinCreated.sellerId.toString(), twin.sellerId, "Seller Id is incorrect"); - assert.equal(eventTwinCreated.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal( + eventTwinCreated.executedBy.toString(), + await assistant.getAddress(), + "Executed by is incorrect" + ); assert.equal(twinInstance.toString(), twin.toString(), "Twin struct is incorrect"); // BundleCreated event @@ -6443,11 +6593,15 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(eventBundleCreated.bundleId.toString(), bundle.id, "Bundle Id is incorrect"); assert.equal(eventBundleCreated.sellerId.toString(), bundle.sellerId, "Seller Id is incorrect"); - assert.equal(eventBundleCreated.executedBy.toString(), assistant.address, "Executed by is incorrect"); + assert.equal( + eventBundleCreated.executedBy.toString(), + await assistant.getAddress(), + "Executed by is incorrect" + ); assert.equal(bundleInstance.toString(), bundle.toString(), "Bundle struct is incorrect"); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); await expect(tx) @@ -6456,16 +6610,16 @@ describe("IBosonOrchestrationHandler", function () { await expect(tx).to.emit(bosonVoucher, "RangeReserved").withArgs(nextOfferId, range.toStruct()); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should update state", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, a preminted offer with condition and a twin with bundle, testing for the events await orchestrationHandler @@ -6477,7 +6631,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), twin, emptyAuthToken, voucherInitValues, @@ -6552,12 +6706,12 @@ describe("IBosonOrchestrationHandler", function () { } // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); - expect(await bosonVoucher.owner()).to.equal(assistant.address, "Wrong voucher clone owner"); + expect(await bosonVoucher.owner()).to.equal(await assistant.getAddress(), "Wrong voucher clone owner"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -6684,7 +6838,7 @@ describe("IBosonOrchestrationHandler", function () { await pauseHandler.connect(pauser).pause([PausableRegion.Exchanges]); // Approve twin transfer - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // Attempt to create a twin expecting revert const reservedRangeLength = offer.quantityAvailable; @@ -6698,7 +6852,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), twin, emptyAuthToken, voucherInitValues, @@ -6717,7 +6871,11 @@ describe("IBosonOrchestrationHandler", function () { offerIds = ["1"]; - condition = mockCondition({ tokenType: TokenType.MultiToken, tokenAddress: other2.address, tokenId: "5150" }); + condition = mockCondition({ + tokenType: TokenType.MultiToken, + tokenAddress: await other2.getAddress(), + tokenId: "5150", + }); expect(condition.isValid()).to.be.true; group = new Group(nextGroupId, seller.id, offerIds); @@ -6745,7 +6903,7 @@ describe("IBosonOrchestrationHandler", function () { nextTwinId = "1"; // Create a valid twin. - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); twin.sellerId = seller.id; // How that twin looks as a returned struct @@ -6754,7 +6912,7 @@ describe("IBosonOrchestrationHandler", function () { it("should emit a SellerCreated, an OfferCreated, a GroupCreated, a TwinCreated and a BundleCreated event", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, an offer with condition, twin and bundle const tx = await orchestrationHandler @@ -6772,12 +6930,12 @@ describe("IBosonOrchestrationHandler", function () { agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); // SellerCreated and OfferCreated events await expect(tx) .to.emit(orchestrationHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, assistant.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await assistant.getAddress()); await expect(tx) .to.emit(orchestrationHandler, "OfferCreated") @@ -6790,7 +6948,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -6827,23 +6985,23 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(bundleInstance.toString(), bundle.toString(), "Bundle struct is incorrect"); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); await expect(tx) .to.emit(bosonVoucher, "RoyaltyPercentageChanged") .withArgs(voucherInitValues.royaltyPercentage); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should update state", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, an offer with condition, twin and bundle await orchestrationHandler @@ -6945,12 +7103,12 @@ describe("IBosonOrchestrationHandler", function () { } // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); - expect(await bosonVoucher.owner()).to.equal(assistant.address, "Wrong voucher clone owner"); + expect(await bosonVoucher.owner()).to.equal(await assistant.getAddress(), "Wrong voucher clone owner"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -6962,7 +7120,7 @@ describe("IBosonOrchestrationHandler", function () { expect(voucherInitValues.isValid()).is.true; // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, an offer with condition, twin and bundle await orchestrationHandler @@ -6981,8 +7139,8 @@ describe("IBosonOrchestrationHandler", function () { ); // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -7001,7 +7159,7 @@ describe("IBosonOrchestrationHandler", function () { [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); // Expectations - let expectedRecipient = ethers.constants.AddressZero; //expect zero address when exchange id does not exist + let expectedRecipient = ZeroAddress; //expect zero address when exchange id does not exist let expectedRoyaltyAmount = "0"; // Zero Fee when exchange id does not exist assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); @@ -7014,7 +7172,7 @@ describe("IBosonOrchestrationHandler", function () { expect(voucherInitValues.isValid()).is.true; // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, an offer with condition, twin and bundle await orchestrationHandler @@ -7033,8 +7191,8 @@ describe("IBosonOrchestrationHandler", function () { ); // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -7053,7 +7211,7 @@ describe("IBosonOrchestrationHandler", function () { [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); // Expectations - let expectedRecipient = ethers.constants.AddressZero; //expect zero address when exchange id does not exist + let expectedRecipient = ZeroAddress; //expect zero address when exchange id does not exist let expectedRoyaltyAmount = "0"; // Zero Fee when exchange id does not exist assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); @@ -7062,7 +7220,7 @@ describe("IBosonOrchestrationHandler", function () { it("should ignore any provided ids and assign the next available", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler const sellerId = seller.id; seller.id = "333"; @@ -7091,9 +7249,9 @@ describe("IBosonOrchestrationHandler", function () { .withArgs( sellerId, sellerStruct, - calculateContractAddress(orchestrationHandler.address, "1"), + calculateContractAddress(await orchestrationHandler.getAddress(), "1"), emptyAuthTokenStruct, - assistant.address + await assistant.getAddress() ); await expect(tx) @@ -7107,7 +7265,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -7162,23 +7320,23 @@ describe("IBosonOrchestrationHandler", function () { agentId = "2"; // argument sent to contract for createAgent will be ignored // Create a valid agent, then set fields in tests directly - agent = mockAgent(other1.address); + agent = mockAgent(await other1.getAddress()); agent.id = agentId; expect(agent.isValid()).is.true; // Create an agent await accountHandler.connect(rando).createAgent(agent); - agentFee = ethers.BigNumber.from(offer.price).mul(agent.feePercentage).div("10000").toString(); + agentFee = ((BigInt(offer.price) * BigInt(agent.feePercentage)) / 10000n).toString(); offerFees.agentFee = agentFee; offerFeesStruct = offerFees.toStruct(); }); it("should emit a SellerCreated, an OfferCreated, a GroupCreated, a TwinCreated and a BundleCreated event", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); // Create a seller, an offer with condition, twin and bundle const tx = await orchestrationHandler @@ -7199,7 +7357,13 @@ describe("IBosonOrchestrationHandler", function () { // SellerCreated and OfferCreated events await expect(tx) .to.emit(orchestrationHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, assistant.address); + .withArgs( + seller.id, + sellerStruct, + expectedCloneAddress, + emptyAuthTokenStruct, + await assistant.getAddress() + ); await expect(tx) .to.emit(orchestrationHandler, "OfferCreated") @@ -7212,7 +7376,7 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); // Events with structs that contain arrays must be tested differently @@ -7249,18 +7413,18 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(bundleInstance.toString(), bundle.toString(), "Bundle struct is incorrect"); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); await expect(tx) .to.emit(bosonVoucher, "RoyaltyPercentageChanged") .withArgs(voucherInitValues.royaltyPercentage); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); }); @@ -7273,12 +7437,18 @@ describe("IBosonOrchestrationHandler", function () { firstTokenId = 1; lastTokenId = firstTokenId + reservedRangeLength - 1; const tokenIdStart = deriveTokenId(offer.id, firstTokenId); - range = new Range(tokenIdStart.toString(), reservedRangeLength.toString(), "0", "0", assistant.address); + range = new Range( + tokenIdStart.toString(), + reservedRangeLength.toString(), + "0", + "0", + await assistant.getAddress() + ); }); it("should emit a SellerCreated, an OfferCreated, a GroupCreated, a TwinCreated, a BundleCreated and a RangeReserved event", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, a preminted offer with condition, twin and bundle const tx = await orchestrationHandler @@ -7290,7 +7460,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), condition, twin, emptyAuthToken, @@ -7298,12 +7468,18 @@ describe("IBosonOrchestrationHandler", function () { agentId ); - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); // SellerCreated, OfferCreated and RangeReserved events await expect(tx) .to.emit(orchestrationHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, assistant.address); + .withArgs( + seller.id, + sellerStruct, + expectedCloneAddress, + emptyAuthTokenStruct, + await assistant.getAddress() + ); await expect(tx) .to.emit(orchestrationHandler, "OfferCreated") @@ -7316,12 +7492,19 @@ describe("IBosonOrchestrationHandler", function () { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address + await assistant.getAddress() ); await expect(tx) .to.emit(orchestrationHandler, "RangeReserved") - .withArgs(nextOfferId, offer.sellerId, firstTokenId, lastTokenId, assistant.address, assistant.address); + .withArgs( + nextOfferId, + offer.sellerId, + firstTokenId, + lastTokenId, + await assistant.getAddress(), + await assistant.getAddress() + ); // Events with structs that contain arrays must be tested differently const txReceipt = await tx.wait(); @@ -7357,7 +7540,7 @@ describe("IBosonOrchestrationHandler", function () { assert.equal(bundleInstance.toString(), bundle.toString(), "Bundle struct is incorrect"); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); await expect(tx) @@ -7366,16 +7549,16 @@ describe("IBosonOrchestrationHandler", function () { await expect(tx).to.emit(bosonVoucher, "RangeReserved").withArgs(nextOfferId, range.toStruct()); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should update state", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler // Create a seller, a preminted offer with condition, twin and bundle await orchestrationHandler @@ -7387,7 +7570,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - assistant.address, + await assistant.getAddress(), condition, twin, emptyAuthToken, @@ -7482,12 +7665,12 @@ describe("IBosonOrchestrationHandler", function () { } // Voucher clone contract - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + expectedCloneAddress = calculateContractAddress(await orchestrationHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); - expect(await bosonVoucher.owner()).to.equal(assistant.address, "Wrong voucher clone owner"); + expect(await bosonVoucher.owner()).to.equal(await assistant.getAddress(), "Wrong voucher clone owner"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -7642,7 +7825,7 @@ describe("IBosonOrchestrationHandler", function () { await pauseHandler.connect(pauser).pause([PausableRegion.Exchanges]); // Approve twin transfer - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // Attempt to create a group, expecting revert const reservedRangeLength = offer.quantityAvailable; @@ -7656,7 +7839,7 @@ describe("IBosonOrchestrationHandler", function () { offerDurations, disputeResolver.id, reservedRangeLength, - bosonVoucher.address, + await bosonVoucher.getAddress(), condition, twin, emptyAuthToken, diff --git a/test/protocol/PauseHandlerTest.js b/test/protocol/PauseHandlerTest.js index 3218d8803..404ddc91f 100644 --- a/test/protocol/PauseHandlerTest.js +++ b/test/protocol/PauseHandlerTest.js @@ -67,7 +67,7 @@ describe("IBosonPauseHandler", function () { // Pause the protocol, testing for the event await expect(pauseHandler.connect(pauser).pause(regions)) .to.emit(pauseHandler, "ProtocolPaused") - .withArgs(regions, pauser.address); + .withArgs(regions, await pauser.getAddress()); }); context("💔 Revert Reasons", async function () { @@ -109,7 +109,7 @@ describe("IBosonPauseHandler", function () { // Unpause the protocol, testing for the event await expect(pauseHandler.connect(pauser).unpause()) .to.emit(pauseHandler, "ProtocolUnpaused") - .withArgs(pauser.address); + .withArgs(await pauser.getAddress()); }); it("should be possible to pause again after an unpause", async function () { @@ -123,7 +123,7 @@ describe("IBosonPauseHandler", function () { regions = [PausableRegion.Funds]; await expect(pauseHandler.connect(pauser).pause(regions)) .to.emit(pauseHandler, "ProtocolPaused") - .withArgs(regions, pauser.address); + .withArgs(regions, await pauser.getAddress()); }); context("💔 Revert Reasons", async function () { @@ -132,7 +132,7 @@ describe("IBosonPauseHandler", function () { await pauseHandler.connect(pauser).pause([PausableRegion.Exchanges]); // Attempt to unpause without PAUSER role, expecting revert - await expect(pauseHandler.connect(rando).unpause([])).to.revertedWith(RevertReasons.ACCESS_DENIED); + await expect(pauseHandler.connect(rando).unpause()).to.revertedWith(RevertReasons.ACCESS_DENIED); }); it("Protocol is not currently paused", async function () { diff --git a/test/protocol/ProtocolDiamondTest.js b/test/protocol/ProtocolDiamondTest.js index 0af807554..8be65e4f6 100644 --- a/test/protocol/ProtocolDiamondTest.js +++ b/test/protocol/ProtocolDiamondTest.js @@ -1,6 +1,6 @@ const { assert, expect } = require("chai"); const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners, getContractAt, getContractFactory, Interface, ZeroAddress } = hre.ethers; const Role = require("../../scripts/domain/Role"); const Facet = require("../../scripts/domain/Facet"); @@ -57,7 +57,7 @@ describe("ProtocolDiamond", async function () { beforeEach(async function () { // Make accounts available - [deployer, admin, upgrader, rando] = await ethers.getSigners(); + [deployer, admin, upgrader, rando] = await getSigners(); // Deploy the Diamond [protocolDiamond, diamondLoupe, diamondCut, erc165, accessController] = await deployProtocolDiamond( @@ -65,23 +65,23 @@ describe("ProtocolDiamond", async function () { ); // Cast Diamond to DiamondLoupeFacet - loupeFacetViaDiamond = await ethers.getContractAt("DiamondLoupeFacet", protocolDiamond.address); + loupeFacetViaDiamond = await getContractAt("DiamondLoupeFacet", await protocolDiamond.getAddress()); // Cast Diamond to DiamondCutFacet - cutFacetViaDiamond = await ethers.getContractAt("DiamondCutFacet", protocolDiamond.address); + cutFacetViaDiamond = await getContractAt("DiamondCutFacet", await protocolDiamond.getAddress()); // Cast Diamond to ERC165Facet - erc165ViaDiamond = await ethers.getContractAt("ERC165Facet", protocolDiamond.address); + erc165ViaDiamond = await getContractAt("ERC165Facet", await protocolDiamond.getAddress()); // Get the facet addresses addresses = Object.assign([], await loupeFacetViaDiamond.facetAddresses()); // Deployer grants ADMIN role to admin address and renounces admin - await accessController.connect(deployer).grantRole(Role.ADMIN, admin.address); - await accessController.connect(deployer).renounceRole(Role.ADMIN, deployer.address); + await accessController.connect(deployer).grantRole(Role.ADMIN, await admin.getAddress()); + await accessController.connect(deployer).renounceRole(Role.ADMIN, await deployer.getAddress()); // Grant UPGRADER role to upgrader account - await accessController.connect(admin).grantRole(Role.UPGRADER, upgrader.address); + await accessController.connect(admin).grantRole(Role.UPGRADER, await upgrader.getAddress()); }); // Interface support (ERC-156 provided by ProtocolDiamond, others by deployed facets) @@ -146,9 +146,9 @@ describe("ProtocolDiamond", async function () { it("should revert if more than 255 functions are added", async () => { // add more than 256 facets // Deploy TestFacet256 - const TestFacet256 = await ethers.getContractFactory("TestFacet256"); + const TestFacet256 = await getContractFactory("TestFacet256"); const testFacet256 = await TestFacet256.deploy(); - await testFacet256.deployed(); + await testFacet256.waitForDeployment(); // Get the TestFacet256 function selectors from the abi selectors = getSelectors(testFacet256); @@ -156,7 +156,7 @@ describe("ProtocolDiamond", async function () { // Define the facet cut facetCuts = [ { - facetAddress: testFacet256.address, + facetAddress: await testFacet256.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, @@ -165,7 +165,7 @@ describe("ProtocolDiamond", async function () { // Send the DiamondCut transaction tx = await cutFacetViaDiamond .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit: "10000000" }); + .diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit: "10000000" }); // this should revert await expect(loupeFacetViaDiamond.facets()).to.be.revertedWith(RevertReasons.TOO_MANY_FUNCTIONS); @@ -180,20 +180,20 @@ describe("ProtocolDiamond", async function () { it("facet addresses should be correct and in order", async () => { // DiamondLoupeFacet was first cut - assert.equal(addresses[0], diamondLoupe.address); + assert.equal(addresses[0], await diamondLoupe.getAddress()); // DiamondCutFacet was second cut - assert.equal(addresses[1], diamondCut.address); + assert.equal(addresses[1], await diamondCut.getAddress()); // ERC165Facet was last cut - assert.equal(addresses[2], erc165.address); + assert.equal(addresses[2], await erc165.getAddress()); }); it("Should return correct addresses even when selectorCount is greater than 8", async () => { // Deploy Test1Facet to have more selectors - Test1Facet = await ethers.getContractFactory("Test1Facet"); + Test1Facet = await getContractFactory("Test1Facet"); test1Facet = await Test1Facet.deploy(); - await test1Facet.deployed(); + await test1Facet.waitForDeployment(); // Get the Test1Facet function selectors from the abi selectors = getSelectors(test1Facet); @@ -201,23 +201,21 @@ describe("ProtocolDiamond", async function () { // Define the facet cut facetCuts = [ { - facetAddress: test1Facet.address, + facetAddress: await test1Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, ]; // Send the DiamondCut transaction - await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); const addresses = await loupeFacetViaDiamond.facetAddresses(); - assert.equal(addresses[0], diamondLoupe.address); - assert.equal(addresses[1], diamondCut.address); - assert.equal(addresses[2], erc165.address); - assert.equal(addresses[3], test1Facet.address); + assert.equal(addresses[0], await diamondLoupe.getAddress()); + assert.equal(addresses[1], await diamondCut.getAddress()); + assert.equal(addresses[2], await erc165.getAddress()); + assert.equal(addresses[3], await test1Facet.getAddress()); assert.equal(addresses.length, 4); }); @@ -225,17 +223,16 @@ describe("ProtocolDiamond", async function () { context("👉 facetFunctionSelectors() ", async () => { it("should return the correct function selectors for the DiamondCutFacet", async () => { - // Test cutFacetViaDiamond selectors selectors = getSelectors(cutFacetViaDiamond); - result = await loupeFacetViaDiamond.facetFunctionSelectors(diamondCut.address); - assert.sameMembers(result, selectors); + result = await loupeFacetViaDiamond.facetFunctionSelectors(await diamondCut.getAddress()); + assert.sameMembers([...result], selectors); }); it("should return the correct function selectors for the DiamondLoupeFacet", async () => { // Test DiamondLoupeFacet selectors selectors = getSelectors(loupeFacetViaDiamond); - result = await loupeFacetViaDiamond.facetFunctionSelectors(diamondLoupe.address); - assert.sameMembers(result, selectors); + result = await loupeFacetViaDiamond.facetFunctionSelectors(await diamondLoupe.getAddress()); + assert.sameMembers([...result], selectors); }); }); @@ -261,32 +258,32 @@ describe("ProtocolDiamond", async function () { context("📋 DiamondCutFacet", async function () { beforeEach(async function () { // Deploy Test1Facet - Test1Facet = await ethers.getContractFactory("Test1Facet"); + Test1Facet = await getContractFactory("Test1Facet"); test1Facet = await Test1Facet.deploy(); - await test1Facet.deployed(); + await test1Facet.waitForDeployment(); // Deploy Test2Facet - Test2Facet = await ethers.getContractFactory("Test2Facet"); + Test2Facet = await getContractFactory("Test2Facet"); test2Facet = await Test2Facet.deploy(); - await test2Facet.deployed(); + await test2Facet.waitForDeployment(); // Deploy Test3Facet - Test3Facet = await ethers.getContractFactory("Test3Facet"); + Test3Facet = await getContractFactory("Test3Facet"); test3Facet = await Test3Facet.deploy(); - await test3Facet.deployed(); + await test3Facet.waitForDeployment(); // N.B. The facets are not yet connected to the diamond in any way, // but following handles prepare us for accessing the diamond via // the ABI of these facets, once their functions have been added. // Cast Diamond to Test1Facet - test1ViaDiamond = await ethers.getContractAt("Test1Facet", protocolDiamond.address); + test1ViaDiamond = await getContractAt("Test1Facet", await protocolDiamond.getAddress()); // Cast Diamond to Test2Facet - test2ViaDiamond = await ethers.getContractAt("Test2Facet", protocolDiamond.address); + test2ViaDiamond = await getContractAt("Test2Facet", await protocolDiamond.getAddress()); // Cast Diamond to Test3Facet - test3ViaDiamond = await ethers.getContractAt("Test3Facet", protocolDiamond.address); + test3ViaDiamond = await getContractAt("Test3Facet", await protocolDiamond.getAddress()); }); context("👉 diamondCut() - Privileged Access", async function () { @@ -297,7 +294,7 @@ describe("ProtocolDiamond", async function () { // Define the facet cut facetCuts = [ { - facetAddress: test1Facet.address, + facetAddress: await test1Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, @@ -305,13 +302,11 @@ describe("ProtocolDiamond", async function () { // non-UPGRADER attempt await expect( - cutFacetViaDiamond.connect(admin).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(admin).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.ONLY_UPGRADER); // UPGRADER attempt - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); @@ -329,16 +324,14 @@ describe("ProtocolDiamond", async function () { // Define the facet cut facetCuts = [ { - facetAddress: test1Facet.address, + facetAddress: await test1Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, ]; // Send the DiamondCut transaction - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); @@ -347,8 +340,8 @@ describe("ProtocolDiamond", async function () { assert.equal(receipt.status, 1, `Diamond upgrade failed: ${tx.hash}`); // Make sure function selectors for the facet are correct - result = await loupeFacetViaDiamond.facetFunctionSelectors(test1Facet.address); - assert.sameMembers(result, selectors); + result = await loupeFacetViaDiamond.facetFunctionSelectors(await test1Facet.getAddress()); + assert.sameMembers([...result], selectors); }); it("should add functions from Test2Facet", async () => { @@ -358,16 +351,14 @@ describe("ProtocolDiamond", async function () { // Define the facet cut facetCuts = [ { - facetAddress: test2Facet.address, + facetAddress: await test2Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, ]; // Send the DiamondCut transaction - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); @@ -376,43 +367,41 @@ describe("ProtocolDiamond", async function () { assert.equal(receipt.status, 1, `Diamond upgrade failed: ${tx.hash}`); // Make sure function selectors for the facet are correct - result = await loupeFacetViaDiamond.facetFunctionSelectors(test2Facet.address); - assert.sameMembers(result, selectors); + result = await loupeFacetViaDiamond.facetFunctionSelectors(await test2Facet.getAddress()); + assert.sameMembers([...result], selectors); }); it("should allow functions from different facets to be added in one transaction", async () => { // Get even numbered selectors from Test1Facet + odd from Test2Facet selectors = [ - getSelectors(test1ViaDiamond).filter((s, i) => i % 2), - getSelectors(test2ViaDiamond).filter((s, i) => !(i % 2)), + getSelectors(test1ViaDiamond).filter((_, i) => i % 2), + getSelectors(test2ViaDiamond).filter((_, i) => !(i % 2)), ]; // Define facet cuts facetCuts = [ { - facetAddress: test1Facet.address, + facetAddress: await test1Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors[0], }, { - facetAddress: test2Facet.address, + facetAddress: await test2Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors[1], }, ]; // Send the DiamondCut transaction - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Be certain transaction was successful assert.equal(receipt.status, 1, `Diamond upgrade failed: ${tx.hash}`); // Ensure the currently installed test selectors are what we added result = [ - await loupeFacetViaDiamond.facetFunctionSelectors(test1Facet.address), - await loupeFacetViaDiamond.facetFunctionSelectors(test2Facet.address), + await loupeFacetViaDiamond.facetFunctionSelectors(await test1Facet.getAddress()), + await loupeFacetViaDiamond.facetFunctionSelectors(await test2Facet.getAddress()), ]; assert.sameMembers(result.flat(), selectors.flat()); }); @@ -421,7 +410,7 @@ describe("ProtocolDiamond", async function () { // Define the facet cut facetCuts = [ { - facetAddress: ethers.constants.AddressZero, + facetAddress: ZeroAddress, action: FacetCutAction.Add, functionSelectors: [], }, @@ -429,7 +418,7 @@ describe("ProtocolDiamond", async function () { // attempt to add zero selectors await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.NO_SELECTORS_TO_CUT); }); @@ -440,20 +429,18 @@ describe("ProtocolDiamond", async function () { // Define the facet cut facetCuts = [ { - facetAddress: test2Facet.address, + facetAddress: await test2Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, ]; // Send the DiamondCut transaction - await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // attempt to add the same selectors again await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.FUNCTION_ALREADY_EXISTS); }); }); @@ -463,21 +450,19 @@ describe("ProtocolDiamond", async function () { // Define the facet cuts facetCuts = [ { - facetAddress: test1Facet.address, + facetAddress: await test1Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: getSelectors(test1Facet), }, { - facetAddress: test2Facet.address, + facetAddress: await test2Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: getSelectors(test2Facet), }, ]; // Send the DiamondCut transaction - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); @@ -494,16 +479,14 @@ describe("ProtocolDiamond", async function () { // Define the facet cuts facetCuts = [ { - facetAddress: ethers.constants.AddressZero, + facetAddress: ZeroAddress, action: FacetCutAction.Remove, functionSelectors: selectors, }, ]; // Send the DiamondCut transaction - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); @@ -512,7 +495,7 @@ describe("ProtocolDiamond", async function () { assert.equal(receipt.status, 1, `Diamond upgrade failed: ${tx.hash}`); // Verify that the function selectors were removed - result = await loupeFacetViaDiamond.facetFunctionSelectors(test1Facet.address); + result = await loupeFacetViaDiamond.facetFunctionSelectors(await test1Facet.getAddress()); assert.sameMembers(result, getSelectors(test1Facet).get(discard)); }); @@ -524,16 +507,14 @@ describe("ProtocolDiamond", async function () { // Define the facet cuts facetCuts = [ { - facetAddress: ethers.constants.AddressZero, + facetAddress: ZeroAddress, action: FacetCutAction.Remove, functionSelectors: selectors, }, ]; // Send the DiamondCut transaction - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); @@ -542,7 +523,7 @@ describe("ProtocolDiamond", async function () { assert.equal(receipt.status, 1, `Diamond upgrade failed: ${tx.hash}`); // Verify that the function selectors were removed - result = await loupeFacetViaDiamond.facetFunctionSelectors(test2Facet.address); + result = await loupeFacetViaDiamond.facetFunctionSelectors(await test2Facet.getAddress()); assert.sameMembers(result, getSelectors(test2Facet).get(discard)); }); @@ -564,16 +545,14 @@ describe("ProtocolDiamond", async function () { // Define the facet cuts facetCuts = [ { - facetAddress: ethers.constants.AddressZero, + facetAddress: ZeroAddress, action: FacetCutAction.Remove, functionSelectors: selectors, }, ]; // Send the DiamondCut transaction - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); @@ -593,14 +572,14 @@ describe("ProtocolDiamond", async function () { assert.equal(facets.length, 1); // loupe // Check that the remaining facet address is correct - assert.equal(facets[0].facetAddress, diamondLoupe.address, "Incorrect facet address"); + assert.equal(facets[0].facetAddress, await diamondLoupe.getAddress(), "Incorrect facet address"); }); it("at least one selector should be removed", async function () { // Define the facet cut facetCuts = [ { - facetAddress: ethers.constants.AddressZero, + facetAddress: ZeroAddress, action: FacetCutAction.Remove, functionSelectors: [], }, @@ -608,7 +587,7 @@ describe("ProtocolDiamond", async function () { // attempt to remove zero selectors await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.NO_SELECTORS_TO_CUT); }); @@ -620,7 +599,7 @@ describe("ProtocolDiamond", async function () { // Define the facet cuts facetCuts = [ { - facetAddress: test1Facet.address, + facetAddress: await test1Facet.getAddress(), action: FacetCutAction.Remove, functionSelectors: selectors, }, @@ -628,7 +607,7 @@ describe("ProtocolDiamond", async function () { // attempt to make remove cut with non zero facet address await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.REMOVING_NON_ZERO_ADDRESS_FACET); }); @@ -636,7 +615,7 @@ describe("ProtocolDiamond", async function () { // Define the facet cut facetCuts = [ { - facetAddress: ethers.constants.AddressZero, + facetAddress: ZeroAddress, action: FacetCutAction.Remove, functionSelectors: getSelectors(test3Facet), }, @@ -644,7 +623,7 @@ describe("ProtocolDiamond", async function () { // attempt to remove function that doesn't exist await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.REMOVING_FUNCTION_DOES_NOT_EXIST); }); @@ -653,21 +632,19 @@ describe("ProtocolDiamond", async function () { // to test that immutable function cannot be replaced facetCuts = [ { - facetAddress: protocolDiamond.address, + facetAddress: await protocolDiamond.getAddress(), action: FacetCutAction.Add, functionSelectors: getSelectors(test3Facet), }, ]; // Send the DiamondCut transaction that adds immutable functions - await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Define the facet cut facetCuts = [ { - facetAddress: ethers.constants.AddressZero, + facetAddress: ZeroAddress, action: FacetCutAction.Remove, functionSelectors: getSelectors(test3Facet), }, @@ -675,7 +652,7 @@ describe("ProtocolDiamond", async function () { // attempt to make remove immutable function await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.REMOVING_IMMUTABLE_FUNCTION); }); }); @@ -685,21 +662,19 @@ describe("ProtocolDiamond", async function () { // Define the facet cuts facetCuts = [ { - facetAddress: test1Facet.address, + facetAddress: await test1Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: getSelectors(test1Facet), }, { - facetAddress: test2Facet.address, + facetAddress: await test2Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: getSelectors(test2Facet), }, ]; // Send the DiamondCut transaction - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); @@ -713,23 +688,21 @@ describe("ProtocolDiamond", async function () { assert.equal(await test2ViaDiamond.test2Func13(), "Boson"); // Deploy Test2FacetUpgrade - Test2FacetUpgrade = await ethers.getContractFactory("Test2FacetUpgrade"); + Test2FacetUpgrade = await getContractFactory("Test2FacetUpgrade"); test2FacetUpgrade = await Test2FacetUpgrade.deploy(); - await test2FacetUpgrade.deployed(); + await test2FacetUpgrade.waitForDeployment(); // Define the facet cut facetCuts = [ { - facetAddress: test2FacetUpgrade.address, + facetAddress: await test2FacetUpgrade.getAddress(), action: FacetCutAction.Replace, functionSelectors: getSelectors(test2FacetUpgrade), }, ]; // Send the DiamondCut transaction - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); @@ -745,7 +718,7 @@ describe("ProtocolDiamond", async function () { // Define the facet cut facetCuts = [ { - facetAddress: ethers.constants.AddressZero, + facetAddress: ZeroAddress, action: FacetCutAction.Replace, functionSelectors: [], }, @@ -753,7 +726,7 @@ describe("ProtocolDiamond", async function () { // attempt to replace zero selectors await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.NO_SELECTORS_TO_CUT); }); @@ -763,21 +736,19 @@ describe("ProtocolDiamond", async function () { // to test that immutable function cannot be replaced facetCuts = [ { - facetAddress: protocolDiamond.address, + facetAddress: await protocolDiamond.getAddress(), action: FacetCutAction.Add, functionSelectors: getSelectors(test3Facet), }, ]; // Send the DiamondCut transaction that adds immutable functions - await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Define the facet cut facetCuts = [ { - facetAddress: test3Facet.address, + facetAddress: await test3Facet.getAddress(), action: FacetCutAction.Replace, functionSelectors: getSelectors(test3Facet), }, @@ -785,7 +756,7 @@ describe("ProtocolDiamond", async function () { // attempt to replace immutable functions await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.REPLACING_IMMUTABLE_FUNCTION); }); @@ -793,7 +764,7 @@ describe("ProtocolDiamond", async function () { // Define the facet cuts facetCuts = [ { - facetAddress: test1Facet.address, + facetAddress: await test1Facet.getAddress(), action: FacetCutAction.Replace, functionSelectors: getSelectors(test1Facet), }, @@ -801,7 +772,7 @@ describe("ProtocolDiamond", async function () { // attempt to replace function with same function await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.REPLACING_WITH_SAME_FUNCTION); }); @@ -809,7 +780,7 @@ describe("ProtocolDiamond", async function () { // Define the facet cut facetCuts = [ { - facetAddress: test3Facet.address, + facetAddress: await test3Facet.getAddress(), action: FacetCutAction.Replace, functionSelectors: getSelectors(test3Facet), }, @@ -817,7 +788,7 @@ describe("ProtocolDiamond", async function () { // attempt to replace function that doesn't exist await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.revertedWith(RevertReasons.REPLACING_FUNCTION_DOES_NOT_EXIST); }); }); @@ -826,7 +797,7 @@ describe("ProtocolDiamond", async function () { // Define the facet cuts facetCuts = [ { - facetAddress: test1Facet.address, + facetAddress: await test1Facet.getAddress(), action: 3, functionSelectors: getSelectors(test1Facet), }, @@ -834,7 +805,7 @@ describe("ProtocolDiamond", async function () { // Send the DiamondCut transaction await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }) ).to.be.reverted; }); }); @@ -843,24 +814,24 @@ describe("ProtocolDiamond", async function () { context("📋 Initializer", async function () { beforeEach(async function () { // Deploy Test3Facet - Test3Facet = await ethers.getContractFactory("Test3Facet"); + Test3Facet = await getContractFactory("Test3Facet"); test3Facet = await Test3Facet.deploy(); - await test3Facet.deployed(); + await test3Facet.waitForDeployment(); // N.B. The facets are not yet connected to the diamond in any way, // but following handles prepare us for accessing the diamond via // the ABI of these facets, once their functions have been added. // Cast Diamond to Test3Facet - test3ViaDiamond = await ethers.getContractAt("Test3Facet", protocolDiamond.address); + test3ViaDiamond = await getContractAt("Test3Facet", await protocolDiamond.getAddress()); }); context("👉 Normal operation", async function () { beforeEach(async function () { // Encode the initialization call initFunction = "initialize(address _testAddress)"; - initInterface = new ethers.utils.Interface([`function ${initFunction}`]); - initCallData = initInterface.encodeFunctionData("initialize", [rando.address]); + initInterface = new Interface([`function ${initFunction}`]); + initCallData = initInterface.encodeFunctionData("initialize", [await rando.getAddress()]); // Get the Test3Facet function selectors from the abi, removing the initializer selectors = getSelectors(test3Facet).remove([initFunction]); @@ -868,7 +839,7 @@ describe("ProtocolDiamond", async function () { // Create facet cut payload facetCuts = [ { - facetAddress: test3Facet.address, + facetAddress: await test3Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, @@ -877,7 +848,7 @@ describe("ProtocolDiamond", async function () { // Execute the Diamond cut tx = await cutFacetViaDiamond .connect(upgrader) - .diamondCut(facetCuts, test3Facet.address, initCallData, { gasLimit }); + .diamondCut(facetCuts, await test3Facet.getAddress(), initCallData, { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); @@ -888,8 +859,8 @@ describe("ProtocolDiamond", async function () { it("Should call an initializer function if supplied", async () => { // Make sure function selectors for the facet are correct - result = await loupeFacetViaDiamond.facetFunctionSelectors(test3Facet.address); - assert.sameMembers(result, selectors); + result = await loupeFacetViaDiamond.facetFunctionSelectors(await test3Facet.getAddress()); + assert.sameMembers([...result], selectors); }); it("Should store initializer state in diamond storage slot when modifier runs", async () => { @@ -901,7 +872,7 @@ describe("ProtocolDiamond", async function () { it("Should store initializer argument in diamond storage slot when method runs", async () => { // Make sure argument passed to initializer got stored when method ran result = await test3ViaDiamond.getTestAddress(); - assert.equal(result, rando.address, "Initializer argument not stored"); + assert.equal(result, await rando.getAddress(), "Initializer argument not stored"); }); it("Should call an initializer function on diamond itself", async () => { @@ -912,23 +883,23 @@ describe("ProtocolDiamond", async function () { // Arguments for Diamond constructor const diamondArgs = [ - accessController.address, - [getFacetAddCut(diamondLoupe), getFacetAddCut(diamondCut), getFacetAddCut(erc165)], + await accessController.getAddress(), + [await getFacetAddCut(diamondLoupe), await getFacetAddCut(diamondCut), await getFacetAddCut(erc165)], interfaces, ]; // Deploy Protocol Diamond - const ProtocolDiamond = await ethers.getContractFactory("TestInitializableDiamond"); + const ProtocolDiamond = await getContractFactory("TestInitializableDiamond"); const protocolDiamond = await ProtocolDiamond.deploy(...diamondArgs); - await protocolDiamond.deployTransaction.wait(); + await protocolDiamond.waitForDeployment(); // Cast new Diamond to DiamondCutFacet - cutFacetViaDiamond = await ethers.getContractAt("DiamondCutFacet", protocolDiamond.address); + cutFacetViaDiamond = await getContractAt("DiamondCutFacet", await protocolDiamond.getAddress()); // Create facet cut payload facetCuts = [ { - facetAddress: protocolDiamond.address, + facetAddress: await protocolDiamond.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, @@ -937,7 +908,7 @@ describe("ProtocolDiamond", async function () { // Execute the Diamond cut await cutFacetViaDiamond .connect(upgrader) - .diamondCut(facetCuts, protocolDiamond.address, initCallData, { gasLimit }); + .diamondCut(facetCuts, await protocolDiamond.getAddress(), initCallData, { gasLimit }); // Make sure initializer state got stored when modifier ran result = await protocolDiamond.isInitialized(); @@ -949,8 +920,8 @@ describe("ProtocolDiamond", async function () { it("Reason supplied by implementation", async () => { // Encode the initialization call initFunction = "initialize(address _testAddress)"; - initInterface = new ethers.utils.Interface([`function ${initFunction}`]); - initCallData = initInterface.encodeFunctionData("initialize", [accessController.address]); + initInterface = new Interface([`function ${initFunction}`]); + initCallData = initInterface.encodeFunctionData("initialize", [await accessController.getAddress()]); // Get the Test3Facet function selectors from the abi, removing the initializer selectors = getSelectors(test3Facet).remove([initFunction]); @@ -958,7 +929,7 @@ describe("ProtocolDiamond", async function () { // Create facet cut payload facetCuts = [ { - facetAddress: test3Facet.address, + facetAddress: await test3Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, @@ -966,15 +937,17 @@ describe("ProtocolDiamond", async function () { // If contract address is supplied Test3Facet's initializer will revert with the specific reason await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, test3Facet.address, initCallData, { gasLimit }) + cutFacetViaDiamond + .connect(upgrader) + .diamondCut(facetCuts, await test3Facet.getAddress(), initCallData, { gasLimit }) ).to.revertedWith(RevertReasons.CONTRACT_NOT_ALLOWED); }); it("Library reason if not supplied by implementation", async () => { // Encode the initialization call initFunction = "initialize(address _testAddress)"; - initInterface = new ethers.utils.Interface([`function ${initFunction}`]); - initCallData = initInterface.encodeFunctionData("initialize", [upgrader.address]); + initInterface = new Interface([`function ${initFunction}`]); + initCallData = initInterface.encodeFunctionData("initialize", [await upgrader.getAddress()]); // Get the Test3Facet function selectors from the abi, removing the initializer selectors = getSelectors(test3Facet).remove([initFunction]); @@ -982,7 +955,7 @@ describe("ProtocolDiamond", async function () { // Create facet cut payload facetCuts = [ { - facetAddress: test3Facet.address, + facetAddress: await test3Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, @@ -991,15 +964,17 @@ describe("ProtocolDiamond", async function () { // If the caller's address is supplied Test3Facet's initializer will revert with no reason // and so the diamondCut function will supply it's own reason await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, test3Facet.address, initCallData, { gasLimit }) + cutFacetViaDiamond + .connect(upgrader) + .diamondCut(facetCuts, await test3Facet.getAddress(), initCallData, { gasLimit }) ).to.revertedWith(RevertReasons.INIT_REVERTED); }); it("_init is address(0) but _calldata is not empty", async () => { // Encode the initialization call initFunction = "initialize(address _testAddress)"; - initInterface = new ethers.utils.Interface([`function ${initFunction}`]); - initCallData = initInterface.encodeFunctionData("initialize", [accessController.address]); + initInterface = new Interface([`function ${initFunction}`]); + initCallData = initInterface.encodeFunctionData("initialize", [await accessController.getAddress()]); // Get the Test3Facet function selectors from the abi, removing the initializer selectors = getSelectors(test3Facet).remove([initFunction]); @@ -1007,7 +982,7 @@ describe("ProtocolDiamond", async function () { // Create facet cut payload facetCuts = [ { - facetAddress: test3Facet.address, + facetAddress: await test3Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, @@ -1015,9 +990,7 @@ describe("ProtocolDiamond", async function () { // If contract address is supplied but _calldata is empty, diamondCut will revert with it's own reason await expect( - cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, initCallData, { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, initCallData, { gasLimit }) ).to.revertedWith(RevertReasons.INIT_ZERO_ADDRESS_NON_EMPTY_CALLDATA); }); @@ -1029,7 +1002,7 @@ describe("ProtocolDiamond", async function () { // Create facet cut payload facetCuts = [ { - facetAddress: test3Facet.address, + facetAddress: await test3Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, @@ -1037,15 +1010,15 @@ describe("ProtocolDiamond", async function () { // If _calldata is empty, but contract address is not supplied, diamondCut will revert with it's own reason await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, test3Facet.address, "0x", { gasLimit }) + cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, await test3Facet.getAddress(), "0x", { gasLimit }) ).to.revertedWith(RevertReasons.INIT_EMPTY_CALLDATA_NON_ZERO_ADDRESS); }); it("_init address has no code", async () => { // Encode the initialization call initFunction = "initialize(address _testAddress)"; - initInterface = new ethers.utils.Interface([`function ${initFunction}`]); - initCallData = initInterface.encodeFunctionData("initialize", [accessController.address]); + initInterface = new Interface([`function ${initFunction}`]); + initCallData = initInterface.encodeFunctionData("initialize", [await accessController.getAddress()]); // Get the Test3Facet function selectors from the abi, removing the initializer selectors = getSelectors(test3Facet).remove([initFunction]); @@ -1053,7 +1026,7 @@ describe("ProtocolDiamond", async function () { // Create facet cut payload facetCuts = [ { - facetAddress: test3Facet.address, + facetAddress: await test3Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: selectors, }, @@ -1061,7 +1034,9 @@ describe("ProtocolDiamond", async function () { // If contract address has no code, diamondCut will revert with it's own reason await expect( - cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, deployer.address, initCallData, { gasLimit }) + cutFacetViaDiamond + .connect(upgrader) + .diamondCut(facetCuts, await deployer.getAddress(), initCallData, { gasLimit }) ).to.revertedWith(RevertReasons.INIT_ADDRESS_WITH_NO_CODE); }); @@ -1071,13 +1046,13 @@ describe("ProtocolDiamond", async function () { // Arguments for Diamond constructor const diamondArgs = [ - ethers.constants.AddressZero, - [getFacetAddCut(diamondLoupe), getFacetAddCut(diamondCut), getFacetAddCut(erc165)], + ZeroAddress, + [await getFacetAddCut(diamondLoupe), await getFacetAddCut(diamondCut), await getFacetAddCut(erc165)], interfaces, ]; // Attempt to deploy Protocol Diamond - const ProtocolDiamond = await ethers.getContractFactory("ProtocolDiamond"); + const ProtocolDiamond = await getContractFactory("ProtocolDiamond"); await expect(ProtocolDiamond.deploy(...diamondArgs)).to.revertedWith(RevertReasons.INVALID_ADDRESS); }); @@ -1088,39 +1063,37 @@ describe("ProtocolDiamond", async function () { context("📋 Proxying", async function () { beforeEach(async function () { // Deploy Test1Facet - Test1Facet = await ethers.getContractFactory("Test1Facet"); + Test1Facet = await getContractFactory("Test1Facet"); test1Facet = await Test1Facet.deploy(); - await test1Facet.deployed(); + await test1Facet.waitForDeployment(); // Deploy Test2Facet - Test2Facet = await ethers.getContractFactory("Test2Facet"); + Test2Facet = await getContractFactory("Test2Facet"); test2Facet = await Test2Facet.deploy(); - await test2Facet.deployed(); + await test2Facet.waitForDeployment(); // Cast Diamond to Test1Facet - test1ViaDiamond = await ethers.getContractAt("Test1Facet", protocolDiamond.address); + test1ViaDiamond = await getContractAt("Test1Facet", await protocolDiamond.getAddress()); // Cast Diamond to Test2Facet - test2ViaDiamond = await ethers.getContractAt("Test2Facet", protocolDiamond.address); + test2ViaDiamond = await getContractAt("Test2Facet", await protocolDiamond.getAddress()); // Define the facet cuts facetCuts = [ { - facetAddress: test1Facet.address, + facetAddress: await test1Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: getSelectors(test1Facet), }, { - facetAddress: test2Facet.address, + facetAddress: await test2Facet.getAddress(), action: FacetCutAction.Add, functionSelectors: getSelectors(test2Facet), }, ]; // Send the DiamondCut transaction - tx = await cutFacetViaDiamond - .connect(upgrader) - .diamondCut(facetCuts, ethers.constants.AddressZero, "0x", { gasLimit }); + tx = await cutFacetViaDiamond.connect(upgrader).diamondCut(facetCuts, ZeroAddress, "0x", { gasLimit }); // Wait for transaction to confirm receipt = await tx.wait(); diff --git a/test/protocol/ProtocolInitializationHandlerTest.js b/test/protocol/ProtocolInitializationHandlerTest.js index 16ba4cb19..416959ff8 100644 --- a/test/protocol/ProtocolInitializationHandlerTest.js +++ b/test/protocol/ProtocolInitializationHandlerTest.js @@ -1,6 +1,6 @@ const { expect } = require("chai"); const hre = require("hardhat"); -const ethers = hre.ethers; +const { getContractAt, getContractFactory, getSigners, encodeBytes32String, AbiCoder, ZeroHash } = hre.ethers; const Role = require("../../scripts/domain/Role"); const { deployProtocolDiamond } = require("../../scripts/util/deploy-protocol-diamond.js"); @@ -22,6 +22,7 @@ describe("ProtocolInitializationHandler", async function () { let erc165; let version; let maxPremintedVouchers, initializationData; + let abiCoder; before(async function () { // get interface Ids @@ -30,41 +31,44 @@ describe("ProtocolInitializationHandler", async function () { beforeEach(async function () { // Make accounts available - [deployer, rando] = await ethers.getSigners(); + [deployer, rando] = await getSigners(); // Deploy the Protocol Diamond [protocolDiamond, , , , accessController] = await deployProtocolDiamond(maxPriorityFeePerGas); // Temporarily grant UPGRADER role to deployer account - await accessController.grantRole(Role.UPGRADER, deployer.address); + await accessController.grantRole(Role.UPGRADER, await deployer.getAddress()); // Temporarily grant UPGRADER role to deployer 1ccount - await accessController.grantRole(Role.UPGRADER, deployer.address); + await accessController.grantRole(Role.UPGRADER, await deployer.getAddress()); // Cast Diamond to IERC165 - erc165 = await ethers.getContractAt("ERC165Facet", protocolDiamond.address); + erc165 = await getContractAt("ERC165Facet", await protocolDiamond.getAddress()); // Cast Diamond to DiamondCutFacet - diamondCutFacet = await ethers.getContractAt("DiamondCutFacet", protocolDiamond.address); + diamondCutFacet = await getContractAt("DiamondCutFacet", await protocolDiamond.getAddress()); // Cast Diamond to ProtocolInitializationHandlerFacet - protocolInitializationFacet = await ethers.getContractAt( + protocolInitializationFacet = await getContractAt( "ProtocolInitializationHandlerFacet", - protocolDiamond.address + await protocolDiamond.getAddress() ); version = "2.2.0"; + abiCoder = AbiCoder.defaultAbiCoder(); + // initialization data for v2.2.0 maxPremintedVouchers = "1000"; - initializationData = ethers.utils.defaultAbiCoder.encode(["uint256"], [maxPremintedVouchers]); + + initializationData = abiCoder.encode(["uint256"], [maxPremintedVouchers]); }); describe("Deploy tests", async function () { context("📋 Initializer", async function () { it("Should initialize version 2.2.0 and emit ProtocolInitialized", async function () { const { cutTransaction } = await deployAndCutFacets( - protocolDiamond.address, + await protocolDiamond.getAddress(), { ProtocolInitializationHandlerFacet: [] }, maxPriorityFeePerGas ); @@ -76,22 +80,20 @@ describe("ProtocolInitializationHandler", async function () { let protocolInitializationFacetDeployed; beforeEach(async function () { - const ProtocolInitilizationContractFactory = await ethers.getContractFactory( - "ProtocolInitializationHandlerFacet" - ); + const ProtocolInitilizationContractFactory = await getContractFactory("ProtocolInitializationHandlerFacet"); protocolInitializationFacetDeployed = await ProtocolInitilizationContractFactory.deploy( await getFees(maxPriorityFeePerGas) ); - await protocolInitializationFacetDeployed.deployTransaction.wait(); + await protocolInitializationFacetDeployed.waitForDeployment(); }); it("Addresses and calldata length mismatch", async function () { - version = ethers.utils.formatBytes32String("2.2.0"); + version = encodeBytes32String("2.2.0"); const callData = protocolInitializationFacetDeployed.interface.encodeFunctionData("initialize", [ version, - [rando.address], + [await rando.getAddress()], [], true, initializationData, @@ -99,11 +101,11 @@ describe("ProtocolInitializationHandler", async function () { [], ]); - let facetCut = getFacetAddCut(protocolInitializationFacetDeployed, [callData.slice(0, 10)]); + let facetCut = await getFacetAddCut(protocolInitializationFacetDeployed, [callData.slice(0, 10)]); const cutArgs = [ [facetCut], - protocolInitializationFacetDeployed.address, + await protocolInitializationFacetDeployed.getAddress(), callData, await getFees(maxPriorityFeePerGas), ]; @@ -115,7 +117,7 @@ describe("ProtocolInitializationHandler", async function () { it("Version is empty", async function () { const callData = protocolInitializationFacetDeployed.interface.encodeFunctionData("initialize", [ - ethers.constants.HashZero, + ZeroHash, [], [], true, @@ -124,11 +126,11 @@ describe("ProtocolInitializationHandler", async function () { [], ]); - let facetCut = getFacetAddCut(protocolInitializationFacetDeployed, [callData.slice(0, 10)]); + let facetCut = await getFacetAddCut(protocolInitializationFacetDeployed, [callData.slice(0, 10)]); const cutArgs = [ [facetCut], - protocolInitializationFacetDeployed.address, + await protocolInitializationFacetDeployed.getAddress(), callData, await getFees(maxPriorityFeePerGas), ]; @@ -139,7 +141,7 @@ describe("ProtocolInitializationHandler", async function () { }); it("Initialize same version twice", async function () { - version = ethers.utils.formatBytes32String("2.2.0"); + version = encodeBytes32String("2.2.0"); const callData = protocolInitializationFacetDeployed.interface.encodeFunctionData("initialize", [ version, @@ -151,32 +153,32 @@ describe("ProtocolInitializationHandler", async function () { [], ]); - let facetCut = getFacetAddCut(protocolInitializationFacetDeployed, [callData.slice(0, 10)]); + let facetCut = await getFacetAddCut(protocolInitializationFacetDeployed, [callData.slice(0, 10)]); await diamondCutFacet.diamondCut( [facetCut], - protocolInitializationFacetDeployed.address, + await protocolInitializationFacetDeployed.getAddress(), callData, await getFees(maxPriorityFeePerGas) ); // Mock a new facet to add to diamond so we can call initialize again - let FacetTestFactory = await ethers.getContractFactory("Test3Facet"); + let FacetTestFactory = await getContractFactory("Test3Facet"); const testFacet = await FacetTestFactory.deploy(await getFees(maxPriorityFeePerGas)); - await testFacet.deployTransaction.wait(); + await testFacet.waitForDeployment(); - const calldataTestFacet = testFacet.interface.encodeFunctionData("initialize", [rando.address]); + const calldataTestFacet = testFacet.interface.encodeFunctionData("initialize", [await rando.getAddress()]); - facetCut = getFacetAddCut(testFacet, [calldataTestFacet.slice(0, 10)]); + facetCut = await getFacetAddCut(testFacet, [calldataTestFacet.slice(0, 10)]); const calldataProtocolInitialization = protocolInitializationFacetDeployed.interface.encodeFunctionData( "initialize", - [version, [testFacet.address], [calldataTestFacet], true, initializationData, [], []] + [version, [await testFacet.getAddress()], [calldataTestFacet], true, initializationData, [], []] ); const cutTransaction = diamondCutFacet.diamondCut( [facetCut], - protocolInitializationFacetDeployed.address, + await protocolInitializationFacetDeployed.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ); @@ -190,30 +192,32 @@ describe("ProtocolInitializationHandler", async function () { // Add protocolInitializationFacet to diamond await deployAndCutFacets( - protocolDiamond.address, + await protocolDiamond.getAddress(), { ProtocolInitializationHandlerFacet: [] }, maxPriorityFeePerGas ); // Get actual deployed protocolInitializationFacet - const diamondLoupe = await ethers.getContractAt("DiamondLoupeFacet", protocolDiamond.address); - const signature = protocolInitializationFacet.interface.getSighash("getVersion()"); + const diamondLoupe = await getContractAt("DiamondLoupeFacet", await protocolDiamond.getAddress()); + const signature = protocolInitializationFacet.interface.fragments.find( + (f) => f.name == "getVersion" + ).selector; const existingFacetAddress = await diamondLoupe.facetAddress(signature); - const protocolInitializationFacet2 = await ethers.getContractAt( + const protocolInitializationFacet2 = await getContractAt( "ProtocolInitializationHandlerFacet", existingFacetAddress ); // Deploy selfDestruct contract that will be called during initialize - const SelfDestructorFactory = await ethers.getContractFactory("SelfDestructor"); + const SelfDestructorFactory = await getContractFactory("SelfDestructor"); const selfDestructor = await SelfDestructorFactory.deploy(); const selfDestructorInitData = selfDestructor.interface.encodeFunctionData("destruct"); // call initialize await expect( protocolInitializationFacet2.initialize( - ethers.utils.formatBytes32String("haha"), - [selfDestructor.address], + encodeBytes32String("haha"), + [await selfDestructor.getAddress()], [selfDestructorInitData], false, "0x", @@ -234,7 +238,7 @@ describe("ProtocolInitializationHandler", async function () { const interfaceId = InterfaceIds[interfaceImplementers["ProtocolInitializationHandlerFacet"]]; const { deployedFacets } = await deployAndCutFacets( - protocolDiamond.address, + await protocolDiamond.getAddress(), { ProtocolInitializationHandlerFacet: [version, [], [], true] }, maxPriorityFeePerGas, version, @@ -260,7 +264,7 @@ describe("ProtocolInitializationHandler", async function () { const configHandlerInterface = InterfaceIds[interfaceImplementers["ConfigHandlerFacet"]]; const accountInterface = InterfaceIds[interfaceImplementers["AccountHandlerFacet"]]; - version = ethers.utils.formatBytes32String("2.3.0"); + version = encodeBytes32String("2.3.0"); const calldataProtocolInitialization = deployedProtocolInitializationHandlerFacet.contract.interface.encodeFunctionData("initialize", [ version, @@ -274,7 +278,7 @@ describe("ProtocolInitializationHandler", async function () { await diamondCutFacet.diamondCut( [], - deployedProtocolInitializationHandlerFacet.contract.address, + await deployedProtocolInitializationHandlerFacet.contract.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ); @@ -296,17 +300,17 @@ describe("ProtocolInitializationHandler", async function () { }); it("Should call facet initializer internally when _addresses and _calldata are supplied", async function () { - let FacetTestFactory = await ethers.getContractFactory("Test3Facet"); + let FacetTestFactory = await getContractFactory("Test3Facet"); const testFacet = await FacetTestFactory.deploy(await getFees(maxPriorityFeePerGas)); - await testFacet.deployTransaction.wait(); + await testFacet.waitForDeployment(); - const calldataTestFacet = testFacet.interface.encodeFunctionData("initialize", [rando.address]); + const calldataTestFacet = testFacet.interface.encodeFunctionData("initialize", [await rando.getAddress()]); - version = ethers.utils.formatBytes32String("2.3.0"); + version = encodeBytes32String("2.3.0"); const calldataProtocolInitialization = deployedProtocolInitializationHandlerFacet.contract.interface.encodeFunctionData("initialize", [ version, - [testFacet.address], + [await testFacet.getAddress()], [calldataTestFacet], true, "0x", @@ -314,38 +318,38 @@ describe("ProtocolInitializationHandler", async function () { [], ]); - const facetCuts = [getFacetAddCut(testFacet)]; + const facetCuts = [await getFacetAddCut(testFacet)]; await diamondCutFacet.diamondCut( facetCuts, - deployedProtocolInitializationHandlerFacet.contract.address, + await deployedProtocolInitializationHandlerFacet.contract.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ); - const testFacetContract = await ethers.getContractAt("Test3Facet", protocolDiamond.address); + const testFacetContract = await getContractAt("Test3Facet", await protocolDiamond.getAddress()); - expect(await testFacetContract.getTestAddress()).to.equal(rando.address); + expect(await testFacetContract.getTestAddress()).to.equal(await rando.getAddress()); }); context("💔 Revert Reasons", async function () { let testFacet, version; beforeEach(async function () { - let FacetTestFactory = await ethers.getContractFactory("Test3Facet"); + let FacetTestFactory = await getContractFactory("Test3Facet"); testFacet = await FacetTestFactory.deploy(await getFees(maxPriorityFeePerGas)); - await testFacet.deployTransaction.wait(); + await testFacet.waitForDeployment(); - version = ethers.utils.formatBytes32String("2.3.0"); + version = encodeBytes32String("2.3.0"); }); it("Delegate call to initialize fails", async function () { - const calldataTestFacet = testFacet.interface.encodeFunctionData("initialize", [testFacet.address]); + const calldataTestFacet = testFacet.interface.encodeFunctionData("initialize", [await testFacet.getAddress()]); const calldataProtocolInitialization = deployedProtocolInitializationHandlerFacet.contract.interface.encodeFunctionData("initialize", [ version, - [testFacet.address], + [await testFacet.getAddress()], [calldataTestFacet], true, initializationData, @@ -353,12 +357,12 @@ describe("ProtocolInitializationHandler", async function () { [], ]); - const facetCuts = [getFacetAddCut(testFacet)]; + const facetCuts = [await getFacetAddCut(testFacet)]; await expect( diamondCutFacet.diamondCut( facetCuts, - deployedProtocolInitializationHandlerFacet.contract.address, + await deployedProtocolInitializationHandlerFacet.contract.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ) @@ -368,12 +372,12 @@ describe("ProtocolInitializationHandler", async function () { it("Default reason if not supplied by implementation", async () => { // If the caller's address is supplied Test3Facet's initializer will revert with no reason // and so the diamondCut function will supply it's own reason - const calldataTestFacet = testFacet.interface.encodeFunctionData("initialize", [deployer.address]); + const calldataTestFacet = testFacet.interface.encodeFunctionData("initialize", [await deployer.getAddress()]); const calldataProtocolInitialization = deployedProtocolInitializationHandlerFacet.contract.interface.encodeFunctionData("initialize", [ version, - [testFacet.address], + [await testFacet.getAddress()], [calldataTestFacet], true, initializationData, @@ -381,12 +385,12 @@ describe("ProtocolInitializationHandler", async function () { [], ]); - const facetCuts = [getFacetAddCut(testFacet)]; + const facetCuts = [await getFacetAddCut(testFacet)]; await expect( diamondCutFacet.diamondCut( facetCuts, - deployedProtocolInitializationHandlerFacet.contract.address, + await deployedProtocolInitializationHandlerFacet.contract.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ) @@ -405,14 +409,12 @@ describe("ProtocolInitializationHandler", async function () { version = "2.1.0"; // Deploy mock protocol initialization facet which simulates state before v2.2.0 - const ProtocolInitilizationContractFactory = await ethers.getContractFactory( - "MockProtocolInitializationHandlerFacet" - ); + const ProtocolInitilizationContractFactory = await getContractFactory("MockProtocolInitializationHandlerFacet"); const mockInitializationFacetDeployed = await ProtocolInitilizationContractFactory.deploy( await getFees(maxPriorityFeePerGas) ); - await mockInitializationFacetDeployed.deployTransaction.wait(); + await mockInitializationFacetDeployed.waitForDeployment(); const facetNames = [ "SellerHandlerFacet", @@ -428,7 +430,7 @@ describe("ProtocolInitializationHandler", async function () { // Make initial deployment (simulate v2.1.0) await deployAndCutFacets( - protocolDiamond.address, + await protocolDiamond.getAddress(), facetsToDeploy, maxPriorityFeePerGas, version, @@ -444,12 +446,11 @@ describe("ProtocolInitializationHandler", async function () { await getFees(maxPriorityFeePerGas) ); - version = ethers.utils.formatBytes32String("2.2.0"); - + version = encodeBytes32String("2.2.0"); // Prepare cut data - facetCut = getFacetAddCut(configHandler); + facetCut = await getFacetAddCut(configHandler); // Attach correct address to configHandler - configHandler = configHandler.attach(protocolDiamond.address); + configHandler = configHandler.attach(await protocolDiamond.getAddress()); // Prepare calldata calldataProtocolInitialization = deployedProtocolInitializationHandlerFacet.interface.encodeFunctionData( "initialize", @@ -460,22 +461,22 @@ describe("ProtocolInitializationHandler", async function () { it("Should emit MaxPremintedVouchersChanged event", async function () { // Make the cut, check the event await expect( - diamondCutFacet.diamondCut( + await diamondCutFacet.diamondCut( [facetCut], - deployedProtocolInitializationHandlerFacet.address, + await deployedProtocolInitializationHandlerFacet.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ) ) .to.emit(configHandler, "MaxPremintedVouchersChanged") - .withArgs(maxPremintedVouchers, deployer.address); + .withArgs(maxPremintedVouchers, await deployer.getAddress()); }); it("Should update state", async function () { // Make the cut, check the event await diamondCutFacet.diamondCut( [facetCut], - deployedProtocolInitializationHandlerFacet.address, + await deployedProtocolInitializationHandlerFacet.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ); @@ -488,7 +489,7 @@ describe("ProtocolInitializationHandler", async function () { it("Max preminted vouchers is zero", async function () { // set invalid maxPremintedVouchers maxPremintedVouchers = "0"; - initializationData = ethers.utils.defaultAbiCoder.encode(["uint256"], [maxPremintedVouchers]); + initializationData = abiCoder.encode(["uint256"], [maxPremintedVouchers]); calldataProtocolInitialization = deployedProtocolInitializationHandlerFacet.interface.encodeFunctionData( "initialize", @@ -499,7 +500,7 @@ describe("ProtocolInitializationHandler", async function () { await expect( diamondCutFacet.diamondCut( [facetCut], - deployedProtocolInitializationHandlerFacet.address, + await deployedProtocolInitializationHandlerFacet.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ) @@ -513,7 +514,7 @@ describe("ProtocolInitializationHandler", async function () { const { deployedFacets: [{ contract: deployedProtocolInitializationHandlerFacet }], } = await deployAndCutFacets( - protocolDiamond.address, + await protocolDiamond.getAddress(), { ProtocolInitializationHandlerFacet: [version, [], [], true] }, maxPriorityFeePerGas, version, @@ -522,13 +523,13 @@ describe("ProtocolInitializationHandler", async function () { ); // Prepare 2.2.0 deployment - version = ethers.utils.formatBytes32String("2.2.0"); + version = encodeBytes32String("2.2.0"); // make diamond cut, expect revert await expect( diamondCutFacet.diamondCut( [facetCut], - deployedProtocolInitializationHandlerFacet.address, + await deployedProtocolInitializationHandlerFacet.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ) @@ -536,6 +537,7 @@ describe("ProtocolInitializationHandler", async function () { }); }); }); + describe("initV2_2_1", async function () { let deployedProtocolInitializationHandlerFacet; let facetCut; @@ -547,7 +549,7 @@ describe("ProtocolInitializationHandler", async function () { const facetsToDeploy = await getV2_2_0DeployConfig(); // Make initial deployment (simulate v2.2.0) - await deployAndCutFacets(protocolDiamond.address, facetsToDeploy, maxPriorityFeePerGas, version); + await deployAndCutFacets(await protocolDiamond.getAddress(), facetsToDeploy, maxPriorityFeePerGas, version); version = "2.2.1"; @@ -559,12 +561,14 @@ describe("ProtocolInitializationHandler", async function () { ); // Prepare cut data - facetCut = getFacetReplaceCut(deployedProtocolInitializationHandlerFacet, ["initialize"]); + facetCut = await getFacetReplaceCut(deployedProtocolInitializationHandlerFacet, [ + deployedProtocolInitializationHandlerFacet.interface.fragments.find((f) => f.name == "initialize").selector, + ]); // Prepare calldata calldataProtocolInitialization = deployedProtocolInitializationHandlerFacet.interface.encodeFunctionData( "initialize", - [ethers.utils.formatBytes32String(version), [], [], true, [], [], []] + [encodeBytes32String(version), [], [], true, "0x", [], []] ); }); @@ -572,7 +576,7 @@ describe("ProtocolInitializationHandler", async function () { // Make the cut, check the event const tx = await diamondCutFacet.diamondCut( [facetCut], - deployedProtocolInitializationHandlerFacet.address, + await deployedProtocolInitializationHandlerFacet.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ); @@ -587,18 +591,18 @@ describe("ProtocolInitializationHandler", async function () { // Prepare calldata const calldataProtocolInitializationWrong = deployedProtocolInitializationHandlerFacet.interface.encodeFunctionData("initialize", [ - ethers.utils.formatBytes32String(wrongVersion), + encodeBytes32String(wrongVersion), [], [], true, - [], + "0x", [], [], ]); await diamondCutFacet.diamondCut( [facetCut], - deployedProtocolInitializationHandlerFacet.address, + await deployedProtocolInitializationHandlerFacet.getAddress(), calldataProtocolInitializationWrong, await getFees(maxPriorityFeePerGas) ); @@ -610,13 +614,15 @@ describe("ProtocolInitializationHandler", async function () { ); // Prepare cut data - facetCut = getFacetReplaceCut(accountHandler, ["initialize"]); + facetCut = await getFacetReplaceCut(accountHandler, [ + accountHandler.interface.fragments.find((f) => f.name == "initialize").selector, + ]); // Make diamond cut, expect revert await expect( diamondCutFacet.diamondCut( [facetCut], - deployedProtocolInitializationHandlerFacet.address, + await deployedProtocolInitializationHandlerFacet.getAddress(), calldataProtocolInitialization, await getFees(maxPriorityFeePerGas) ) diff --git a/test/protocol/SellerHandlerTest.js b/test/protocol/SellerHandlerTest.js index f282f44b3..3fbbdcb65 100644 --- a/test/protocol/SellerHandlerTest.js +++ b/test/protocol/SellerHandlerTest.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, getContractAt, getSigners } = ethers; const { expect, assert } = require("chai"); const Seller = require("../../scripts/domain/Seller"); const AuthToken = require("../../scripts/domain/AuthToken"); @@ -69,23 +70,27 @@ describe("SellerHandler", function () { // make all account the same authTokenOwner = assistant = admin; - clerk = { address: ethers.constants.AddressZero }; - [deployer] = await ethers.getSigners(); + clerk = { address: ZeroAddress }; + [deployer] = await getSigners(); // Deploy mock ERC721 tokens [mockAuthERC721Contract, mockAuthERC721Contract2] = await deployMockTokens(["Foreign721", "Foreign721"]); await expect( - configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.Lens, mockAuthERC721Contract.address) + configHandler + .connect(deployer) + .setAuthTokenContract(AuthTokenType.Lens, await mockAuthERC721Contract.getAddress()) ) .to.emit(configHandler, "AuthTokenContractChanged") - .withArgs(AuthTokenType.Lens, mockAuthERC721Contract.address, deployer.address); + .withArgs(AuthTokenType.Lens, await mockAuthERC721Contract.getAddress(), await deployer.getAddress()); await expect( - configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.ENS, mockAuthERC721Contract2.address) + configHandler + .connect(deployer) + .setAuthTokenContract(AuthTokenType.ENS, await mockAuthERC721Contract2.getAddress()) ) .to.emit(configHandler, "AuthTokenContractChanged") - .withArgs(AuthTokenType.ENS, mockAuthERC721Contract2.address, deployer.address); + .withArgs(AuthTokenType.ENS, await mockAuthERC721Contract2.getAddress(), await deployer.getAddress()); await mockAuthERC721Contract.connect(authTokenOwner).mint(8400, 1); @@ -104,10 +109,10 @@ describe("SellerHandler", function () { // Create a valid seller, then set fields in tests directly seller = mockSeller( - assistant.address, - admin.address, + await assistant.getAddress(), + await admin.getAddress(), clerk.address, - treasury.address, + await treasury.getAddress(), true, "https://ipfs.io/ipfs/originalUri" ); @@ -122,7 +127,7 @@ describe("SellerHandler", function () { expect(voucherInitValues.isValid()).is.true; // expected address of the first clone - expectedCloneAddress = calculateContractAddress(accountHandler.address, "1"); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "1"); // AuthTokens emptyAuthToken = mockAuthToken(); @@ -146,10 +151,10 @@ describe("SellerHandler", function () { await expect(tx) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, admin.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await admin.getAddress()); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); @@ -161,25 +166,25 @@ describe("SellerHandler", function () { .to.emit(bosonVoucher, "VoucherInitialized") .withArgs(seller.id, voucherInitValues.royaltyPercentage, contractURI); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should emit a SellerCreated event when auth token is not empty", async function () { // Create a seller, testing for the event - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; sellerStruct = seller.toStruct(); const tx = await accountHandler.connect(authTokenOwner).createSeller(seller, authToken, voucherInitValues); await expect(tx) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, authTokenOwner.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, await authTokenOwner.getAddress()); // Voucher clone contract - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged").withArgs(contractURI); @@ -191,11 +196,11 @@ describe("SellerHandler", function () { .to.emit(bosonVoucher, "VoucherInitialized") .withArgs(seller.id, voucherInitValues.royaltyPercentage, contractURI); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx) .to.emit(bosonVoucher, "OwnershipTransferred") - .withArgs(ethers.constants.AddressZero, assistant.address); + .withArgs(ZeroAddress, await assistant.getAddress()); }); it("should update state when authToken is empty", async function () { @@ -220,11 +225,11 @@ describe("SellerHandler", function () { } // Voucher clone contract - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); - expect(await bosonVoucher.owner()).to.equal(assistant.address, "Wrong voucher clone owner"); + expect(await bosonVoucher.owner()).to.equal(await assistant.getAddress(), "Wrong voucher clone owner"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -238,7 +243,7 @@ describe("SellerHandler", function () { // Create a seller await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -257,7 +262,7 @@ describe("SellerHandler", function () { [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); // Expectations - let expectedRecipient = ethers.constants.AddressZero; //expect zero address when exchange id does not exist + let expectedRecipient = ZeroAddress; //expect zero address when exchange id does not exist let expectedRoyaltyAmount = "0"; // Zero Fee when exchange id does not exist assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); @@ -272,7 +277,7 @@ describe("SellerHandler", function () { // Create a seller await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -291,7 +296,7 @@ describe("SellerHandler", function () { [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); // Expectations - let expectedRecipient = ethers.constants.AddressZero; //expect zero address when exchange id does not exist + let expectedRecipient = ZeroAddress; //expect zero address when exchange id does not exist let expectedRoyaltyAmount = "0"; // Zero Fee when exchange id does not exist assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); @@ -299,7 +304,7 @@ describe("SellerHandler", function () { }); it("should update state when authToken is not empty", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Create a seller await accountHandler.connect(authTokenOwner).createSeller(seller, authToken, voucherInitValues); @@ -322,11 +327,11 @@ describe("SellerHandler", function () { } // Voucher clone contract - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); - expect(await bosonVoucher.owner()).to.equal(assistant.address, "Wrong voucher clone owner"); + expect(await bosonVoucher.owner()).to.equal(await assistant.getAddress(), "Wrong voucher clone owner"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); expect(await bosonVoucher.contractURI()).to.equal(contractURI, "Wrong contract URI"); expect(await bosonVoucher.name()).to.equal(VOUCHER_NAME + " " + seller.id, "Wrong voucher client name"); expect(await bosonVoucher.symbol()).to.equal(VOUCHER_SYMBOL + "_" + seller.id, "Wrong voucher client symbol"); @@ -339,7 +344,7 @@ describe("SellerHandler", function () { // Create a seller, testing for the event await expect(accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(sellerId, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, admin.address); + .withArgs(sellerId, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await admin.getAddress()); // wrong seller id should not exist [exists] = await accountHandler.connect(rando).getSeller(seller.id); @@ -351,10 +356,10 @@ describe("SellerHandler", function () { }); it("should be possible to use the same address for assistant, admin and treasury", async function () { - seller.assistant = other1.address; - seller.admin = other1.address; - seller.clerk = ethers.constants.AddressZero; - seller.treasury = other1.address; + seller.assistant = await other1.getAddress(); + seller.admin = await other1.getAddress(); + seller.clerk = ZeroAddress; + seller.treasury = await other1.getAddress(); //Create struct again with new addresses sellerStruct = seller.toStruct(); @@ -362,50 +367,61 @@ describe("SellerHandler", function () { // Create a seller, testing for the event await expect(accountHandler.connect(other1).createSeller(seller, emptyAuthToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, other1.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await other1.getAddress()); }); it("should be possible to use non-unique treasury address", async function () { // Create a seller, testing for the event await expect(accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, admin.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await admin.getAddress()); seller.id = accountId.next().value; - seller.assistant = other1.address; - seller.admin = other1.address; + seller.assistant = await other1.getAddress(); + seller.admin = await other1.getAddress(); //Create struct again with new addresses sellerStruct = seller.toStruct(); // expected address of the first clone - expectedCloneAddress = calculateContractAddress(accountHandler.address, "2"); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "2"); // Create a seller, testing for the event await expect(accountHandler.connect(other1).createSeller(seller, emptyAuthToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, other1.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await other1.getAddress()); }); it("every seller should get a different clone address", async function () { // Create a seller, testing for the event await expect(accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, admin.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await admin.getAddress()); // second seller - expectedCloneAddress = calculateContractAddress(accountHandler.address, "2"); - seller = mockSeller(other1.address, other1.address, ethers.constants.AddressZero, other1.address); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "2"); + seller = mockSeller( + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() + ); // Create a seller, testing for the event await expect(accountHandler.connect(other1).createSeller(seller, emptyAuthToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, seller.toStruct(), expectedCloneAddress, emptyAuthTokenStruct, other1.address); + .withArgs( + seller.id, + seller.toStruct(), + expectedCloneAddress, + emptyAuthTokenStruct, + await other1.getAddress() + ); }); it("should be possible to create a seller with same auth token id but different type", async function () { // Set admin == zero address because seller will be created with auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; //Create struct again with new address sellerStruct = seller.toStruct(); @@ -413,15 +429,15 @@ describe("SellerHandler", function () { // Create a seller, testing for the event await expect(accountHandler.connect(authTokenOwner).createSeller(seller, authToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, authTokenOwner.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, await authTokenOwner.getAddress()); - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); // Update assistant address so we can create a seller with the same auth token id but different type const tx = await accountHandler.connect(authTokenOwner).updateSeller(seller, authToken); pendingSellerUpdate = seller.clone(); - pendingSellerUpdate.treasury = ethers.constants.AddressZero; + pendingSellerUpdate.treasury = ZeroAddress; pendingSellerUpdate.active = false; pendingSellerUpdate.metadataUri = ""; pendingSellerUpdate.id = "0"; @@ -435,13 +451,13 @@ describe("SellerHandler", function () { await expect(tx) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdateStruct, pendingAuthTokenStruct, authTokenOwner.address); + .withArgs(seller.id, pendingSellerUpdateStruct, pendingAuthTokenStruct, await authTokenOwner.getAddress()); sellerStruct = seller.toStruct(); // Nothing pending left - pendingSellerUpdate.assistant = ethers.constants.AddressZero; - pendingSellerUpdate.clerk = ethers.constants.AddressZero; + pendingSellerUpdate.assistant = ZeroAddress; + pendingSellerUpdate.clerk = ZeroAddress; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); // Assistant address owner must approve the update @@ -455,11 +471,11 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, authTokenStruct, pendingAuthTokenStruct, - other1.address + await other1.getAddress() ); seller.id = accountId.next().value; - seller.assistant = authTokenOwner.address; + seller.assistant = await authTokenOwner.getAddress(); //Create struct again with new addresses sellerStruct = seller.toStruct(); @@ -472,17 +488,17 @@ describe("SellerHandler", function () { await mockAuthERC721Contract2.connect(authTokenOwner).mint(8400, 1); // expected address of the first clone - expectedCloneAddress = calculateContractAddress(accountHandler.address, "2"); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "2"); // Create a seller, testing for the event await expect(accountHandler.connect(authTokenOwner).createSeller(seller, authToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, authTokenOwner.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, await authTokenOwner.getAddress()); }); it("should be possible to create a seller with same auth token type but different id", async function () { // Set admin == zero address because seller will be created with auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; //Create struct again with new address sellerStruct = seller.toStruct(); @@ -490,13 +506,13 @@ describe("SellerHandler", function () { // Create a seller, testing for the event await expect(accountHandler.connect(authTokenOwner).createSeller(seller, authToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, authTokenOwner.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, await authTokenOwner.getAddress()); - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); pendingSellerUpdate = seller.clone(); pendingSellerUpdate.id = "0"; - pendingSellerUpdate.treasury = ethers.constants.AddressZero; + pendingSellerUpdate.treasury = ZeroAddress; pendingSellerUpdate.metadataUri = ""; pendingSellerUpdate.active = false; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); @@ -512,11 +528,11 @@ describe("SellerHandler", function () { await expect(tx) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdateStruct, pendingAuthTokenStruct, authTokenOwner.address); + .withArgs(seller.id, pendingSellerUpdateStruct, pendingAuthTokenStruct, await authTokenOwner.getAddress()); // Nothing pending left - pendingSellerUpdate.assistant = ethers.constants.AddressZero; - pendingSellerUpdate.clerk = ethers.constants.AddressZero; + pendingSellerUpdate.assistant = ZeroAddress; + pendingSellerUpdate.clerk = ZeroAddress; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); sellerStruct = seller.toStruct(); @@ -530,12 +546,12 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, authTokenStruct, pendingAuthTokenStruct, - other1.address + await other1.getAddress() ); const newAuthTokenOwner = rando; seller.id = accountId.next().value; - seller.assistant = newAuthTokenOwner.address; + seller.assistant = await newAuthTokenOwner.getAddress(); //Create struct again with new addresses sellerStruct = seller.toStruct(); @@ -548,12 +564,18 @@ describe("SellerHandler", function () { await mockAuthERC721Contract.connect(rando).mint(authToken.tokenId, 1); // expected address of the first clone - expectedCloneAddress = calculateContractAddress(accountHandler.address, "2"); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "2"); // Create a seller, testing for the event await expect(accountHandler.connect(rando).createSeller(seller, authToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, authTokenStruct, newAuthTokenOwner.address); + .withArgs( + seller.id, + sellerStruct, + expectedCloneAddress, + authTokenStruct, + await newAuthTokenOwner.getAddress() + ); }); context("💔 Revert Reasons", async function () { @@ -581,21 +603,21 @@ describe("SellerHandler", function () { await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); // Update seller assistant - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); // Approve the update await accountHandler.connect(other1).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant]); - seller.admin = other1.address; + seller.admin = await other1.getAddress(); // Attempt to Create a seller with non-unique assistant, expecting revert await expect( accountHandler.connect(other1).createSeller(seller, emptyAuthToken, voucherInitValues) ).to.revertedWith(RevertReasons.SELLER_ADDRESS_MUST_BE_UNIQUE); - seller.admin = admin.address; - seller.assistant = assistant.address; + seller.admin = await admin.getAddress(); + seller.assistant = await assistant.getAddress(); // Attempt to Create a seller with non-unique admin, expecting revert await expect( @@ -608,13 +630,13 @@ describe("SellerHandler", function () { await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); // Update seller assistant - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); // Approve the update await accountHandler.connect(other1).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant]); - seller.admin = other1.address; + seller.admin = await other1.getAddress(); // Attempt to Create a seller with non-unique assistant, expecting revert await expect( @@ -622,8 +644,8 @@ describe("SellerHandler", function () { ).to.revertedWith(RevertReasons.SELLER_ADDRESS_MUST_BE_UNIQUE); // Update seller admin - seller.admin = other3.address; - seller.assistant = assistant.address; + seller.admin = await other3.getAddress(); + seller.assistant = await assistant.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); @@ -631,7 +653,7 @@ describe("SellerHandler", function () { await accountHandler.connect(other3).optInToSellerUpdate(seller.id, [SellerUpdateFields.Admin]); await accountHandler.connect(assistant).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant]); - seller.assistant = other3.address; + seller.assistant = await other3.getAddress(); // Attempt to Create a seller with non-unique admin, expecting revert await expect( @@ -641,20 +663,20 @@ describe("SellerHandler", function () { it("addresses are not unique to this seller Id when address used for same role and the seller is created with auth token", async function () { // Create a seller - seller.admin = rando.address; - seller.assistant = rando.address; + seller.admin = await rando.getAddress(); + seller.assistant = await rando.getAddress(); seller2 = mockSeller( - authTokenOwner.address, - ethers.constants.AddressZero, - ethers.constants.AddressZero, - authTokenOwner.address + await authTokenOwner.getAddress(), + ZeroAddress, + ZeroAddress, + await authTokenOwner.getAddress() ); await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); // Update the seller, so assistant matches authTokenOwner - seller.assistant = authTokenOwner.address; + seller.assistant = await authTokenOwner.getAddress(); await accountHandler.connect(rando).updateSeller(seller, emptyAuthToken); // Approve the update @@ -674,7 +696,7 @@ describe("SellerHandler", function () { }); it("admin address is zero address and AuthTokenType is None", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Attempt to Create a seller, expecting revert await expect( @@ -684,8 +706,8 @@ describe("SellerHandler", function () { it("authToken is not unique to this seller", async function () { // Set admin == zero address because seller will be created with auth token - seller.admin = ethers.constants.AddressZero; - seller.assistant = authTokenOwner.address; + seller.admin = ZeroAddress; + seller.assistant = await authTokenOwner.getAddress(); // Create a seller await accountHandler.connect(authTokenOwner).createSeller(seller, authToken, voucherInitValues); @@ -698,7 +720,7 @@ describe("SellerHandler", function () { it("authTokenType is Custom", async function () { // Set admin == zero address because seller will be created with auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; authToken.tokenType = AuthTokenType.Custom; @@ -709,7 +731,7 @@ describe("SellerHandler", function () { }); it("Caller is not the supplied admin", async function () { - seller.assistant = rando.address; + seller.assistant = await rando.getAddress(); // Attempt to Create a seller with admin not the same to caller address await expect( @@ -719,8 +741,8 @@ describe("SellerHandler", function () { it("Caller does not own supplied auth token", async function () { // Set admin == zero address because seller will be created with auth token - seller.admin = ethers.constants.AddressZero; - seller.assistant = rando.address; + seller.admin = ZeroAddress; + seller.assistant = await rando.getAddress(); // Attempt to Create a seller without owning the auth token await expect( @@ -729,7 +751,7 @@ describe("SellerHandler", function () { }); it("Caller is not the supplied assistant", async function () { - seller.admin = rando.address; + seller.admin = await rando.getAddress(); // Attempt to Create a seller with assistant not the same to caller address await expect( @@ -738,9 +760,9 @@ describe("SellerHandler", function () { }); it("Clerk is not a zero address", async function () { - seller.admin = rando.address; - seller.assistant = rando.address; - seller.clerk = rando.address; + seller.admin = await rando.getAddress(); + seller.assistant = await rando.getAddress(); + seller.clerk = await rando.getAddress(); // Attempt to Create a seller with clerk not the same to caller address await expect( @@ -749,8 +771,8 @@ describe("SellerHandler", function () { }); it("addresses are the zero address", async function () { - seller.assistant = ethers.constants.AddressZero; - seller.treasury = ethers.constants.AddressZero; + seller.assistant = ZeroAddress; + seller.treasury = ZeroAddress; // Attempt to update a seller, expecting revert await expect( @@ -759,7 +781,7 @@ describe("SellerHandler", function () { }); it("Assistant address is zero address", async function () { - seller.assistant = ethers.constants.AddressZero; + seller.assistant = ZeroAddress; // Attempt to Create a seller with assistant == zero address await expect( @@ -768,7 +790,7 @@ describe("SellerHandler", function () { }); it("Treasury address is zero address", async function () { - seller.treasury = ethers.constants.AddressZero; + seller.treasury = ZeroAddress; // Attempt to Create a seller with treasury == zero address await expect( @@ -788,13 +810,18 @@ describe("SellerHandler", function () { expect(authToken.isValid()).is.true; // Seller can have either admin address or auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Create a seller await accountHandler.connect(authTokenOwner).createSeller(seller, authToken, voucherInitValues); // Create a another seller - seller2 = mockSeller(other1.address, other1.address, ethers.constants.AddressZero, other1.address); + seller2 = mockSeller( + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() + ); expect(seller2.isValid()).is.true; await accountHandler.connect(other1).createSeller(seller2, emptyAuthToken, voucherInitValues); @@ -865,13 +892,18 @@ describe("SellerHandler", function () { expect(authToken.isValid()).is.true; // Seller can have either admin address or auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Create a seller await accountHandler.connect(authTokenOwner).createSeller(seller, authToken, voucherInitValues); // Create a another seller - seller2 = mockSeller(other1.address, other1.address, ethers.constants.AddressZero, other1.address); + seller2 = mockSeller( + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() + ); expect(seller2.isValid()).is.true; contractURI = `https://ipfs.io/ipfs/QmW2WQi7j6c7UgJTarActp7tDNikE4B2qXtFCfLPdsgaTQ`; @@ -887,7 +919,7 @@ describe("SellerHandler", function () { it("should return the correct seller when searching on assistant address", async function () { [exists, sellerStruct, authTokenStruct] = await accountHandler .connect(rando) - .getSellerByAddress(assistant.address); + .getSellerByAddress(await assistant.getAddress()); expect(exists).is.true; @@ -909,7 +941,7 @@ describe("SellerHandler", function () { it("should return the correct seller when searching on admin address", async function () { [exists, sellerStruct, emptyAuthTokenStruct] = await accountHandler .connect(rando) - .getSellerByAddress(other1.address); + .getSellerByAddress(await other1.getAddress()); expect(exists).is.true; @@ -931,7 +963,7 @@ describe("SellerHandler", function () { it("should return exists false and default values when searching on treasury address", async function () { [exists, sellerStruct, emptyAuthTokenStruct] = await accountHandler .connect(rando) - .getSellerByAddress(treasury.address); + .getSellerByAddress(await treasury.getAddress()); expect(exists).is.false; @@ -942,7 +974,7 @@ describe("SellerHandler", function () { // Returned values should be the default value for it's data type for ([key, value] of Object.entries(returnedSeller)) { if (key != "active") { - expect(value == 0).is.true || expect(value === ethers.constants.AddressZero).is.true; + expect(value == 0).is.true || expect(value === ZeroAddress).is.true; } else { expect(value).is.false; } @@ -957,7 +989,7 @@ describe("SellerHandler", function () { it("should return exists false and default values when searching on unassociated address", async function () { [exists, sellerStruct, emptyAuthTokenStruct] = await accountHandler .connect(rando) - .getSellerByAddress(deployer.address); + .getSellerByAddress(await deployer.getAddress()); expect(exists).is.false; @@ -968,7 +1000,7 @@ describe("SellerHandler", function () { // Returned values should be the default value for it's data type for ([key, value] of Object.entries(returnedSeller)) { if (key != "active") { - expect(value == 0).is.true || expect(value === ethers.constants.AddressZero).is.true; + expect(value == 0).is.true || expect(value === ZeroAddress).is.true; } else { expect(value).is.false; } @@ -994,7 +1026,7 @@ describe("SellerHandler", function () { // Returned values should be the default value for it's data type for ([key, value] of Object.entries(returnedSeller)) { if (key != "active") { - expect(value == 0).is.true || expect(value === ethers.constants.AddressZero).is.true; + expect(value == 0).is.true || expect(value === ZeroAddress).is.true; } else { expect(value).is.false; } @@ -1009,7 +1041,7 @@ describe("SellerHandler", function () { it("should return exists false and default values when searching on zero address", async function () { [exists, sellerStruct, emptyAuthTokenStruct] = await accountHandler .connect(rando) - .getSellerByAddress(ethers.constants.AddressZero); + .getSellerByAddress(ZeroAddress); expect(exists).is.false; @@ -1020,7 +1052,7 @@ describe("SellerHandler", function () { // Returned values should be the default value for it's data type for ([key, value] of Object.entries(returnedSeller)) { if (key != "active") { - expect(value == 0).is.true || expect(value === ethers.constants.AddressZero).is.true; + expect(value == 0).is.true || expect(value === ZeroAddress).is.true; } else { expect(value).is.false; } @@ -1046,13 +1078,18 @@ describe("SellerHandler", function () { expect(authToken2.isValid()).is.true; // Seller can have either admin address or auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Create a seller await accountHandler.connect(authTokenOwner).createSeller(seller, authToken, voucherInitValues); // Create seller 2 - seller2 = mockSeller(other1.address, other1.address, ethers.constants.AddressZero, other1.address); + seller2 = mockSeller( + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() + ); expect(seller2.isValid()).is.true; contractURI = `https://ipfs.io/ipfs/QmW2WQi7j6c7UgJTarActp7tDNikE4B2qXtFCfLPdsgaTQ`; @@ -1060,12 +1097,7 @@ describe("SellerHandler", function () { await accountHandler.connect(other1).createSeller(seller2, emptyAuthToken, voucherInitValues); // Create seller 3 - seller3 = mockSeller( - other5.address, - ethers.constants.AddressZero, - ethers.constants.AddressZero, - treasury.address - ); + seller3 = mockSeller(await other5.getAddress(), ZeroAddress, ZeroAddress, await treasury.getAddress()); expect(seller3.isValid()).is.true; contractURI = `https://ipfs.io/ipfs/QmPChd2hVbrJ6bfo3WBcTW4iZnpHm8TEzWkLHmLpXhF68A`; @@ -1125,12 +1157,7 @@ describe("SellerHandler", function () { expect(authToken3.isValid()).is.true; // Create seller 4 - seller4 = mockSeller( - rando.address, - ethers.constants.AddressZero, - ethers.constants.AddressZero, - treasury.address - ); + seller4 = mockSeller(await rando.getAddress(), ZeroAddress, ZeroAddress, await treasury.getAddress()); expect(seller4.isValid()).is.true; await mockAuthERC721Contract2.connect(rando).mint(authToken3.tokenId, 1); @@ -1181,12 +1208,7 @@ describe("SellerHandler", function () { expect(authToken3.isValid()).is.true; // Create seller 4 - seller4 = mockSeller( - rando.address, - ethers.constants.AddressZero, - ethers.constants.AddressZero, - treasury.address - ); + seller4 = mockSeller(await rando.getAddress(), ZeroAddress, ZeroAddress, await treasury.getAddress()); expect(seller4.isValid()).is.true; await mockAuthERC721Contract.connect(rando).mint(authToken3.tokenId, 1); @@ -1245,7 +1267,7 @@ describe("SellerHandler", function () { // Returned values should be the default value for it's data type for ([key, value] of Object.entries(returnedSeller)) { if (key != "active") { - expect(value == 0).is.true || expect(value === ethers.constants.AddressZero).is.true; + expect(value == 0).is.true || expect(value === ZeroAddress).is.true; } else { expect(value).is.false; } @@ -1262,10 +1284,10 @@ describe("SellerHandler", function () { beforeEach(async function () { pendingSellerUpdate = seller.clone(); pendingSellerUpdate.id = "0"; - pendingSellerUpdate.treasury = ethers.constants.AddressZero; - pendingSellerUpdate.clerk = ethers.constants.AddressZero; - pendingSellerUpdate.admin = ethers.constants.AddressZero; - pendingSellerUpdate.assistant = ethers.constants.AddressZero; + pendingSellerUpdate.treasury = ZeroAddress; + pendingSellerUpdate.clerk = ZeroAddress; + pendingSellerUpdate.admin = ZeroAddress; + pendingSellerUpdate.assistant = ZeroAddress; pendingSellerUpdate.active = false; pendingSellerUpdate.metadataUri = ""; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); @@ -1275,18 +1297,18 @@ describe("SellerHandler", function () { }); it("should emit a SellerUpdateApplied and OwnershipTransferred event with correct values if values change", async function () { - seller.treasury = other4.address; + seller.treasury = await other4.getAddress(); seller.metadataUri = "https://ipfs.io/ipfs/updatedUri"; // Treasury and metadataURI are only values that can be update without address owner authorization sellerStruct = seller.toStruct(); - seller.admin = ethers.constants.AddressZero; - seller.assistant = other1.address; + seller.admin = ZeroAddress; + seller.assistant = await other1.getAddress(); expect(seller.isValid()).is.true; pendingSellerUpdate = seller.clone(); pendingSellerUpdate.id = "0"; - pendingSellerUpdate.treasury = ethers.constants.AddressZero; + pendingSellerUpdate.treasury = ZeroAddress; pendingSellerUpdate.metadataUri = ""; pendingSellerUpdate.active = false; expect(pendingSellerUpdate.isValid()).is.true; @@ -1307,26 +1329,28 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, emptyAuthTokenStruct, pendingAuthTokenStruct, - admin.address + await admin.getAddress() ); // Testing for the SellerUpdatePending event await expect(tx) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdateStruct, pendingAuthTokenStruct, admin.address); + .withArgs(seller.id, pendingSellerUpdateStruct, pendingAuthTokenStruct, await admin.getAddress()); // Update seller assistant tx = await accountHandler.connect(other1).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant]); // Voucher clone contract - const bosonVoucherCloneAddress = calculateContractAddress(exchangeHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", bosonVoucherCloneAddress); + const bosonVoucherCloneAddress = calculateContractAddress(await exchangeHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", bosonVoucherCloneAddress); - await expect(tx).to.emit(bosonVoucher, "OwnershipTransferred").withArgs(assistant.address, other1.address); + await expect(tx) + .to.emit(bosonVoucher, "OwnershipTransferred") + .withArgs(await assistant.getAddress(), await other1.getAddress()); - pendingSellerUpdate.assistant = ethers.constants.AddressZero; + pendingSellerUpdate.assistant = ZeroAddress; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); - seller.admin = admin.address; + seller.admin = await admin.getAddress(); sellerStruct = seller.toStruct(); // Check assistant update @@ -1338,7 +1362,7 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, emptyAuthTokenStruct, pendingAuthTokenStruct, - other1.address + await other1.getAddress() ); // Update seller auth token @@ -1348,7 +1372,7 @@ describe("SellerHandler", function () { pendingAuthToken = emptyAuthToken; pendingAuthTokenStruct = pendingAuthToken.toStruct(); - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; sellerStruct = seller.toStruct(); // Check auth token update @@ -1360,20 +1384,20 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, authTokenStruct, pendingAuthTokenStruct, - authTokenOwner.address + await authTokenOwner.getAddress() ); }); it("should only emit SellerUpdatePending event if no update has been immediately applied", async function () { - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); const tx = await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); // SellerUpdateApplied should not be emit because no value has immediately updated await expect(tx).to.not.emit(accountHandler, "SellerUpdateApplied"); // Voucher clone contract - const bosonVoucherCloneAddress = calculateContractAddress(exchangeHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", bosonVoucherCloneAddress); + const bosonVoucherCloneAddress = calculateContractAddress(await exchangeHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", bosonVoucherCloneAddress); // Since assistant stayed the same yet, clone contract ownership should not be transferred immediately await expect(tx).to.not.emit(bosonVoucher, "OwnershipTransferred"); @@ -1383,9 +1407,9 @@ describe("SellerHandler", function () { }); it("should update state of all fields except Id and active flag", async function () { - seller.assistant = other1.address; - seller.admin = ethers.constants.AddressZero; - seller.treasury = other4.address; + seller.assistant = await other1.getAddress(); + seller.admin = ZeroAddress; + seller.treasury = await other4.getAddress(); seller.active = false; //Update should not change id or active flag @@ -1420,10 +1444,10 @@ describe("SellerHandler", function () { } //Check that old addresses are no longer mapped. We don't map the treasury address. - [exists] = await accountHandler.connect(rando).getSellerByAddress(assistant.address); + [exists] = await accountHandler.connect(rando).getSellerByAddress(await assistant.getAddress()); expect(exists).to.be.false; - [exists] = await accountHandler.connect(rando).getSellerByAddress(admin.address); + [exists] = await accountHandler.connect(rando).getSellerByAddress(await admin.getAddress()); expect(exists).to.be.false; //Check that new addresses are mapped. We don't map the treasury address. @@ -1435,31 +1459,28 @@ describe("SellerHandler", function () { expect(exists).to.be.false; // Voucher clone contract - const bosonVoucherCloneAddress = calculateContractAddress(exchangeHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", bosonVoucherCloneAddress); + const bosonVoucherCloneAddress = calculateContractAddress(await exchangeHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", bosonVoucherCloneAddress); expect(await bosonVoucher.owner()).to.equal(seller.assistant, "Wrong voucher clone owner"); }); it("should update state from auth token to empty auth token", async function () { - seller2 = mockSeller( - other1.address, - ethers.constants.AddressZero, - ethers.constants.AddressZero, - other1.address - ); + seller2 = mockSeller(await other1.getAddress(), ZeroAddress, ZeroAddress, await other1.getAddress()); expect(seller2.isValid()).is.true; // msg.sender must be equal to seller's assistant - await mockAuthERC721Contract.connect(authTokenOwner).transferFrom(authTokenOwner.address, other1.address, 8400); + await mockAuthERC721Contract + .connect(authTokenOwner) + .transferFrom(await authTokenOwner.getAddress(), await other1.getAddress(), 8400); const newAuthTokenOwner = other1; // Create a seller with auth token await accountHandler.connect(newAuthTokenOwner).createSeller(seller2, authToken, voucherInitValues); - seller2.assistant = other5.address; - seller2.admin = other6.address; - seller2.treasury = other7.address; + seller2.assistant = await other5.getAddress(); + seller2.admin = await other6.getAddress(); + seller2.treasury = await other7.getAddress(); seller2.active = false; //Update should not change id or active flag @@ -1494,13 +1515,13 @@ describe("SellerHandler", function () { } //Check that old addresses are no longer mapped. We don't map the treasury address. - [exists] = await accountHandler.connect(rando).getSellerByAddress(other1.address); + [exists] = await accountHandler.connect(rando).getSellerByAddress(await other1.getAddress()); expect(exists).to.be.false; - [exists] = await accountHandler.connect(rando).getSellerByAddress(ethers.constants.AddressZero); + [exists] = await accountHandler.connect(rando).getSellerByAddress(ZeroAddress); expect(exists).to.be.false; - [exists] = await accountHandler.connect(rando).getSellerByAddress(other3.address); + [exists] = await accountHandler.connect(rando).getSellerByAddress(await other3.getAddress()); expect(exists).to.be.false; //Check that new addresses are mapped. We don't map the treasury address. @@ -1511,31 +1532,28 @@ describe("SellerHandler", function () { expect(exists).to.be.true; // Voucher clone contract - const bosonVoucherCloneAddress = calculateContractAddress(exchangeHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", bosonVoucherCloneAddress); + const bosonVoucherCloneAddress = calculateContractAddress(await exchangeHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", bosonVoucherCloneAddress); expect(await bosonVoucher.owner()).to.equal(seller.assistant, "Wrong voucher clone owner"); }); it("should update state from auth token to new auth token", async function () { - seller2 = mockSeller( - other1.address, - ethers.constants.AddressZero, - ethers.constants.AddressZero, - other1.address - ); + seller2 = mockSeller(await other1.getAddress(), ZeroAddress, ZeroAddress, await other1.getAddress()); expect(seller2.isValid()).is.true; // msg.sender must be equal to seller's assistant - await mockAuthERC721Contract.connect(authTokenOwner).transferFrom(authTokenOwner.address, other1.address, 8400); + await mockAuthERC721Contract + .connect(authTokenOwner) + .transferFrom(await authTokenOwner.getAddress(), await other1.getAddress(), 8400); const newAuthTokenOwner = other1; // Create a seller with auth token await accountHandler.connect(newAuthTokenOwner).createSeller(seller2, authToken, voucherInitValues); - seller2.assistant = other5.address; - seller2.admin = ethers.constants.AddressZero; - seller2.treasury = other7.address; + seller2.assistant = await other5.getAddress(); + seller2.admin = ZeroAddress; + seller2.treasury = await other7.getAddress(); seller2.active = false; await mockAuthERC721Contract2.connect(newAuthTokenOwner).mint(0, 1); @@ -1572,13 +1590,13 @@ describe("SellerHandler", function () { } //Check that old addresses are no longer mapped. We don't map the treasury address. - [exists] = await accountHandler.connect(rando).getSellerByAddress(other1.address); + [exists] = await accountHandler.connect(rando).getSellerByAddress(await other1.getAddress()); expect(exists).to.be.false; - [exists] = await accountHandler.connect(rando).getSellerByAddress(ethers.constants.AddressZero); + [exists] = await accountHandler.connect(rando).getSellerByAddress(ZeroAddress); expect(exists).to.be.false; - [exists] = await accountHandler.connect(rando).getSellerByAddress(other3.address); + [exists] = await accountHandler.connect(rando).getSellerByAddress(await other3.getAddress()); expect(exists).to.be.false; //Check that new addresses are mapped. We don't map the treasury address. @@ -1589,14 +1607,14 @@ describe("SellerHandler", function () { expect(exists).to.be.false; // Voucher clone contract - const bosonVoucherCloneAddress = calculateContractAddress(exchangeHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", bosonVoucherCloneAddress); + const bosonVoucherCloneAddress = calculateContractAddress(await exchangeHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("OwnableUpgradeable", bosonVoucherCloneAddress); expect(await bosonVoucher.owner()).to.equal(seller.assistant, "Wrong voucher clone owner"); }); it("should update only one address", async function () { - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); sellerStruct = seller.toStruct(); @@ -1626,12 +1644,7 @@ describe("SellerHandler", function () { it("should update the correct seller", async function () { // Configure another seller - seller2 = mockSeller( - other1.address, - ethers.constants.AddressZero, - ethers.constants.AddressZero, - other1.address - ); + seller2 = mockSeller(await other1.getAddress(), ZeroAddress, ZeroAddress, await other1.getAddress()); expect(seller2.isValid()).is.true; contractURI = `https://ipfs.io/ipfs/QmW2WQi7j6c7UgJTarActp7tDNikE4B2qXtFCfLPdsgaTQ`; @@ -1647,9 +1660,9 @@ describe("SellerHandler", function () { await accountHandler.connect(authTokenOwner).createSeller(seller2, authToken2, voucherInitValues); //Update seller2 - seller2.assistant = rando.address; - seller2.admin = ethers.constants.AddressZero; - seller2.treasury = rando.address; + seller2.assistant = await rando.getAddress(); + seller2.admin = ZeroAddress; + seller2.treasury = await rando.getAddress(); seller2.active = false; //Update should not change id or active flag @@ -1706,9 +1719,9 @@ describe("SellerHandler", function () { }); it("should be able to only update with new admin address", async function () { - seller.admin = other2.address; + seller.admin = await other2.getAddress(); sellerStruct = seller.toStruct(); - pendingSellerUpdate.admin = other2.address; + pendingSellerUpdate.admin = await other2.getAddress(); pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); // Update seller @@ -1717,9 +1730,9 @@ describe("SellerHandler", function () { // Testing for the SellerUpdatePending event await expect(tx) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, admin.address); + .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, await admin.getAddress()); - pendingSellerUpdate.admin = ethers.constants.AddressZero; + pendingSellerUpdate.admin = ZeroAddress; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); // Approve update @@ -1731,12 +1744,12 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, emptyAuthTokenStruct, emptyAuthTokenStruct, - other2.address + await other2.getAddress() ); - seller.admin = other3.address; + seller.admin = await other3.getAddress(); sellerStruct = seller.toStruct(); - pendingSellerUpdate.admin = other3.address; + pendingSellerUpdate.admin = await other3.getAddress(); pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); // Update seller @@ -1745,9 +1758,9 @@ describe("SellerHandler", function () { // Testing for the SellerUpdatePending event await expect(tx) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, other2.address); + .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, await other2.getAddress()); - pendingSellerUpdate.admin = ethers.constants.AddressZero; + pendingSellerUpdate.admin = ZeroAddress; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); // Approve update @@ -1759,7 +1772,7 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, emptyAuthTokenStruct, emptyAuthTokenStruct, - other3.address + await other3.getAddress() ); // Attempt to update the seller with original admin address, expecting revert @@ -1769,13 +1782,13 @@ describe("SellerHandler", function () { }); it("should be able to only update with new auth token", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; sellerStruct = seller.toStruct(); // Update seller, testing for the event await expect(accountHandler.connect(admin).updateSeller(seller, authToken)) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdateStruct, authTokenStruct, admin.address); + .withArgs(seller.id, pendingSellerUpdateStruct, authTokenStruct, await admin.getAddress()); // Approve update await expect( @@ -1788,15 +1801,17 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, authTokenStruct, emptyAuthTokenStruct, - authTokenOwner.address + await authTokenOwner.getAddress() ); - seller.assistant = other3.address; - pendingSellerUpdate.assistant = other3.address; + seller.assistant = await other3.getAddress(); + pendingSellerUpdate.assistant = await other3.getAddress(); pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); // Transfer ownership of auth token because owner must be different from old admin - await mockAuthERC721Contract.connect(authTokenOwner).transferFrom(authTokenOwner.address, other1.address, 8400); + await mockAuthERC721Contract + .connect(authTokenOwner) + .transferFrom(await authTokenOwner.getAddress(), await other1.getAddress(), 8400); const newAuthTokenOwner = other1; // Update seller @@ -1805,10 +1820,10 @@ describe("SellerHandler", function () { // Testing for the SellerUpdatePending event await expect(tx) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, newAuthTokenOwner.address); + .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, await newAuthTokenOwner.getAddress()); sellerStruct = seller.toStruct(); - pendingSellerUpdate.assistant = ethers.constants.AddressZero; + pendingSellerUpdate.assistant = ZeroAddress; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); // Approve update @@ -1820,7 +1835,7 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, authTokenStruct, emptyAuthTokenStruct, - other3.address + await other3.getAddress() ); // Attempt to update the seller with original admin address, expecting revertStruct @@ -1832,15 +1847,15 @@ describe("SellerHandler", function () { it("should be possible to use non-unique treasury address", async function () { seller2 = seller.clone(); seller2.id = accountId.next().value; - seller2.treasury = other2.address; + seller2.treasury = await other2.getAddress(); - seller.assistant = other1.address; - seller.admin = other1.address; + seller.assistant = await other1.getAddress(); + seller.admin = await other1.getAddress(); pendingSellerUpdate = seller.clone(); pendingSellerUpdate.active = false; pendingSellerUpdate.id = "0"; - pendingSellerUpdate.treasury = ethers.constants.AddressZero; + pendingSellerUpdate.treasury = ZeroAddress; pendingSellerUpdate.metadataUri = ""; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); @@ -1850,7 +1865,7 @@ describe("SellerHandler", function () { // Testing for the SellerUpdatePending event await expect(tx) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, admin.address); + .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, await admin.getAddress()); //Create struct again with new addresses sellerStruct = seller.toStruct(); @@ -1863,28 +1878,28 @@ describe("SellerHandler", function () { // Make sure seller treasury didn't change [, sellerStruct, authTokenStruct] = await accountHandler.connect(rando).getSeller(seller.id); let returnedSeller = Seller.fromStruct(sellerStruct); - expect(returnedSeller.treasury).to.equal(treasury.address); + expect(returnedSeller.treasury).to.equal(await treasury.getAddress()); // Create seller 2 await accountHandler.connect(admin).createSeller(seller2, emptyAuthToken, voucherInitValues); // Update seller 2 treasury - seller2.treasury = treasury.address; + seller2.treasury = await treasury.getAddress(); await accountHandler.connect(admin).updateSeller(seller2, emptyAuthToken); // Check seller 2 treasury [, sellerStruct, authTokenStruct] = await accountHandler.connect(rando).getSeller(seller2.id); let returnedSeller2 = Seller.fromStruct(sellerStruct); - expect(returnedSeller2.treasury).to.equal(treasury.address); + expect(returnedSeller2.treasury).to.equal(await treasury.getAddress()); }); it("should be possible to use the same address for assistant, admin and treasury", async function () { // Only treasury doesn't need owner approval and will be updated immediately - seller.treasury = other1.address; + seller.treasury = await other1.getAddress(); sellerStruct = seller.toStruct(); - seller.assistant = other1.address; - seller.admin = other1.address; + seller.assistant = await other1.getAddress(); + seller.admin = await other1.getAddress(); // Update seller const tx = await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); @@ -1893,7 +1908,7 @@ describe("SellerHandler", function () { pendingSellerUpdate = seller.clone(); pendingSellerUpdate.id = "0"; pendingSellerUpdate.active = false; - pendingSellerUpdate.treasury = ethers.constants.AddressZero; + pendingSellerUpdate.treasury = ZeroAddress; pendingSellerUpdate.metadataUri = ""; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); @@ -1906,19 +1921,19 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, emptyAuthTokenStruct, emptyAuthTokenStruct, - admin.address + await admin.getAddress() ); // Testing for the SellerUpdatePending event await expect(tx) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, admin.address); + .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, await admin.getAddress()); sellerStruct = seller.toStruct(); // Nothing pending left - pendingSellerUpdate.admin = ethers.constants.AddressZero; - pendingSellerUpdate.clerk = ethers.constants.AddressZero; - pendingSellerUpdate.assistant = ethers.constants.AddressZero; + pendingSellerUpdate.admin = ZeroAddress; + pendingSellerUpdate.clerk = ZeroAddress; + pendingSellerUpdate.assistant = ZeroAddress; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); // Approve update @@ -1934,7 +1949,7 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, emptyAuthTokenStruct, emptyAuthTokenStruct, - other1.address + await other1.getAddress() ); }); @@ -1975,8 +1990,8 @@ describe("SellerHandler", function () { }); it("addresses are the zero address", async function () { - seller.assistant = ethers.constants.AddressZero; - seller.treasury = ethers.constants.AddressZero; + seller.assistant = ZeroAddress; + seller.treasury = ZeroAddress; // Attempt to update a seller, expecting revert await expect(accountHandler.connect(authTokenOwner).updateSeller(seller, emptyAuthToken)).to.revertedWith( @@ -1985,7 +2000,7 @@ describe("SellerHandler", function () { }); it("Assistant is the zero address", async function () { - seller.assistant = ethers.constants.AddressZero; + seller.assistant = ZeroAddress; // Attempt to update a seller, expecting revert await expect(accountHandler.connect(authTokenOwner).updateSeller(seller, emptyAuthToken)).to.revertedWith( @@ -1994,7 +2009,7 @@ describe("SellerHandler", function () { }); it("Clerk is not a zero address", async function () { - seller.clerk = rando.address; + seller.clerk = await rando.getAddress(); // Attempt to update a seller, expecting revert await expect(accountHandler.connect(authTokenOwner).updateSeller(seller, emptyAuthToken)).to.revertedWith( @@ -2003,7 +2018,7 @@ describe("SellerHandler", function () { }); it("Treasury is the zero address", async function () { - seller.treasury = ethers.constants.AddressZero; + seller.treasury = ZeroAddress; // Attempt to update a seller, expecting revert await expect(accountHandler.connect(authTokenOwner).updateSeller(seller, emptyAuthToken)).to.revertedWith( @@ -2013,28 +2028,28 @@ describe("SellerHandler", function () { it("addresses are not unique to this seller Id when addresses used for same role", async function () { seller.id = accountId.next().value; - seller.assistant = other1.address; - seller.admin = other1.address; - seller.treasury = other1.address; + seller.assistant = await other1.getAddress(); + seller.admin = await other1.getAddress(); + seller.treasury = await other1.getAddress(); seller.active = true; sellerStruct = seller.toStruct(); - expectedCloneAddress = calculateContractAddress(accountHandler.address, "2"); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "2"); //Create second seller await expect(accountHandler.connect(other1).createSeller(seller, emptyAuthToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, other1.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await other1.getAddress()); //Set assistant address value to be same as first seller created in Seller Methods beforeEach - seller.assistant = assistant.address; //already being used by seller 1 + seller.assistant = await assistant.getAddress(); //already being used by seller 1 // Attempt to update seller 2 with non-unique assistant, expecting revert await expect(accountHandler.connect(other1).updateSeller(seller, emptyAuthToken)).to.revertedWith( RevertReasons.SELLER_ADDRESS_MUST_BE_UNIQUE ); - seller.admin = admin.address; //already being used by seller 1 - seller.assistant = other1.address; + seller.admin = await admin.getAddress(); //already being used by seller 1 + seller.assistant = await other1.getAddress(); // Attempt to update a seller with non-unique admin, expecting revert await expect(accountHandler.connect(other1).updateSeller(seller, emptyAuthToken)).to.revertedWith( @@ -2044,20 +2059,20 @@ describe("SellerHandler", function () { it("addresses are not unique to this seller Id when address used for different role", async function () { seller.id = accountId.next().value; - seller.assistant = other1.address; - seller.admin = other1.address; - seller.treasury = other1.address; + seller.assistant = await other1.getAddress(); + seller.admin = await other1.getAddress(); + seller.treasury = await other1.getAddress(); seller.active = true; sellerStruct = seller.toStruct(); - expectedCloneAddress = calculateContractAddress(accountHandler.address, "2"); + expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "2"); //Create second seller await expect(accountHandler.connect(other1).createSeller(seller, emptyAuthToken, voucherInitValues)) .to.emit(accountHandler, "SellerCreated") - .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, other1.address); + .withArgs(seller.id, sellerStruct, expectedCloneAddress, emptyAuthTokenStruct, await other1.getAddress()); //Set seller 2's admin address to seller 1's assistant address - seller.admin = assistant.address; + seller.admin = await assistant.getAddress(); // Attempt to update seller 2 with non-unique assistant, expecting revert await expect(accountHandler.connect(other1).updateSeller(seller, emptyAuthToken)).to.revertedWith( @@ -2065,8 +2080,8 @@ describe("SellerHandler", function () { ); //Set seller 2's assistant address to seller 1's admin address - seller.admin = other1.address; - seller.assistant = admin.address; + seller.admin = await other1.getAddress(); + seller.assistant = await admin.getAddress(); // Attempt to update a seller with non-unique admin, expecting revert await expect(accountHandler.connect(other1).updateSeller(seller, emptyAuthToken)).to.revertedWith( @@ -2082,7 +2097,7 @@ describe("SellerHandler", function () { }); it("admin address is zero address and AuthTokenType is None", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Attempt to Create a seller, expecting revert await expect(accountHandler.connect(admin).updateSeller(seller, emptyAuthToken)).to.revertedWith( @@ -2092,7 +2107,7 @@ describe("SellerHandler", function () { it("authToken is not unique to this seller", async function () { // Set admin == zero address because seller will be updated with auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Update seller 1 to have auth token await accountHandler.connect(admin).updateSeller(seller, authToken); @@ -2100,13 +2115,18 @@ describe("SellerHandler", function () { await accountHandler.connect(authTokenOwner).optInToSellerUpdate(seller.id, [SellerUpdateFields.AuthToken]); //Set seller 2's auth token to empty - seller2 = mockSeller(other1.address, other1.address, ethers.constants.AddressZero, other1.address); + seller2 = mockSeller( + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() + ); expect(seller2.isValid()).is.true; // Create a seller with auth token await accountHandler.connect(other1).createSeller(seller2, emptyAuthToken, voucherInitValues); - seller2.admin = ethers.constants.AddressZero; + seller2.admin = ZeroAddress; // Attempt to update seller2 with non-unique authToken used by seller 1 await expect(accountHandler.connect(other1).updateSeller(seller2, authToken)).to.revertedWith( @@ -2116,7 +2136,7 @@ describe("SellerHandler", function () { it("authTokenType is Custom", async function () { // Set admin == zero address because seller will be created with auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; authToken.tokenType = AuthTokenType.Custom; @@ -2129,12 +2149,7 @@ describe("SellerHandler", function () { it("seller is not owner of auth token currently stored for seller", async function () { const authTokenOwner = other1; //Create seller 2 with auth token - seller2 = mockSeller( - other1.address, - ethers.constants.AddressZero, - ethers.constants.AddressZero, - other1.address - ); + seller2 = mockSeller(await other1.getAddress(), ZeroAddress, ZeroAddress, await other1.getAddress()); expect(seller2.isValid()).is.true; //Create auth token for token Id that seller does not own @@ -2147,7 +2162,9 @@ describe("SellerHandler", function () { await accountHandler.connect(authTokenOwner).createSeller(seller2, authToken2, voucherInitValues); //Transfer the token to a different address - await mockAuthERC721Contract2.connect(authTokenOwner).transferFrom(authTokenOwner.address, other7.address, 0); + await mockAuthERC721Contract2 + .connect(authTokenOwner) + .transferFrom(await authTokenOwner.getAddress(), await other7.getAddress(), 0); // Attempt to update seller2 for token that seller doesn't own await expect(accountHandler.connect(authTokenOwner).updateSeller(seller2, authToken2)).to.revertedWith( @@ -2159,12 +2176,7 @@ describe("SellerHandler", function () { const authTokenOwner = other1; //Create seller 2 with auth token - seller2 = mockSeller( - other1.address, - ethers.constants.AddressZero, - ethers.constants.AddressZero, - other1.address - ); + seller2 = mockSeller(await other1.getAddress(), ZeroAddress, ZeroAddress, await other1.getAddress()); expect(seller2.isValid()).is.true; //Create auth token for token Id that seller does not own @@ -2189,10 +2201,10 @@ describe("SellerHandler", function () { beforeEach(async function () { pendingSellerUpdate = seller.clone(); pendingSellerUpdate.id = "0"; - pendingSellerUpdate.treasury = ethers.constants.AddressZero; - pendingSellerUpdate.clerk = ethers.constants.AddressZero; - pendingSellerUpdate.admin = ethers.constants.AddressZero; - pendingSellerUpdate.assistant = ethers.constants.AddressZero; + pendingSellerUpdate.treasury = ZeroAddress; + pendingSellerUpdate.clerk = ZeroAddress; + pendingSellerUpdate.admin = ZeroAddress; + pendingSellerUpdate.assistant = ZeroAddress; pendingSellerUpdate.active = false; pendingSellerUpdate.metadataUri = ""; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); @@ -2201,7 +2213,7 @@ describe("SellerHandler", function () { }); it("New assistant should opt-in to update seller", async function () { - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); sellerStruct = seller.toStruct(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); @@ -2214,12 +2226,12 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, emptyAuthTokenStruct, emptyAuthTokenStruct, - other1.address + await other1.getAddress() ); }); it("New admin should opt-in to update seller", async function () { - seller.admin = other1.address; + seller.admin = await other1.getAddress(); sellerStruct = seller.toStruct(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); @@ -2232,13 +2244,13 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, emptyAuthTokenStruct, emptyAuthTokenStruct, - other1.address + await other1.getAddress() ); }); it("Should update admin and assistant in a single call ", async function () { - seller.admin = other1.address; - seller.assistant = other1.address; + seller.admin = await other1.getAddress(); + seller.assistant = await other1.getAddress(); sellerStruct = seller.toStruct(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); @@ -2255,13 +2267,13 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, emptyAuthTokenStruct, emptyAuthTokenStruct, - other1.address + await other1.getAddress() ); }); it("Should update assistant and auth token in a single call when addresses are the same ", async function () { - seller.admin = ethers.constants.AddressZero; - seller.assistant = authTokenOwner.address; + seller.admin = ZeroAddress; + seller.assistant = await authTokenOwner.getAddress(); sellerStruct = seller.toStruct(); await accountHandler.connect(admin).updateSeller(seller, authToken); @@ -2278,12 +2290,12 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, authTokenStruct, emptyAuthTokenStruct, - authTokenOwner.address + await authTokenOwner.getAddress() ); }); it("New auth token owner should opt-in to update seller", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; sellerStruct = seller.toStruct(); await accountHandler.connect(admin).updateSeller(seller, authToken); @@ -2298,23 +2310,23 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, authTokenStruct, emptyAuthTokenStruct, - authTokenOwner.address + await authTokenOwner.getAddress() ); }); it("Auth token can be used again if it was previously removed", async function () { // Update a seller to use auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; await accountHandler.connect(admin).updateSeller(seller, authToken); await accountHandler.connect(authTokenOwner).optInToSellerUpdate(seller.id, [SellerUpdateFields.AuthToken]); // Update seller to not use auth token anymore - seller.admin = other1.address; + seller.admin = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); await accountHandler.connect(other1).optInToSellerUpdate(seller.id, [SellerUpdateFields.Admin]); // Update back to auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; sellerStruct = seller.toStruct(); await accountHandler.connect(other1).updateSeller(seller, authToken); await expect( @@ -2327,31 +2339,31 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, authTokenStruct, emptyAuthTokenStruct, - authTokenOwner.address + await authTokenOwner.getAddress() ); }); it("If updateSeller is called twice with no optIn in between, pendingSellerUpdate is populated with the data from second call", async function () { - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); pendingSellerUpdate = seller.clone(); pendingSellerUpdate.id = "0"; - pendingSellerUpdate.treasury = ethers.constants.AddressZero; - pendingSellerUpdate.clerk = ethers.constants.AddressZero; - pendingSellerUpdate.admin = ethers.constants.AddressZero; + pendingSellerUpdate.treasury = ZeroAddress; + pendingSellerUpdate.clerk = ZeroAddress; + pendingSellerUpdate.admin = ZeroAddress; pendingSellerUpdate.active = false; pendingSellerUpdate.metadataUri = ""; pendingSellerUpdateStruct = pendingSellerUpdate.toStruct(); await expect(accountHandler.connect(admin).updateSeller(seller, emptyAuthToken)) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, admin.address); + .withArgs(seller.id, pendingSellerUpdateStruct, emptyAuthTokenStruct, await admin.getAddress()); - seller.assistant = other2.address; + seller.assistant = await other2.getAddress(); sellerStruct = seller.toStruct(); const pendingSellerUpdate2 = pendingSellerUpdate.clone(); - pendingSellerUpdate2.assistant = ethers.constants.AddressZero; + pendingSellerUpdate2.assistant = ZeroAddress; const pendingSellerUpdate2Struct = pendingSellerUpdate2.toStruct(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); @@ -2368,16 +2380,16 @@ describe("SellerHandler", function () { pendingSellerUpdate2Struct, emptyAuthTokenStruct, emptyAuthTokenStruct, - other2.address + await other2.getAddress() ); // Set admin == zero address because seller will be created with auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; sellerStruct = seller.toStruct(); await expect(accountHandler.connect(admin).updateSeller(seller, authToken)) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdate2Struct, authTokenStruct, admin.address); + .withArgs(seller.id, pendingSellerUpdate2Struct, authTokenStruct, await admin.getAddress()); // Set different token Id, keeping auth token type the same const authToken2 = authToken.clone(); @@ -2389,7 +2401,7 @@ describe("SellerHandler", function () { await expect(accountHandler.connect(admin).updateSeller(seller, authToken2)) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdate2Struct, authToken2Struct, admin.address); + .withArgs(seller.id, pendingSellerUpdate2Struct, authToken2Struct, await admin.getAddress()); await expect( accountHandler.connect(authTokenOwner).optInToSellerUpdate(seller.id, [SellerUpdateFields.AuthToken]) @@ -2403,12 +2415,12 @@ describe("SellerHandler", function () { pendingSellerUpdate2Struct, authToken2Struct, emptyAuthTokenStruct, - rando.address + await rando.getAddress() ); }); it("Should not emit 'SellerUpdateApplied' event if caller doesn't specify any field", async function () { - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); await expect(accountHandler.connect(other1).optInToSellerUpdate(seller.id, [])).to.not.emit( @@ -2418,7 +2430,7 @@ describe("SellerHandler", function () { }); it("Should not emit 'SellerUpdateApplied'event if there is no pending update for specified field", async function () { - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); await expect( @@ -2428,8 +2440,8 @@ describe("SellerHandler", function () { context("💔 Revert Reasons", async function () { it("There are no pending updates", async function () { - seller.admin = other1.address; - seller.assistant = other1.address; + seller.admin = await other1.getAddress(); + seller.assistant = await other1.getAddress(); sellerStruct = seller.toStruct(); // No pending update auth token @@ -2447,7 +2459,7 @@ describe("SellerHandler", function () { pendingSellerUpdateStruct, emptyAuthTokenStruct, emptyAuthTokenStruct, - other1.address + await other1.getAddress() ); await expect(accountHandler.connect(other1).optInToSellerUpdate(seller.id, [])).to.revertedWith( @@ -2457,21 +2469,21 @@ describe("SellerHandler", function () { it("authToken is not unique to this seller", async function () { // Set admin == zero address because seller will be created with auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; // Request auth token update for seller 1 await accountHandler.connect(admin).updateSeller(seller, authToken); await mockAuthERC721Contract .connect(authTokenOwner) - .transferFrom(authTokenOwner.address, rando.address, 8400); + .transferFrom(await authTokenOwner.getAddress(), await rando.getAddress(), 8400); const newAuthTokenOwner = rando; seller2 = mockSeller( - newAuthTokenOwner.address, - ethers.constants.AddressZero, - ethers.constants.AddressZero, - newAuthTokenOwner.address + await newAuthTokenOwner.getAddress(), + ZeroAddress, + ZeroAddress, + await newAuthTokenOwner.getAddress() ); expect(seller2.isValid()).is.true; @@ -2485,7 +2497,7 @@ describe("SellerHandler", function () { }); it("Caller is not the new admin", async function () { - seller.admin = other1.address; + seller.admin = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); @@ -2495,7 +2507,7 @@ describe("SellerHandler", function () { }); it("Caller is not the new assistant", async function () { - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); @@ -2505,7 +2517,7 @@ describe("SellerHandler", function () { }); it("Should revert if the caller is not the new auth token owner", async function () { - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; await accountHandler.connect(admin).updateSeller(seller, authToken); @@ -2515,7 +2527,7 @@ describe("SellerHandler", function () { }); it("The sellers region of protocol is paused", async function () { - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); @@ -2529,11 +2541,16 @@ describe("SellerHandler", function () { it("Admin is not unique to this seller", async function () { // Update seller admin - seller.admin = other1.address; + seller.admin = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); // Create seller with same admin - seller2 = mockSeller(other1.address, other1.address, ethers.constants.AddressZero, other1.address); + seller2 = mockSeller( + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() + ); expect(seller2.isValid()).is.true; await accountHandler.connect(other1).createSeller(seller2, emptyAuthToken, voucherInitValues); @@ -2546,11 +2563,16 @@ describe("SellerHandler", function () { it("Assistant is not unique to this seller", async function () { // Update seller assistant - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); // Create seller with same assistant - seller2 = mockSeller(other1.address, other1.address, ethers.constants.AddressZero, other1.address); + seller2 = mockSeller( + await other1.getAddress(), + await other1.getAddress(), + ZeroAddress, + await other1.getAddress() + ); expect(seller2.isValid()).is.true; await accountHandler.connect(other1).createSeller(seller2, emptyAuthToken, voucherInitValues); @@ -2562,7 +2584,7 @@ describe("SellerHandler", function () { }); it("Seller tries to update the clerk", async function () { - seller.assistant = other1.address; + seller.assistant = await other1.getAddress(); await accountHandler.connect(admin).updateSeller(seller, emptyAuthToken); diff --git a/test/protocol/TwinHandlerTest.js b/test/protocol/TwinHandlerTest.js index 6bb404c33..5d8b548ba 100644 --- a/test/protocol/TwinHandlerTest.js +++ b/test/protocol/TwinHandlerTest.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, MaxUint256 } = ethers; const { expect, assert } = require("chai"); const Twin = require("../../scripts/domain/Twin"); const Bundle = require("../../scripts/domain/Bundle"); @@ -63,7 +64,7 @@ describe("IBosonTwinHandler", function () { // make all account the same assistant = admin; - clerk = { address: ethers.constants.AddressZero }; + clerk = { address: ZeroAddress }; // Deploy the mock tokens [bosonToken, foreign721, foreign1155, fallbackError] = await deployMockTokens(); @@ -98,7 +99,12 @@ describe("IBosonTwinHandler", function () { id = "1"; // argument sent to contract for createSeller will be ignored // Create a valid seller, then set fields in tests directly - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); expect(seller.isValid()).is.true; // VoucherInitValues @@ -115,7 +121,7 @@ describe("IBosonTwinHandler", function () { invalidTwinId = "222"; // Create a valid twin, then set fields in tests directly - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); expect(twin.isValid()).is.true; // How that twin looks as a returned struct @@ -129,10 +135,10 @@ describe("IBosonTwinHandler", function () { context("👉 createTwin()", async function () { it("should emit a TwinCreated event", async function () { - twin.tokenAddress = bosonToken.address; + twin.tokenAddress = await bosonToken.getAddress(); // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // Create a twin, testing for the event const tx = await twinHandler.connect(assistant).createTwin(twin); @@ -153,7 +159,7 @@ describe("IBosonTwinHandler", function () { twin.id = "444"; // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // Create a twin, testing for the event const tx = await twinHandler.connect(assistant).createTwin(twin); @@ -188,11 +194,11 @@ describe("IBosonTwinHandler", function () { }); it("should emit a TwinCreated event for ERC721 token address", async function () { - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); // Mint a token and approve twinHandler contract to transfer it await foreign721.connect(assistant).mint(twin.tokenId, "1"); - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); // Create a twin, testing for the event const tx = await twinHandler.connect(assistant).createTwin(twin); @@ -210,11 +216,11 @@ describe("IBosonTwinHandler", function () { }); it("should emit a TwinCreated event for ERC1155 token address", async function () { - twin.tokenAddress = foreign1155.address; + twin.tokenAddress = await foreign1155.getAddress(); // Mint a token and approve twinHandler contract to transfer it await foreign1155.connect(assistant).mint(twin.tokenId, twin.amount); - await foreign1155.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign1155.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); // Create a twin, testing for the event const tx = await twinHandler.connect(assistant).createTwin(twin); @@ -235,12 +241,12 @@ describe("IBosonTwinHandler", function () { twin.supplyAvailable = "10"; twin.amount = "0"; twin.tokenId = "5"; - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); twin.tokenType = TokenType.NonFungibleToken; // Mint a token and approve twinHandler contract to transfer it await foreign721.connect(assistant).mint(twin.tokenId, twin.supplyAvailable); - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); // Create first twin with ids range: ["5"..."14"] await twinHandler.connect(assistant).createTwin(twin); @@ -252,10 +258,10 @@ describe("IBosonTwinHandler", function () { }); it("It is possible to add an ERC721 with unlimited supply if token is not used yet", async function () { - twin.supplyAvailable = ethers.constants.MaxUint256.toString(); + twin.supplyAvailable = MaxUint256.toString(); twin.amount = "0"; twin.tokenId = "0"; - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); twin.tokenType = TokenType.NonFungibleToken; // another erc721 token @@ -263,11 +269,11 @@ describe("IBosonTwinHandler", function () { let twin2 = twin.clone(); twin2.supplyAvailable = "1500"; - twin2.tokenAddress = foreign721_2.address; + twin2.tokenAddress = await foreign721_2.getAddress(); // Approve twinHandler contract to transfer it - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); - await foreign721_2.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); + await foreign721_2.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); // Create a twin with limited supply await twinHandler.connect(assistant).createTwin(twin); @@ -277,10 +283,10 @@ describe("IBosonTwinHandler", function () { }); it("It is possible to add ERC721 even if another ERC721 with unlimited supply exists", async function () { - twin.supplyAvailable = ethers.constants.MaxUint256.toString(); + twin.supplyAvailable = MaxUint256.toString(); twin.amount = "0"; twin.tokenId = "0"; - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); twin.tokenType = TokenType.NonFungibleToken; // another erc721 token @@ -288,11 +294,11 @@ describe("IBosonTwinHandler", function () { let twin2 = twin.clone(); twin2.supplyAvailable = "1500"; - twin2.tokenAddress = foreign721_2.address; + twin2.tokenAddress = await foreign721_2.getAddress(); // Approve twinHandler contract to transfer it - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); - await foreign721_2.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); + await foreign721_2.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); // Create a twin with unlimited supply await twinHandler.connect(assistant).createTwin(twin); @@ -303,10 +309,10 @@ describe("IBosonTwinHandler", function () { it("Should ignore twin id set by seller and use nextAccountId on twins entity", async function () { twin.id = "666"; - twin.tokenAddress = bosonToken.address; + twin.tokenAddress = await bosonToken.getAddress(); // Approve twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); await twinHandler.connect(assistant).createTwin(twin); @@ -336,7 +342,7 @@ describe("IBosonTwinHandler", function () { it("protocol is not approved to transfer the ERC20 token", async function () { //ERC20 token address - twin.tokenAddress = bosonToken.address; + twin.tokenAddress = await bosonToken.getAddress(); await expect(twinHandler.connect(assistant).createTwin(twin)).to.revertedWith( RevertReasons.NO_TRANSFER_APPROVED @@ -345,7 +351,7 @@ describe("IBosonTwinHandler", function () { it("protocol is not approved to transfer the ERC721 token", async function () { //ERC721 token address - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); await expect(twinHandler.connect(assistant).createTwin(twin)).to.revertedWith( RevertReasons.NO_TRANSFER_APPROVED @@ -354,7 +360,7 @@ describe("IBosonTwinHandler", function () { it("protocol is not approved to transfer the ERC1155 token", async function () { //ERC1155 token address - twin.tokenAddress = foreign1155.address; + twin.tokenAddress = await foreign1155.getAddress(); await expect(twinHandler.connect(assistant).createTwin(twin)).to.revertedWith( RevertReasons.NO_TRANSFER_APPROVED @@ -364,12 +370,12 @@ describe("IBosonTwinHandler", function () { it("supplyAvailable is zero", async function () { // Mint a token and approve twinHandler contract to transfer it await foreign721.connect(assistant).mint(twin.tokenId, "1"); - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); twin.supplyAvailable = "0"; twin.amount = "0"; twin.tokenId = "1"; - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); twin.tokenType = TokenType.NonFungibleToken; await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( @@ -379,11 +385,11 @@ describe("IBosonTwinHandler", function () { it("Amount is greater than supply available and token type is FungibleToken", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); twin.supplyAvailable = "10"; twin.amount = "20"; - twin.tokenAddress = bosonToken.address; + twin.tokenAddress = await bosonToken.getAddress(); twin.tokenType = TokenType.FungibleToken; await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( @@ -394,11 +400,11 @@ describe("IBosonTwinHandler", function () { it("Amount is greater than supply available and token type is MultiToken", async function () { // Mint a token and approve twinHandler contract to transfer it await foreign1155.connect(assistant).mint(twin.tokenId, "1"); - await foreign1155.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign1155.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); twin.supplyAvailable = "10"; twin.amount = "20"; - twin.tokenAddress = foreign1155.address; + twin.tokenAddress = await foreign1155.getAddress(); twin.tokenType = TokenType.MultiToken; await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( @@ -408,10 +414,10 @@ describe("IBosonTwinHandler", function () { it("Amount is zero and token type is FungibleToken", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); twin.amount = "0"; - twin.tokenAddress = bosonToken.address; + twin.tokenAddress = await bosonToken.getAddress(); twin.tokenType = TokenType.FungibleToken; await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( @@ -422,10 +428,10 @@ describe("IBosonTwinHandler", function () { it("Amount is zero and token type is MultiToken", async function () { // Mint a token and approve twinHandler contract to transfer it await foreign1155.connect(assistant).mint(twin.tokenId, "1"); - await foreign1155.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign1155.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); twin.amount = "0"; - twin.tokenAddress = foreign1155.address; + twin.tokenAddress = await foreign1155.getAddress(); twin.tokenType = TokenType.MultiToken; await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( @@ -434,14 +440,14 @@ describe("IBosonTwinHandler", function () { }); it("Amount is zero and token type is NonFungibleToken", async function () { - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); twin.tokenType = TokenType.NonFungibleToken; twin.amount = "1"; twin.tokenId = "1"; // Mint a token and approve twinHandler contract to transfer it await foreign721.connect(assistant).mint(twin.tokenId, "1"); - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( RevertReasons.INVALID_TWIN_PROPERTY @@ -452,12 +458,12 @@ describe("IBosonTwinHandler", function () { twin.supplyAvailable = "10"; twin.amount = "0"; twin.tokenId = "5"; - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); twin.tokenType = TokenType.NonFungibleToken; // Mint a token and approve twinHandler contract to transfer it await foreign721.connect(assistant).mint(twin.tokenId, twin.supplyAvailable); - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); // Create first twin with ids range: ["5"..."14"] await twinHandler.connect(assistant).createTwin(twin); @@ -490,12 +496,12 @@ describe("IBosonTwinHandler", function () { }); it("token address has been used in another twin with unlimited supply", async function () { - twin.supplyAvailable = ethers.constants.MaxUint256; + twin.supplyAvailable = MaxUint256; twin.tokenType = TokenType.NonFungibleToken; - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); twin.amount = "0"; - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); // Create twin with unlimited supply await twinHandler.connect(assistant).createTwin(twin); @@ -508,13 +514,13 @@ describe("IBosonTwinHandler", function () { }); it("Supply range overflow", async function () { - twin.supplyAvailable = ethers.constants.MaxUint256.div(10).mul(8).toString(); + twin.supplyAvailable = ((MaxUint256 / 10n) * 8n).toString(); twin.tokenType = TokenType.NonFungibleToken; - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); twin.amount = "0"; - twin.tokenId = ethers.constants.MaxUint256.sub(twin.supplyAvailable).add(1).toString(); + twin.tokenId = (MaxUint256 - BigInt(twin.supplyAvailable) + 1n).toString(); - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); // Create new twin with same token address await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( @@ -523,13 +529,13 @@ describe("IBosonTwinHandler", function () { }); it("Token with unlimited supply with starting tokenId to high", async function () { - twin.supplyAvailable = ethers.constants.MaxUint256.toString(); + twin.supplyAvailable = MaxUint256.toString(); twin.tokenType = TokenType.NonFungibleToken; - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); twin.amount = "0"; - twin.tokenId = ethers.constants.MaxUint256.add(1).div(2).add(1).toString(); + twin.tokenId = ((MaxUint256 + 1n) / 2n + 1n).toString(); - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); // Create new twin with same token address await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( @@ -539,7 +545,7 @@ describe("IBosonTwinHandler", function () { context("Token address is unsupported", async function () { it("Token address is a zero address", async function () { - twin.tokenAddress = ethers.constants.AddressZero; + twin.tokenAddress = ZeroAddress; await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( RevertReasons.UNSUPPORTED_TOKEN @@ -547,7 +553,7 @@ describe("IBosonTwinHandler", function () { }); it("Token address is a contract address that does not support the isApprovedForAll", async function () { - twin.tokenAddress = twinHandler.address; + twin.tokenAddress = await twinHandler.getAddress(); await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( RevertReasons.UNSUPPORTED_TOKEN @@ -555,7 +561,7 @@ describe("IBosonTwinHandler", function () { }); it("Token address is a contract that reverts from a fallback method", async function () { - twin.tokenAddress = fallbackError.address; + twin.tokenAddress = await fallbackError.getAddress(); await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( RevertReasons.UNSUPPORTED_TOKEN @@ -563,9 +569,9 @@ describe("IBosonTwinHandler", function () { }); it("Token address is a contract that doesn't implement IERC721 interface when selected token type is NonFungible", async function () { - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); twin.tokenType = TokenType.NonFungibleToken; - twin.tokenAddress = bosonToken.address; + twin.tokenAddress = await bosonToken.getAddress(); await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( RevertReasons.INVALID_TOKEN_ADDRESS @@ -573,9 +579,9 @@ describe("IBosonTwinHandler", function () { }); it("Token address is a contract that doesn't implement IERC1155 interface when selected token type is MultiToken", async function () { - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); twin.tokenType = TokenType.MultiToken; - twin.tokenAddress = bosonToken.address; + twin.tokenAddress = await bosonToken.getAddress(); await expect(twinHandler.connect(assistant).createTwin(twin)).to.be.revertedWith( RevertReasons.INVALID_TOKEN_ADDRESS @@ -588,7 +594,7 @@ describe("IBosonTwinHandler", function () { context("👉 removeTwin()", async function () { beforeEach(async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // Create a twin await twinHandler.connect(assistant).createTwin(twin); @@ -602,7 +608,7 @@ describe("IBosonTwinHandler", function () { // Remove the twin, testing for the event. await expect(twinHandler.connect(assistant).removeTwin(twin.id)) .to.emit(twinHandler, "TwinDeleted") - .withArgs(twin.id, twin.sellerId, assistant.address); + .withArgs(twin.id, twin.sellerId, await assistant.getAddress()); // Expect twin to be not found. [success] = await twinHandler.connect(rando).getTwin(twin.id); @@ -611,11 +617,11 @@ describe("IBosonTwinHandler", function () { it("should make twin range available again if token type is NonFungible", async function () { twin.tokenType = TokenType.NonFungibleToken; - twin.tokenAddress = foreign721.address; + twin.tokenAddress = await foreign721.getAddress(); twin.amount = "0"; const expectedNewTwinId = "2"; - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); // Create a twin with range: [0,1499] await twinHandler.connect(assistant).createTwin(twin); @@ -632,7 +638,7 @@ describe("IBosonTwinHandler", function () { // Create a twin with range: [0,1499] let twin1 = twin.clone(); twin1.tokenType = TokenType.NonFungibleToken; - twin1.tokenAddress = foreign721.address; + twin1.tokenAddress = await foreign721.getAddress(); twin1.amount = "0"; twin1.id = "2"; @@ -646,7 +652,7 @@ describe("IBosonTwinHandler", function () { twin3.tokenId = "5000"; twin3.id = "3"; - await foreign721.connect(assistant).setApprovalForAll(twinHandler.address, true); + await foreign721.connect(assistant).setApprovalForAll(await twinHandler.getAddress(), true); await twinHandler.connect(assistant).createTwin(twin1); await twinHandler.connect(assistant).createTwin(twin2); @@ -731,7 +737,7 @@ describe("IBosonTwinHandler", function () { context("👉 getTwin()", async function () { beforeEach(async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // Create a twin await twinHandler.connect(assistant).createTwin(twin); @@ -771,7 +777,7 @@ describe("IBosonTwinHandler", function () { context("👉 getNextTwinId()", async function () { beforeEach(async function () { // Create another valid seller. - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); + seller = mockSeller(await rando.getAddress(), await rando.getAddress(), ZeroAddress, await rando.getAddress()); expect(seller.isValid()).is.true; // AuthToken @@ -780,7 +786,7 @@ describe("IBosonTwinHandler", function () { await accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues); // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(rando).approve(twinHandler.address, 1); + await bosonToken.connect(rando).approve(await twinHandler.getAddress(), 1); // Create a twin await twinHandler.connect(rando).createTwin(twin); @@ -807,7 +813,7 @@ describe("IBosonTwinHandler", function () { it("should be incremented after a twin is created", async function () { // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // Create another twin await twinHandler.connect(assistant).createTwin(twin); diff --git a/test/protocol/clients/BeaconClientProxy.js b/test/protocol/clients/BeaconClientProxy.js index 42ee8923d..7e9256020 100644 --- a/test/protocol/clients/BeaconClientProxy.js +++ b/test/protocol/clients/BeaconClientProxy.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { getSigners } = hre.ethers; const { deployProtocolClients } = require("../../../scripts/util/deploy-protocol-clients"); const { expect } = require("chai"); @@ -11,10 +11,10 @@ describe("BeaconClientProxy", function () { beforeEach(async function () { // Set signers (fake protocol address to test issue and burn voucher without protocol dependencie) - [protocol, rando] = await ethers.getSigners(); + [protocol, rando] = await getSigners(); // deploy proxy - const protocolClientArgs = [protocol.address]; + const protocolClientArgs = [await protocol.getAddress()]; const [, , proxies] = await deployProtocolClients(protocolClientArgs, maxPriorityFeePerGas); [proxy] = proxies; }); @@ -22,7 +22,7 @@ describe("BeaconClientProxy", function () { context("initializable", function () { context("💔 Revert Reasons", async function () { it("should revert if trying to initialize again", async function () { - await expect(proxy.connect(rando).initialize(rando.address)).to.be.revertedWith( + await expect(proxy.connect(rando).initialize(await rando.getAddress())).to.be.revertedWith( "Initializable: contract is already initialized" ); }); diff --git a/test/protocol/clients/BosonVoucherTest.js b/test/protocol/clients/BosonVoucherTest.js index b4b9e9894..cd522d592 100644 --- a/test/protocol/clients/BosonVoucherTest.js +++ b/test/protocol/clients/BosonVoucherTest.js @@ -1,6 +1,6 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, getSigners, getContractAt, getContractFactory, provider, parseUnits, MaxUint256 } = ethers; -const DisputeResolutionTerms = require("../../../scripts/domain/DisputeResolutionTerms"); const { getInterfaceIds } = require("../../../scripts/config/supported-interfaces.js"); const Role = require("../../../scripts/domain/Role"); const { DisputeResolverFee } = require("../../../scripts/domain/DisputeResolverFee"); @@ -32,8 +32,6 @@ const { deriveTokenId, } = require("../../util/utils.js"); const { deployMockTokens } = require("../../../scripts/util/deploy-mock-tokens"); -const { deployMockContract } = require("@ethereum-waffle/mock-contract"); -const FormatTypes = ethers.utils.FormatTypes; describe("IBosonVoucher", function () { let interfaceIds; @@ -54,10 +52,8 @@ describe("IBosonVoucher", function () { treasuryDR, seller, foreign20; - let beacon; let disputeResolver, disputeResolverFees; let emptyAuthToken; - let agentId; let voucherInitValues, contractURI, royaltyPercentage, exchangeId, offerPrice; let forwarder; let snapshotId; @@ -70,7 +66,7 @@ describe("IBosonVoucher", function () { interfaceIds = { IBosonVoucher, IERC721, IERC2981 }; // Mock forwarder to test metatx - const MockForwarder = await ethers.getContractFactory("MockForwarder"); + const MockForwarder = await getContractFactory("MockForwarder"); forwarder = await MockForwarder.deploy(); @@ -86,28 +82,28 @@ describe("IBosonVoucher", function () { ({ signers: [protocol, buyer, rando, rando2, admin, treasury, adminDR, treasuryDR], contractInstances: { accountHandler, offerHandler, exchangeHandler, fundsHandler, configHandler }, - extraReturnValues: { bosonVoucher, beacon, accessController }, + extraReturnValues: { bosonVoucher, accessController }, } = await setupTestEnvironment(contracts, { - forwarderAddress: [forwarder.address], + forwarderAddress: [await forwarder.getAddress()], })); // make all account the same assistant = admin; assistantDR = adminDR; - clerk = clerkDR = { address: ethers.constants.AddressZero }; - [deployer] = await ethers.getSigners(); + clerk = clerkDR = { address: ZeroAddress }; + [deployer] = await getSigners(); // Grant protocol role to eoa so it's easier to test - await accessController.grantRole(Role.PROTOCOL, protocol.address); + await accessController.grantRole(Role.PROTOCOL, await protocol.getAddress()); // Initialize voucher contract const sellerId = 1; // prepare the VoucherInitValues voucherInitValues = mockVoucherInitValues(); - const bosonVoucherInit = await ethers.getContractAt("BosonVoucher", bosonVoucher.address); + const bosonVoucherInit = await getContractAt("BosonVoucher", await bosonVoucher.getAddress()); - await bosonVoucherInit.initializeVoucher(sellerId, assistant.address, voucherInitValues); + await bosonVoucherInit.initializeVoucher(sellerId, await assistant.getAddress(), voucherInitValues); [foreign20] = await deployMockTokens(["Foreign20", "BosonToken"]); @@ -118,6 +114,9 @@ describe("IBosonVoucher", function () { afterEach(async function () { await revertToSnapshot(snapshotId); snapshotId = await getSnapshot(); + + // Reset + accountId.next(true); }); // Interface support @@ -141,324 +140,284 @@ describe("IBosonVoucher", function () { context("General", async function () { it("Contract can receive native token", async function () { - const balanceBefore = await ethers.provider.getBalance(bosonVoucher.address); + const balanceBefore = await provider.getBalance(await bosonVoucher.getAddress()); - const amount = ethers.utils.parseUnits("1", "ether"); + const amount = parseUnits("1", "ether"); - await admin.sendTransaction({ to: bosonVoucher.address, value: amount }); + await admin.sendTransaction({ to: await bosonVoucher.getAddress(), value: amount }); - const balanceAfter = await ethers.provider.getBalance(bosonVoucher.address); - expect(balanceAfter.sub(balanceBefore)).to.eq(amount); + const balanceAfter = await provider.getBalance(await bosonVoucher.getAddress()); + expect(balanceAfter - balanceBefore).to.eq(amount); }); it("Cannot initialize voucher twice", async function () { - const initalizableClone = await ethers.getContractAt("IInitializableVoucherClone", bosonVoucher.address); - await expect(initalizableClone.initializeVoucher(2, assistant.address, voucherInitValues)).to.be.revertedWith( - RevertReasons.INITIALIZABLE_ALREADY_INITIALIZED - ); + const initalizableClone = await getContractAt("IInitializableVoucherClone", await bosonVoucher.getAddress()); + await expect( + initalizableClone.initializeVoucher(2, await assistant.getAddress(), voucherInitValues) + ).to.be.revertedWith(RevertReasons.INITIALIZABLE_ALREADY_INITIALIZED); }); }); - context("issueVoucher()", function () { - let buyerStruct; - let buyerWallet; + context("Offer must exist", async function () { + let offer, offerDates, offerDurations, disputeResolverId; - beforeEach(function () { - buyerStruct = mockBuyer(buyer.address).toStruct(); - buyerWallet = buyerStruct[1]; - }); + before(async function () { + const bosonVoucherCloneAddress = calculateContractAddress(await exchangeHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", bosonVoucherCloneAddress); - after(async function () { - // Reset the accountId iterator - accountId.next(true); - }); + seller = mockSeller( + await assistant.getAddress(), + await admin.getAddress(), + clerk.address, + await treasury.getAddress() + ); - it("should issue a voucher with success", async function () { - const balanceBefore = await bosonVoucher.balanceOf(buyer.address); - await bosonVoucher.connect(protocol).issueVoucher(0, buyerWallet); + // Prepare the AuthToken and VoucherInitValues + emptyAuthToken = mockAuthToken(); + voucherInitValues = mockVoucherInitValues(); + await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); + + // Create a valid dispute resolver + disputeResolver = mockDisputeResolver( + await assistantDR.getAddress(), + await adminDR.getAddress(), + clerkDR.address, + await treasuryDR.getAddress(), + true + ); - const balanceAfter = await bosonVoucher.balanceOf(buyer.address); + // Create DisputeResolverFee array so offer creation will succeed + disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", "0")]; + const sellerAllowList = []; - expect(balanceAfter.sub(balanceBefore)).eq(1); - }); + // Register the dispute resolver + await accountHandler + .connect(adminDR) + .createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList); - it("should issue a voucher if it does not overlap with range", async function () { - const offerId = "5"; - const start = "10"; - const length = "123"; - const tokenId = deriveTokenId(offerId, start); // token within reserved range + ({ offer, offerDates, offerDurations, disputeResolverId } = await mockOffer()); + offer.quantityAvailable = "1000"; - // Deploy mock protocol - await deployMockProtocol(); + await offerHandler.connect(assistant).createOffer(offer, offerDates, offerDurations, disputeResolverId, "0"); - // Reserve a range - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); + const amount = BigInt(offer.sellerDeposit) * BigInt(offer.quantityAvailable); - // Token id just below the range - await expect(() => - bosonVoucher.connect(protocol).issueVoucher(tokenId.sub(1), buyerWallet) - ).to.changeTokenBalance(bosonVoucher, buyer, 1); + await fundsHandler.connect(admin).depositFunds(seller.id, ZeroAddress, amount, { + value: amount, + }); - // Token id just above the range - await expect(() => - bosonVoucher.connect(protocol).issueVoucher(tokenId.add(length), buyerWallet) - ).to.changeTokenBalance(bosonVoucher, buyer, 1); + // Get snapshot id + snapshotId = await getSnapshot(); }); - context("💔 Revert Reasons", async function () { - it("should revert if caller does not have PROTOCOL role", async function () { - // Expect revert if random user attempts to issue voucher - await expect(bosonVoucher.connect(rando).issueVoucher(0, buyerWallet)).to.be.revertedWith( - RevertReasons.ACCESS_DENIED - ); + context("issueVoucher()", function () { + let buyerStruct; + let buyerWallet; + + before(async function () { + buyerStruct = mockBuyer(await buyer.getAddress()).toStruct(); + buyerWallet = buyerStruct[1]; + }); - // Grant PROTOCOL role to random user address - await accessController.grantRole(Role.PROTOCOL, rando.address); + it("should issue a voucher with success", async function () { + const balanceBefore = await bosonVoucher.balanceOf(await buyer.getAddress()); + await bosonVoucher.connect(protocol).issueVoucher(0, buyerWallet); - // Attempt to issue voucher again as a random user - const balanceBefore = await bosonVoucher.balanceOf(buyer.address); - await bosonVoucher.connect(rando).issueVoucher(0, buyerWallet); - const balanceAfter = await bosonVoucher.balanceOf(buyer.address); + const balanceAfter = await bosonVoucher.balanceOf(await buyer.getAddress()); - expect(balanceAfter.sub(balanceBefore)).eq(1); + expect(balanceAfter - balanceBefore).eq(1); }); - it("issueVoucher should revert if exchange id falls within a pre-minted offer's range", async function () { - const offerId = "5"; + it("should issue a voucher if it does not overlap with range", async function () { + const offerId = "1"; const start = "10"; const length = "123"; - const tokenId = deriveTokenId(offerId, "15"); // token within reserved range - - // Deploy mock protocol - await deployMockProtocol(); + const tokenId = deriveTokenId(offerId, start); // token within reserved range // Reserve a range - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - // Expect revert if random user attempts to issue voucher - await expect(bosonVoucher.connect(protocol).issueVoucher(tokenId, buyerWallet)).to.be.revertedWith( - RevertReasons.EXCHANGE_ID_IN_RESERVED_RANGE - ); + // Token id just below the range + await expect(() => + bosonVoucher.connect(protocol).issueVoucher(tokenId - 1n, buyerWallet) + ).to.changeTokenBalance(bosonVoucher, buyer, 1); + + // Token id just above the range + await expect(() => + bosonVoucher.connect(protocol).issueVoucher(tokenId + BigInt(length), buyerWallet) + ).to.changeTokenBalance(bosonVoucher, buyer, 1); }); - }); - }); - context("reserveRange()", function () { - let offerId, start, length; - let range; + context("💔 Revert Reasons", async function () { + it("should revert if caller does not have PROTOCOL role", async function () { + // Expect revert if random user attempts to issue voucher + await expect(bosonVoucher.connect(rando).issueVoucher(0, buyerWallet)).to.be.revertedWith( + RevertReasons.ACCESS_DENIED + ); - beforeEach(async function () { - offerId = "5"; - start = "10"; - length = "123"; - const tokenStartId = deriveTokenId(offerId, start); + // Grant PROTOCOL role to random user address + await accessController.grantRole(Role.PROTOCOL, await rando.getAddress()); - range = new Range(tokenStartId.toString(), length, "0", "0", assistant.address); - }); + // Attempt to issue voucher again as a random user + const balanceBefore = await bosonVoucher.balanceOf(await buyer.getAddress()); + await bosonVoucher.connect(rando).issueVoucher(0, buyerWallet); + const balanceAfter = await bosonVoucher.balanceOf(await buyer.getAddress()); - it("Should emit event RangeReserved", async function () { - // Reserve range, test for event - await expect(bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address)) - .to.emit(bosonVoucher, "RangeReserved") - .withArgs(offerId, range.toStruct()); - }); + expect(balanceAfter - balanceBefore).eq(1); + }); - it("Should update state", async function () { - // Reserve range - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); - - // Get range object from contract - const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); - assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); - - // Mock getOffer call, otherwise getAvailablePreMints will return 0 - const mockProtocol = await deployMockProtocol(); - const { offer, offerDates, offerDurations, offerFees } = await mockOffer(); - const disputeResolutionTerms = new DisputeResolutionTerms("0", "0", "0", "0"); - await mockProtocol.mock.getMaxPremintedVouchers.returns("1000"); - await mockProtocol.mock.getOffer.returns( - true, - offer, - offerDates, - offerDurations, - disputeResolutionTerms, - offerFees - ); + it("issueVoucher should revert if exchange id falls within a pre-minted offer's range", async function () { + const offerId = "1"; + const start = "10"; + const length = "123"; + const tokenId = deriveTokenId(offerId, "15"); // token within reserved range + + // Reserve a range + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - // Get available premints from contract - const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toString(), length, "Available Premints mismatch"); + // Expect revert if random user attempts to issue voucher + await expect(bosonVoucher.connect(protocol).issueVoucher(tokenId, buyerWallet)).to.be.revertedWith( + RevertReasons.EXCHANGE_ID_IN_RESERVED_RANGE + ); + }); + }); }); - context("Owner range is contract", async function () { + context("reserveRange()", function () { + let offerId, start, length; + let range; + beforeEach(async function () { - range.owner = bosonVoucher.address; + offerId = "1"; + start = "10"; + length = "123"; + + const tokenStartId = deriveTokenId(offerId, start); + range = new Range(tokenStartId.toString(), length, "0", "0", await assistant.getAddress()); }); it("Should emit event RangeReserved", async function () { // Reserve range, test for event - await expect(bosonVoucher.connect(protocol).reserveRange(offerId, start, length, bosonVoucher.address)) + await expect(bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress())) .to.emit(bosonVoucher, "RangeReserved") .withArgs(offerId, range.toStruct()); }); it("Should update state", async function () { // Reserve range - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, bosonVoucher.address); + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); // Get range object from contract const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); - // Mock getOffer call, otherwise getAvailablePreMints will return 0 - const mockProtocol = await deployMockProtocol(); - const { offer, offerDates, offerDurations, offerFees } = await mockOffer(); - const disputeResolutionTerms = new DisputeResolutionTerms("0", "0", "0", "0"); - await mockProtocol.mock.getMaxPremintedVouchers.returns("1000"); - await mockProtocol.mock.getOffer.returns( - true, - offer, - offerDates, - offerDurations, - disputeResolutionTerms, - offerFees - ); - // Get available premints from contract const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); assert.equal(availablePremints.toString(), length, "Available Premints mismatch"); }); - }); - context("💔 Revert Reasons", async function () { - it("caller does not have PROTOCOL role", async function () { - await expect( - bosonVoucher.connect(rando).reserveRange(offerId, start, length, assistant.address) - ).to.be.revertedWith(RevertReasons.ACCESS_DENIED); - }); + context("Owner range is contract", async function () { + beforeEach(async function () { + range.owner = await bosonVoucher.getAddress(); + }); - it("Start id is not greater than zero for the first range", async function () { - // Set start id to 0 - start = 0; + it("Should emit event RangeReserved", async function () { + // Reserve range, test for event + await expect( + bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await bosonVoucher.getAddress()) + ) + .to.emit(bosonVoucher, "RangeReserved") + .withArgs(offerId, range.toStruct()); + }); - // Try to reserve range, it should fail - await expect( - bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address) - ).to.be.revertedWith(RevertReasons.INVALID_RANGE_START); - }); + it("Should update state", async function () { + // Reserve range + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await bosonVoucher.getAddress()); - it("Range length is zero", async function () { - // Set length to 0 - length = "0"; + // Get range object from contract + const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); + assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); - // Try to reserve range, it should fail - await expect( - bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address) - ).to.be.revertedWith(RevertReasons.INVALID_RANGE_LENGTH); + // Get available premints from contract + const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); + assert.equal(availablePremints.toString(), length, "Available Premints mismatch"); + }); }); - it("Range length is too large, i.e., would cause an overflow", async function () { - // Set such numbers that would cause an overflow - start = ethers.constants.MaxUint256.div(2).add(2); - length = ethers.constants.MaxUint256.div(2); - - // Try to reserve range, it should fail - await expect( - bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address) - ).to.be.revertedWith(RevertReasons.INVALID_RANGE_LENGTH); - }); + context("💔 Revert Reasons", async function () { + it("caller does not have PROTOCOL role", async function () { + await expect( + bosonVoucher.connect(rando).reserveRange(offerId, start, length, await assistant.getAddress()) + ).to.be.revertedWith(RevertReasons.ACCESS_DENIED); + }); - it("Offer id is already associated with a range", async function () { - // Reserve range for an offer - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); + it("Start id is not greater than zero for the first range", async function () { + // Set start id to 0 + start = 0; - start = Number(start) + Number(length) + 1; + // Try to reserve range, it should fail + await expect( + bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()) + ).to.be.revertedWith(RevertReasons.INVALID_RANGE_START); + }); - // Try to reserve range for the same offer, it should fail - await expect( - bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address) - ).to.be.revertedWith(RevertReasons.OFFER_RANGE_ALREADY_RESERVED); - }); + it("Range length is zero", async function () { + // Set length to 0 + length = "0"; - it("_to address isn't contract address or contract owner address", async function () { - // Try to reserve range for rando address, it should fail - await expect( - bosonVoucher.connect(protocol).reserveRange(offerId, start, length, rando.address) - ).to.be.revertedWith(RevertReasons.INVALID_TO_ADDRESS); - }); - }); - }); + // Try to reserve range, it should fail + await expect( + bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()) + ).to.be.revertedWith(RevertReasons.INVALID_RANGE_LENGTH); + }); - context("preMint()", function () { - let offerId, start, length, amount; - let mockProtocol; - let offer, offerDates, offerDurations, offerFees, disputeResolutionTerms; + it("Range length is too large, i.e., would cause an overflow", async function () { + // Set such numbers that would cause an overflow + start = MaxUint256 / 2n + 2n; + length = MaxUint256 / 2n; - beforeEach(async function () { - mockProtocol = await deployMockProtocol(); - ({ offer, offerDates, offerDurations, offerFees } = await mockOffer()); - disputeResolutionTerms = new DisputeResolutionTerms("0", "0", "0", "0"); - await mockProtocol.mock.getMaxPremintedVouchers.returns("1000"); - await mockProtocol.mock.getOffer.returns( - true, - offer, - offerDates, - offerDurations, - disputeResolutionTerms, - offerFees - ); + // Try to reserve range, it should fail + await expect( + bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()) + ).to.be.revertedWith(RevertReasons.INVALID_RANGE_LENGTH); + }); - // reserve a range - offerId = "5"; - start = 10; - length = "1000"; - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); + it("Offer id is already associated with a range", async function () { + // Reserve range for an offer + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - // amount to mint - amount = 50; - }); + start = Number(start) + Number(length) + 1; - it("Should emit Transfer events", async function () { - // Premint tokens, test for event - const tx = await bosonVoucher.connect(assistant).preMint(offerId, amount); + // Try to reserve range for the same offer, it should fail + await expect( + bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()) + ).to.be.revertedWith(RevertReasons.OFFER_RANGE_ALREADY_RESERVED); + }); - // Expect an event for every mint - start = deriveTokenId(offerId, start); - for (let i = 0; i < Number(amount); i++) { - await expect(tx) - .to.emit(bosonVoucher, "Transfer") - .withArgs(ethers.constants.AddressZero, assistant.address, start.add(i)); - } + it("_to address isn't contract address or contract owner address", async function () { + // Try to reserve range for rando address, it should fail + await expect( + bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await rando.getAddress()) + ).to.be.revertedWith(RevertReasons.INVALID_TO_ADDRESS); + }); + }); }); - it("Should emit VouchersPreMinted event", async function () { - // Premint tokens, test for event - const tx = await bosonVoucher.connect(assistant).preMint(offerId, amount); - - start = deriveTokenId(offerId, start); + context("preMint()", function () { + let offerId, start, length, amount; - await expect(tx).to.emit(bosonVoucher, "VouchersPreMinted").withArgs(offerId, start, start.add(amount).sub(1)); - }); - - context("Owner range is contract", async function () { beforeEach(async function () { - offer.id = offerId = ++offerId; - await mockProtocol.mock.getOffer.returns( - true, - offer, - offerDates, - offerDurations, - disputeResolutionTerms, - offerFees - ); - // reserve a range - start = "1010"; - length = "1000"; - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, bosonVoucher.address); + offerId = "1"; + start = 10; + length = "990"; + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); + + // amount to mint + amount = "50"; }); - it("Transfer event should emit contract address", async function () { + it("Should emit Transfer events", async function () { // Premint tokens, test for event const tx = await bosonVoucher.connect(assistant).preMint(offerId, amount); @@ -467,12 +426,75 @@ describe("IBosonVoucher", function () { for (let i = 0; i < Number(amount); i++) { await expect(tx) .to.emit(bosonVoucher, "Transfer") - .withArgs(ethers.constants.AddressZero, bosonVoucher.address, start.add(i)); + .withArgs(ZeroAddress, await assistant.getAddress(), start + BigInt(i)); } }); + it("Should emit VouchersPreMinted event", async function () { + // Premint tokens, test for event + const tx = await bosonVoucher.connect(assistant).preMint(offerId, amount); + + start = deriveTokenId(offerId, start); + + await expect(tx) + .to.emit(bosonVoucher, "VouchersPreMinted") + .withArgs(offerId, start, start + BigInt(amount) - 1n); + }); + + context("Owner range is contract", async function () { + beforeEach(async function () { + offer.id = offerId = ++offerId; + + await offerHandler.connect(assistant).createOffer(offer, offerDates, offerDurations, disputeResolverId, "0"); + + // reserve a range + start = "1010"; + length = "1000"; + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await bosonVoucher.getAddress()); + }); + + it("Transfer event should emit contract address", async function () { + // Premint tokens, test for event + const tx = await bosonVoucher.connect(assistant).preMint(offerId, amount); + + // Expect an event for every mint + start = deriveTokenId(offerId, start); + for (let i = 0; i < Number(amount); i++) { + await expect(tx) + .to.emit(bosonVoucher, "Transfer") + .withArgs(ZeroAddress, await bosonVoucher.getAddress(), start + BigInt(i)); + } + }); + + it("Should update state", async function () { + let contractBalanceBefore = await bosonVoucher.balanceOf(await bosonVoucher.getAddress()); + + // Premint tokens + await bosonVoucher.connect(assistant).preMint(offerId, amount); + + // Expect a correct owner for all preminted tokens + start = deriveTokenId(offerId, start); + for (let i = 0; i < Number(amount); i++) { + let tokenId = start + BigInt(i); + let tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await bosonVoucher.getAddress(), `Wrong token owner for token ${tokenId}`); + } + + // Token that is inside a range, but wasn't preminted yet should not have an owner + await expect(bosonVoucher.ownerOf(start + amount + 1)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); + + // Contract's balance should be updated for the total mint amount + let contractBalanceAfter = await bosonVoucher.balanceOf(await bosonVoucher.getAddress()); + assert.equal(contractBalanceAfter, contractBalanceBefore + BigInt(amount), "Balance mismatch"); + + // Get available premints from contract + const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); + assert.equal(availablePremints, BigInt(length) - BigInt(amount), "Available Premints mismatch"); + }); + }); + it("Should update state", async function () { - let contractBalanceBefore = await bosonVoucher.balanceOf(bosonVoucher.address); + let sellerBalanceBefore = await bosonVoucher.balanceOf(await assistant.getAddress()); // Premint tokens await bosonVoucher.connect(assistant).preMint(offerId, amount); @@ -480,1535 +502,1493 @@ describe("IBosonVoucher", function () { // Expect a correct owner for all preminted tokens start = deriveTokenId(offerId, start); for (let i = 0; i < Number(amount); i++) { - let tokenId = start.add(i); + let tokenId = start + BigInt(i); let tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, bosonVoucher.address, `Wrong token owner for token ${tokenId}`); + assert.equal(tokenOwner, await assistant.getAddress(), `Wrong token owner for token ${tokenId}`); } // Token that is inside a range, but wasn't preminted yet should not have an owner - await expect(bosonVoucher.ownerOf(start.add(amount).add(1))).to.be.revertedWith( + await expect(bosonVoucher.ownerOf(start + BigInt(amount) + 1n)).to.be.revertedWith( RevertReasons.ERC721_NON_EXISTENT ); - // Contract's balance should be updated for the total mint amount - let contractBalanceAfter = await bosonVoucher.balanceOf(bosonVoucher.address); - assert.equal(contractBalanceAfter.toNumber(), contractBalanceBefore.add(amount).toNumber(), "Balance mismatch"); + // Seller's balance should be updated for the total mint amount + let sellerBalanceAfter = await bosonVoucher.balanceOf(await assistant.getAddress()); + assert.equal(sellerBalanceAfter, sellerBalanceBefore + BigInt(amount), "Balance mismatch"); // Get available premints from contract const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toNumber(), Number(length) - Number(amount), "Available Premints mismatch"); + assert.equal(availablePremints, BigInt(length) - BigInt(amount), "Available Premints mismatch"); }); - }); - it("Should update state", async function () { - let sellerBalanceBefore = await bosonVoucher.balanceOf(assistant.address); + it("MetaTx: forwarder can execute preMint on behalf of seller", async function () { + const nonce = Number(await forwarder.getNonce(await assistant.getAddress())); + + const types = { + ForwardRequest: [ + { name: "from", type: "address" }, + { name: "to", type: "address" }, + { name: "nonce", type: "uint256" }, + { name: "data", type: "bytes" }, + ], + }; + + const functionSignature = bosonVoucher.interface.encodeFunctionData("preMint", [offerId, amount]); + + const message = { + from: await assistant.getAddress(), + to: await bosonVoucher.getAddress(), + nonce: nonce, + data: functionSignature, + }; + + const { signature } = await prepareDataSignatureParameters( + assistant, + types, + "ForwardRequest", + message, + await forwarder.getAddress(), + "MockForwarder", + "0.0.1", + "0Z" + ); - // Premint tokens - await bosonVoucher.connect(assistant).preMint(offerId, amount); + const tx = await forwarder.execute(message, signature); - // Expect a correct owner for all preminted tokens - start = deriveTokenId(offerId, start); - for (let i = 0; i < Number(amount); i++) { - let tokenId = start.add(i); - let tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, assistant.address, `Wrong token owner for token ${tokenId}`); - } + // Expect an event for every mint + start = deriveTokenId(offerId, start); + for (let i = 0; i < Number(amount); i++) { + await expect(tx) + .to.emit(bosonVoucher, "Transfer") + .withArgs(ZeroAddress, await assistant.getAddress(), start + BigInt(i)); + } + }); - // Token that is inside a range, but wasn't preminted yet should not have an owner - await expect(bosonVoucher.ownerOf(start.add(amount).add(1))).to.be.revertedWith( - RevertReasons.ERC721_NON_EXISTENT - ); + context("💔 Revert Reasons", async function () { + it("Caller is not the owner", async function () { + await expect(bosonVoucher.connect(rando).preMint(offerId, amount)).to.be.revertedWith( + RevertReasons.OWNABLE_NOT_OWNER + ); + }); - // Seller's balance should be updated for the total mint amount - let sellerBalanceAfter = await bosonVoucher.balanceOf(assistant.address); - assert.equal(sellerBalanceAfter.toNumber(), sellerBalanceBefore.add(amount).toNumber(), "Balance mismatch"); + it("Offer id is not associated with a range", async function () { + // Set invalid offer id + offerId = 15; - // Get available premints from contract - const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toNumber(), Number(length) - Number(amount), "Available Premints mismatch"); - }); + // Try to premint, it should fail + await expect(bosonVoucher.connect(assistant).preMint(offerId, amount)).to.be.revertedWith( + RevertReasons.NO_RESERVED_RANGE_FOR_OFFER + ); + }); - it("MetaTx: forwarder can execute preMint on behalf of seller", async function () { - const nonce = Number(await forwarder.getNonce(assistant.address)); + it("Amount to mint is more than remaining un-minted in range", async function () { + // Mint 50 tokens + await bosonVoucher.connect(assistant).preMint(offerId, amount); - const types = { - ForwardRequest: [ - { name: "from", type: "address" }, - { name: "to", type: "address" }, - { name: "nonce", type: "uint256" }, - { name: "data", type: "bytes" }, - ], - }; + // Set invalid amount + amount = "990"; // length is 1000, already minted 50 - const functionSignature = bosonVoucher.interface.encodeFunctionData("preMint", [offerId, amount]); + // Try to premint, it should fail + await expect(bosonVoucher.connect(assistant).preMint(offerId, amount)).to.be.revertedWith( + RevertReasons.INVALID_AMOUNT_TO_MINT + ); + }); - const message = { - from: assistant.address, - to: bosonVoucher.address, - nonce: nonce, - data: functionSignature, - }; + it("Offer already expired", async function () { + // Skip to after offer expiration + await setNextBlockTimestamp(Number(BigInt(offerDates.validUntil) + 1n)); - const { signature } = await prepareDataSignatureParameters( - assistant, - types, - "ForwardRequest", - message, - forwarder.address, - "MockForwarder", - "0.0.1", - "0Z" - ); + // Try to premint, it should fail + await expect(bosonVoucher.connect(assistant).preMint(offerId, amount)).to.be.revertedWith( + RevertReasons.OFFER_EXPIRED_OR_VOIDED + ); + }); - const tx = await forwarder.execute(message, signature); + it("Offer is voided", async function () { + await offerHandler.connect(assistant).voidOffer(offerId); - // Expect an event for every mint - start = deriveTokenId(offerId, start); - for (let i = 0; i < Number(amount); i++) { - await expect(tx) - .to.emit(bosonVoucher, "Transfer") - .withArgs(ethers.constants.AddressZero, assistant.address, start.add(i)); - } + // Try to premint, it should fail + await expect(bosonVoucher.connect(assistant).preMint(offerId, amount)).to.be.revertedWith( + RevertReasons.OFFER_EXPIRED_OR_VOIDED + ); + }); + }); }); - context("💔 Revert Reasons", async function () { - it("Caller is not the owner", async function () { - await expect(bosonVoucher.connect(rando).preMint(offerId, amount)).to.be.revertedWith( - RevertReasons.OWNABLE_NOT_OWNER - ); - }); + context("burnPremintedVouchers()", function () { + let offerId, start, length, amount; - it("Offer id is not associated with a range", async function () { - // Set invalid offer id - offerId = 15; + beforeEach(async function () { + offerId = "1"; - // Try to premint, it should fail - await expect(bosonVoucher.connect(assistant).preMint(offerId, amount)).to.be.revertedWith( - RevertReasons.NO_RESERVED_RANGE_FOR_OFFER - ); - }); + // reserve a range + start = "1"; + length = "1000"; + + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - it("Amount to mint is more than remaining un-minted in range", async function () { - // Mint 50 tokens + // amount to mint + amount = "5"; await bosonVoucher.connect(assistant).preMint(offerId, amount); - // Set invalid amount - amount = "990"; // length is 1000, already minted 50 + // Void offer + await offerHandler.connect(assistant).voidOffer(offerId); + }); - // Try to premint, it should fail - await expect(bosonVoucher.connect(assistant).preMint(offerId, amount)).to.be.revertedWith( - RevertReasons.INVALID_AMOUNT_TO_MINT - ); + it("Should emit Transfer events", async function () { + // Burn tokens, test for event + const tx = await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); + + // Expect an event for every burn + start = deriveTokenId(offerId, start); + for (let i = 0; i < Number(amount); i++) { + await expect(tx) + .to.emit(bosonVoucher, "Transfer") + .withArgs(await assistant.getAddress(), ZeroAddress, start + BigInt(i)); + } }); - it("Too many to mint in a single transaction", async function () { - await mockProtocol.mock.getMaxPremintedVouchers.returns("100"); + it("Should update state", async function () { + let sellerBalanceBefore = await bosonVoucher.balanceOf(await assistant.getAddress()); - // Set invalid amount - amount = "101"; + // Burn tokens + await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); - // Try to premint, it should fail - await expect(bosonVoucher.connect(assistant).preMint(offerId, amount)).to.be.revertedWith( - RevertReasons.TOO_MANY_TO_MINT - ); - }); + // All burned tokens should not have an owner + const startId = deriveTokenId(offerId, start); + for (let i = 0; i < Number(amount); i++) { + let tokenId = startId + BigInt(i); + await expect(bosonVoucher.ownerOf(tokenId)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); + } + + // Seller's balance should be decreased for the total burn amount + let sellerBalanceAfter = await bosonVoucher.balanceOf(await assistant.getAddress()); + assert.equal(sellerBalanceAfter, sellerBalanceBefore - BigInt(amount), "Balance mismatch"); - it("Offer already expired", async function () { - // Skip to after offer expiration - await setNextBlockTimestamp(ethers.BigNumber.from(offerDates.validUntil).add(1).toHexString()); + // Get available premints from contract + const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); + assert.equal(availablePremints, 0n, "Available Premints mismatch"); - // Try to premint, it should fail - await expect(bosonVoucher.connect(assistant).preMint(offerId, amount)).to.be.revertedWith( - RevertReasons.OFFER_EXPIRED_OR_VOIDED + // Last burned id should be updated + const tokenIdStart = deriveTokenId(offerId, start); + const lastBurnedId = tokenIdStart + BigInt(amount) - 1n; + const range = new Range( + tokenIdStart.toString(), + length, + amount, + lastBurnedId.toString(), + await assistant.getAddress() ); + const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); + assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); }); - it("Offer is voided", async function () { - // Make offer voided - offer.voided = true; - await mockProtocol.mock.getOffer.returns( - true, - offer, - offerDates, - offerDurations, - disputeResolutionTerms, - offerFees - ); + context("Contract owner is not owner of preminted vouchers", function () { + it("Ownership is transferred", async function () { + // Transfer ownership to rando + await bosonVoucher.connect(protocol).transferOwnership(await rando.getAddress()); + + // Burn tokens, test for event + let tx; + await expect(() => { + tx = bosonVoucher.connect(rando).burnPremintedVouchers(offerId); + return tx; + }).to.changeTokenBalance(bosonVoucher, assistant, BigInt(amount) * -1n); + + // Expect an event for every burn, where owner is the old owner (assistant) + const tokenIdStart = deriveTokenId(offerId, start); + for (let i = 0; i < Number(amount); i++) { + await expect(tx) + .to.emit(bosonVoucher, "Transfer") + .withArgs(await assistant.getAddress(), ZeroAddress, tokenIdStart + BigInt(i)); + } + }); - // Try to premint, it should fail - await expect(bosonVoucher.connect(assistant).preMint(offerId, amount)).to.be.revertedWith( - RevertReasons.OFFER_EXPIRED_OR_VOIDED - ); + it("Contract itself is the owner", async function () { + offer.id = offerId = ++offerId; + offer.quantityAvailable = "2000"; + + await offerHandler.connect(assistant).createOffer(offer, offerDates, offerDurations, disputeResolverId, "0"); + + // reserve a range + start = "2000"; + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await bosonVoucher.getAddress()); + + // amount to mint + amount = "10"; + await bosonVoucher.connect(assistant).preMint(offerId, amount); + + await offerHandler.connect(assistant).voidOffer(offerId); + + // Burn tokens, test for event + let tx; + await expect(() => { + tx = bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); + return tx; + }).to.changeTokenBalance(bosonVoucher, bosonVoucher, BigInt(amount) * -1n); + + // Expect an event for every burn + const tokenIdStart = deriveTokenId(offerId, start); + for (let i = 0; i < Number(amount); i++) { + await expect(tx) + .to.emit(bosonVoucher, "Transfer") + .withArgs(await bosonVoucher.getAddress(), ZeroAddress, tokenIdStart + BigInt(i)); + } + }); }); - }); - }); - context("burnPremintedVouchers()", function () { - let offerId, start, length, amount; - let mockProtocol; - let offer, offerDates, offerDurations, offerFees, disputeResolutionTerms; - let maxPremintedVouchers; + it("Should skip all vouchers were already committed", async function () { + // make offer not voided so premint is possible + offer.voided = false; + // make offer not voided + offer.id = offerId = ++offerId; + length = amount = "10"; + start = "1"; - beforeEach(async function () { - offerId = "5"; - maxPremintedVouchers = "10"; - - mockProtocol = await deployMockProtocol(); - ({ offer, offerDates, offerDurations, offerFees } = await mockOffer()); - disputeResolutionTerms = new DisputeResolutionTerms("0", "0", "0", "0"); - await mockProtocol.mock.getMaxPremintedVouchers.returns(maxPremintedVouchers); - await mockProtocol.mock.getOffer - .withArgs(offerId) - .returns(true, offer, offerDates, offerDurations, disputeResolutionTerms, offerFees); - - // reserve a range - start = "10"; - length = "1000"; - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); - - // amount to mint - amount = "5"; - await bosonVoucher.connect(assistant).preMint(offerId, amount); - - // "void" the offer - offer.voided = true; - await mockProtocol.mock.getOffer - .withArgs(offerId) - .returns(true, offer, offerDates, offerDurations, disputeResolutionTerms, offerFees); - }); + const assistantAddress = await assistant.getAddress(); - it("Should emit Transfer events", async function () { - // Burn tokens, test for event - const tx = await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); + await offerHandler.connect(assistant).createOffer(offer, offerDates, offerDurations, disputeResolverId, "0"); - // Number of events emitted should be equal to amount - assert.equal((await tx.wait()).events.length, Number(amount), "Wrong number of events emitted"); + await offerHandler.connect(assistant).reserveRange(offerId, length, assistantAddress); - // Expect an event for every burn - start = deriveTokenId(offerId, start); - for (let i = 0; i < Number(amount); i++) { - await expect(tx) - .to.emit(bosonVoucher, "Transfer") - .withArgs(assistant.address, ethers.constants.AddressZero, start.add(i)); - } - }); + await bosonVoucher.connect(assistant).preMint(offerId, length); - it("Should update state", async function () { - let sellerBalanceBefore = await bosonVoucher.balanceOf(assistant.address); - - // Burn tokens - await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); - - // All burned tokens should not have an owner - const startId = deriveTokenId(offerId, start); - for (let i = 0; i < Number(amount); i++) { - let tokenId = startId.add(i); - await expect(bosonVoucher.ownerOf(tokenId)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); - } - - // Seller's balance should be decreased for the total burn amount - let sellerBalanceAfter = await bosonVoucher.balanceOf(assistant.address); - assert.equal(sellerBalanceAfter.toNumber(), sellerBalanceBefore.sub(amount).toNumber(), "Balance mismatch"); - - // Get available premints from contract - const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toNumber(), 0, "Available Premints mismatch"); - - // Last burned id should be updated - const tokenIdStart = deriveTokenId(offerId, start); - const lastBurnedId = tokenIdStart.add(amount - 1); - const range = new Range(tokenIdStart.toString(), length, amount, lastBurnedId.toString(), assistant.address); - const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); - assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); - }); + let committedVouchers = [2, 4].map((tokenId) => deriveTokenId(offerId, tokenId)); - context("Contract owner is not owner of preminted vouchers", function () { - it("Ownership is transferred", async function () { - // Transfer ownership to rando - await bosonVoucher.connect(protocol).transferOwnership(rando.address); + // Transfer some preminted vouchers + const buyerAddress = await buyer.getAddress(); + await Promise.all( + committedVouchers.map((tokenId) => + bosonVoucher.connect(assistant).transferFrom(assistantAddress, buyerAddress, tokenId) + ) + ); - // Burn tokens, test for event - let tx; - await expect(() => { - tx = bosonVoucher.connect(rando).burnPremintedVouchers(offerId); - return tx; - }).to.changeTokenBalance(bosonVoucher, assistant, Number(amount) * -1); + await offerHandler.connect(assistant).voidOffer(offerId); - // Number of events emitted should be equal to amount - tx = await tx; - assert.equal((await tx.wait()).events.length, Number(amount), "Wrong number of events emitted"); + // Burn tokens, test for event + let tx = await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); + + // All burned tokens should not have an owner, but commited ones should + const startId = deriveTokenId(offerId, start); + for (let i = 0; i < Number(length); i++) { + let tokenId = startId + BigInt(i); + if (committedVouchers.includes(tokenId)) { + // Check that owner is buyer. + expect(await bosonVoucher.ownerOf(tokenId)).to.equal(buyerAddress); + } else { + // Check that Transfer event was emitted and owner does not exist anymore + await expect(tx) + .to.emit(bosonVoucher, "Transfer") + .withArgs(await assistant.getAddress(), ZeroAddress, tokenId); + await expect(bosonVoucher.ownerOf(tokenId)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); + } + } - // Expect an event for every burn, where owner is the old owner (assistant) + // Last burned id should be updated const tokenIdStart = deriveTokenId(offerId, start); - for (let i = 0; i < Number(amount); i++) { - await expect(tx) - .to.emit(bosonVoucher, "Transfer") - .withArgs(assistant.address, ethers.constants.AddressZero, tokenIdStart.add(i)); - } + const lastBurnedId = tokenIdStart + BigInt(amount) - 1n; + const range = new Range( + tokenIdStart.toString(), + length, + amount, + lastBurnedId.toString(), + await assistant.getAddress() + ); + const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); + assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); }); - it("Contract itself is the owner", async function () { - // create a new offer, so new range owner can be set - offerId = "6"; + it("Burning is possible if offer not voided, but just expired", async function () { + // make offer not voided so premint is possible offer.voided = false; - await mockProtocol.mock.getOffer - .withArgs(offerId) - .returns(true, offer, offerDates, offerDurations, disputeResolutionTerms, offerFees); + // make offer not voided + offer.id = offerId = ++offerId; - // reserve a range - start = "2000"; - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, bosonVoucher.address); + await offerHandler.connect(assistant).createOffer(offer, offerDates, offerDurations, disputeResolverId, "0"); - // amount to mint - amount = "10"; - await bosonVoucher.connect(assistant).preMint(offerId, amount); + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - // "void" the offer - offer.voided = true; - await mockProtocol.mock.getOffer - .withArgs(offerId) - .returns(true, offer, offerDates, offerDurations, disputeResolutionTerms, offerFees); + // Mint another 10 vouchers, so that there are 15 in total + await bosonVoucher.connect(assistant).preMint(offerId, 10); - // Burn tokens, test for event - let tx; - await expect(() => { - tx = bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); - return tx; - }).to.changeTokenBalance(bosonVoucher, bosonVoucher, Number(amount) * -1); + // skip to after offer expiration + await setNextBlockTimestamp(Number(BigInt(offerDates.validUntil) + 1n)); - // Number of events emitted should be equal to amount - tx = await tx; - assert.equal((await tx.wait()).events.length, Number(amount), "Wrong number of events emitted"); + // Burn tokens, test for event + const tx = await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); // Expect an event for every burn - const tokenIdStart = deriveTokenId(offerId, start); + start = deriveTokenId(offerId, start); for (let i = 0; i < Number(amount); i++) { await expect(tx) .to.emit(bosonVoucher, "Transfer") - .withArgs(bosonVoucher.address, ethers.constants.AddressZero, tokenIdStart.add(i)); + .withArgs(await assistant.getAddress(), ZeroAddress, start + BigInt(i)); } }); - }); - - it("Should burn all vouchers if there is less than MaxPremintedVouchers to burn", async function () { - // Burn tokens, test for event - let tx = await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); - // Number of events emitted should be equal to amount - assert.equal((await tx.wait()).events.length, Number(amount), "Wrong number of events emitted"); + context("💔 Revert Reasons", async function () { + it("Caller is not the owner", async function () { + await expect(bosonVoucher.connect(rando).burnPremintedVouchers(offerId)).to.be.revertedWith( + RevertReasons.OWNABLE_NOT_OWNER + ); + }); - // Last burned id should be updated - const tokenIdStart = deriveTokenId(offerId, start); - const lastBurnedId = tokenIdStart.add(amount - 1); - const range = new Range(tokenIdStart.toString(), length, amount, lastBurnedId.toString(), assistant.address); - const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); - assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); + it("Offer id is not associated with a range", async function () { + // Set invalid offer id + offerId = 15; - // Second call should revert since there's nothing to burn - await expect(bosonVoucher.connect(assistant).burnPremintedVouchers(offerId)).to.be.revertedWith( - RevertReasons.NOTHING_TO_BURN - ); - }); + // Try to burn, it should fail + await expect(bosonVoucher.connect(assistant).burnPremintedVouchers(offerId)).to.be.revertedWith( + RevertReasons.NO_RESERVED_RANGE_FOR_OFFER + ); + }); - it("Should burn only first MaxPremintedVouchers vouchers if there is more than MaxPremintedVouchers to burn", async function () { - // make offer not voided so premint is possible - offer.voided = false; - await mockProtocol.mock.getOffer - .withArgs(offerId) - .returns(true, offer, offerDates, offerDurations, disputeResolutionTerms, offerFees); - - // Mint another 10 vouchers, so that there are 15 in total - await bosonVoucher.connect(assistant).preMint(offerId, 10); - amount = `${Number(amount) + 10}`; - - // "void" the offer - offer.voided = true; - await mockProtocol.mock.getOffer - .withArgs(offerId) - .returns(true, offer, offerDates, offerDurations, disputeResolutionTerms, offerFees); - - // Burn tokens, test for event - let tx = await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); - - // Number of events emitted should be equal to maxPremintedVouchers - assert.equal((await tx.wait()).events.length, Number(maxPremintedVouchers), "Wrong number of events emitted"); - - // Last burned id should be updated - const tokenIdStart = deriveTokenId(offerId, start); - let lastBurnedId = tokenIdStart.add(maxPremintedVouchers - 1); - let range = new Range(tokenIdStart.toString(), length, amount, lastBurnedId.toString(), assistant.address); - let returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); - assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); - - // Second call should burn the difference - tx = await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); - - // Number of events emitted should be equal to amount - assert.equal( - (await tx.wait()).events.length, - Number(amount) - maxPremintedVouchers, - "Wrong number of events emitted" - ); + it("Offer is still valid", async function () { + // make offer not voided + offer.id = offerId = ++offerId; - // Last burned id should be updated - lastBurnedId = tokenIdStart.add(amount - 1); - range = new Range(tokenIdStart.toString(), length, amount, lastBurnedId.toString(), assistant.address); - returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); - assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); - - // All burned tokens should not have an owner - for (let i = 0; i < Number(amount); i++) { - let tokenId = tokenIdStart.add(i); - await expect(bosonVoucher.ownerOf(tokenId)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); - } - - // Second call should revert since there's nothing to burn - await expect(bosonVoucher.connect(assistant).burnPremintedVouchers(offerId)).to.be.revertedWith( - RevertReasons.NOTHING_TO_BURN - ); - }); + await offerHandler.connect(assistant).createOffer(offer, offerDates, offerDurations, disputeResolverId, "0"); - it("Should skip all vouchers were already committed", async function () { - let committedVouchers = [11, 14].map((tokenId) => deriveTokenId(offerId, tokenId).toString()); + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - // Transfer some preminted vouchers - await mockProtocol.mock.commitToPreMintedOffer.returns(); - await Promise.all( - committedVouchers.map((tokenId) => - bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId) - ) - ); + // Mint another 10 vouchers, so that there are 15 in total + await bosonVoucher.connect(assistant).preMint(offerId, 10); - // Burn tokens, test for event - let tx = await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); + // Try to burn, it should fail + await expect(bosonVoucher.connect(assistant).burnPremintedVouchers(offerId)).to.be.revertedWith( + RevertReasons.OFFER_STILL_VALID + ); + }); - // Number of events emitted should be equal to amount of preminted vouchers decreased by length of committed vouchers - // We test this to indirectly verify that no events were emitted for committed vouchers - assert.equal( - (await tx.wait()).events.length, - Number(amount) - committedVouchers.length, - "Wrong number of events emitted" - ); + it("Nothing to burn", async function () { + // Burn tokens + await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); - // All burned tokens should not have an owner, but commited ones should - const startId = deriveTokenId(offerId, start); - for (let i = 0; i < Number(amount); i++) { - let tokenId = startId.add(i).toString(); - if (committedVouchers.includes(tokenId)) { - // Check that owner is buyer. - expect(await bosonVoucher.ownerOf(tokenId)).to.equal(buyer.address); - } else { - // Check that Transfer event was emitted and owner does not exist anymore - await expect(tx) - .to.emit(bosonVoucher, "Transfer") - .withArgs(assistant.address, ethers.constants.AddressZero, tokenId); - await expect(bosonVoucher.ownerOf(tokenId)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); - } - } - - // Last burned id should be updated - const tokenIdStart = deriveTokenId(offerId, start); - const lastBurnedId = tokenIdStart.add(amount - 1); - const range = new Range(tokenIdStart.toString(), length, amount, lastBurnedId.toString(), assistant.address); - const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); - assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); + // Try to burn, it should fail + await expect(bosonVoucher.connect(assistant).burnPremintedVouchers(offerId)).to.be.revertedWith( + RevertReasons.NOTHING_TO_BURN + ); + }); + }); }); - it("Burning is possible if offer not voided, but just expired", async function () { - // make offer not voided so premint is possible - offer.voided = false; - await mockProtocol.mock.getOffer - .withArgs(offerId) - .returns(true, offer, offerDates, offerDurations, disputeResolutionTerms, offerFees); - // skip to after offer expiration - await setNextBlockTimestamp(ethers.BigNumber.from(offerDates.validUntil).add(1).toHexString()); + context("getAvailablePreMints()", function () { + let offerId, start, length, amount; - // Burn tokens, test for event - const tx = await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); + beforeEach(async function () { + // reserve a range + offerId = "1"; + start = "10"; + length = "990"; + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - // Number of events emitted should be equal to amount - assert.equal((await tx.wait()).events.length, Number(amount), "Wrong number of events emitted"); + // amount to mint + amount = 50; + }); - // Expect an event for every burn - start = deriveTokenId(offerId, start); - for (let i = 0; i < Number(amount); i++) { - await expect(tx) - .to.emit(bosonVoucher, "Transfer") - .withArgs(assistant.address, ethers.constants.AddressZero, start.add(i)); - } - }); + it("If nothing was preminted, return full range", async function () { + // Get available premints from contract + const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); + assert.equal(availablePremints.toString(), length, "Available Premints mismatch"); + }); - context("💔 Revert Reasons", async function () { - it("Caller is not the owner", async function () { - await expect(bosonVoucher.connect(rando).burnPremintedVouchers(offerId)).to.be.revertedWith( - RevertReasons.OWNABLE_NOT_OWNER - ); + it("Part of range is preminted", async function () { + // Premint tokens + await bosonVoucher.connect(assistant).preMint(offerId, amount); + + // Get available premints from contract + let newAmount = BigInt(length) - BigInt(amount); + let availablePremints = await bosonVoucher.getAvailablePreMints(offerId); + assert.equal(availablePremints, newAmount, "Available Premints mismatch"); + + // Premint again + await bosonVoucher.connect(assistant).preMint(offerId, amount); + newAmount -= BigInt(amount); + availablePremints = await bosonVoucher.getAvailablePreMints(offerId); + assert.equal(availablePremints, newAmount, "Available Premints mismatch"); }); - it("Offer id is not associated with a range", async function () { - // Set invalid offer id - offerId = 15; + it("Range is fully minted", async function () { + // Adjust config value + await configHandler.connect(deployer).setMaxPremintedVouchers(length); - // Try to burn, it should fail - await expect(bosonVoucher.connect(assistant).burnPremintedVouchers(offerId)).to.be.revertedWith( - RevertReasons.NO_RESERVED_RANGE_FOR_OFFER - ); + // Premint tokens + await bosonVoucher.connect(assistant).preMint(offerId, length); + + // Get available premints from contract + let availablePremints = await bosonVoucher.getAvailablePreMints(offerId); + assert.equal(availablePremints, 0, "Available Premints mismatch"); }); - it("Offer is still valid", async function () { - // make offer not voided - offer.voided = false; - await mockProtocol.mock.getOffer - .withArgs(offerId) - .returns(true, offer, offerDates, offerDurations, disputeResolutionTerms, offerFees); + it("Range for offer does not exist", async function () { + // Set invalid offer id + offerId = "20"; - // Try to burn, it should fail - await expect(bosonVoucher.connect(assistant).burnPremintedVouchers(offerId)).to.be.revertedWith( - RevertReasons.OFFER_STILL_VALID - ); + // Get available premints from contract + let availablePremints = await bosonVoucher.getAvailablePreMints(offerId); + assert.equal(availablePremints, 0, "Available Premints mismatch"); }); - it("Nothing to burn", async function () { - // Burn tokens - await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); + it("Should be 0 if offer is voided", async function () { + await offerHandler.connect(assistant).voidOffer(offerId); - // Try to burn, it should fail - await expect(bosonVoucher.connect(assistant).burnPremintedVouchers(offerId)).to.be.revertedWith( - RevertReasons.NOTHING_TO_BURN - ); + // Get available premints from contract + let availablePremints = await bosonVoucher.getAvailablePreMints(offerId); + assert.equal(availablePremints, 0, "Available Premints mismatch"); }); - }); - }); - context("getAvailablePreMints()", function () { - let offerId, start, length, amount; - let offer, offerDates, offerDurations, offerFees; - let disputeResolutionTerms; - let mockProtocol; + it("Should be 0 if offer is expired", async function () { + // Skip to after offer expiry + await setNextBlockTimestamp(Number(BigInt(offerDates.validUntil) + 1n)); - beforeEach(async function () { - // reserve a range - offerId = "5"; - start = "10"; - length = "1000"; - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); - - // amount to mint - amount = 50; - - mockProtocol = await deployMockProtocol(); - ({ offer, offerDates, offerDurations, offerFees } = await mockOffer()); - disputeResolutionTerms = new DisputeResolutionTerms("0", "0", "0", "0"); - await mockProtocol.mock.getMaxPremintedVouchers.returns("1000"); - await mockProtocol.mock.getOffer.returns( - true, - offer, - offerDates, - offerDurations, - disputeResolutionTerms, - offerFees - ); + // Get available premints from contract + let availablePremints = await bosonVoucher.getAvailablePreMints(offerId); + assert.equal(availablePremints, 0, "Available Premints mismatch"); + }); }); - it("If nothing was preminted, return full range", async function () { - // Get available premints from contract - const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toString(), length, "Available Premints mismatch"); - }); + context("getRange()", function () { + let offerId, start, length, amount; + let range; - it("Part of range is preminted", async function () { - // Premint tokens - await bosonVoucher.connect(assistant).preMint(offerId, amount); + beforeEach(async function () { + // reserve a range + offerId = "1"; + start = "10"; + length = "990"; + const tokenIdStart = deriveTokenId(offerId, start); - // Get available premints from contract - let newAmount = Number(length) - Number(amount); - let availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toNumber(), newAmount, "Available Premints mismatch"); + range = new Range(tokenIdStart.toString(), length, "0", "0", await assistant.getAddress()); - // Premint again - await bosonVoucher.connect(assistant).preMint(offerId, amount); - newAmount -= Number(amount); - availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toNumber(), newAmount, "Available Premints mismatch"); - }); + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - it("Range is fully minted", async function () { - // Adjust config value - await configHandler.connect(deployer).setMaxPremintedVouchers(length); + // amount to premint + amount = "50"; + range.minted = amount; + await bosonVoucher.connect(assistant).preMint(offerId, amount); + }); - // Premint tokens - await bosonVoucher.connect(assistant).preMint(offerId, length); + it("Get range object for offer with reserved range", async function () { + // Get range object from contract + const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); + assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); + }); - // Get available premints from contract - let availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toNumber(), 0, "Available Premints mismatch"); + it("Get empty range if offer has no reserved ranges", async function () { + // Set invalid offer and empty range + offerId = "20"; + range = new Range("0", "0", "0", "0", ZeroAddress); + + // Get range object from contract + const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); + assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); + }); }); - it("Range for offer does not exist", async function () { - // Set invalid offer id - offerId = "20"; + context("ownerOf()", function () { + let offerId, start, length, amount; - // Get available premints from contract - let availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toNumber(), 0, "Available Premints mismatch"); - }); + context("No preminted tokens", async function () { + it("Returns true owner if token exists", async function () { + let tokenId = "100000"; + // Issue ordinary voucher + await bosonVoucher.connect(protocol).issueVoucher(tokenId, await buyer.getAddress()); - it("Should be 0 if offer is voided", async function () { - // void offer - offer.voided = true; - await mockProtocol.mock.getOffer.returns( - true, - offer, - offerDates, - offerDurations, - disputeResolutionTerms, - offerFees - ); + // Token owner should be the buyer + let tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await buyer.getAddress(), "Token owner mismatch"); + }); - // Get available premints from contract - let availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toNumber(), 0, "Available Premints mismatch"); - }); + context("💔 Revert Reasons", async function () { + it("Token does not exist", async function () { + let tokenId = "10"; + await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( + RevertReasons.ERC721_NON_EXISTENT + ); + }); + }); + }); - it("Should be 0 if offer is expired", async function () { - // Skip to after offer expiry - await setNextBlockTimestamp(ethers.BigNumber.from(offerDates.validUntil).add(1).toHexString()); + context("With preminted tokens", async function () { + beforeEach(async function () { + // reserve a range + offerId = "1"; + start = "10"; + length = "150"; + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - // Get available premints from contract - let availablePremints = await bosonVoucher.getAvailablePreMints(offerId); - assert.equal(availablePremints.toNumber(), 0, "Available Premints mismatch"); - }); - }); + // amount to premint + amount = 50; + await bosonVoucher.connect(assistant).preMint(offerId, amount); + }); - context("getRange()", function () { - let offerId, start, length, amount; - let range; + it("Returns true owner if token exists - via issue voucher", async function () { + let tokenId = "100000"; - beforeEach(async function () { - // reserve a range - offerId = "5"; - start = "10"; - length = "1000"; - const tokenIdStart = deriveTokenId(offerId, start); - - range = new Range(tokenIdStart.toString(), length, "0", "0", assistant.address); - - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); - - const mockProtocol = await deployMockProtocol(); - const { offer, offerDates, offerDurations, offerFees } = await mockOffer(); - const disputeResolutionTerms = new DisputeResolutionTerms("0", "0", "0", "0"); - await mockProtocol.mock.getMaxPremintedVouchers.returns("1000"); - await mockProtocol.mock.getOffer.returns( - true, - offer, - offerDates, - offerDurations, - disputeResolutionTerms, - offerFees - ); + // Issue ordinary voucher + await bosonVoucher.connect(protocol).issueVoucher(tokenId, await buyer.getAddress()); - // amount to premint - amount = "50"; - range.minted = amount; - await bosonVoucher.connect(assistant).preMint(offerId, amount); - }); + // Token owner should be the buyer + let tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await buyer.getAddress(), "Token owner mismatch"); + }); - it("Get range object for offer with reserved range", async function () { - // Get range object from contract - const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); - assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); - }); + it("Returns true owner if token exists - via preminted voucher transfer.", async function () { + let exchangeId = "25"; // tokens between 10 and 60 are preminted + const tokenId = deriveTokenId(offerId, exchangeId); - it("Get empty range if offer has no reserved ranges", async function () { - // Set invalid offer and empty range - offerId = "20"; - range = new Range("0", "0", "0", "0", ethers.constants.AddressZero); + // Transfer preminted token + await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); - // Get range object from contract - const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); - assert.equal(returnedRange.toString(), range.toString(), "Range mismatch"); - }); - }); + // Token owner should be the buyer + let tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await buyer.getAddress(), "Token owner mismatch"); + }); - context("ownerOf()", function () { - let offerId, start, length, amount; - let offer, offerDates, offerDurations, offerFees, disputeResolutionTerms; - let mockProtocol; + it("Returns seller if token is preminted and not transferred yet", async function () { + // Token owner should be the seller for all preminted tokens + let startTokenId = deriveTokenId(offerId, start); + let endTokenId = startTokenId + BigInt(amount); + for (let i = startTokenId; i < endTokenId; i = i + 1n) { + let tokenOwner = await bosonVoucher.ownerOf(i); + assert.equal(tokenOwner, await assistant.getAddress(), `Token owner mismatch ${i.toString()}`); + } + }); - context("No preminted tokens", async function () { - it("Returns true owner if token exists", async function () { - let tokenId = "100000"; - // Issue ordinary voucher - await bosonVoucher.connect(protocol).issueVoucher(tokenId, buyer.address); + it("Multiple ranges", async function () { + // Add five more ranges + // This tests more getPreMintStatus than ownerOf + // Might even be put into integration tests + let previousOfferId = Number(offerId); + let previousStartId = Number(start); + let ranges = [new Range(Number(start), length, amount, "0")]; + length = Number(length); - // Token owner should be the buyer - let tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, buyer.address, "Token owner mismatch"); - }); + offerId = ++previousOfferId; - context("💔 Revert Reasons", async function () { - it("Token does not exist", async function () { - let tokenId = "10"; - await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( - RevertReasons.ERC721_NON_EXISTENT - ); - }); - }); - }); + while (offerId <= 6) { + start = previousStartId + length + 100; - context("With preminted tokens", async function () { - beforeEach(async function () { - // reserve a range - offerId = "5"; - start = "10"; - length = "150"; - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); - - mockProtocol = await deployMockProtocol(); - ({ offer, offerDates, offerDurations, offerFees } = await mockOffer()); - disputeResolutionTerms = new DisputeResolutionTerms("0", "0", "0", "0"); - await mockProtocol.mock.getMaxPremintedVouchers.returns("1000"); - await mockProtocol.mock.getOffer.returns( - true, - offer, - offerDates, - offerDurations, - disputeResolutionTerms, - offerFees - ); + await offerHandler + .connect(assistant) + .createOffer(offer, offerDates, offerDurations, disputeResolverId, "0"); - // amount to premint - amount = 50; - await bosonVoucher.connect(assistant).preMint(offerId, amount); - }); + // reserve length + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - it("Returns true owner if token exists - via issue voucher", async function () { - let tokenId = "100000"; + // amount to premint + amount = length - (offerId - 2) * 30; + await bosonVoucher.connect(assistant).preMint(offerId, amount); + ranges.push(new Range(start, length, amount, "0")); + + previousStartId = start; + offerId++; + } - // Define what should be returned when getExchange is called - await mockProtocol.mock.getExchange.withArgs(tokenId).returns(true, mockExchange({ offerId }), mockVoucher()); + let endTokenId = previousStartId + length; // last range end + let rangeIndex = 0; + let currentRange = ranges[rangeIndex]; + let currentRangeMintEndId = currentRange.start + currentRange.minted - 1; + let currentRangeEndId = currentRange.start + length - 1; + offerId = 1; + + for (let i = 0; i < endTokenId; i++) { + const tokenId = deriveTokenId(offerId, i); + if (i < currentRange.start) { + // tokenId not in range + await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( + RevertReasons.ERC721_NON_EXISTENT + ); + } else if (i <= currentRangeMintEndId) { + // tokenId in range and minted. Seller should be the owner + let tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await assistant.getAddress(), `Token owner mismatch ${tokenId.toString()}`); + } else if (i <= currentRangeEndId) { + // tokenId still in range, but not minted yet + await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( + RevertReasons.ERC721_NON_EXISTENT + ); + } else { + // tokenId outside the current range + // Change current range + if (rangeIndex < ranges.length) { + currentRange = ranges[++rangeIndex]; + currentRangeMintEndId = currentRange.start + currentRange.minted - 1; + currentRangeEndId = currentRange.start + currentRange.length - 1; + offerId++; + } + // Technically, next range could be consecutive and next call should return seller's address + // But range construction in this test ensures gaps between ranges + await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( + RevertReasons.ERC721_NON_EXISTENT + ); + } + } + }); - // Issue ordinary voucher - await bosonVoucher.connect(protocol).issueVoucher(tokenId, buyer.address); + it("Consecutive ranges", async function () { + // Make two consecutive ranges + let nextOfferId = Number(offerId) + 1; + let nextStartId = Number(start) + Number(length); + let nextLength = "10"; + let nextAmount = "5"; - // Token owner should be the buyer - let tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, buyer.address, "Token owner mismatch"); - }); + await offerHandler.connect(assistant).createOffer(offer, offerDates, offerDurations, disputeResolverId, "0"); - it("Returns true owner if token exists - via preminted voucher transfer.", async function () { - let exchangeId = "25"; // tokens between 10 and 60 are preminted - const tokenId = deriveTokenId(offerId, exchangeId); + // reserve length + await bosonVoucher + .connect(protocol) + .reserveRange(nextOfferId, nextStartId, nextLength, await assistant.getAddress()); - const mockProtocol = await deployMockProtocol(); + // amount to premint + await bosonVoucher.connect(assistant).preMint(nextOfferId, nextAmount); - // Define what should be returned when commitToPreMintedOffer is called - await mockProtocol.mock.commitToPreMintedOffer.returns(); + // First range - preminted tokens + let startTokenId = deriveTokenId(offerId, start); + let endTokenId = startTokenId + BigInt(amount); - // Transfer preminted token - await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + for (let i = startTokenId; i < endTokenId; i = i + 1n) { + let tokenOwner = await bosonVoucher.ownerOf(i); + assert.equal(tokenOwner, await assistant.getAddress(), `Token owner mismatch ${i.toString()}`); + } - // Token owner should be the buyer - let tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, buyer.address, "Token owner mismatch"); - }); + // First range - not preminted tokens + startTokenId = endTokenId; - it("Returns seller if token is preminted and not transferred yet", async function () { - // Token owner should be the seller for all preminted tokens - let startTokenId = deriveTokenId(offerId, start); - let endTokenId = startTokenId.add(amount); - for (let i = startTokenId; i.lt(endTokenId); i = i.add(1)) { - let tokenOwner = await bosonVoucher.ownerOf(i); - assert.equal(tokenOwner, assistant.address, `Token owner mismatch ${i.toString()}`); - } - }); + let endExchangeId = Number(start) + Number(length); + endTokenId = deriveTokenId(offerId, endExchangeId); - it("Multiple ranges", async function () { - // Add five more ranges - // This tests more getPreMintStatus than ownerOf - // Might even be put into integration tests - // Adjust config value - await configHandler.connect(deployer).setMaxPremintedVouchers("10000"); - let previousOfferId = Number(offerId); - let previousStartId = Number(start); - let ranges = [new Range(Number(start), length, amount, "0")]; - length = Number(length); + for (let i = startTokenId; i < endTokenId; i = i + 1n) { + await expect(bosonVoucher.connect(rando).ownerOf(i)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); + } - for (let i = 0; i < 5; i++) { - offerId = previousOfferId + (i + 1) * 6; - start = previousStartId + length + 100; + // Second range - preminted tokens + startTokenId = deriveTokenId(nextOfferId, endExchangeId); - // reserve length - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); + endTokenId = startTokenId + BigInt(nextAmount); + for (let i = startTokenId; i < endTokenId; i = i + 1n) { + let tokenOwner = await bosonVoucher.ownerOf(i); + assert.equal(tokenOwner, await assistant.getAddress(), `Token owner mismatch ${i.toString()}`); + } - // amount to premint - amount = length - i * 30; - await bosonVoucher.connect(assistant).preMint(offerId, amount); - ranges.push(new Range(start, length, amount, "0")); + // Second range - not preminted tokens + startTokenId = endTokenId; - previousStartId = start; - previousOfferId = offerId; - } + endExchangeId += Number(nextLength); + endTokenId = deriveTokenId(nextOfferId, endExchangeId); - let endTokenId = previousStartId + length; // last range end - let rangeIndex = 0; - let currentRange = ranges[rangeIndex]; - let currentRangeMintEndId = currentRange.start + currentRange.minted - 1; - let currentRangeEndId = currentRange.start + length - 1; - - offerId = "5"; - for (let i = 0; i < endTokenId; i++) { - const tokenId = deriveTokenId(offerId, i); - if (i < currentRange.start) { - // tokenId not in range + for (let i = startTokenId; i < endTokenId; i = i + 1n) { + await expect(bosonVoucher.connect(rando).ownerOf(i)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); + } + }); + + context("💔 Revert Reasons", async function () { + it("Token is outside any range and not minted", async function () { + let tokenId = "200000"; await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( RevertReasons.ERC721_NON_EXISTENT ); - } else if (i <= currentRangeMintEndId) { - // tokenId in range and minted. Seller should be the owner + }); + + it("Token is inside a range, but not minted yet", async function () { + let startTokenId = deriveTokenId(offerId, Number(start) + Number(amount)); + let endTokenId = deriveTokenId(offerId, Number(start) + Number(length)); + + // None of reserved but not preminted tokens should have an owner + for (let i = startTokenId; i < endTokenId; i = i + 1n) { + await expect(bosonVoucher.connect(rando).ownerOf(i)).to.be.revertedWith( + RevertReasons.ERC721_NON_EXISTENT + ); + } + }); + + it("Token was preminted, transferred and burned", async function () { + let exchangeId = "26"; + const tokenId = deriveTokenId(offerId, exchangeId); + + // Token owner should be the seller let tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, assistant.address, `Token owner mismatch ${tokenId.toString()}`); - } else if (i <= currentRangeEndId) { - // tokenId still in range, but not minted yet + assert.equal(tokenOwner, await assistant.getAddress(), "Token owner mismatch"); + + // Transfer preminted token + await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); + + // Token owner should be the buyer + tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await buyer.getAddress(), "Token owner mismatch"); + + // Simulate burn + await bosonVoucher.connect(protocol).burnVoucher(tokenId); + + // Token should have no owner await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( RevertReasons.ERC721_NON_EXISTENT ); - } else { - // tokenId outside the current range - // Change current range - if (rangeIndex < ranges.length) { - currentRange = ranges[++rangeIndex]; - currentRangeMintEndId = currentRange.start + currentRange.minted - 1; - currentRangeEndId = currentRange.start + currentRange.length - 1; - offerId = Number(offerId) + rangeIndex * 6; - } - // Technically, next range could be consecutive and next call should return seller's address - // But range construction in this test ensures gaps between ranges + }); + + it("Token was preminted, not transferred and burned", async function () { + let exchangeId = "26"; + const tokenId = deriveTokenId(offerId, exchangeId); + + // Token owner should be the seller + let tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await assistant.getAddress(), "Token owner mismatch"); + + await offerHandler.connect(assistant).voidOffer(offerId); + + // Burn preminted voucher + await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); + + // Token should have no owner await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( RevertReasons.ERC721_NON_EXISTENT ); - } - } + }); + }); }); + }); - it("Consecutive ranges", async function () { - // Make two consecutive ranges - let nextOfferId = Number(offerId) + 1; - let nextStartId = Number(start) + Number(length); - let nextLength = "10"; - let nextAmount = "5"; + context("Token transfers", function () { + const transferFunctions = { + "transferFrom()": { + selector: "transferFrom(address,address,uint256)", + }, + "safeTransferFrom()": { + selector: "safeTransferFrom(address,address,uint256)", + }, + "safeTransferFrom() with bytes": { + selector: "safeTransferFrom(address,address,uint256,bytes)", + additionalArgs: ["0x"], + }, + }; - // reserve length - await bosonVoucher.connect(protocol).reserveRange(nextOfferId, nextStartId, nextLength, assistant.address); + Object.keys(transferFunctions).forEach(function (transferFunction) { + context(transferFunction, function () { + let tokenId, offerId, buyerId; + let selector = transferFunctions[transferFunction].selector; + let additionalArgs = transferFunctions[transferFunction].additionalArgs ?? []; - // amount to premint - await bosonVoucher.connect(assistant).preMint(nextOfferId, nextAmount); - - // First range - preminted tokens - let startTokenId = deriveTokenId(offerId, start); - let endTokenId = startTokenId.add(amount); - for (let i = startTokenId; i.lt(endTokenId); i = i.add(1)) { - let tokenOwner = await bosonVoucher.ownerOf(i); - assert.equal(tokenOwner, assistant.address, `Token owner mismatch ${i.toString()}`); - } + context("Transfer of an actual voucher", async function () { + beforeEach(async function () { + exchangeId = offerId = "1"; + tokenId = deriveTokenId(offerId, exchangeId); - // First range - not preminted tokens - startTokenId = endTokenId; - let endExchangeId = Number(start) + Number(length); - endTokenId = deriveTokenId(offerId, endExchangeId); - for (let i = startTokenId; i.lt(endTokenId); i = i.add(1)) { - await expect(bosonVoucher.connect(rando).ownerOf(i)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); - } + // commit and create buyer account + await exchangeHandler.commitToOffer(await buyer.getAddress(), offerId, { value: offer.price }); + }); - // Second range - preminted tokens - startTokenId = deriveTokenId(nextOfferId, endExchangeId); - endTokenId = startTokenId.add(nextAmount); - for (let i = startTokenId; i.lt(endTokenId); i = i.add(1)) { - let tokenOwner = await bosonVoucher.ownerOf(i); - assert.equal(tokenOwner, assistant.address, `Token owner mismatch ${i.toString()}`); - } + it("Should emit a Transfer event", async function () { + await expect( + bosonVoucher + .connect(buyer) + [selector](await buyer.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ) + .to.emit(bosonVoucher, "Transfer") + .withArgs(await buyer.getAddress(), await rando.getAddress(), tokenId); + }); - // Second range - not preminted tokens - startTokenId = endTokenId; - endExchangeId += Number(nextLength); - endTokenId = deriveTokenId(nextOfferId, endExchangeId); - for (let i = startTokenId; i.lt(endTokenId); i = i.add(1)) { - await expect(bosonVoucher.connect(rando).ownerOf(i)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); - } - }); + it("Should update state", async function () { + // Before transfer, buyer should be the owner + let tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await buyer.getAddress(), "Buyer is not the owner"); - context("💔 Revert Reasons", async function () { - it("Token is outside any range and not minted", async function () { - let tokenId = "200000"; - await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( - RevertReasons.ERC721_NON_EXISTENT - ); - }); + await bosonVoucher + .connect(buyer) + [selector](await buyer.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs); - it("Token is inside a range, but not minted yet", async function () { - let startTokenId = deriveTokenId(offerId, Number(start) + Number(amount)); - let endTokenId = deriveTokenId(offerId, Number(start) + Number(length)); + // After transfer, rando should be the owner + tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await rando.getAddress(), "Rando is not the owner"); + }); - // None of reserved but not preminted tokens should have an owner - for (let i = startTokenId; i.lt(endTokenId); i = i.add(1)) { - await expect(bosonVoucher.connect(rando).ownerOf(i)).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); - } - }); + it("Should call onVoucherTransferred", async function () { + buyerId = 4n; + await expect( + bosonVoucher + .connect(buyer) + [selector](await buyer.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ) + .to.emit(exchangeHandler, "VoucherTransferred") + .withArgs(offerId, exchangeId, buyerId, await bosonVoucher.getAddress()); + }); - it("Token was preminted, transferred and burned", async function () { - let exchangeId = "26"; - const tokenId = deriveTokenId(offerId, exchangeId); + it("Transfer on behalf of should work normally", async function () { + // Approve another address to transfer the voucher + await bosonVoucher.connect(buyer).setApprovalForAll(await rando2.getAddress(), true); - // Mock exchange handler methods (easier and more efficient than creating a real offer) - const mockProtocol = await deployMockProtocol(); + await expect( + bosonVoucher + .connect(rando2) + [selector](await buyer.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ) + .to.emit(bosonVoucher, "Transfer") + .withArgs(await buyer.getAddress(), await rando.getAddress(), tokenId); + }); - // Define what should be returned when commitToPreMintedOffer is called - await mockProtocol.mock.commitToPreMintedOffer.returns(); + it("If seller is the true owner of voucher, transfer should work same as for others", async function () { + buyerId = 5n; + await bosonVoucher + .connect(buyer) + [selector](await buyer.getAddress(), await assistant.getAddress(), tokenId, ...additionalArgs); - // Token owner should be the seller - let tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, assistant.address, "Token owner mismatch"); + const tx = await bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs); - // Transfer preminted token - await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + await expect(tx) + .to.emit(bosonVoucher, "Transfer") + .withArgs(await assistant.getAddress(), await rando.getAddress(), tokenId); - // Token owner should be the buyer - tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, buyer.address, "Token owner mismatch"); + await expect(tx) + .to.emit(exchangeHandler, "VoucherTransferred") + .withArgs(offerId, exchangeId, buyerId, await bosonVoucher.getAddress()); + }); - // Simulate burn - await bosonVoucher.connect(protocol).burnVoucher(tokenId); + context("💔 Revert Reasons", async function () { + it("From does not own the voucher", async function () { + await expect( + bosonVoucher + .connect(rando) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ).to.be.revertedWith(RevertReasons.ERC721_CALLER_NOT_OWNER_OR_APPROVED); + }); + }); + }); - // Token should have no owner - await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( - RevertReasons.ERC721_NON_EXISTENT - ); - }); + context("Transfer of a preminted voucher when owner is assistant", async function () { + let voucherRedeemableFrom, voucherValid, offerValid; - it("Token was preminted, not transferred and burned", async function () { - let exchangeId = "26"; - const tokenId = deriveTokenId(offerId, exchangeId); + beforeEach(async function () { + exchangeId = offerId = "1"; + const amount = "5"; - // Token owner should be the seller - let tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, assistant.address, "Token owner mismatch"); - - // Void the offer - offer.voided = true; - await mockProtocol.mock.getOffer.returns( - true, - offer, - offerDates, - offerDurations, - disputeResolutionTerms, - offerFees - ); + buyerId = 3n; - // Burn preminted voucher - await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); + await offerHandler.connect(assistant).reserveRange(offerId, amount, await assistant.getAddress()); - // Token should have no owner - await expect(bosonVoucher.connect(rando).ownerOf(tokenId)).to.be.revertedWith( - RevertReasons.ERC721_NON_EXISTENT - ); - }); - }); - }); - }); + // amount to premint + await bosonVoucher.connect(assistant).preMint(offerId, amount); + tokenId = deriveTokenId(offerId, exchangeId); - context("Token transfers", function () { - let bosonVoucher; + voucherRedeemableFrom = offerDates.voucherRedeemableFrom; + voucherValid = offerDurations.voucherValid; + offerValid = offerDates.validUntil; + }); - afterEach(async function () { - // Reset the accountId iterator - accountId.next(true); - }); + it("Should emit a Transfer event", async function () { + await expect( + bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ) + .to.emit(bosonVoucher, "Transfer") + .withArgs(await assistant.getAddress(), await rando.getAddress(), tokenId); + }); - const transferFunctions = { - "transferFrom()": { - selector: "transferFrom(address,address,uint256)", - }, - "safeTransferFrom()": { - selector: "safeTransferFrom(address,address,uint256)", - }, - "safeTransferFrom() with bytes": { - selector: "safeTransferFrom(address,address,uint256,bytes)", - additionalArgs: ["0x"], - }, - }; + it("Should update state", async function () { + // Before transfer, seller should be the owner + let tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await assistant.getAddress(), "Seller is not the owner"); - beforeEach(async function () { - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + await bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs); - // Prepare the AuthToken and VoucherInitValues - emptyAuthToken = mockAuthToken(); - voucherInitValues = mockVoucherInitValues(); - await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); + // After transfer, rando should be the owner + tokenOwner = await bosonVoucher.ownerOf(tokenId); + assert.equal(tokenOwner, await rando.getAddress(), "Rando is not the owner"); + }); - agentId = "0"; // agent id is optional while creating an offer + it("Should call commitToPreMintedOffer", async function () { + const tx = await bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs); + + // Get the block timestamp of the confirmed tx + const blockNumber = tx.blockNumber; + const block = await provider.getBlock(blockNumber); + + // Prepare exchange and voucher for validation + const exchange = mockExchange({ id: exchangeId, offerId, buyerId, finalizedDate: "0" }); + const voucher = mockVoucher({ redeemedDate: "0" }); + + // Update the committed date in the expected exchange struct with the block timestamp of the tx + voucher.committedDate = block.timestamp; + + // Update the validUntilDate date in the expected exchange struct + voucher.validUntilDate = calculateVoucherExpiry(block, voucherRedeemableFrom, voucherValid); + + // First transfer should call commitToPreMintedOffer + await expect(tx) + .to.emit(exchangeHandler, "BuyerCommitted") + .withArgs( + offerId, + buyerId, + exchangeId, + exchange.toStruct(), + voucher.toStruct(), + await bosonVoucher.getAddress() + ); + }); - // Create a valid dispute resolver - disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, - clerkDR.address, - treasuryDR.address, - true - ); + it("Second transfer should behave as normal voucher transfer", async function () { + // First transfer should call commitToPreMintedOffer, and not onVoucherTransferred + let tx = await bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs); + await expect(tx).to.emit(exchangeHandler, "BuyerCommitted"); + await expect(tx).to.not.emit(exchangeHandler, "VoucherTransferred"); + + // Second transfer should call onVoucherTransferred, and not commitToPreMintedOffer + tx = await bosonVoucher + .connect(rando) + [selector](await rando.getAddress(), await assistant.getAddress(), tokenId, ...additionalArgs); + await expect(tx).to.emit(exchangeHandler, "VoucherTransferred"); + await expect(tx).to.not.emit(exchangeHandler, "BuyerCommitted"); + + // Next transfer should call onVoucherTransferred, and not commitToPreMintedOffer, even if seller is the owner + tx = await bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs); + await expect(tx).to.emit(exchangeHandler, "VoucherTransferred"); + await expect(tx).to.not.emit(exchangeHandler, "BuyerCommitted"); + }); - // Create DisputeResolverFee array so offer creation will succeed - disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")]; - const sellerAllowList = []; + it("Transfer on behalf of should work normally", async function () { + // Approve another address to transfer the voucher + await bosonVoucher.connect(assistant).setApprovalForAll(await rando2.getAddress(), true); - // Register the dispute resolver - await accountHandler - .connect(adminDR) - .createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList); - }); + await expect( + bosonVoucher + .connect(rando2) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ) + .to.emit(bosonVoucher, "Transfer") + .withArgs(await assistant.getAddress(), await rando.getAddress(), tokenId); + }); - Object.keys(transferFunctions).forEach(function (transferFunction) { - context(transferFunction, function () { - let tokenId, offerId; - let selector = transferFunctions[transferFunction].selector; - let additionalArgs = transferFunctions[transferFunction].additionalArgs ?? []; + context("💔 Revert Reasons", async function () { + it("Cannot transfer preminted voucher twice", async function () { + // Make first transfer + await bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await buyer.getAddress(), tokenId, ...additionalArgs); + + // Second transfer should fail, since voucher has an owner + await expect( + bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ).to.be.revertedWith(RevertReasons.ERC721_CALLER_NOT_OWNER_OR_APPROVED); + }); - context("Transfer of an actual voucher", async function () { - beforeEach(async function () { - // Create an offer - const { offer, offerDates, offerDurations, disputeResolverId } = await mockOffer(); - await offerHandler - .connect(assistant) - .createOffer( - offer.toStruct(), - offerDates.toStruct(), - offerDurations.toStruct(), - disputeResolverId, - agentId - ); - await fundsHandler - .connect(admin) - .depositFunds(seller.id, ethers.constants.AddressZero, offer.sellerDeposit, { - value: offer.sellerDeposit, + it("Transfer preminted voucher, which was committed and burned already", async function () { + await bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await buyer.getAddress(), tokenId, ...additionalArgs); + + // Redeem voucher, effectively burning it + await setNextBlockTimestamp(Number(voucherRedeemableFrom)); + await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); + + // Transfer should fail, since voucher has been burned + await expect( + bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); }); - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id, { value: offer.price }); - exchangeId = offerId = "1"; - tokenId = deriveTokenId(offerId, exchangeId); - mockBuyer(); // call it just so accountId is correct + it("Transfer preminted voucher, which was not committed but burned already", async function () { + // Void offer + await offerHandler.connect(assistant).voidOffer(offerId); - // Update boson voucher address to actual seller's voucher - const voucherAddress = calculateContractAddress(accountHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherAddress); - }); + // Burn preminted vouchers + await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); - it("Should emit a Transfer event", async function () { - await expect( - bosonVoucher.connect(buyer)[selector](buyer.address, rando.address, tokenId, ...additionalArgs) - ) - .to.emit(bosonVoucher, "Transfer") - .withArgs(buyer.address, rando.address, tokenId); - }); + // None of reserved but not preminted tokens should have an owner + await expect( + bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); + }); - it("Should update state", async function () { - // Before transfer, buyer should be the owner - let tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, buyer.address, "Buyer is not the owner"); + it("Transfer preminted voucher, where offer was voided", async function () { + // Void offer + await offerHandler.connect(assistant).voidOffer(offerId); - await bosonVoucher.connect(buyer)[selector](buyer.address, rando.address, tokenId, ...additionalArgs); + // Transfer should fail, since protocol reverts + await expect( + bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ).to.be.revertedWith(RevertReasons.OFFER_HAS_BEEN_VOIDED); + }); - // After transfer, rando should be the owner - tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, rando.address, "Rando is not the owner"); - }); + it("Transfer preminted voucher, where offer has expired", async function () { + // Skip past offer expiry + await setNextBlockTimestamp(Number(offerValid)); - it("Should call onVoucherTransferred", async function () { - const randoBuyer = mockBuyer(); - await expect( - bosonVoucher.connect(buyer)[selector](buyer.address, rando.address, tokenId, ...additionalArgs) - ) - .to.emit(exchangeHandler, "VoucherTransferred") - .withArgs(offerId, exchangeId, randoBuyer.id, bosonVoucher.address); + // Transfer should fail, since protocol reverts + await expect( + bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ).to.be.revertedWith(RevertReasons.OFFER_HAS_EXPIRED); + }); + + it("Transfer preminted voucher, but from is not the voucher owner", async function () { + await bosonVoucher + .connect(assistant) + [selector](await assistant.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs); + + // next token id. Make sure that assistant is the owner + tokenId = tokenId + 1n; + let tokenOwner = await bosonVoucher.ownerOf(tokenId.toString()); + assert.equal(tokenOwner, await assistant.getAddress(), "Seller is not the owner"); + + // Following call should fail, since rando is not the owner of preminted voucher + await expect( + bosonVoucher + .connect(rando) + [selector](await rando.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs) + ).to.be.revertedWith(RevertReasons.NO_SILENT_MINT_ALLOWED); + }); + }); }); - it("Transfer on behalf of should work normally", async function () { - // Approve another address to transfer the voucher - await bosonVoucher.connect(buyer).setApprovalForAll(rando2.address, true); + context("Transfer of a preminted voucher when owner is contract", async function () { + beforeEach(async function () { + exchangeId = offerId = "1"; - await expect( - bosonVoucher.connect(rando2)[selector](buyer.address, rando.address, tokenId, ...additionalArgs) - ) - .to.emit(bosonVoucher, "Transfer") - .withArgs(buyer.address, rando.address, tokenId); - }); + tokenId = deriveTokenId(offerId, exchangeId); + const amount = "5"; - it("If seller is the true owner of voucher, transfer should work same as for others", async function () { - mockBuyer(); // Call to properly update nextAccountId - await bosonVoucher.connect(buyer)[selector](buyer.address, assistant.address, tokenId, ...additionalArgs); + buyerId = 3n; - const tx = await bosonVoucher - .connect(assistant) - [selector](assistant.address, rando.address, tokenId, ...additionalArgs); + await offerHandler.connect(assistant).reserveRange(offerId, amount, await bosonVoucher.getAddress()); - await expect(tx).to.emit(bosonVoucher, "Transfer").withArgs(assistant.address, rando.address, tokenId); + // amount to premint + await bosonVoucher.connect(assistant).preMint(offerId, amount); + }); - const randoBuyer = mockBuyer(); + it("If voucher contract is the owner of voucher, transfer on behalf of should work normally", async function () { + // Approve another address to transfer the voucher + await bosonVoucher.connect(assistant).setApprovalForAllToContract(await rando2.getAddress(), true); - await expect(tx) - .to.emit(exchangeHandler, "VoucherTransferred") - .withArgs(offerId, exchangeId, randoBuyer.id, bosonVoucher.address); - }); + const tx = await bosonVoucher + .connect(rando2) + [selector](await bosonVoucher.getAddress(), await rando.getAddress(), tokenId, ...additionalArgs); - context("💔 Revert Reasons", async function () { - it("From does not own the voucher", async function () { - await expect( - bosonVoucher.connect(rando)[selector](assistant.address, rando.address, tokenId, ...additionalArgs) - ).to.be.revertedWith(RevertReasons.ERC721_CALLER_NOT_OWNER_OR_APPROVED); + await expect(tx) + .to.emit(bosonVoucher, "Transfer") + .withArgs(await bosonVoucher.getAddress(), await rando.getAddress(), tokenId); }); }); }); + }); + }); - context("Transfer of a preminted voucher when owner is assistant", async function () { - let voucherRedeemableFrom, voucherValid, offerValid; - beforeEach(async function () { - // Create preminted offer - const { offer, offerDates, offerDurations, disputeResolverId } = await mockOffer(); - offer.quantityAvailable = "2"; - await offerHandler - .connect(assistant) - .createOffer( - offer.toStruct(), - offerDates.toStruct(), - offerDurations.toStruct(), - disputeResolverId, - agentId - ); + context("tokenURI", function () { + let metadataUri, offerId; - // Reserve range to assistant - await offerHandler.connect(assistant).reserveRange(offer.id, offer.quantityAvailable, assistant.address); - // Pool needs to cover both seller deposit and price - const pool = ethers.BigNumber.from(offer.sellerDeposit).add(offer.price); - await fundsHandler.connect(admin).depositFunds(seller.id, ethers.constants.AddressZero, pool, { - value: pool, - }); + beforeEach(async function () { + offerId = "1"; + metadataUri = offer.metadataUri; + }); - // Store correct values - voucherRedeemableFrom = offerDates.voucherRedeemableFrom; - voucherValid = offerDurations.voucherValid; - offerValid = offerDates.validUntil; - exchangeId = offerId = "1"; - tokenId = deriveTokenId(offerId, exchangeId); + it("should return the correct tokenURI", async function () { + const buyerAddress = await buyer.getAddress(); - // Update boson voucher address to actual seller's voucher - const voucherAddress = calculateContractAddress(accountHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherAddress); + await exchangeHandler.connect(buyer).commitToOffer(buyerAddress, offerId, { value: offer.price }); - // amount to premint - await bosonVoucher.connect(assistant).preMint(offerId, offer.quantityAvailable); - }); + const tokenId = deriveTokenId(offerId, 1); + const tokenURI = await bosonVoucher.tokenURI(tokenId); + expect(tokenURI).eq(metadataUri); + }); - it("Should emit a Transfer event", async function () { - await expect( - bosonVoucher.connect(assistant)[selector](assistant.address, rando.address, tokenId, ...additionalArgs) - ) - .to.emit(bosonVoucher, "Transfer") - .withArgs(assistant.address, rando.address, tokenId); - }); + it("should return empty tokenURI if token does not exist", async function () { + const tokenURI = await bosonVoucher.tokenURI(10); + expect(tokenURI).eq(""); + }); - it("Should update state", async function () { - // Before transfer, seller should be the owner - let tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, assistant.address, "Seller is not the owner"); + context("pre-minted", async function () { + let start, tokenId; + beforeEach(async function () { + // reserve a range + start = "10"; + const length = "1"; + await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, await assistant.getAddress()); - await bosonVoucher - .connect(assistant) - [selector](assistant.address, rando.address, tokenId, ...additionalArgs); + // premint + await bosonVoucher.connect(assistant).preMint(offerId, 1); - // After transfer, rando should be the owner - tokenOwner = await bosonVoucher.ownerOf(tokenId); - assert.equal(tokenOwner, rando.address, "Rando is not the owner"); - }); + tokenId = deriveTokenId(offerId, start); + }); - it("Should call commitToPreMintedOffer", async function () { - const randoBuyer = mockBuyer(); - const tx = await bosonVoucher - .connect(assistant) - [selector](assistant.address, rando.address, tokenId, ...additionalArgs); + it("should return the correct tokenURI", async function () { + const tokenURI = await bosonVoucher.tokenURI(tokenId); + expect(tokenURI).eq(metadataUri); + }); + + it("should return correct tokenURI when token is preminted and transferred", async function () { + await bosonVoucher + .connect(assistant) + .transferFrom(await assistant.getAddress(), await buyer.getAddress(), tokenId); + + const tokenURI = await bosonVoucher.tokenURI(tokenId); + expect(tokenURI).eq(metadataUri); + }); + }); + }); - // Get the block timestamp of the confirmed tx - const blockNumber = tx.blockNumber; - const block = await ethers.provider.getBlock(blockNumber); + context("EIP2981 NFT Royalty fee", function () { + let offerId; + beforeEach(async function () { + offerId = "1"; + exchangeId = "1"; + offerPrice = offer.price; - // Prepare exchange and voucher for validation - const exchange = mockExchange({ id: exchangeId, offerId, buyerId: randoBuyer.id, finalizedDate: "0" }); - const voucher = mockVoucher({ redeemedDate: "0" }); + await exchangeHandler.connect(buyer).commitToOffer(await buyer.getAddress(), offerId, { value: offer.price }); + }); - // Update the committed date in the expected exchange struct with the block timestamp of the tx - voucher.committedDate = block.timestamp.toString(); - // Update the validUntilDate date in the expected exchange struct - voucher.validUntilDate = calculateVoucherExpiry(block, voucherRedeemableFrom, voucherValid); - // First transfer should call commitToPreMintedOffer - await expect(tx) - .to.emit(exchangeHandler, "BuyerCommitted") - .withArgs( - offerId, - randoBuyer.id, - exchangeId, - exchange.toStruct(), - voucher.toStruct(), - bosonVoucher.address - ); - }); + context("setRoyaltyPercentage()", function () { + beforeEach(async function () { + // give ownership to assistant + await bosonVoucher.connect(protocol).transferOwnership(await assistant.getAddress()); + }); - it("Second transfer should behave as normal voucher transfer", async function () { - // First transfer should call commitToPreMintedOffer, and not onVoucherTransferred - let tx = await bosonVoucher - .connect(assistant) - [selector](assistant.address, rando.address, tokenId, ...additionalArgs); - await expect(tx).to.emit(exchangeHandler, "BuyerCommitted"); - await expect(tx).to.not.emit(exchangeHandler, "VoucherTransferred"); - - // Second transfer should call onVoucherTransferred, and not commitToPreMintedOffer - tx = await bosonVoucher - .connect(rando) - [selector](rando.address, assistant.address, tokenId, ...additionalArgs); - await expect(tx).to.emit(exchangeHandler, "VoucherTransferred"); - await expect(tx).to.not.emit(exchangeHandler, "BuyerCommitted"); - - // Next transfer should call onVoucherTransferred, and not commitToPreMintedOffer, even if seller is the owner - tx = await bosonVoucher - .connect(assistant) - [selector](assistant.address, rando.address, tokenId, ...additionalArgs); - await expect(tx).to.emit(exchangeHandler, "VoucherTransferred"); - await expect(tx).to.not.emit(exchangeHandler, "BuyerCommitted"); - }); + it("should emit RoyaltyPercentageChanged event", async function () { + royaltyPercentage = "0"; //0% + await expect(bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage)) + .to.emit(bosonVoucher, "RoyaltyPercentageChanged") + .withArgs(royaltyPercentage); + }); - it("Transfer on behalf of should work normally", async function () { - // Approve another address to transfer the voucher - await bosonVoucher.connect(assistant).setApprovalForAll(rando2.address, true); + it("should set a royalty fee percentage", async function () { + // First, set royalty fee as 0 + royaltyPercentage = "0"; //0% + await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - await expect( - bosonVoucher.connect(rando2)[selector](assistant.address, rando.address, tokenId, ...additionalArgs) - ) - .to.emit(bosonVoucher, "Transfer") - .withArgs(assistant.address, rando.address, tokenId); - }); + let receiver, royaltyAmount; + [receiver, royaltyAmount] = await bosonVoucher.connect(rando).royaltyInfo(exchangeId, offerPrice); - context("💔 Revert Reasons", async function () { - it("Cannot transfer preminted voucher twice", async function () { - // Make first transfer - await bosonVoucher - .connect(assistant) - [selector](assistant.address, buyer.address, tokenId, ...additionalArgs); + // Expectations + let expectedRecipient = seller.treasury; + let expectedRoyaltyAmount = "0"; - // Second transfer should fail, since voucher has an owner - await expect( - bosonVoucher.connect(assistant)[selector](assistant.address, rando.address, tokenId, ...additionalArgs) - ).to.be.revertedWith(RevertReasons.ERC721_CALLER_NOT_OWNER_OR_APPROVED); - }); + assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); + assert.equal(royaltyAmount.toString(), expectedRoyaltyAmount, "Royalty amount is incorrect"); - it("Transfer preminted voucher, which was committed and burned already", async function () { - await bosonVoucher - .connect(assistant) - [selector](assistant.address, buyer.address, tokenId, ...additionalArgs); + // Now, set royalty fee as 10% + royaltyPercentage = "1000"; //10% + await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - // Redeem voucher, effectively burning it - await setNextBlockTimestamp(ethers.BigNumber.from(voucherRedeemableFrom).toHexString()); - await exchangeHandler.connect(buyer).redeemVoucher(exchangeId); + [receiver, royaltyAmount] = await bosonVoucher.connect(rando).royaltyInfo(exchangeId, offerPrice); - // Transfer should fail, since voucher has been burned - await expect( - bosonVoucher.connect(assistant)[selector](assistant.address, rando.address, tokenId, ...additionalArgs) - ).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); - }); + // Expectations + expectedRecipient = seller.treasury; + expectedRoyaltyAmount = applyPercentage(offerPrice, royaltyPercentage); - it("Transfer preminted voucher, which was not committed but burned already", async function () { - // Void offer - await offerHandler.connect(assistant).voidOffer(offerId); + assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); + assert.equal(royaltyAmount.toString(), expectedRoyaltyAmount, "Royalty amount is incorrect"); + }); - // Burn preminted vouchers - await bosonVoucher.connect(assistant).burnPremintedVouchers(offerId); + context("💔 Revert Reasons", async function () { + it("should revert if caller is not the owner", async function () { + // random caller + await expect(bosonVoucher.connect(rando).setRoyaltyPercentage(royaltyPercentage)).to.be.revertedWith( + RevertReasons.OWNABLE_NOT_OWNER + ); - // None of reserved but not preminted tokens should have an owner - await expect( - bosonVoucher.connect(assistant)[selector](assistant.address, rando.address, tokenId, ...additionalArgs) - ).to.be.revertedWith(RevertReasons.ERC721_NON_EXISTENT); - }); + // protocol as the caller + await expect(bosonVoucher.connect(protocol).setRoyaltyPercentage(royaltyPercentage)).to.be.revertedWith( + RevertReasons.OWNABLE_NOT_OWNER + ); + }); + + it("should revert if royaltyPercentage is greater than max royalty percentage defined in the protocol", async function () { + // Set royalty fee as 15% (protocol limit is 10%) + royaltyPercentage = "1500"; //15% + + // royalty percentage too high, expectig revert + await expect(bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage)).to.be.revertedWith( + RevertReasons.ROYALTY_FEE_INVALID + ); + }); + }); + }); + + context("getRoyaltyPercentage()", function () { + it("should return the royalty fee percentage", async function () { + // give ownership to assistant + await bosonVoucher.connect(protocol).transferOwnership(await assistant.getAddress()); + + royaltyPercentage = "1000"; //10% + await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); + + expect(await bosonVoucher.connect(rando).getRoyaltyPercentage()).to.equal( + royaltyPercentage, + "Invalid royalty percentage" + ); + }); + }); + + context("royaltyInfo()", function () { + beforeEach(async function () { + // give ownership to assistant + await bosonVoucher.connect(protocol).transferOwnership(await assistant.getAddress()); + }); - it("Transfer preminted voucher, where offer was voided", async function () { - // Void offer - await offerHandler.connect(assistant).voidOffer(offerId); + it("should return a recipient and royalty fee", async function () { + // First, set royalty fee as 0 + royaltyPercentage = "0"; //0% + await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - // Transfer should fail, since protocol reverts - await expect( - bosonVoucher.connect(assistant)[selector](assistant.address, rando.address, tokenId, ...additionalArgs) - ).to.be.revertedWith(RevertReasons.OFFER_HAS_BEEN_VOIDED); - }); + let receiver, royaltyAmount; + [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); - it("Transfer preminted voucher, where offer has expired", async function () { - // Skip past offer expiry - await setNextBlockTimestamp(ethers.BigNumber.from(offerValid).toHexString()); + // Expectations + let expectedRecipient = seller.treasury; + let expectedRoyaltyAmount = "0"; - // Transfer should fail, since protocol reverts - await expect( - bosonVoucher.connect(assistant)[selector](assistant.address, rando.address, tokenId, ...additionalArgs) - ).to.be.revertedWith(RevertReasons.OFFER_HAS_EXPIRED); - }); + assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); + assert.equal(royaltyAmount.toString(), expectedRoyaltyAmount, "Royalty amount is incorrect"); - it("Transfer preminted voucher, but from is not the voucher owner", async function () { - await bosonVoucher - .connect(assistant) - [selector](assistant.address, rando.address, tokenId, ...additionalArgs); + // Now, set royalty fee as 10% + royaltyPercentage = "1000"; //10% + await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - // next token id. Make sure that assistant is the owner - tokenId = tokenId.add(1); - let tokenOwner = await bosonVoucher.ownerOf(tokenId.toString()); - assert.equal(tokenOwner, assistant.address, "Seller is not the owner"); + [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); - // Following call should fail, since rando is not the owner of preminted voucher - await expect( - bosonVoucher.connect(rando)[selector](rando.address, rando.address, tokenId, ...additionalArgs) - ).to.be.revertedWith(RevertReasons.NO_SILENT_MINT_ALLOWED); - }); - }); - }); + // Expectations + expectedRecipient = seller.treasury; + expectedRoyaltyAmount = applyPercentage(offerPrice, royaltyPercentage); - context("Transfer of a preminted voucher when owner is contract", async function () { - beforeEach(async function () { - // Create preminted offer - const { offer, offerDates, offerDurations, disputeResolverId } = await mockOffer(); - offer.quantityAvailable = "2"; + assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); + assert.equal(royaltyAmount.toString(), expectedRoyaltyAmount, "Royalty amount is incorrect"); - await offerHandler - .connect(assistant) - .createOffer( - offer.toStruct(), - offerDates.toStruct(), - offerDurations.toStruct(), - disputeResolverId, - agentId - ); + // Any random address can check the royalty info + // Now, set royalty fee as 8% + royaltyPercentage = "800"; //8% + await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - // Update boson voucher address to actual seller's voucher - const voucherAddress = calculateContractAddress(accountHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherAddress); + [receiver, royaltyAmount] = await bosonVoucher.connect(rando).royaltyInfo(exchangeId, offerPrice); - // Reserve range to contract - await offerHandler.connect(assistant).reserveRange(offer.id, offer.quantityAvailable, bosonVoucher.address); + // Expectations + expectedRecipient = seller.treasury; + expectedRoyaltyAmount = applyPercentage(offerPrice, royaltyPercentage); - // Pool needs to cover both seller deposit and price - const pool = ethers.BigNumber.from(offer.sellerDeposit).add(offer.price); - await fundsHandler.connect(admin).depositFunds(seller.id, ethers.constants.AddressZero, pool, { - value: pool, - }); + assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); + assert.equal(royaltyAmount.toString(), expectedRoyaltyAmount, "Royalty amount is incorrect"); + }); - // Store correct values - exchangeId = offerId = "1"; - tokenId = deriveTokenId(offerId, exchangeId); + it("if exchange doesn't exist it should return 0 values", async function () { + // Set royalty fee as 10% + royaltyPercentage = "1000"; //10% + await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - // amount to premint - await bosonVoucher.connect(assistant).preMint(offerId, offer.quantityAvailable); - }); + // Set inexistent exchangeId + exchangeId = "100000"; + const [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); - it("If voucher contract is the owner of voucher, transfer on behalf of should work normally", async function () { - // Approve another address to transfer the voucher - await bosonVoucher.connect(assistant).setApprovalForAllToContract(rando2.address, true); + // Receiver and amount should be 0 + assert.equal(receiver, ZeroAddress, "Recipient address is incorrect"); + assert.equal(royaltyAmount, 0n, "Royalty amount is incorrect"); + }); + }); - const tx = await bosonVoucher - .connect(rando2) - [selector](bosonVoucher.address, rando.address, tokenId, ...additionalArgs); + context("💔 Revert Reasons", async function () { + it("should revert during create seller if royaltyPercentage is greater than max royalty percentage defined in the protocol", async function () { + // create invalid voucherInitValues + royaltyPercentage = "2000"; // 20% + voucherInitValues = new VoucherInitValues("ContractURI", royaltyPercentage); + + // create another seller + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + ZeroAddress, + await rando.getAddress() + ); - await expect(tx).to.emit(bosonVoucher, "Transfer").withArgs(bosonVoucher.address, rando.address, tokenId); - }); + // royalty percentage too high, expectig revert + await expect( + accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues) + ).to.be.revertedWith(RevertReasons.ROYALTY_FEE_INVALID); }); }); }); - }); - - context("burnVoucher()", function () { - after(async function () { - // Reset the accountId iterator - accountId.next(true); - }); - - it("should burn a voucher with success", async function () { - const buyerStruct = mockBuyer(buyer.address).toStruct(); - const buyerWallet = buyerStruct[1]; - await bosonVoucher.connect(protocol).issueVoucher(0, buyerWallet); - - const balanceBefore = await bosonVoucher.balanceOf(buyer.address); + context("withdrawToProtocol", function () { + it("Can withdraw native token", async function () { + const sellersFundsBefore = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - await bosonVoucher.connect(protocol).burnVoucher(0); - - const balanceAfter = await bosonVoucher.balanceOf(buyer.address); + const amount = parseUnits("1", "ether"); + await admin.sendTransaction({ to: await bosonVoucher.getAddress(), value: amount }); - expect(balanceBefore.sub(balanceAfter)).eq(1); - }); + await expect(() => bosonVoucher.connect(rando).withdrawToProtocol([ZeroAddress])).to.changeEtherBalances( + [bosonVoucher, fundsHandler], + [amount * -1n, amount] + ); - it("should revert if caller does not have PROTOCOL role", async function () { - // Expect revert if random user attempts to burn voucher - await expect(bosonVoucher.connect(rando).burnVoucher(0)).to.be.revertedWith(RevertReasons.ACCESS_DENIED); + const { availableAmount } = sellersFundsBefore.funds.find((fund) => fund.tokenAddress == ZeroAddress); - // Grant PROTOCOL role to random user address - await accessController.grantRole(Role.PROTOCOL, rando.address); + // Seller's available balance should increase + const expectedAvailableFunds = new FundsList([ + new Funds(ZeroAddress, "Native currency", (BigInt(availableAmount) + BigInt(amount)).toString()), + ]); - // Prepare to burn voucher as a random user - const buyerStruct = mockBuyer(buyer.address).toStruct(); - const buyerWallet = buyerStruct[1]; - await bosonVoucher.connect(protocol).issueVoucher(0, buyerWallet); - const balanceBefore = await bosonVoucher.balanceOf(buyer.address); + const sellerFundsAfter = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - //Attempt to burn voucher as a random user - await bosonVoucher.connect(protocol).burnVoucher(0); - const balanceAfter = await bosonVoucher.balanceOf(buyer.address); + expect(sellerFundsAfter).to.eql(expectedAvailableFunds); + }); - expect(balanceBefore.sub(balanceAfter)).eq(1); - }); - }); + it("Can withdraw ERC20", async function () { + const amount = parseUnits("1", "ether"); + await foreign20.connect(deployer).mint(await deployer.getAddress(), amount); + await foreign20.connect(deployer).transfer(await bosonVoucher.getAddress(), amount); - context("tokenURI", function () { - let metadataUri, offerId, offerPrice; - let bosonVoucher; + const foreign20Address = await foreign20.getAddress(); + await expect(() => bosonVoucher.connect(rando).withdrawToProtocol([foreign20Address])).to.changeTokenBalances( + foreign20, + [bosonVoucher, fundsHandler], + [amount * -1n, amount] + ); - beforeEach(async function () { - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); + // Seller's available balance should increase + const expectedAvailableFunds = new Funds(await foreign20.getAddress(), "Foreign20", amount.toString()); - // prepare the VoucherInitValues - voucherInitValues = mockVoucherInitValues(); - expect(voucherInitValues.isValid()).is.true; + // first item is AddressZero + const [, sellerFundsAfter] = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)).funds; + expect(sellerFundsAfter).to.eql(expectedAvailableFunds); + }); - // AuthToken - emptyAuthToken = mockAuthToken(); - expect(emptyAuthToken.isValid()).is.true; + it("Should withdraw all tokens when list length > 1", async function () { + const { funds: sellerFundsBefore } = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); + sellerFundsBefore[1] = new Funds(await foreign20.getAddress(), "Foreign20", "0"); - agentId = "0"; // agent id is optional while creating an offer + const amount = parseUnits("1", "ether"); + await admin.sendTransaction({ to: await bosonVoucher.getAddress(), value: amount }); + await foreign20.connect(deployer).mint(await deployer.getAddress(), amount); + await foreign20.connect(deployer).transfer(await bosonVoucher.getAddress(), amount); - // Create a valid dispute resolver - disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, - clerkDR.address, - treasuryDR.address, - true - ); - expect(disputeResolver.isValid()).is.true; + const foreign20Address = await foreign20.getAddress(); + let tx; + await expect(() => { + tx = bosonVoucher.connect(rando).withdrawToProtocol([ZeroAddress, foreign20Address]); + return tx; + }).to.changeTokenBalances(foreign20, [bosonVoucher, fundsHandler], [amount * -1n, amount]); + await expect(() => tx).to.changeEtherBalances([bosonVoucher, fundsHandler], [amount * -1n, amount]); - //Create DisputeResolverFee array so offer creation will succeed - disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")]; + const { funds: sellerFundsAfter } = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - // Make empty seller list, so every seller is allowed - const sellerAllowList = []; + expect( + sellerFundsBefore.map((f) => { + return { ...f, availableAmount: (BigInt(f.availableAmount) + amount).toString() }; + }) + ).to.eql(sellerFundsAfter); + }); + }); - // Register the dispute resolver - await accountHandler - .connect(adminDR) - .createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList); + context("getSellerId()", function () { + it("should return the seller id", async function () { + await bosonVoucher.connect(protocol).transferOwnership(await assistant.getAddress()); - const { offer, offerDates, offerDurations, disputeResolverId } = await mockOffer(); - offerId = offer.id; - offerPrice = offer.price; + expect(await bosonVoucher.connect(rando).getSellerId()).to.equal(seller.id, "Invalid seller id returned"); - await offerHandler - .connect(assistant) - .createOffer(offer.toStruct(), offerDates.toStruct(), offerDurations.toStruct(), disputeResolverId, agentId); + // Reset the accountId iterator + accountId.next(true); + }); - const pool = ethers.BigNumber.from(offer.sellerDeposit).add(offer.price); + it("should return 0 if the seller doesn't exist", async function () { + await bosonVoucher.connect(protocol).transferOwnership(await rando.getAddress()); + expect(await bosonVoucher.getSellerId()).to.equal(0, "Invalid seller id returned"); + }); + }); + }); - await fundsHandler.connect(admin).depositFunds(seller.id, ethers.constants.AddressZero, pool, { value: pool }); + context("burnVoucher()", function () { + it("should burn a voucher with success", async function () { + const buyerStruct = mockBuyer(await buyer.getAddress()).toStruct(); + const buyerWallet = buyerStruct[1]; - metadataUri = offer.metadataUri; + await bosonVoucher.connect(protocol).issueVoucher(0, buyerWallet); - // Update boson voucher address to actual seller's voucher - const voucherAddress = calculateContractAddress(accountHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherAddress); - }); + const balanceBefore = await bosonVoucher.balanceOf(await buyer.getAddress()); - afterEach(async function () { - // Reset the accountId iterator - accountId.next(true); - }); + await bosonVoucher.connect(protocol).burnVoucher(0); - it("should return the correct tokenURI", async function () { - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offerId, { value: offerPrice }); - const tokenId = deriveTokenId(offerId, 1); - const tokenURI = await bosonVoucher.tokenURI(tokenId); - expect(tokenURI).eq(metadataUri); - }); + const balanceAfter = await bosonVoucher.balanceOf(await buyer.getAddress()); - it("should return empty tokenURI if token does not exist", async function () { - const tokenURI = await bosonVoucher.tokenURI(10); - expect(tokenURI).eq(""); + expect(balanceBefore - balanceAfter).eq(1); }); - context("pre-minted", async function () { - let start, tokenId; - beforeEach(async function () { - // reserve a range - start = "10"; - const length = "1"; - await bosonVoucher.connect(protocol).reserveRange(offerId, start, length, assistant.address); - - // premint - await bosonVoucher.connect(assistant).preMint(offerId, 1); + it("should revert if caller does not have PROTOCOL role", async function () { + // Expect revert if random user attempts to burn voucher + await expect(bosonVoucher.connect(rando).burnVoucher(0)).to.be.revertedWith(RevertReasons.ACCESS_DENIED); - tokenId = deriveTokenId(offerId, start); - }); + // Grant PROTOCOL role to random user address + await accessController.grantRole(Role.PROTOCOL, await rando.getAddress()); - it("should return the correct tokenURI", async function () { - const tokenURI = await bosonVoucher.tokenURI(tokenId); - expect(tokenURI).eq(metadataUri); - }); + // Prepare to burn voucher as a random user + const buyerStruct = mockBuyer(await buyer.getAddress()).toStruct(); + const buyerWallet = buyerStruct[1]; + await bosonVoucher.connect(protocol).issueVoucher(0, buyerWallet); + const balanceBefore = await bosonVoucher.balanceOf(await buyer.getAddress()); - it("should return correct tokenURI when token is preminted and transferred", async function () { - await bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.address, tokenId); + //Attempt to burn voucher as a random user + await bosonVoucher.connect(protocol).burnVoucher(0); + const balanceAfter = await bosonVoucher.balanceOf(await buyer.getAddress()); - const tokenURI = await bosonVoucher.tokenURI(tokenId); - expect(tokenURI).eq(metadataUri); - }); + expect(balanceBefore - balanceAfter).eq(1); }); }); context("transferOwnership()", function () { it("should emit OwnershipTransferred", async function () { - const ownable = await ethers.getContractAt("OwnableUpgradeable", bosonVoucher.address); - await expect(bosonVoucher.connect(protocol).transferOwnership(rando.address)) + const ownable = await getContractAt("OwnableUpgradeable", await bosonVoucher.getAddress()); + await expect(bosonVoucher.connect(protocol).transferOwnership(await rando.getAddress())) .to.emit(ownable, "OwnershipTransferred") - .withArgs(assistant.address, rando.address); + .withArgs(await assistant.getAddress(), await rando.getAddress()); }); it("should transfer ownership with success", async function () { - await bosonVoucher.connect(protocol).transferOwnership(assistant.address); + await bosonVoucher.connect(protocol).transferOwnership(await assistant.getAddress()); - const ownable = await ethers.getContractAt("OwnableUpgradeable", bosonVoucher.address); + const ownable = await getContractAt("OwnableUpgradeable", await bosonVoucher.getAddress()); const owner = await ownable.owner(); - expect(owner).eq(assistant.address, "Wrong owner"); + expect(owner).eq(await assistant.getAddress(), "Wrong owner"); }); context("💔 Revert Reasons", async function () { it("should revert if caller does not have PROTOCOL role", async function () { - await expect(bosonVoucher.connect(rando).transferOwnership(assistant.address)).to.be.revertedWith( + await expect(bosonVoucher.connect(rando).transferOwnership(await assistant.getAddress())).to.be.revertedWith( RevertReasons.ACCESS_DENIED ); }); it("Even the current owner cannot transfer the ownership", async function () { // successfully transfer to assistant - await bosonVoucher.connect(protocol).transferOwnership(assistant.address); + await bosonVoucher.connect(protocol).transferOwnership(await assistant.getAddress()); // owner tries to transfer, it should fail - await expect(bosonVoucher.connect(assistant).transferOwnership(rando.address)).to.be.revertedWith( + await expect(bosonVoucher.connect(assistant).transferOwnership(await rando.getAddress())).to.be.revertedWith( RevertReasons.ACCESS_DENIED ); }); it("Current owner cannot renounce the ownership", async function () { // successfully transfer to assistant - await bosonVoucher.connect(protocol).transferOwnership(assistant.address); + await bosonVoucher.connect(protocol).transferOwnership(await assistant.getAddress()); - const ownable = await ethers.getContractAt("OwnableUpgradeable", bosonVoucher.address); + const ownable = await getContractAt("OwnableUpgradeable", await bosonVoucher.getAddress()); // owner tries to renounce ownership, it should fail await expect(ownable.connect(assistant).renounceOwnership()).to.be.revertedWith(RevertReasons.ACCESS_DENIED); @@ -2016,7 +1996,7 @@ describe("IBosonVoucher", function () { it("Transferring ownership to 0 is not allowed", async function () { // try to transfer ownership to address 0, should fail - await expect(bosonVoucher.connect(protocol).transferOwnership(ethers.constants.AddressZero)).to.be.revertedWith( + await expect(bosonVoucher.connect(protocol).transferOwnership(ZeroAddress)).to.be.revertedWith( RevertReasons.OWNABLE_ZERO_ADDRESS ); }); @@ -2026,7 +2006,7 @@ describe("IBosonVoucher", function () { context("setContractURI()", function () { beforeEach(async function () { // give ownership to assistant - await bosonVoucher.connect(protocol).transferOwnership(assistant.address); + await bosonVoucher.connect(protocol).transferOwnership(await assistant.getAddress()); contractURI = "newContractURI"; }); @@ -2058,270 +2038,23 @@ describe("IBosonVoucher", function () { }); }); - context("EIP2981 NFT Royalty fee", function () { - beforeEach(async function () { - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); - - // prepare the VoucherInitValues - voucherInitValues = mockVoucherInitValues(); - voucherInitValues.royaltyPercentage = "1000"; // 10% - expect(voucherInitValues.isValid()).is.true; - - // AuthToken - emptyAuthToken = mockAuthToken(); - expect(emptyAuthToken.isValid()).is.true; - - await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); - - agentId = "0"; // agent id is optional while creating an offer - - // Create a valid dispute resolver - disputeResolver = mockDisputeResolver( - assistantDR.address, - adminDR.address, - clerkDR.address, - treasuryDR.address, - true - ); - expect(disputeResolver.isValid()).is.true; - - //Create DisputeResolverFee array so offer creation will succeed - disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")]; - - // Make empty seller list, so every seller is allowed - const sellerAllowList = []; - - // Register the dispute resolver - await accountHandler - .connect(adminDR) - .createDisputeResolver(disputeResolver, disputeResolverFees, sellerAllowList); - - const { offer, offerDates, offerDurations, disputeResolverId } = await mockOffer(); - await offerHandler - .connect(assistant) - .createOffer(offer.toStruct(), offerDates.toStruct(), offerDurations.toStruct(), disputeResolverId, agentId); - await fundsHandler - .connect(admin) - .depositFunds(seller.id, ethers.constants.AddressZero, offer.sellerDeposit, { value: offer.sellerDeposit }); - await exchangeHandler.connect(buyer).commitToOffer(buyer.address, offer.id, { value: offer.price }); - - exchangeId = "1"; - - offerPrice = offer.price; - }); - - afterEach(async function () { - // Reset the accountId iterator - accountId.next(true); - }); - - context("setRoyaltyPercentage()", function () { - beforeEach(async function () { - // give ownership to assistant - await bosonVoucher.connect(protocol).transferOwnership(assistant.address); - }); - - it("should emit RoyaltyPercentageChanged event", async function () { - royaltyPercentage = "0"; //0% - await expect(bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage)) - .to.emit(bosonVoucher, "RoyaltyPercentageChanged") - .withArgs(royaltyPercentage); - }); - - it("should set a royalty fee percentage", async function () { - // First, set royalty fee as 0 - royaltyPercentage = "0"; //0% - await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - - let receiver, royaltyAmount; - [receiver, royaltyAmount] = await bosonVoucher.connect(rando).royaltyInfo(exchangeId, offerPrice); - - // Expectations - let expectedRecipient = seller.treasury; - let expectedRoyaltyAmount = "0"; - - assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); - assert.equal(royaltyAmount.toString(), expectedRoyaltyAmount, "Royalty amount is incorrect"); - - // Now, set royalty fee as 10% - royaltyPercentage = "1000"; //10% - await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - - [receiver, royaltyAmount] = await bosonVoucher.connect(rando).royaltyInfo(exchangeId, offerPrice); - - // Expectations - expectedRecipient = seller.treasury; - expectedRoyaltyAmount = applyPercentage(offerPrice, royaltyPercentage); - - assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); - assert.equal(royaltyAmount.toString(), expectedRoyaltyAmount, "Royalty amount is incorrect"); - }); - - context("💔 Revert Reasons", async function () { - it("should revert if caller is not the owner", async function () { - // random caller - await expect(bosonVoucher.connect(rando).setRoyaltyPercentage(royaltyPercentage)).to.be.revertedWith( - RevertReasons.OWNABLE_NOT_OWNER - ); - - // protocol as the caller - await expect(bosonVoucher.connect(protocol).setRoyaltyPercentage(royaltyPercentage)).to.be.revertedWith( - RevertReasons.OWNABLE_NOT_OWNER - ); - }); - - it("should revert if royaltyPercentage is greater than max royalty percentage defined in the protocol", async function () { - // Set royalty fee as 15% (protocol limit is 10%) - royaltyPercentage = "1500"; //15% - - // royalty percentage too high, expectig revert - await expect(bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage)).to.be.revertedWith( - RevertReasons.ROYALTY_FEE_INVALID - ); - }); - }); - }); - - context("getRoyaltyPercentage()", function () { - it("should return the royalty fee percentage", async function () { - // give ownership to assistant - await bosonVoucher.connect(protocol).transferOwnership(assistant.address); - - royaltyPercentage = "1000"; //10% - await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - - expect(await bosonVoucher.connect(rando).getRoyaltyPercentage()).to.equal( - royaltyPercentage, - "Invalid royalty percentage" - ); - }); - }); - - context("royaltyInfo()", function () { - beforeEach(async function () { - // give ownership to assistant - await bosonVoucher.connect(protocol).transferOwnership(assistant.address); - }); - - it("should return a recipient and royalty fee", async function () { - // First, set royalty fee as 0 - royaltyPercentage = "0"; //0% - await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - - let receiver, royaltyAmount; - [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); - - // Expectations - let expectedRecipient = seller.treasury; - let expectedRoyaltyAmount = "0"; - - assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); - assert.equal(royaltyAmount.toString(), expectedRoyaltyAmount, "Royalty amount is incorrect"); - - // Now, set royalty fee as 10% - royaltyPercentage = "1000"; //10% - await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - - [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); - - // Expectations - expectedRecipient = seller.treasury; - expectedRoyaltyAmount = applyPercentage(offerPrice, royaltyPercentage); - - assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); - assert.equal(royaltyAmount.toString(), expectedRoyaltyAmount, "Royalty amount is incorrect"); - - // Any random address can check the royalty info - // Now, set royalty fee as 8% - royaltyPercentage = "800"; //8% - await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - - [receiver, royaltyAmount] = await bosonVoucher.connect(rando).royaltyInfo(exchangeId, offerPrice); - - // Expectations - expectedRecipient = seller.treasury; - expectedRoyaltyAmount = applyPercentage(offerPrice, royaltyPercentage); - - assert.equal(receiver, expectedRecipient, "Recipient address is incorrect"); - assert.equal(royaltyAmount.toString(), expectedRoyaltyAmount, "Royalty amount is incorrect"); - }); - - it("if exchange doesn't exist it should return 0 values", async function () { - // Set royalty fee as 10% - royaltyPercentage = "1000"; //10% - await bosonVoucher.connect(assistant).setRoyaltyPercentage(royaltyPercentage); - - // Set inexistent exchangeId - exchangeId = "100000"; - const [receiver, royaltyAmount] = await bosonVoucher.connect(assistant).royaltyInfo(exchangeId, offerPrice); - - // Receiver and amount should be 0 - assert.equal(receiver, ethers.constants.AddressZero, "Recipient address is incorrect"); - assert.equal(royaltyAmount.toNumber(), 0, "Royalty amount is incorrect"); - }); - }); - - context("💔 Revert Reasons", async function () { - it("should revert during create seller if royaltyPercentage is greater than max royalty percentage defined in the protocol", async function () { - // create invalid voucherInitValues - royaltyPercentage = "2000"; // 20% - voucherInitValues = new VoucherInitValues("ContractURI", royaltyPercentage); - - // create another seller - seller = mockSeller(rando.address, rando.address, ethers.constants.AddressZero, rando.address); - seller.id = "2"; - - // royalty percentage too high, expectig revert - await expect( - accountHandler.connect(rando).createSeller(seller, emptyAuthToken, voucherInitValues) - ).to.be.revertedWith(RevertReasons.ROYALTY_FEE_INVALID); - }); - }); - }); - - context("getSellerId()", function () { - it("should return the seller id", async function () { - // prepare the VoucherInitValues - voucherInitValues = mockVoucherInitValues(); - expect(voucherInitValues.isValid()).is.true; - - // AuthToken - emptyAuthToken = mockAuthToken(); - expect(emptyAuthToken.isValid()).is.true; - - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); - - await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); - - await bosonVoucher.connect(protocol).transferOwnership(assistant.address); - - expect(await bosonVoucher.connect(rando).getSellerId()).to.equal(seller.id, "Invalid seller id returned"); - - // Reset the accountId iterator - accountId.next(true); - }); - - it("should return 0 if the seller doesn't exist", async function () { - await bosonVoucher.connect(protocol).transferOwnership(rando.address); - expect(await bosonVoucher.getSellerId()).to.equal(0, "Invalid seller id returned"); - }); - }); - context("callExternalContract()", function () { let mockSimpleContract, calldata; beforeEach(async function () { // Deploy a random contract - const MockSimpleContract = await ethers.getContractFactory("MockSimpleContract"); + const MockSimpleContract = await getContractFactory("MockSimpleContract"); mockSimpleContract = await MockSimpleContract.deploy(); - await mockSimpleContract.deployed(); + await mockSimpleContract.waitForDeployment(); // Generate calldata calldata = mockSimpleContract.interface.encodeFunctionData("testEvent"); }); it("Should call external contract and emit its events", async function () { - const tx = await bosonVoucher.connect(assistant).callExternalContract(mockSimpleContract.address, calldata); + const tx = await bosonVoucher + .connect(assistant) + .callExternalContract(await mockSimpleContract.getAddress(), calldata); const receipt = await tx.wait(); const event = getEvent(receipt, mockSimpleContract, "TestEvent"); @@ -2331,14 +2064,14 @@ describe("IBosonVoucher", function () { context("💔 Revert Reasons", async function () { it("_to is the zero address", async function () { - await expect( - bosonVoucher.connect(assistant).callExternalContract(ethers.constants.AddressZero, calldata) - ).to.be.revertedWith(RevertReasons.INVALID_ADDRESS); + await expect(bosonVoucher.connect(assistant).callExternalContract(ZeroAddress, calldata)).to.be.revertedWith( + RevertReasons.INVALID_ADDRESS + ); }); it("Caller is not the contract owner", async function () { await expect( - bosonVoucher.connect(rando).callExternalContract(mockSimpleContract.address, calldata) + bosonVoucher.connect(rando).callExternalContract(await mockSimpleContract.getAddress(), calldata) ).to.be.revertedWith(RevertReasons.OWNABLE_NOT_OWNER); }); @@ -2346,176 +2079,97 @@ describe("IBosonVoucher", function () { calldata = mockSimpleContract.interface.encodeFunctionData("testRevert"); await expect( - bosonVoucher.connect(assistant).callExternalContract(mockSimpleContract.address, calldata) + bosonVoucher.connect(assistant).callExternalContract(await mockSimpleContract.getAddress(), calldata) ).to.be.revertedWith("Reverted"); }); it("To address is not a contract", async function () { - await expect(bosonVoucher.connect(assistant).callExternalContract(rando.address, calldata)).to.be.reverted; + await expect( + bosonVoucher.connect(assistant).callExternalContract(await rando.getAddress(), calldata) + ).to.be.reverted; }); it("Owner tries to invoke method to transfer funds", async function () { - const erc20 = await ethers.getContractFactory("Foreign20"); + const erc20 = await getContractFactory("Foreign20"); // transfer - calldata = erc20.interface.encodeFunctionData("transfer", [assistant.address, 20]); - await expect(bosonVoucher.connect(assistant).callExternalContract(rando.address, calldata)).to.be.revertedWith( - RevertReasons.FUNCTION_NOT_ALLOWLISTED - ); + calldata = erc20.interface.encodeFunctionData("transfer", [await assistant.getAddress(), 20]); + await expect( + bosonVoucher.connect(assistant).callExternalContract(await rando.getAddress(), calldata) + ).to.be.revertedWith(RevertReasons.FUNCTION_NOT_ALLOWLISTED); // transferFrom - calldata = erc20.interface.encodeFunctionData("transferFrom", [bosonVoucher.address, assistant.address, 20]); - await expect(bosonVoucher.connect(assistant).callExternalContract(rando.address, calldata)).to.be.revertedWith( - RevertReasons.FUNCTION_NOT_ALLOWLISTED - ); + calldata = erc20.interface.encodeFunctionData("transferFrom", [ + await bosonVoucher.getAddress(), + await assistant.getAddress(), + 20, + ]); + await expect( + bosonVoucher.connect(assistant).callExternalContract(await rando.getAddress(), calldata) + ).to.be.revertedWith(RevertReasons.FUNCTION_NOT_ALLOWLISTED); // approve - calldata = erc20.interface.encodeFunctionData("approve", [assistant.address, 20]); - await expect(bosonVoucher.connect(assistant).callExternalContract(rando.address, calldata)).to.be.revertedWith( - RevertReasons.FUNCTION_NOT_ALLOWLISTED - ); + calldata = erc20.interface.encodeFunctionData("approve", [await assistant.getAddress(), 20]); + await expect( + bosonVoucher.connect(assistant).callExternalContract(await rando.getAddress(), calldata) + ).to.be.revertedWith(RevertReasons.FUNCTION_NOT_ALLOWLISTED); // DAI - const dai = await ethers.getContractAt("DAIAliases", ethers.constants.AddressZero); + const dai = await getContractAt("DAIAliases", ZeroAddress); // push - calldata = dai.interface.encodeFunctionData("push", [assistant.address, 20]); - await expect(bosonVoucher.connect(assistant).callExternalContract(rando.address, calldata)).to.be.revertedWith( - RevertReasons.FUNCTION_NOT_ALLOWLISTED - ); + calldata = dai.interface.encodeFunctionData("push", [await assistant.getAddress(), 20]); + await expect( + bosonVoucher.connect(assistant).callExternalContract(await rando.getAddress(), calldata) + ).to.be.revertedWith(RevertReasons.FUNCTION_NOT_ALLOWLISTED); // move - calldata = dai.interface.encodeFunctionData("move", [bosonVoucher.address, assistant.address, 20]); - await expect(bosonVoucher.connect(assistant).callExternalContract(rando.address, calldata)).to.be.revertedWith( - RevertReasons.FUNCTION_NOT_ALLOWLISTED - ); + calldata = dai.interface.encodeFunctionData("move", [ + await bosonVoucher.getAddress(), + await assistant.getAddress(), + 20, + ]); + await expect( + bosonVoucher.connect(assistant).callExternalContract(await rando.getAddress(), calldata) + ).to.be.revertedWith(RevertReasons.FUNCTION_NOT_ALLOWLISTED); }); }); }); context("setApprovalForAllToContract", function () { it("Should emit ApprovalForAll event", async function () { - await expect(bosonVoucher.connect(assistant).setApprovalForAllToContract(rando.address, true)) + await expect(bosonVoucher.connect(assistant).setApprovalForAllToContract(await rando.getAddress(), true)) .to.emit(bosonVoucher, "ApprovalForAll") - .withArgs(bosonVoucher.address, rando.address, true); + .withArgs(await bosonVoucher.getAddress(), await rando.getAddress(), true); }); context("💔 Revert Reasons", async function () { it("should revert if caller is not the owner", async function () { // Expect revert if random user attempts to set approval - await expect(bosonVoucher.connect(rando).setApprovalForAllToContract(rando.address, true)).to.revertedWith( - RevertReasons.OWNABLE_NOT_OWNER - ); + await expect( + bosonVoucher.connect(rando).setApprovalForAllToContract(await rando.getAddress(), true) + ).to.revertedWith(RevertReasons.OWNABLE_NOT_OWNER); }); it("should revert if operator is zero address", async function () { // Expect revert if random user attempts to set approval - await expect( - bosonVoucher.connect(assistant).setApprovalForAllToContract(ethers.constants.AddressZero, true) - ).to.revertedWith(RevertReasons.INVALID_ADDRESS); + await expect(bosonVoucher.connect(assistant).setApprovalForAllToContract(ZeroAddress, true)).to.revertedWith( + RevertReasons.INVALID_ADDRESS + ); }); }); }); - context("withdrawToProtocol", function () { - beforeEach(async function () { - seller = mockSeller(assistant.address, admin.address, clerk.address, treasury.address); - - // Prepare the AuthToken and VoucherInitValues - emptyAuthToken = mockAuthToken(); - voucherInitValues = mockVoucherInitValues(); - await accountHandler.connect(admin).createSeller(seller, emptyAuthToken, voucherInitValues); - }); - - afterEach(async function () { - // Reset the accountId iterator - accountId.next(true); - }); - - it("Can withdraw native token", async function () { - // Sellers available funds should be empty - const sellersFundsBefore = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - let expectedAvailableFunds = new FundsList([]); - expect(sellersFundsBefore).to.eql(expectedAvailableFunds); - - const amount = ethers.utils.parseUnits("1", "ether"); - await admin.sendTransaction({ to: bosonVoucher.address, value: amount }); - - await expect(() => - bosonVoucher.connect(rando).withdrawToProtocol([ethers.constants.AddressZero]) - ).to.changeEtherBalances([bosonVoucher, fundsHandler], [amount.mul(-1), amount]); - }); - - it("Can withdraw ERC20", async function () { - // Sellers available funds should be empty - const sellersFundsBefore = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - let expectedAvailableFunds = new FundsList([]); - expect(sellersFundsBefore).to.eql(expectedAvailableFunds); - - const amount = ethers.utils.parseUnits("1", "ether"); - await foreign20.connect(deployer).mint(deployer.address, amount); - await foreign20.connect(deployer).transfer(bosonVoucher.address, amount); - - await expect(() => bosonVoucher.connect(rando).withdrawToProtocol([foreign20.address])).to.changeTokenBalances( - foreign20, - [bosonVoucher, fundsHandler], - [amount.mul(-1), amount] - ); - - // Seller's available balance should increase - expectedAvailableFunds = new FundsList([new Funds(foreign20.address, "Foreign20", amount.toString())]); - const sellerFundsAfter = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - expect(sellerFundsAfter).to.eql(expectedAvailableFunds); - }); - - it("Should withdraw all tokens when list length > 1", async function () { - // Sellers available funds should be empty - const sellersFundsBefore = FundsList.fromStruct(await fundsHandler.getAvailableFunds(seller.id)); - let expectedAvailableFunds = new FundsList([]); - expect(sellersFundsBefore).to.eql(expectedAvailableFunds); - - const amount = ethers.utils.parseUnits("1", "ether"); - await admin.sendTransaction({ to: bosonVoucher.address, value: amount }); - await foreign20.connect(deployer).mint(deployer.address, amount); - await foreign20.connect(deployer).transfer(bosonVoucher.address, amount); - - let tx; - await expect(() => { - tx = bosonVoucher.connect(rando).withdrawToProtocol([ethers.constants.AddressZero, foreign20.address]); - return tx; - }).to.changeTokenBalances(foreign20, [bosonVoucher, fundsHandler], [amount.mul(-1), amount]); - await expect(() => tx).to.changeEtherBalances([bosonVoucher, fundsHandler], [amount.mul(-1), amount]); - }); - }); - context("onERC721Received", function () { it("Should return correct selector value", async function () { - const expectedSelector = bosonVoucher.interface.getSighash("onERC721Received(address,address,uint256,bytes)"); - const returnedSelector = await bosonVoucher.callStatic.onERC721Received( - assistant.address, - rando.address, + const expectedSelector = bosonVoucher.interface.fragments.find((f) => f.name == "onERC721Received").selector; + const returnedSelector = await bosonVoucher.onERC721Received.staticCall( + await assistant.getAddress(), + await rando.getAddress(), "1", "0x" ); expect(returnedSelector).to.equal(expectedSelector); }); }); - - async function deployMockProtocol() { - const exchangeHandlerABI = exchangeHandler.interface.format(FormatTypes.json); - const configHandlerABI = configHandler.interface.format(FormatTypes.json); - const offerHandlerABI = offerHandler.interface.format(FormatTypes.json); - const mockProtocol = await deployMockContract(deployer, [ - ...JSON.parse(exchangeHandlerABI), - ...JSON.parse(configHandlerABI), - ...JSON.parse(offerHandlerABI), - ]); //deploys mock - - // Update protocol address on beacon - await beacon.connect(deployer).setProtocolAddress(mockProtocol.address); - - await mockProtocol.mock.getAccessControllerAddress.returns(accessController.address); - - return mockProtocol; - } }); diff --git a/test/protocol/clients/ClientExternalAddressesTest.js b/test/protocol/clients/ClientExternalAddressesTest.js index 1ebf0354a..1ed60d0b1 100644 --- a/test/protocol/clients/ClientExternalAddressesTest.js +++ b/test/protocol/clients/ClientExternalAddressesTest.js @@ -1,5 +1,5 @@ const { ethers } = require("hardhat"); - +const { getSigners, ZeroAddress, getContractFactory } = ethers; const { gasLimit } = require("../../../environments"); const { deployProtocolClientImpls } = require("../../../scripts/util/deploy-protocol-client-impls.js"); const { deployProtocolClientBeacons } = require("../../../scripts/util/deploy-protocol-client-beacons.js"); @@ -25,7 +25,7 @@ describe("IClientExternalAddresses", function () { extraReturnValues: { beacon }, } = await setupTestEnvironment(contracts)); - [deployer] = await ethers.getSigners(); + [deployer] = await getSigners(); // Get snapshot id snapshotId = await getSnapshot(); @@ -41,14 +41,14 @@ describe("IClientExternalAddresses", function () { context("👉 setImplementation()", async function () { beforeEach(async function () { // set new value for voucher implementation - voucherImplementation = other1.address; // random address, just for test + voucherImplementation = await other1.getAddress(); // random address, just for test }); it("should emit an Upgraded event", async function () { // Set new implementation, testing for the event await expect(beacon.connect(deployer).setImplementation(voucherImplementation)) .to.emit(beacon, "Upgraded") - .withArgs(voucherImplementation, deployer.address); + .withArgs(voucherImplementation, await deployer.getAddress()); }); it("should update state", async function () { @@ -69,7 +69,7 @@ describe("IClientExternalAddresses", function () { it("implementation address is the zero address", async function () { // Attempt to set new implementation, expecting revert - await expect(beacon.connect(deployer).setImplementation(ethers.constants.AddressZero)).to.revertedWith( + await expect(beacon.connect(deployer).setImplementation(ZeroAddress)).to.revertedWith( RevertReasons.INVALID_ADDRESS ); }); @@ -79,14 +79,14 @@ describe("IClientExternalAddresses", function () { context("👉 setProtocolAddress()", async function () { beforeEach(async function () { // set new value for protocol address - protocolAddress = other3.address; // random address, just for test + protocolAddress = await other3.getAddress(); // random address, just for test }); it("should emit a ProtocolAddressChanged event", async function () { // Set new protocol address, testing for the event await expect(beacon.connect(deployer).setProtocolAddress(protocolAddress)) .to.emit(beacon, "ProtocolAddressChanged") - .withArgs(protocolAddress, deployer.address); + .withArgs(protocolAddress, await deployer.getAddress()); }); it("should update state", async function () { @@ -107,7 +107,7 @@ describe("IClientExternalAddresses", function () { it("protocol address is the zero address", async function () { // Attempt to set new protocol address, expecting revert - await expect(beacon.connect(deployer).setProtocolAddress(ethers.constants.AddressZero)).to.revertedWith( + await expect(beacon.connect(deployer).setProtocolAddress(ZeroAddress)).to.revertedWith( RevertReasons.INVALID_ADDRESS ); }); @@ -118,13 +118,10 @@ describe("IClientExternalAddresses", function () { context("💔 Revert Reasons", async function () { it("_protocolAddress address is the zero address", async function () { // Deploy Protocol Client implementation contracts - const protocolClientImpls = await deployProtocolClientImpls( - [ethers.constants.AddressZero], - maxPriorityFeePerGas - ); + const protocolClientImpls = await deployProtocolClientImpls([ZeroAddress], maxPriorityFeePerGas); // Deploy Protocol Client beacon contracts - const protocolClientArgs = [ethers.constants.AddressZero]; + const protocolClientArgs = [ZeroAddress]; await expect( deployProtocolClientBeacons(protocolClientImpls, protocolClientArgs, maxPriorityFeePerGas) ).to.revertedWith(RevertReasons.INVALID_ADDRESS); @@ -135,10 +132,10 @@ describe("IClientExternalAddresses", function () { const protocolClientArgs = [protocolDiamondAddress]; // Deploy the ClientBeacon for BosonVoucher - const ClientBeacon = await ethers.getContractFactory("BosonClientBeacon"); - await expect( - ClientBeacon.deploy(...protocolClientArgs, ethers.constants.AddressZero, { gasLimit }) - ).to.revertedWith(RevertReasons.INVALID_ADDRESS); + const ClientBeacon = await getContractFactory("BosonClientBeacon"); + await expect(ClientBeacon.deploy(...protocolClientArgs, ZeroAddress, { gasLimit })).to.revertedWith( + RevertReasons.INVALID_ADDRESS + ); }); }); }); diff --git a/test/upgrade/01_generic.js b/test/upgrade/01_generic.js index 88bbeef46..ed86a62ea 100644 --- a/test/upgrade/01_generic.js +++ b/test/upgrade/01_generic.js @@ -1,6 +1,6 @@ const shell = require("shelljs"); const hre = require("hardhat"); -const ethers = hre.ethers; +const { ZeroAddress, provider } = hre.ethers; const { assert, expect } = require("chai"); const { mockOffer, mockVoucher, mockExchange } = require("../util/mock"); const { getEvent, calculateVoucherExpiry, getSnapshot, revertToSnapshot } = require("../util/utils.js"); @@ -153,26 +153,26 @@ function getGenericContext( const offerPrice = offer.price; const buyer = preUpgradeEntities.buyers[1]; let msgValue; - if (offer.exchangeToken == ethers.constants.AddressZero) { + if (offer.exchangeToken == ZeroAddress) { msgValue = offerPrice; } else { // approve token transfer msgValue = 0; await mockToken.connect(buyer.wallet).approve(protocolDiamondAddress, offerPrice); - await mockToken.mint(buyer.wallet.address, offerPrice); + await mockToken.mint(buyer.wallet, offerPrice); } // Commit to offer const exchangeId = await exchangeHandler.getNextExchangeId(); const tx = await exchangeHandler .connect(buyer.wallet) - .commitToOffer(buyer.wallet.address, offer.id, { value: msgValue }); + .commitToOffer(buyer.wallet, offer.id, { value: msgValue }); const txReceipt = await tx.wait(); const event = getEvent(txReceipt, exchangeHandler, "BuyerCommitted"); // Get the block timestamp of the confirmed tx const blockNumber = tx.blockNumber; - const block = await ethers.provider.getBlock(blockNumber); + const block = await provider.getBlock(blockNumber); // Set expected voucher values const voucher = mockVoucher({ @@ -210,7 +210,7 @@ function getGenericContext( const buyerWallet = preUpgradeEntities.buyers[exchange.buyerIndex].wallet; await expect(exchangeHandler.connect(buyerWallet).redeemVoucher(exchange.exchangeId)) .to.emit(exchangeHandler, "VoucherRedeemed") - .withArgs(exchange.offerId, exchange.exchangeId, buyerWallet.address); + .withArgs(exchange.offerId, exchange.exchangeId, await buyerWallet.getAddress()); }); it("Cancel old voucher", async function () { @@ -218,7 +218,7 @@ function getGenericContext( const buyerWallet = preUpgradeEntities.buyers[exchange.buyerIndex].wallet; await expect(exchangeHandler.connect(buyerWallet).cancelVoucher(exchange.exchangeId)) .to.emit(exchangeHandler, "VoucherCanceled") - .withArgs(exchange.offerId, exchange.exchangeId, buyerWallet.address); + .withArgs(exchange.offerId, exchange.exchangeId, await buyerWallet.getAddress()); }); it("Revoke old voucher", async function () { @@ -227,7 +227,7 @@ function getGenericContext( const seller = preUpgradeEntities.sellers.find((s) => s.seller.id == offer.offer.sellerId); await expect(exchangeHandler.connect(seller.wallet).revokeVoucher(exchange.exchangeId)) .to.emit(exchangeHandler, "VoucherRevoked") - .withArgs(exchange.offerId, exchange.exchangeId, seller.wallet.address); + .withArgs(exchange.offerId, exchange.exchangeId, seller.wallet); }); it("Escalate old dispute", async function () { @@ -237,7 +237,7 @@ function getGenericContext( const offer = preUpgradeEntities.offers.find((o) => o.offer.id == exchange.offerId); await expect(disputeHandler.connect(buyerWallet).escalateDispute(exchange.exchangeId)) .to.emit(disputeHandler, "DisputeEscalated") - .withArgs(exchange.exchangeId, offer.disputeResolverId, buyerWallet.address); + .withArgs(exchange.exchangeId, offer.disputeResolverId, await buyerWallet.getAddress()); }); it("Old buyer commits to new offer", async function () { @@ -264,13 +264,13 @@ function getGenericContext( const offerPrice = offer.price; const tx = await exchangeHandler .connect(buyer.wallet) - .commitToOffer(buyer.wallet.address, offer.id, { value: offerPrice }); + .commitToOffer(buyer.wallet, offer.id, { value: offerPrice }); const txReceipt = await tx.wait(); const event = getEvent(txReceipt, exchangeHandler, "BuyerCommitted"); // Get the block timestamp of the confirmed tx const blockNumber = tx.blockNumber; - const block = await ethers.provider.getBlock(blockNumber); + const block = await provider.getBlock(blockNumber); // Set expected voucher values const voucher = mockVoucher({ @@ -309,7 +309,7 @@ function getGenericContext( await expect(offerHandler.connect(seller.wallet).voidOffer(offerId)) .to.emit(offerHandler, "OfferVoided") - .withArgs(offerId, seller.seller.id, seller.wallet.address); + .withArgs(offerId, seller.seller.id, seller.wallet); }); }); }; diff --git a/test/upgrade/2.0.0-2.1.0.js b/test/upgrade/2.0.0-2.1.0.js index b2b6d9bb8..80869aa57 100644 --- a/test/upgrade/2.0.0-2.1.0.js +++ b/test/upgrade/2.0.0-2.1.0.js @@ -1,4 +1,5 @@ const { ethers } = require("hardhat"); +const { ZeroAddress, getSigners } = ethers; const { assert, expect } = require("chai"); const Seller = require("../../scripts/domain/Seller"); const AuthToken = require("../../scripts/domain/AuthToken"); @@ -37,7 +38,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation before(async function () { try { // Make accounts available - [deployer, rando, admin, assistant, clerk, treasury] = await ethers.getSigners(); + [deployer, rando, admin, assistant, clerk, treasury] = await getSigners(); ({ protocolDiamondAddress, protocolContracts, mockContracts } = await deploySuite(deployer, version)); @@ -113,10 +114,10 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation const seller = oldSeller.seller.clone(); - seller.admin = admin.address; - seller.assistant = assistant.address; - seller.clerk = clerk.address; - seller.treasury = treasury.address; + seller.admin = await admin.getAddress(); + seller.assistant = await assistant.getAddress(); + seller.clerk = await clerk.getAddress(); + seller.treasury = await treasury.getAddress(); const authToken = mockAuthToken(); @@ -157,10 +158,10 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation disputeResolver.escalationResponsePeriod = Number( Number(disputeResolver.escalationResponsePeriod) - 100 ).toString(); - disputeResolver.assistant = assistant.address; - disputeResolver.admin = admin.address; - disputeResolver.clerk = clerk.address; - disputeResolver.treasury = treasury.address; + disputeResolver.assistant = await assistant.getAddress(); + disputeResolver.admin = await admin.getAddress(); + disputeResolver.clerk = await clerk.getAddress(); + disputeResolver.treasury = await treasury.getAddress(); disputeResolver.metadataUri = "https://ipfs.io/ipfs/updatedUri"; disputeResolver.active = false; @@ -238,14 +239,14 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation const oldSeller = preUpgradeEntities.sellers[3]; const seller = oldSeller.seller.clone(); - seller.treasury = treasury.address; - seller.admin = admin.address; - seller.assistant = assistant.address; - seller.clerk = clerk.address; + seller.treasury = await treasury.getAddress(); + seller.admin = await admin.getAddress(); + seller.assistant = await assistant.getAddress(); + seller.clerk = await clerk.getAddress(); const pendingSellerUpdate = seller.clone(); pendingSellerUpdate.id = "0"; - pendingSellerUpdate.treasury = ethers.constants.AddressZero; + pendingSellerUpdate.treasury = ZeroAddress; pendingSellerUpdate.active = false; const expectedSeller = oldSeller.seller.clone(); @@ -269,18 +270,18 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation pendingSellerUpdate.toStruct(), oldSellerAuthToken, pendingAuthTokenStruct, - oldSeller.wallet.address + oldSeller.wallet ); // Testing for the SellerUpdatePending event await expect(tx) .to.emit(accountHandler, "SellerUpdatePending") - .withArgs(seller.id, pendingSellerUpdate.toStruct(), pendingAuthTokenStruct, oldSeller.wallet.address); + .withArgs(seller.id, pendingSellerUpdate.toStruct(), pendingAuthTokenStruct, oldSeller.wallet); // Update seller assistant tx = await accountHandler.connect(assistant).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant]); - pendingSellerUpdate.assistant = ethers.constants.AddressZero; + pendingSellerUpdate.assistant = ZeroAddress; expectedSeller.assistant = seller.assistant; // Check assistant update @@ -292,13 +293,13 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation pendingSellerUpdate.toStruct(), oldSellerAuthToken, pendingAuthTokenStruct, - assistant.address + await assistant.getAddress() ); // Update seller clerk tx = await accountHandler.connect(clerk).optInToSellerUpdate(seller.id, [SellerUpdateFields.Clerk]); - pendingSellerUpdate.clerk = ethers.constants.AddressZero; + pendingSellerUpdate.clerk = ZeroAddress; expectedSeller.clerk = seller.clerk; // Check assistant update @@ -310,13 +311,13 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation pendingSellerUpdate.toStruct(), oldSellerAuthToken, pendingAuthTokenStruct, - clerk.address + await clerk.getAddress() ); // Update seller admin tx = await accountHandler.connect(admin).optInToSellerUpdate(seller.id, [SellerUpdateFields.Admin]); - pendingSellerUpdate.admin = ethers.constants.AddressZero; + pendingSellerUpdate.admin = ZeroAddress; expectedSeller.admin = seller.admin; // Check assistant update @@ -328,7 +329,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation pendingSellerUpdate.toStruct(), authToken.toStruct(), pendingAuthTokenStruct, - admin.address + await admin.getAddress() ); }); @@ -341,10 +342,10 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation disputeResolver.escalationResponsePeriod = Number( Number(disputeResolver.escalationResponsePeriod) - 100 ).toString(); - disputeResolver.assistant = assistant.address; - disputeResolver.admin = admin.address; - disputeResolver.clerk = clerk.address; - disputeResolver.treasury = treasury.address; + disputeResolver.assistant = await assistant.getAddress(); + disputeResolver.admin = await admin.getAddress(); + disputeResolver.clerk = await clerk.getAddress(); + disputeResolver.treasury = await treasury.getAddress(); disputeResolver.metadataUri = "https://ipfs.io/ipfs/updatedUri"; disputeResolver.active = false; @@ -352,7 +353,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation disputeResolverPendingUpdate.id = "0"; disputeResolverPendingUpdate.escalationResponsePeriod = "0"; disputeResolverPendingUpdate.metadataUri = ""; - disputeResolverPendingUpdate.treasury = ethers.constants.AddressZero; + disputeResolverPendingUpdate.treasury = ZeroAddress; const expectedDisputeResolver = oldDisputeResolver.disputeResolver.clone(); expectedDisputeResolver.escalationResponsePeriod = disputeResolver.escalationResponsePeriod; @@ -362,11 +363,11 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Update dispute resolver await expect(accountHandler.connect(oldDisputeResolver.wallet).updateDisputeResolver(disputeResolver)) .to.emit(accountHandler, "DisputeResolverUpdatePending") - .withArgs(disputeResolver.id, disputeResolverPendingUpdate.toStruct(), oldDisputeResolver.wallet.address); + .withArgs(disputeResolver.id, disputeResolverPendingUpdate.toStruct(), oldDisputeResolver.wallet); // Approve assistant update expectedDisputeResolver.assistant = disputeResolver.assistant; - disputeResolverPendingUpdate.assistant = ethers.constants.AddressZero; + disputeResolverPendingUpdate.assistant = ZeroAddress; await expect( accountHandler @@ -378,12 +379,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation disputeResolver.id, expectedDisputeResolver.toStruct(), disputeResolverPendingUpdate.toStruct(), - assistant.address + await assistant.getAddress() ); // Approve admin update expectedDisputeResolver.admin = disputeResolver.admin; - disputeResolverPendingUpdate.admin = ethers.constants.AddressZero; + disputeResolverPendingUpdate.admin = ZeroAddress; await expect( accountHandler @@ -395,12 +396,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation disputeResolver.id, expectedDisputeResolver.toStruct(), disputeResolverPendingUpdate.toStruct(), - admin.address + await admin.getAddress() ); // Approve clerk update expectedDisputeResolver.clerk = disputeResolver.clerk; - disputeResolverPendingUpdate.clerk = ethers.constants.AddressZero; + disputeResolverPendingUpdate.clerk = ZeroAddress; await expect( accountHandler @@ -412,7 +413,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation disputeResolver.id, expectedDisputeResolver.toStruct(), disputeResolverPendingUpdate.toStruct(), - clerk.address + await clerk.getAddress() ); }); }); diff --git a/test/upgrade/2.1.0-2.2.0.js b/test/upgrade/2.1.0-2.2.0.js index e0bbfc5f6..bb63bd1d6 100644 --- a/test/upgrade/2.1.0-2.2.0.js +++ b/test/upgrade/2.1.0-2.2.0.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { ZeroAddress, getContractAt, getSigners, provider, randomBytes, keccak256, toUtf8Bytes } = hre.ethers; const { assert, expect } = require("chai"); const DisputeResolver = require("../../scripts/domain/DisputeResolver"); const { @@ -21,7 +21,6 @@ const { revertState, } = require("../util/upgrade"); const { getGenericContext } = require("./01_generic"); -const { keccak256, toUtf8Bytes } = require("ethers/lib/utils"); const TokenType = require("../../scripts/domain/TokenType"); const Twin = require("../../scripts/domain/Twin"); const { @@ -63,7 +62,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation before(async function () { try { // Make accounts available - [deployer, rando, , assistant] = await ethers.getSigners(); + [deployer, rando, , assistant] = await getSigners(); ({ protocolDiamondAddress, protocolContracts, mockContracts } = await deploySuite(deployer, newVersion)); ({ twinHandler, disputeHandler } = protocolContracts); @@ -136,7 +135,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation preUpgradeEntities ); - snapshot = await ethers.provider.send("evm_snapshot", []); + snapshot = await provider.send("evm_snapshot", []); // This context is placed in an uncommon place due to order of test execution. // Generic context needs values that are set in "before", however "before" is executed before tests, not before suites @@ -167,8 +166,8 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation afterEach(async function () { // Revert to state right after the upgrade. // This is used so the lengthly setup (deploy+upgrade) is done only once. - await ethers.provider.send("evm_revert", [snapshot]); - snapshot = await ethers.provider.send("evm_snapshot", []); + await provider.send("evm_revert", [snapshot]); + snapshot = await provider.send("evm_snapshot", []); }); after(async function () { @@ -191,10 +190,10 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation const { contracts } = readContracts(31337, "hardhat", "upgrade-test"); const orchestrationHandler1 = contracts.find((i) => i.name === "OrchestrationHandlerFacet1"); - const diamondLoupe = await ethers.getContractAt("DiamondLoupeFacet", protocolDiamondAddress); + const diamondLoupe = await getContractAt("DiamondLoupeFacet", protocolDiamondAddress); for (const selector of selectors) { - expect(await diamondLoupe.facetAddress(selector)).to.equal(orchestrationHandler1.address); + expect(await diamondLoupe.facetAddress(selector)).to.equal(await orchestrationHandler1.getAddress()); } }); }); @@ -212,7 +211,14 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation expect(exist, "DR should not exist").to.be.false; // New DR must be created with active = true - const DR = mockDisputeResolver(rando.address, rando.address, rando.address, rando.address, true, true); + const DR = mockDisputeResolver( + await rando.getAddress(), + await rando.getAddress(), + await rando.getAddress(), + await rando.getAddress(), + true, + true + ); DR.id = nextAccountId.toString(); await accountHandler.connect(rando).createDisputeResolver(DR, [], []); @@ -228,12 +234,21 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation const { nextAccountId } = protocolContractState.accountContractState; // Create seller - const seller = mockSeller(assistant.address, assistant.address, assistant.address, assistant.address, true); + const seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + await assistant.getAddress(), + await assistant.getAddress(), + true + ); await accountHandler.connect(assistant).createSeller(seller, mockAuthToken(), mockVoucherInitValues()); // Voucher contract - const expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, sellers.length + 1); - const bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + const expectedCloneAddress = calculateContractAddress( + await orchestrationHandler.getAddress(), + sellers.length + 1 + ); + const bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); // Validate voucher name and symbol expect(await bosonVoucher.name()).to.equal( @@ -309,7 +324,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation const offer = preUpgradeEntities.offers.find((o) => o.offer.id == exchange.offerId); const seller = preUpgradeEntities.sellers.find((s) => s.seller.id == offer.offer.sellerId); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", seller.voucherContractAddress); + bosonVoucher = await getContractAt("IBosonVoucher", seller.voucherContractAddress); tokenId = exchange.exchangeId; sellerWallet = seller.wallet; }); @@ -320,12 +335,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Protocol event await expect(tx) .to.emit(exchangeHandler, "VoucherRedeemed") - .withArgs(exchange.offerId, exchange.exchangeId, buyerWallet.address); + .withArgs(exchange.offerId, exchange.exchangeId, await buyerWallet.getAddress()); // Voucher burned event await expect(tx) .to.emit(bosonVoucher, "Transfer") - .withArgs(buyerWallet.address, ethers.constants.AddressZero, tokenId); + .withArgs(await buyerWallet.getAddress(), ZeroAddress, tokenId); }); it("Cancel old voucher", async function () { @@ -334,12 +349,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Protocol event await expect(tx) .to.emit(exchangeHandler, "VoucherCanceled") - .withArgs(exchange.offerId, exchange.exchangeId, buyerWallet.address); + .withArgs(exchange.offerId, exchange.exchangeId, await buyerWallet.getAddress()); // Voucher burned event await expect(tx) .to.emit(bosonVoucher, "Transfer") - .withArgs(buyerWallet.address, ethers.constants.AddressZero, tokenId); + .withArgs(await buyerWallet.getAddress(), ZeroAddress, tokenId); }); it("Revoke old voucher", async function () { @@ -348,12 +363,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Protocol event await expect(tx) .to.emit(exchangeHandler, "VoucherRevoked") - .withArgs(exchange.offerId, exchange.exchangeId, sellerWallet.address); + .withArgs(exchange.offerId, exchange.exchangeId, await sellerWallet.getAddress()); // Voucher burned event await expect(tx) .to.emit(bosonVoucher, "Transfer") - .withArgs(buyerWallet.address, ethers.constants.AddressZero, tokenId); + .withArgs(await buyerWallet.getAddress(), ZeroAddress, tokenId); }); }); @@ -367,11 +382,11 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation let price; ({ id: offerId, price } = preUpgradeEntities.offers[0].offer); - await exchangeHandler.commitToOffer(buyerWallet.address, offerId, { value: price }); + await exchangeHandler.commitToOffer(await buyerWallet.getAddress(), offerId, { value: price }); const offer = preUpgradeEntities.offers.find((o) => o.offer.id == offerId); const seller = preUpgradeEntities.sellers.find((s) => s.seller.id == offer.offer.sellerId); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", seller.voucherContractAddress); + bosonVoucher = await getContractAt("IBosonVoucher", seller.voucherContractAddress); tokenId = deriveTokenId(offerId, exchangeId); sellerWallet = seller.wallet; }); @@ -382,12 +397,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Protocol event await expect(tx) .to.emit(exchangeHandler, "VoucherRedeemed") - .withArgs(offerId, exchangeId, buyerWallet.address); + .withArgs(offerId, exchangeId, await buyerWallet.getAddress()); // Voucher burned event await expect(tx) .to.emit(bosonVoucher, "Transfer") - .withArgs(buyerWallet.address, ethers.constants.AddressZero, tokenId); + .withArgs(await buyerWallet.getAddress(), ZeroAddress, tokenId); }); it("Cancel new voucher", async function () { @@ -396,12 +411,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Protocol event await expect(tx) .to.emit(exchangeHandler, "VoucherCanceled") - .withArgs(offerId, exchangeId, buyerWallet.address); + .withArgs(offerId, exchangeId, await buyerWallet.getAddress()); // Voucher burned event await expect(tx) .to.emit(bosonVoucher, "Transfer") - .withArgs(buyerWallet.address, ethers.constants.AddressZero, tokenId); + .withArgs(await buyerWallet.getAddress(), ZeroAddress, tokenId); }); it("Revoke new voucher", async function () { @@ -410,12 +425,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Protocol event await expect(tx) .to.emit(exchangeHandler, "VoucherRevoked") - .withArgs(offerId, exchangeId, sellerWallet.address); + .withArgs(offerId, exchangeId, await sellerWallet.getAddress()); // Voucher burned event await expect(tx) .to.emit(bosonVoucher, "Transfer") - .withArgs(buyerWallet.address, ethers.constants.AddressZero, tokenId); + .withArgs(await buyerWallet.getAddress(), ZeroAddress, tokenId); }); }); @@ -423,7 +438,13 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation let seller, functionSignature, metaTransactionType, customTransactionType, nonce, message; beforeEach(async function () { - seller = mockSeller(assistant.address, assistant.address, assistant.address, assistant.address, true); + seller = mockSeller( + await assistant.getAddress(), + await assistant.getAddress(), + await assistant.getAddress(), + await assistant.getAddress(), + true + ); // Prepare the function signature for the facet function. functionSignature = accountHandler.interface.encodeFunctionData("createSeller", [ @@ -445,13 +466,13 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation MetaTransaction: metaTransactionType, }; - nonce = parseInt(ethers.utils.randomBytes(8)); + nonce = parseInt(randomBytes(8)); // Prepare the message message = { nonce, - from: assistant.address, - contractAddress: accountHandler.address, + from: await assistant.getAddress(), + contractAddress: await accountHandler.getAddress(), functionName: "createSeller((uint256,address,address,address,address,bool),(uint256,uint8),(string,uint256))", functionSignature: functionSignature, @@ -465,17 +486,25 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // send a meta transaction, check for event await expect( metaTransactionsHandler .connect(deployer) - .executeMetaTransaction(assistant.address, message.functionName, functionSignature, nonce, r, s, v) + .executeMetaTransaction( + await assistant.getAddress(), + message.functionName, + functionSignature, + nonce, + r, + s, + v + ) ) .to.emit(metaTransactionsHandler, "MetaTransactionExecuted") - .withArgs(assistant.address, deployer.address, message.functionName, nonce); + .withArgs(await assistant.getAddress(), await deployer.getAddress(), message.functionName, nonce); }); it("Meta transaction should fail when function name is not allowlisted", async function () { @@ -487,14 +516,22 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation customTransactionType, "MetaTransaction", message, - metaTransactionsHandler.address + await metaTransactionsHandler.getAddress() ); // Execute meta transaction, expecting revert. await expect( metaTransactionsHandler .connect(assistant) - .executeMetaTransaction(assistant.address, message.functionName, functionSignature, nonce, r, s, v) + .executeMetaTransaction( + await assistant.getAddress(), + message.functionName, + functionSignature, + nonce, + r, + s, + v + ) ).to.revertedWith(RevertReasons.FUNCTION_NOT_ALLOWLISTED); }); @@ -537,12 +574,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Enable functions await expect(metaTransactionsHandler.connect(deployer).setAllowlistedFunctions(functionHashList, true)) .to.emit(metaTransactionsHandler, "FunctionsAllowlisted") - .withArgs(functionHashList, true, deployer.address); + .withArgs(functionHashList, true, await deployer.getAddress()); // Disable functions await expect(metaTransactionsHandler.connect(deployer).setAllowlistedFunctions(functionHashList, false)) .to.emit(metaTransactionsHandler, "FunctionsAllowlisted") - .withArgs(functionHashList, false, deployer.address); + .withArgs(functionHashList, false, await deployer.getAddress()); }); it("👉 isFunctionAllowlisted(bytes32)", async function () { @@ -612,7 +649,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Set new value await expect(configHandler.connect(deployer).setMaxPremintedVouchers(100)) .to.emit(configHandler, "MaxPremintedVouchersChanged") - .withArgs(100, deployer.address); + .withArgs(100, await deployer.getAddress()); // Verify that new value is stored expect(await configHandler.connect(rando).getMaxPremintedVouchers()).to.equal("100"); @@ -659,9 +696,18 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation DRs: [, disputeResolver], // take DR that has empty allow list } = preUpgradeEntities; - seller = mockSeller(rando.address, rando.address, rando.address, rando.address, true); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + await rando.getAddress(), + await rando.getAddress(), + true + ); disputeResolverId = disputeResolver.id; - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, sellers.length + 1); + expectedCloneAddress = calculateContractAddress( + await orchestrationHandler.getAddress(), + sellers.length + 1 + ); ({ offer, offerDates, offerDurations } = await mockOffer()); agentId = 0; @@ -690,17 +736,17 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation await expect(tx).to.emit(orchestrationHandler, "OfferCreated"); // Voucher clone contract - let bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + let bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged"); await expect(tx).to.emit(bosonVoucher, "RoyaltyPercentageChanged"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); // Different ABI + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); // Different ABI await expect(tx).to.emit(bosonVoucher, "OwnershipTransferred"); }); it("👉 createSellerAndOfferWithCondition", async function () { const condition = mockCondition({ - tokenAddress: rando.address, + tokenAddress: await rando.getAddress(), tokenType: TokenType.MultiToken, tokenId: "5150", }); @@ -725,11 +771,11 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation await expect(tx).to.emit(orchestrationHandler, "GroupCreated"); // Voucher clone contract - let bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + let bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged"); await expect(tx).to.emit(bosonVoucher, "RoyaltyPercentageChanged"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "OwnershipTransferred"); }); @@ -739,9 +785,9 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation beforeEach(async function () { [bosonToken] = await deployMockTokens(); // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(rando).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(rando).approve(await twinHandler.getAddress(), 1); // approving the twin handler - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); }); it("👉 createSellerAndOfferAndTwinWithBundle", async function () { @@ -767,17 +813,17 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation await expect(tx).to.emit(orchestrationHandler, "BundleCreated"); // Voucher clone contract - let bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + let bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged"); await expect(tx).to.emit(bosonVoucher, "RoyaltyPercentageChanged"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "OwnershipTransferred"); }); it("👉 createSellerAndOfferWithConditionAndTwinAndBundle", async function () { const condition = mockCondition({ - tokenAddress: rando.address, + tokenAddress: await rando.getAddress(), tokenType: TokenType.MultiToken, tokenId: "5150", }); @@ -806,11 +852,11 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation await expect(tx).to.emit(orchestrationHandler, "BundleCreated"); // Voucher clone contract - let bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + let bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged"); await expect(tx).to.emit(bosonVoucher, "RoyaltyPercentageChanged"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "OwnershipTransferred"); }); }); @@ -834,7 +880,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation it("👉 createOfferWithCondition", async function () { const condition = mockCondition({ - tokenAddress: rando.address, + tokenAddress: await rando.getAddress(), tokenType: TokenType.MultiToken, tokenId: "5150", }); @@ -870,9 +916,9 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation beforeEach(async function () { [bosonToken] = await deployMockTokens(); // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); }); it("👉 createOfferAndTwinWithBundle", async function () { @@ -889,7 +935,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation it("👉 createOfferWithConditionAndTwinAndBundle", async function () { const condition = mockCondition({ - tokenAddress: rando.address, + tokenAddress: await rando.getAddress(), tokenType: TokenType.MultiToken, tokenId: "5150", }); @@ -928,9 +974,18 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation DRs: [, disputeResolver], // take DR that has empty allow list } = preUpgradeEntities; - seller = mockSeller(rando.address, rando.address, rando.address, rando.address, true); + seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + await rando.getAddress(), + await rando.getAddress(), + true + ); disputeResolverId = disputeResolver.id; - expectedCloneAddress = calculateContractAddress(orchestrationHandler.address, sellers.length + 1); + expectedCloneAddress = calculateContractAddress( + await orchestrationHandler.getAddress(), + sellers.length + 1 + ); ({ offer, offerDates, offerDurations } = await mockOffer()); reservedRangeLength = offer.quantityAvailable; @@ -951,7 +1006,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation offerDurations, disputeResolverId, reservedRangeLength, - rando.address, + await rando.getAddress(), authToken, voucherInitValues, agentId @@ -963,18 +1018,18 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation await expect(tx).to.emit(orchestrationHandler, "RangeReserved"); // Voucher clone contract - let bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + let bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged"); await expect(tx).to.emit(bosonVoucher, "RoyaltyPercentageChanged"); await expect(tx).to.emit(bosonVoucher, "RangeReserved"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); // Different ABI + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); // Different ABI await expect(tx).to.emit(bosonVoucher, "OwnershipTransferred"); }); it("👉 createSellerAndPremintedOfferWithCondition", async function () { const condition = mockCondition({ - tokenAddress: rando.address, + tokenAddress: await rando.getAddress(), tokenType: TokenType.MultiToken, tokenId: "5150", }); @@ -988,7 +1043,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation offerDurations, disputeResolverId, reservedRangeLength, - rando.address, + await rando.getAddress(), condition, authToken, voucherInitValues, @@ -1002,12 +1057,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation await expect(tx).to.emit(orchestrationHandler, "GroupCreated"); // Voucher clone contract - let bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + let bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged"); await expect(tx).to.emit(bosonVoucher, "RoyaltyPercentageChanged"); await expect(tx).to.emit(bosonVoucher, "RangeReserved"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "OwnershipTransferred"); }); @@ -1017,9 +1072,9 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation beforeEach(async function () { [bosonToken] = await deployMockTokens(); // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(rando).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(rando).approve(await twinHandler.getAddress(), 1); // approving the twin handler - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); }); it("👉 createSellerAndPremintedOfferAndTwinWithBundle", async function () { @@ -1033,7 +1088,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation offerDurations, disputeResolverId, reservedRangeLength, - rando.address, + await rando.getAddress(), twin, authToken, voucherInitValues, @@ -1048,18 +1103,18 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation await expect(tx).to.emit(orchestrationHandler, "BundleCreated"); // Voucher clone contract - let bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + let bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged"); await expect(tx).to.emit(bosonVoucher, "RoyaltyPercentageChanged"); await expect(tx).to.emit(bosonVoucher, "RangeReserved"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "OwnershipTransferred"); }); it("👉 createSellerAndPremintedOfferWithConditionAndTwinAndBundle", async function () { const condition = mockCondition({ - tokenAddress: rando.address, + tokenAddress: await rando.getAddress(), tokenType: TokenType.MultiToken, tokenId: "5150", }); @@ -1074,7 +1129,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation offerDurations, disputeResolverId, reservedRangeLength, - rando.address, + await rando.getAddress(), condition, twin, authToken, @@ -1091,12 +1146,12 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation await expect(tx).to.emit(orchestrationHandler, "BundleCreated"); // Voucher clone contract - let bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + let bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "ContractURIChanged"); await expect(tx).to.emit(bosonVoucher, "RoyaltyPercentageChanged"); await expect(tx).to.emit(bosonVoucher, "RangeReserved"); - bosonVoucher = await ethers.getContractAt("OwnableUpgradeable", expectedCloneAddress); + bosonVoucher = await getContractAt("OwnableUpgradeable", expectedCloneAddress); await expect(tx).to.emit(bosonVoucher, "OwnershipTransferred"); }); }); @@ -1120,13 +1175,13 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation assistant = seller.wallet; // Voucher clone contract - const expectedCloneAddress = calculateContractAddress(accountHandler.address, "1"); - bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + const expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), "1"); + bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); }); it("👉 createPremintedOfferWithCondition", async function () { const condition = mockCondition({ - tokenAddress: rando.address, + tokenAddress: await rando.getAddress(), tokenType: TokenType.MultiToken, tokenId: "5150", }); @@ -1139,7 +1194,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation offerDurations, disputeResolverId, reservedRangeLength, - assistant.address, + await assistant.getAddress(), condition, agentId ); @@ -1159,7 +1214,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation offerDurations, disputeResolverId, reservedRangeLength, - assistant.address, + await assistant.getAddress(), "1", // seller already has a group with id 1 (from populateProtocolContract) agentId ); @@ -1177,9 +1232,9 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation beforeEach(async function () { [bosonToken] = await deployMockTokens(); // Approving the twinHandler contract to transfer seller's tokens - await bosonToken.connect(assistant).approve(twinHandler.address, 1); // approving the twin handler + await bosonToken.connect(assistant).approve(await twinHandler.getAddress(), 1); // approving the twin handler - twin = mockTwin(bosonToken.address); + twin = mockTwin(await bosonToken.getAddress()); }); it("👉 createPremintedOfferAndTwinWithBundle", async function () { @@ -1192,7 +1247,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation offerDurations, disputeResolverId, reservedRangeLength, - assistant.address, + await assistant.getAddress(), twin, agentId ); @@ -1207,7 +1262,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation it("👉 createPremintedOfferWithConditionAndTwinAndBundle", async function () { const condition = mockCondition({ - tokenAddress: rando.address, + tokenAddress: await rando.getAddress(), tokenType: TokenType.MultiToken, tokenId: "5150", }); @@ -1221,7 +1276,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation offerDurations, disputeResolverId, reservedRangeLength, - assistant.address, + await assistant.getAddress(), condition, twin, agentId @@ -1263,20 +1318,22 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation const tokenId = deriveTokenId(offer.id, exchangeId); // Reserve range - await offerHandler.connect(assistant).reserveRange(offer.id, offer.quantityAvailable, assistant.address); + await offerHandler + .connect(assistant) + .reserveRange(offer.id, offer.quantityAvailable, await assistant.getAddress()); // TODO: remove this once newVersion is 2.2.0 (not 2.2.0-rc.1) await configHandler.connect(deployer).setMaxPremintedVouchers(100); // Boson voucher contract address const sellerIndex = sellers.findIndex((s) => s.id === seller.id); - const voucherCloneAddress = calculateContractAddress(accountHandler.address, sellerIndex + 1); - const bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherCloneAddress); + const voucherCloneAddress = calculateContractAddress(await accountHandler.getAddress(), sellerIndex + 1); + const bosonVoucher = await getContractAt("BosonVoucher", voucherCloneAddress); await bosonVoucher.connect(assistant).preMint(offer.id, offer.quantityAvailable); // Commit to preminted offer, testing for the event await expect( - bosonVoucher.connect(assistant).transferFrom(assistant.address, buyer.wallet.address, tokenId) + bosonVoucher.connect(assistant).transferFrom(await assistant.getAddress(), buyer.wallet, tokenId) ).to.emit(exchangeHandler, "BuyerCommitted"); }); }); @@ -1285,18 +1342,22 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation it("👉 reserveRange for assistant", async function () { // Reserve range await expect( - offerHandler.connect(assistant).reserveRange(offer.id, offer.quantityAvailable, assistant.address) + offerHandler + .connect(assistant) + .reserveRange(offer.id, offer.quantityAvailable, await assistant.getAddress()) ).to.emit(offerHandler, "RangeReserved"); }); it("👉 reserveRange to contract", async function () { // Voucher contract const sellerIndex = sellers.findIndex((s) => s.id === seller.id); - const expectedCloneAddress = calculateContractAddress(accountHandler.address, sellerIndex + 1); - const bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + const expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), sellerIndex + 1); + const bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); await expect( - offerHandler.connect(assistant).reserveRange(offer.id, offer.quantityAvailable, bosonVoucher.address) + offerHandler + .connect(assistant) + .reserveRange(offer.id, offer.quantityAvailable, await bosonVoucher.getAddress()) ).to.emit(offerHandler, "RangeReserved"); }); }); @@ -1318,7 +1379,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation twin.id = "666"; // Approve twinHandler to transfer assistant tokens - await mockToken.connect(assistant).approve(twinHandler.address, twin.amount); + await mockToken.connect(assistant).approve(await twinHandler.getAddress(), twin.amount); // Create twin await twinHandler.connect(assistant).createTwin(twin); @@ -1349,14 +1410,14 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation // Reserve range const length = "1"; - const tx = await offerHandler.connect(assistant).reserveRange(offerId, length, assistant.address); + const tx = await offerHandler.connect(assistant).reserveRange(offerId, length, await assistant.getAddress()); const { events } = await tx.wait(); const { startExchangeId } = events.find((e) => e.event === "RangeReserved").args; // Find voucher contract const sellerIndex = sellers.findIndex((s) => s.id === seller.id); - const expectedCloneAddress = calculateContractAddress(accountHandler.address, sellerIndex + 1); - const bosonVoucher = await ethers.getContractAt("IBosonVoucher", expectedCloneAddress); + const expectedCloneAddress = calculateContractAddress(await accountHandler.getAddress(), sellerIndex + 1); + const bosonVoucher = await getContractAt("IBosonVoucher", expectedCloneAddress); // Premint await bosonVoucher.connect(assistant).preMint(offerId, 1); diff --git a/test/upgrade/2.2.0-2.2.1.js b/test/upgrade/2.2.0-2.2.1.js index 149d49410..11d96159d 100644 --- a/test/upgrade/2.2.0-2.2.1.js +++ b/test/upgrade/2.2.0-2.2.1.js @@ -1,6 +1,7 @@ const hre = require("hardhat"); const { RevertReasons } = require("../../scripts/config/revert-reasons.js"); -const ethers = hre.ethers; +const { getSigners, getContractAt } = hre.ethers; + const { getSnapshot, revertToSnapshot } = require("../util/utils"); const { getStateModifyingFunctionsHashes } = require("../../scripts/util/diamond-utils.js"); @@ -36,7 +37,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation before(async function () { try { // Make accounts available - [deployer, rando] = await ethers.getSigners(); + [deployer, rando] = await getSigners(); let contractsBefore; @@ -86,7 +87,7 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation contractsAfter = { ...contractsBefore }; for (const [handlerName, interfaceName] of Object.entries(newHandlers)) { - contractsAfter[handlerName] = await ethers.getContractAt(interfaceName, protocolDiamondAddress); + contractsAfter[handlerName] = await getContractAt(interfaceName, protocolDiamondAddress); } ({ accountHandler } = contractsAfter); @@ -215,7 +216,14 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation it("New seller has metadataUri field", async function () { const { nextAccountId } = accountContractState; - const seller = mockSeller(rando.address, rando.address, rando.address, rando.address, true, "metadata"); + const seller = mockSeller( + await rando.getAddress(), + await rando.getAddress(), + await rando.getAddress(), + await rando.getAddress(), + true, + "metadata" + ); const authToken = mockAuthToken(); const voucherInitValues = mockVoucherInitValues(); @@ -225,9 +233,9 @@ describe("[@skip-on-coverage] After facet upgrade, everything is still operation .withArgs( nextAccountId, seller, - calculateContractAddress(accountHandler.address, nextAccountId), + calculateContractAddress(await accountHandler.getAddress(), nextAccountId), authToken, - rando.address + await rando.getAddress() ); }); }); diff --git a/test/upgrade/clients/01_generic.js b/test/upgrade/clients/01_generic.js index a986e43b9..874738474 100644 --- a/test/upgrade/clients/01_generic.js +++ b/test/upgrade/clients/01_generic.js @@ -1,5 +1,4 @@ const shell = require("shelljs"); -const { ethers } = require("hardhat"); const { assert } = require("chai"); const { getStorageLayout, @@ -80,18 +79,18 @@ function getGenericContext( // loop matches the loop in populateVoucherContract for (let j = i; j < buyers.length; j++) { const offer = preUpgradeEntities.offers[i + j].offer; - const sellerId = ethers.BigNumber.from(offer.sellerId).toHexString(); + const sellerId = BigInt(offer.sellerId).toString(); // Find the voucher data for the seller const voucherData = voucherContractStateAfterUpgradeAndActions.find( - (vd) => vd.sellerId.toHexString() == sellerId + (vd) => vd.sellerId.toString() == sellerId ); const buyerWallet = buyers[j].wallet; - const buyerIndex = entities.findIndex((e) => e.wallet.address == buyerWallet.address); + const buyerIndex = entities.findIndex((e) => e.wallet == buyerWallet); // Update the balance of the buyer - voucherData.balanceOf[buyerIndex] = voucherData.balanceOf[buyerIndex].sub(1); + voucherData.balanceOf[buyerIndex] = voucherData.balanceOf[buyerIndex] - 1; } } diff --git a/test/upgrade/clients/BosonVoucher-2.1.0-2.2.0.js b/test/upgrade/clients/BosonVoucher-2.1.0-2.2.0.js index d2449bf2b..ce7c8c67a 100644 --- a/test/upgrade/clients/BosonVoucher-2.1.0-2.2.0.js +++ b/test/upgrade/clients/BosonVoucher-2.1.0-2.2.0.js @@ -1,5 +1,6 @@ const hre = require("hardhat"); const ethers = hre.ethers; +const { parseUnits, ZeroAddress, getSigners, Contract, getContractAt, getContractFactory } = ethers; const { assert, expect } = require("chai"); const { deploySuite, @@ -61,7 +62,7 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio before(async function () { try { // Make accounts available - [deployer, assistant, rando] = await ethers.getSigners(); + [deployer, assistant, rando] = await getSigners(); // temporary update config, so compiler outputs storage layout for (const compiler of hre.config.solidity.compilers) { @@ -158,10 +159,10 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio // Create a seller sellerId = await accountHandler.getNextAccountId(); const seller = mockSeller( - assistant.address, - assistant.address, - ethers.constants.AddressZero, - assistant.address, + await assistant.getAddress(), + await assistant.getAddress(), + ZeroAddress, + await assistant.getAddress(), true ); const voucherInitValues = mockVoucherInitValues(); @@ -173,14 +174,14 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio // Create a valid dispute resolver disputeResolverId = await accountHandler.getNextAccountId(); const disputeResolver = mockDisputeResolver( - assistant.address, - assistant.address, - assistant.address, - assistant.address, + await assistant.getAddress(), + await assistant.getAddress(), + await assistant.getAddress(), + await assistant.getAddress(), true, true ); - const disputeResolverFees = [new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0")]; + const disputeResolverFees = [new DisputeResolverFee(ZeroAddress, "Native", "0")]; const sellerAllowList = []; await accountHandler .connect(assistant) @@ -197,15 +198,15 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio await fundsHandler .connect(assistant) - .depositFunds(sellerId, ethers.constants.AddressZero, offer.sellerDeposit, { value: offer.sellerDeposit }); + .depositFunds(sellerId, ZeroAddress, offer.sellerDeposit, { value: offer.sellerDeposit }); start = await exchangeHandler.getNextExchangeId(); length = "80"; amount = "50"; // amount to mint - bosonVoucher = await ethers.getContractAt( + bosonVoucher = await getContractAt( "BosonVoucher", - calculateContractAddress(exchangeHandler.address, preUpgradeEntities.sellers.length + 1) + calculateContractAddress(await exchangeHandler.getAddress(), preUpgradeEntities.sellers.length + 1) ); // Adjust maximum preminted vouchers @@ -214,7 +215,7 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio it("reserveRange()", async function () { // Reserve range for the assistant, test for event - await expect(offerHandler.connect(assistant).reserveRange(offerId, length, assistant.address)).to.emit( + await expect(offerHandler.connect(assistant).reserveRange(offerId, length, await assistant.getAddress())).to.emit( bosonVoucher, "RangeReserved" ); @@ -226,16 +227,15 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio ++offerId; // Reserve range for the contract, test for event - await expect(offerHandler.connect(assistant).reserveRange(offerId, length, bosonVoucher.address)).to.emit( - bosonVoucher, - "RangeReserved" - ); + await expect( + offerHandler.connect(assistant).reserveRange(offerId, length, await bosonVoucher.getAddress()) + ).to.emit(bosonVoucher, "RangeReserved"); }); context("preMint()", async function () { it("seller can pre mint vouchers", async function () { // Reserve range - await offerHandler.connect(assistant).reserveRange(offerId, length, assistant.address); + await offerHandler.connect(assistant).reserveRange(offerId, length, await assistant.getAddress()); // Premint tokens, test for event await expect(bosonVoucher.connect(assistant).preMint(offerId, amount)).to.emit(bosonVoucher, "Transfer"); @@ -253,21 +253,21 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio } = preUpgradeEntities.sellers[sellersLength - 1]; // reassign assistant because signer must be on provider default accounts in order to call eth_signTypedData_v4 - assistant = (await ethers.getSigners())[2]; - seller.assistant = assistant.address; + assistant = (await getSigners())[2]; + seller.assistant = await assistant.getAddress(); await accountHandler.connect(wallet).updateSeller(seller, authToken); await accountHandler.connect(assistant).optInToSellerUpdate(seller.id, [SellerUpdateFields.Assistant]); // Reserve range - await offerHandler.connect(assistant).reserveRange(offerId, length, assistant.address); + await offerHandler.connect(assistant).reserveRange(offerId, length, await assistant.getAddress()); // Get last seller voucher - bosonVoucher = await ethers.getContractAt( + bosonVoucher = await getContractAt( "BosonVoucher", - calculateContractAddress(exchangeHandler.address, sellersLength) + calculateContractAddress(await exchangeHandler.getAddress(), sellersLength) ); - const nonce = Number(await forwarder.getNonce(assistant.address)); + const nonce = Number(await forwarder.getNonce(await assistant.getAddress())); const types = { ForwardRequest: [ @@ -281,8 +281,8 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio const functionSignature = bosonVoucher.interface.encodeFunctionData("preMint", [offerId, amount]); const message = { - from: assistant.address, - to: bosonVoucher.address, + from: await assistant.getAddress(), + to: await bosonVoucher.getAddress(), nonce: nonce, data: functionSignature, }; @@ -292,7 +292,7 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio types, "ForwardRequest", message, - forwarder.address, + await forwarder.getAddress(), "MockForwarder", "0.0.1", "0Z" @@ -305,7 +305,7 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio it("burnPremintedVouchers()", async function () { // Reserve range and premint tokens - await offerHandler.connect(assistant).reserveRange(offerId, length, assistant.address); + await offerHandler.connect(assistant).reserveRange(offerId, length, await assistant.getAddress()); await bosonVoucher.connect(assistant).preMint(offerId, amount); // void the offer @@ -317,10 +317,10 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio it("getRange()", async function () { // Reserve range - await offerHandler.connect(assistant).reserveRange(offerId, length, assistant.address); + await offerHandler.connect(assistant).reserveRange(offerId, length, await assistant.getAddress()); const startTokenId = deriveTokenId(offerId, start); - const range = new Range(startTokenId.toString(), length, "0", "0", assistant.address); + const range = new Range(startTokenId.toString(), length, "0", "0", await assistant.getAddress()); // Get range object from contract const returnedRange = Range.fromStruct(await bosonVoucher.getRangeByOfferId(offerId)); @@ -329,7 +329,7 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio it("getAvailablePreMints()", async function () { // Reserve range - await offerHandler.connect(assistant).reserveRange(offerId, length, assistant.address); + await offerHandler.connect(assistant).reserveRange(offerId, length, await assistant.getAddress()); // Get available premints from contract const availablePremints = await bosonVoucher.getAvailablePreMints(offerId); @@ -338,48 +338,49 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio it("callExternalContract()", async function () { // Deploy a random contract - const MockSimpleContract = await ethers.getContractFactory("MockSimpleContract"); + const MockSimpleContract = await getContractFactory("MockSimpleContract"); const mockSimpleContract = await MockSimpleContract.deploy(); await mockSimpleContract.deployed(); // Generate calldata const calldata = mockSimpleContract.interface.encodeFunctionData("testEvent"); - await expect(bosonVoucher.connect(assistant).callExternalContract(mockSimpleContract.address, calldata)) + await expect( + bosonVoucher.connect(assistant).callExternalContract(await mockSimpleContract.getAddress(), calldata) + ) .to.emit(mockSimpleContract, "TestEvent") .withArgs("1"); }); it("setApprovalForAllToContract()", async function () { - await expect(bosonVoucher.connect(assistant).setApprovalForAllToContract(rando.address, true)) + await expect(bosonVoucher.connect(assistant).setApprovalForAllToContract(await rando.getAddress(), true)) .to.emit(bosonVoucher, "ApprovalForAll") - .withArgs(bosonVoucher.address, rando.address, true); + .withArgs(await bosonVoucher.getAddress(), await rando.getAddress(), true); }); context("withdrawToProtocol()", async function () { beforeEach(async function () { - // For some reason, ethers.getContractAt and changeEtherBalances don't work together, so we need to explicitly instantiate the contract - bosonVoucher = new ethers.Contract(bosonVoucher.address, bosonVoucher.interface, deployer); + // For some reason, getContractAt and changeEtherBalances don't work together, so we need to explicitly instantiate the contract + bosonVoucher = new Contract(await bosonVoucher.getAddress(), bosonVoucher.interface, deployer); }); it("Can withdraw native token", async function () { // Sellers initial available funds const sellersFundsBefore = FundsList.fromStruct(await fundsHandler.getAvailableFunds(sellerId)); - let expectedAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", offer.sellerDeposit), - ]); + let expectedAvailableFunds = new FundsList([new Funds(ZeroAddress, "Native currency", offer.sellerDeposit)]); expect(sellersFundsBefore).to.eql(expectedAvailableFunds); - const amount = ethers.utils.parseUnits("1", "ether"); - await deployer.sendTransaction({ to: bosonVoucher.address, value: amount }); + const amount = parseUnits("1", "ether"); + await deployer.sendTransaction({ to: await bosonVoucher.getAddress(), value: amount }); - await expect(() => - bosonVoucher.connect(rando).withdrawToProtocol([ethers.constants.AddressZero]) - ).to.changeEtherBalances([bosonVoucher, fundsHandler], [amount.mul(-1), amount]); + await expect(() => bosonVoucher.connect(rando).withdrawToProtocol([ZeroAddress])).to.changeEtherBalances( + [bosonVoucher, fundsHandler], + [amount * -1, amount] + ); // Seller's available balance should increase expectedAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", amount.add(offer.sellerDeposit).toString()), + new Funds(ZeroAddress, "Native currency", amount + offer.sellerDeposit.toString()), ]); const sellerFundsAfter = FundsList.fromStruct(await fundsHandler.getAvailableFunds(sellerId)); expect(sellerFundsAfter).to.eql(expectedAvailableFunds); @@ -388,25 +389,24 @@ describe("[@skip-on-coverage] After client upgrade, everything is still operatio it("Can withdraw ERC20", async function () { // Sellers initial available funds const sellersFundsBefore = FundsList.fromStruct(await fundsHandler.getAvailableFunds(sellerId)); - let expectedAvailableFunds = new FundsList([ - new Funds(ethers.constants.AddressZero, "Native currency", offer.sellerDeposit), - ]); + let expectedAvailableFunds = new FundsList([new Funds(ZeroAddress, "Native currency", offer.sellerDeposit)]); expect(sellersFundsBefore).to.eql(expectedAvailableFunds); const [foreign20] = await deployMockTokens(["Foreign20"]); - const amount = ethers.utils.parseUnits("1", "ether"); - await foreign20.connect(deployer).mint(deployer.address, amount); - await foreign20.connect(deployer).transfer(bosonVoucher.address, amount); + const amount = parseUnits("1", "ether"); + await foreign20.connect(deployer).mint(await deployer.getAddress(), amount); + await foreign20.connect(deployer).transfer(await bosonVoucher.getAddress(), amount); - await expect(() => bosonVoucher.connect(rando).withdrawToProtocol([foreign20.address])).to.changeTokenBalances( + const foreign20Address = await foreign20.getAddress(); + await expect(() => bosonVoucher.connect(rando).withdrawToProtocol([foreign20Address])).to.changeTokenBalances( foreign20, [bosonVoucher, fundsHandler], - [amount.mul(-1), amount] + [amount * -1, amount] ); // Seller's available balance should increase - expectedAvailableFunds.funds.push(new Funds(foreign20.address, "Foreign20", amount.toString())); + expectedAvailableFunds.funds.push(new Funds(await foreign20.getAddress(), "Foreign20", amount.toString())); const sellerFundsAfter = FundsList.fromStruct(await fundsHandler.getAvailableFunds(sellerId)); expect(sellerFundsAfter).to.eql(expectedAvailableFunds); }); diff --git a/test/util/constants.js b/test/util/constants.js index eaa521d5e..1fdd7a2c2 100644 --- a/test/util/constants.js +++ b/test/util/constants.js @@ -1,18 +1,16 @@ const environments = require("../../environments"); -const hre = require("hardhat"); -const ethers = hre.ethers; // Some periods in seconds -const oneDay = 86400; // 1 day in seconds -const ninetyDays = oneDay * 90; // 90 days in seconds -const oneWeek = oneDay * 7; // 7 days in seconds -const oneMonth = oneDay * 31; // 31 days in seconds +const oneDay = 86400n; // 1 day in seconds +const ninetyDays = oneDay * 90n; // 90 days in seconds +const oneWeek = oneDay * 7n; // 7 days in seconds +const oneMonth = oneDay * 31n; // 31 days in seconds const VOUCHER_NAME = "Boson Voucher (rNFT)"; const VOUCHER_SYMBOL = "BOSON_VOUCHER_RNFT"; const SEAPORT_ADDRESS = "0x00000000000001ad428e4906aE43D8F9852d0dD6"; // 1.4 -const tipMultiplier = ethers.BigNumber.from(environments.tipMultiplier); +const tipMultiplier = BigInt(environments.tipMultiplier); const tipSuggestion = "1500000000"; // ethers.js always returns this constant, it does not vary per block -const maxPriorityFeePerGas = ethers.BigNumber.from(tipSuggestion).mul(tipMultiplier); +const maxPriorityFeePerGas = BigInt(tipSuggestion) * tipMultiplier; exports.oneDay = oneDay; exports.ninetyDays = ninetyDays; diff --git a/test/util/mock.js b/test/util/mock.js index fdf913b81..cc18ff4d3 100644 --- a/test/util/mock.js +++ b/test/util/mock.js @@ -1,5 +1,5 @@ const hre = require("hardhat"); -const ethers = hre.ethers; +const { ZeroAddress, provider, parseUnits } = hre.ethers; const decache = require("decache"); const Condition = require("../../scripts/domain/Condition"); @@ -50,14 +50,12 @@ function mockOfferDurations() { async function mockOfferDates() { // Get the current block info - const blockNumber = await ethers.provider.getBlockNumber(); - const block = await ethers.provider.getBlock(blockNumber); + const blockNumber = await provider.getBlockNumber(); + const block = await provider.getBlock(blockNumber); - const validFrom = ethers.BigNumber.from(block.timestamp).toString(); // valid from now - const validUntil = ethers.BigNumber.from(block.timestamp) - .add(oneMonth * 6) - .toString(); // until 6 months - const voucherRedeemableFrom = ethers.BigNumber.from(block.timestamp).add(oneWeek).toString(); // redeemable in 1 week + const validFrom = BigInt(block.timestamp).toString(); // valid from now + const validUntil = (BigInt(block.timestamp) + BigInt(oneMonth) * BigInt(6)).toString(); // until 6 months + const voucherRedeemableFrom = (BigInt(block.timestamp) + BigInt(oneWeek)).toString(); // redeemable in 1 week const voucherRedeemableUntil = "0"; // mocks use voucher valid duration rather than fixed date, override in tests as needed // Create a valid offerDates, then set fields in tests directly @@ -68,12 +66,12 @@ async function mockOfferDates() { async function mockOffer() { const id = "1"; const sellerId = "1"; // argument sent to contract for createOffer will be ignored - const price = ethers.utils.parseUnits("1.5", "ether").toString(); - const sellerDeposit = ethers.utils.parseUnits("0.25", "ether").toString(); + const price = parseUnits("1.5", "ether").toString(); + const sellerDeposit = parseUnits("0.25", "ether").toString(); const protocolFee = applyPercentage(price, "200"); - const buyerCancelPenalty = ethers.utils.parseUnits("0.05", "ether").toString(); + const buyerCancelPenalty = parseUnits("0.05", "ether").toString(); const quantityAvailable = "1"; - const exchangeToken = ethers.constants.AddressZero.toString(); // Zero addy ~ chain base currency + const exchangeToken = ZeroAddress.toString(); // Zero addy ~ chain base currency const metadataHash = "QmYXc12ov6F2MZVZwPs5XeCBbf61cW3wKRk8h3D5NTYj4T"; // not an actual metadataHash, just some data for tests const metadataUri = `https://ipfs.io/ipfs/${metadataHash}`; const voided = false; @@ -164,7 +162,7 @@ function mockAgent(wallet) { } function mockOfferFees(protocolFee, agentFee) { - return new OfferFees(protocolFee, agentFee); + return new OfferFees(protocolFee.toString(), agentFee.toString()); } function mockVoucherInitValues() { @@ -221,7 +219,7 @@ async function mockReceipt() { const buyerId = "1"; const sellerId = "2"; const agentId = "3"; - const twinReceipt = mockTwinReceipt(ethers.constants.AddressZero); + const twinReceipt = mockTwinReceipt(ZeroAddress); return new Receipt( exchange.id, @@ -251,7 +249,7 @@ function mockCondition({ method, tokenType, tokenAddress, tokenId, threshold, ma return new Condition( method ?? EvaluationMethod.Threshold, tokenType ?? TokenType.FungibleToken, - tokenAddress ?? ethers.constants.AddressZero, + tokenAddress ?? ZeroAddress, tokenId ?? "0", threshold ?? "1", maxCommits ?? "1" diff --git a/test/util/upgrade.js b/test/util/upgrade.js index 9979ef44c..48389f0cf 100644 --- a/test/util/upgrade.js +++ b/test/util/upgrade.js @@ -2,8 +2,18 @@ const shell = require("shelljs"); const _ = require("lodash"); const { getStorageAt } = require("@nomicfoundation/hardhat-network-helpers"); const hre = require("hardhat"); -const ethers = hre.ethers; -const { keccak256, formatBytes32String } = ethers.utils; +const { + keccak256, + formatBytes32String, + ZeroAddress, + getContractAt, + Wallet, + provider, + parseEther, + toUtf8Bytes, + getContractFactory, + getSigners, +} = hre.ethers; const AuthToken = require("../../scripts/domain/AuthToken"); const { getMetaTransactionsHandlerFacetInitArgs } = require("../../scripts/config/facet-deploy.js"); const AuthTokenType = require("../../scripts/domain/AuthTokenType"); @@ -78,16 +88,18 @@ async function deploySuite(deployer, newVersion) { // checkout old version const { oldVersion: tag, deployScript: scriptsTag } = versionTags; + console.log("only", versionTags); console.log(`Fetching tags`); shell.exec(`git fetch --force --tags origin`); console.log(`Checking out version ${tag}`); shell.exec(`rm -rf contracts/*`); - shell.exec(`git checkout ${tag} contracts`); + shell.exec(`find contracts -type f | xargs git checkout ${tag} --`); + if (scriptsTag) { console.log(`Checking out scripts on version ${scriptsTag}`); shell.exec(`rm -rf scripts/*`); - shell.exec(`git checkout ${scriptsTag} scripts`); + shell.exec(`git checkout ${scriptsTag} scripts/**`); } const deployConfig = facets.deploy[tag]; @@ -96,6 +108,7 @@ async function deploySuite(deployer, newVersion) { throw new Error(`No deploy config found for tag ${tag}`); } + await hre.run("compile"); // run deploy suite, which automatically compiles the contracts await hre.run("deploy-suite", { env: "upgrade-test", @@ -104,15 +117,15 @@ async function deploySuite(deployer, newVersion) { }); // Read contract info from file - const chainId = (await hre.ethers.provider.getNetwork()).chainId; + const chainId = (await provider.getNetwork()).chainId; const contractsFile = readContracts(chainId, "hardhat", "upgrade-test"); // Get AccessController abstraction const accessControllerInfo = contractsFile.contracts.find((i) => i.name === "AccessController"); - const accessController = await ethers.getContractAt("AccessController", accessControllerInfo.address); + const accessController = await getContractAt("AccessController", accessControllerInfo.address); // Temporarily grant UPGRADER role to deployer account - await accessController.grantRole(Role.UPGRADER, deployer.address); + await accessController.grantRole(Role.UPGRADER, await deployer.getAddress()); // Get protocolDiamondAddress const protocolDiamondAddress = contractsFile.contracts.find((i) => i.name === "ProtocolDiamond").address; @@ -121,27 +134,27 @@ async function deploySuite(deployer, newVersion) { await accessController.grantRole(Role.PROTOCOL, protocolDiamondAddress); // Cast Diamond to interfaces - const accountHandler = await ethers.getContractAt("IBosonAccountHandler", protocolDiamondAddress); - const bundleHandler = await ethers.getContractAt("IBosonBundleHandler", protocolDiamondAddress); - const disputeHandler = await ethers.getContractAt("IBosonDisputeHandler", protocolDiamondAddress); - const exchangeHandler = await ethers.getContractAt("IBosonExchangeHandler", protocolDiamondAddress); - const fundsHandler = await ethers.getContractAt("IBosonFundsHandler", protocolDiamondAddress); - const groupHandler = await ethers.getContractAt("IBosonGroupHandler", protocolDiamondAddress); - const offerHandler = await ethers.getContractAt("IBosonOfferHandler", protocolDiamondAddress); - const orchestrationHandler = await ethers.getContractAt("IBosonOrchestrationHandler", protocolDiamondAddress); - const twinHandler = await ethers.getContractAt("IBosonTwinHandler", protocolDiamondAddress); - const pauseHandler = await ethers.getContractAt("IBosonPauseHandler", protocolDiamondAddress); - const metaTransactionsHandler = await ethers.getContractAt("IBosonMetaTransactionsHandler", protocolDiamondAddress); - const configHandler = await ethers.getContractAt("IBosonConfigHandler", protocolDiamondAddress); - const ERC165Facet = await ethers.getContractAt("ERC165Facet", protocolDiamondAddress); - const protocolInitializationHandler = await ethers.getContractAt( + const accountHandler = await getContractAt("IBosonAccountHandler", protocolDiamondAddress); + const bundleHandler = await getContractAt("IBosonBundleHandler", protocolDiamondAddress); + const disputeHandler = await getContractAt("IBosonDisputeHandler", protocolDiamondAddress); + const exchangeHandler = await getContractAt("IBosonExchangeHandler", protocolDiamondAddress); + const fundsHandler = await getContractAt("IBosonFundsHandler", protocolDiamondAddress); + const groupHandler = await getContractAt("IBosonGroupHandler", protocolDiamondAddress); + const offerHandler = await getContractAt("IBosonOfferHandler", protocolDiamondAddress); + const orchestrationHandler = await getContractAt("IBosonOrchestrationHandler", protocolDiamondAddress); + const twinHandler = await getContractAt("IBosonTwinHandler", protocolDiamondAddress); + const pauseHandler = await getContractAt("IBosonPauseHandler", protocolDiamondAddress); + const metaTransactionsHandler = await getContractAt("IBosonMetaTransactionsHandler", protocolDiamondAddress); + const configHandler = await getContractAt("IBosonConfigHandler", protocolDiamondAddress); + const ERC165Facet = await getContractAt("ERC165Facet", protocolDiamondAddress); + const protocolInitializationHandler = await getContractAt( "IBosonProtocolInitializationHandler", protocolDiamondAddress ); // create mock token for auth const [mockAuthERC721Contract] = await deployMockTokens(["Foreign721"]); - configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.Lens, mockAuthERC721Contract.address); + configHandler.connect(deployer).setAuthTokenContract(AuthTokenType.Lens, await mockAuthERC721Contract.getAddress()); // create mock token for offers const [mockToken, mockConditionalToken, mockTwin721_1, mockTwin721_2, mockTwin20, mockTwin1155] = @@ -223,7 +236,7 @@ async function upgradeSuite(protocolDiamondAddress, upgradedInterfaces, override // Cast to updated interface let newHandlers = {}; for (const [handlerName, interfaceName] of Object.entries(upgradedInterfaces)) { - newHandlers[handlerName] = await ethers.getContractAt(interfaceName, protocolDiamondAddress); + newHandlers[handlerName] = await getContractAt(interfaceName, protocolDiamondAddress); } return newHandlers; @@ -242,13 +255,13 @@ async function upgradeClients() { await hre.run("compile"); // Mock forwarder to test metatx - const MockForwarder = await ethers.getContractFactory("MockForwarder"); + const MockForwarder = await getContractFactory("MockForwarder"); const forwarder = await MockForwarder.deploy(); const clientConfig = { META_TRANSACTION_FORWARDER: { - hardhat: forwarder.address, + hardhat: await forwarder.getAddress(), }, }; @@ -328,13 +341,13 @@ async function populateProtocolContract( let voucherIndex = 1; for (const entity of entities) { - const wallet = ethers.Wallet.createRandom(); - const connectedWallet = wallet.connect(ethers.provider); + const wallet = Wallet.createRandom(); + const connectedWallet = wallet.connect(provider); //Fund the new wallet let tx = { - to: connectedWallet.address, + to: await connectedWallet.getAddress(), // Convert currency unit from ether to wei - value: ethers.utils.parseEther("10"), + value: parseEther("10"), }; await deployer.sendTransaction(tx); @@ -342,19 +355,19 @@ async function populateProtocolContract( switch (entity) { case entityType.DR: { const clerkAddress = versionsWithClerkRole.includes(isBefore ? versionTags.oldVersion : versionTags.newVersion) - ? wallet.address - : ethers.constants.AddressZero; + ? await wallet.getAddress() + : ZeroAddress; const disputeResolver = mockDisputeResolver( - wallet.address, - wallet.address, + await wallet.getAddress(), + await wallet.getAddress(), clerkAddress, - wallet.address, + await wallet.getAddress(), true, true ); const disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0"), - new DisputeResolverFee(mockToken.address, "MockToken", "0"), + new DisputeResolverFee(ZeroAddress, "Native", "0"), + new DisputeResolverFee(await mockToken.getAddress(), "MockToken", "0"), ]; const sellerAllowList = []; disputeResolver.id = nextAccountId.toString(); @@ -379,9 +392,15 @@ async function populateProtocolContract( case entityType.SELLER: { const clerkAddress = versionsWithClerkRole.includes(isBefore ? versionTags.oldVersion : versionTags.newVersion) - ? wallet.address - : ethers.constants.AddressZero; - const seller = mockSeller(wallet.address, wallet.address, clerkAddress, wallet.address, true); + ? await wallet.getAddress() + : ZeroAddress; + const seller = mockSeller( + await wallet.getAddress(), + await wallet.getAddress(), + clerkAddress, + await wallet.getAddress(), + true + ); const id = (seller.id = nextAccountId.toString()); let authToken; @@ -392,7 +411,7 @@ async function populateProtocolContract( authToken = mockAuthToken(); } else { // use auth token - seller.admin = ethers.constants.AddressZero; + seller.admin = ZeroAddress; await mockAuthERC721Contract.connect(connectedWallet).mint(101 * id, 1); authToken = new AuthToken(`${101 * id}`, AuthTokenType.Lens); } @@ -400,7 +419,7 @@ async function populateProtocolContract( const voucherInitValues = new VoucherInitValues(`http://seller${id}.com/uri`, id * 10); await accountHandler.connect(connectedWallet).createSeller(seller, authToken, voucherInitValues); - const voucherContractAddress = calculateContractAddress(accountHandler.address, voucherIndex++); + const voucherContractAddress = calculateContractAddress(await accountHandler.getAddress(), voucherIndex++); sellers.push({ wallet: connectedWallet, id, @@ -412,12 +431,12 @@ async function populateProtocolContract( }); // mint mock token to sellers just in case they need them - await mockToken.mint(connectedWallet.address, "10000000000"); + await mockToken.mint(await connectedWallet.getAddress(), "10000000000"); await mockToken.connect(connectedWallet).approve(protocolDiamondAddress, "10000000000"); break; } case entityType.AGENT: { - const agent = mockAgent(wallet.address); + const agent = mockAgent(await wallet.getAddress()); await accountHandler.connect(connectedWallet).createAgent(agent); @@ -427,12 +446,12 @@ async function populateProtocolContract( } case entityType.BUYER: { // no need to explicitly create buyer, since it's done automatically during commitToOffer - const buyer = mockBuyer(wallet.address); + const buyer = mockBuyer(await wallet.getAddress()); buyer.id = nextAccountId.toString(); buyers.push({ wallet: connectedWallet, id: buyer.id, buyer }); // mint them conditional token in case they need it - await mockConditionalToken.mint(wallet.address, "10"); + await mockConditionalToken.mint(await wallet.getAddress(), "10"); break; } } @@ -449,7 +468,7 @@ async function populateProtocolContract( } // create offers - first seller has 5 offers, second 4, third 3 etc - let offerId = (await offerHandler.getNextOfferId()).toNumber(); + let offerId = Number(await offerHandler.getNextOfferId()); for (let i = 0; i < sellers.length; i++) { for (let j = i; j >= 0; j--) { // Mock offer, offerDates and offerDurations @@ -465,17 +484,13 @@ async function populateProtocolContract( // Default offer is in native token. Change every other to mock token if (offerId % 2 == 0) { - offer.exchangeToken = mockToken.address; + offer.exchangeToken = await mockToken.getAddress(); } // Set unique offer dates based on offer id const now = offerDates.validFrom; - offerDates.validFrom = ethers.BigNumber.from(now) - .add(oneMonth + offerId * 1000) - .toString(); - offerDates.validUntil = ethers.BigNumber.from(now) - .add(oneMonth * 6 * (offerId + 1)) - .toString(); + offerDates.validFrom = (BigInt(now) + oneMonth + BigInt(offerId) * 1000n).toString(); + offerDates.validUntil = (BigInt(now) + oneMonth * 6n * BigInt(offerId) + 1n).toString(); // Set unique offerDurations based on offer id offerDurations.disputePeriod = `${(offerId + 1) * oneMonth}`; @@ -495,8 +510,8 @@ async function populateProtocolContract( sellers[j].offerIds.push(offerId); // Deposit seller funds so the commit will succeed - const sellerPool = ethers.BigNumber.from(offer.quantityAvailable).mul(offer.price).toString(); - const msgValue = offer.exchangeToken == ethers.constants.AddressZero ? sellerPool : "0"; + const sellerPool = BigInt(offer.quantityAvailable) * BigInt(offer.price); + const msgValue = offer.exchangeToken == ZeroAddress ? sellerPool : "0"; await fundsHandler .connect(sellers[j].wallet) .depositFunds(sellers[j].seller.id, offer.exchangeToken, sellerPool, { value: msgValue }); @@ -506,12 +521,12 @@ async function populateProtocolContract( } // group some offers - let groupId = (await groupHandler.getNextGroupId()).toNumber(); + let groupId = Number(await groupHandler.getNextGroupId()); for (let i = 0; i < sellers.length; i = i + 2) { const seller = sellers[i]; const group = new Group(groupId, seller.seller.id, seller.offerIds); // group all seller's offers const condition = mockCondition({ - tokenAddress: mockConditionalToken.address, + tokenAddress: await mockConditionalToken.getAddress(), maxCommits: "10", }); await groupHandler.connect(seller.wallet).createGroup(group, condition); @@ -522,8 +537,8 @@ async function populateProtocolContract( } // create some twins and bundles - let twinId = (await twinHandler.getNextTwinId()).toNumber(); - let bundleId = (await bundleHandler.getNextBundleId()).toNumber(); + let twinId = Number(await twinHandler.getNextTwinId()); + let bundleId = Number(await bundleHandler.getNextBundleId()); for (let i = 1; i < sellers.length; i = i + 2) { const seller = sellers[i]; const sellerId = seller.id; @@ -534,7 +549,7 @@ async function populateProtocolContract( await mockTwinTokens[1].connect(seller.wallet).setApprovalForAll(protocolDiamondAddress, true); // create multiple ranges - const twin721 = mockTwin(ethers.constants.AddressZero, TokenType.NonFungibleToken); + const twin721 = mockTwin(ZeroAddress, TokenType.NonFungibleToken); twin721.amount = "0"; // min supply available for twin721 is the total amount to cover all offers bundled @@ -560,7 +575,7 @@ async function populateProtocolContract( } // fungible - const twin20 = mockTwin(mockTwin20.address, TokenType.FungibleToken); + const twin20 = mockTwin(await mockTwin20.getAddress(), TokenType.FungibleToken); twin20.id = twinId; twin20.amount = sellerId; @@ -569,7 +584,7 @@ async function populateProtocolContract( await mockTwin20.connect(seller.wallet).approve(protocolDiamondAddress, twin20.supplyAvailable); // mint tokens to be transferred on redeem - await mockTwin20.connect(seller.wallet).mint(seller.wallet.address, twin20.supplyAvailable * twin20.amount); + await mockTwin20.connect(seller.wallet).mint(seller.wallet, twin20.supplyAvailable * twin20.amount); await twinHandler.connect(seller.wallet).createTwin(twin20); twins.push(twin20); @@ -577,7 +592,7 @@ async function populateProtocolContract( twinId++; // multitoken twin - const twin1155 = mockTwin(mockTwin1155.address, TokenType.MultiToken); + const twin1155 = mockTwin(await mockTwin1155.getAddress(), TokenType.MultiToken); await mockTwin1155.connect(seller.wallet).setApprovalForAll(protocolDiamondAddress, true); for (let j = 0; j < 3; j++) { twin1155.tokenId = `${j * 30000 + sellerId * 300}`; @@ -603,22 +618,24 @@ async function populateProtocolContract( // commit to some offers: first buyer commit to 1 offer, second to 2, third to 3 etc await setNextBlockTimestamp(Number(offers[offers.length - 1].offerDates.validFrom)); // When latest offer is valid, also other offers are valid - let exchangeId = (await exchangeHandler.getNextExchangeId()).toNumber(); + let exchangeId = Number(await exchangeHandler.getNextExchangeId()); for (let i = 0; i < buyers.length; i++) { for (let j = i; j < buyers.length; j++) { const offer = offers[i + j].offer; // some offers will be picked multiple times, some never. const offerPrice = offer.price; const buyerWallet = buyers[j].wallet; let msgValue; - if (offer.exchangeToken == ethers.constants.AddressZero) { + if (offer.exchangeToken == ZeroAddress) { msgValue = offerPrice; } else { // approve token transfer msgValue = 0; await mockToken.connect(buyerWallet).approve(protocolDiamondAddress, offerPrice); - await mockToken.mint(buyerWallet.address, offerPrice); + await mockToken.mint(await buyerWallet.getAddress(), offerPrice); } - await exchangeHandler.connect(buyerWallet).commitToOffer(buyerWallet.address, offer.id, { value: msgValue }); + await exchangeHandler + .connect(buyerWallet) + .commitToOffer(await buyerWallet.getAddress(), offer.id, { value: msgValue }); exchanges.push({ exchangeId: exchangeId, offerId: offer.id, buyerIndex: j }); exchangeId++; } @@ -669,7 +686,7 @@ async function getProtocolContractState( { mockToken, mockTwinTokens }, { DRs, sellers, buyers, agents, offers, exchanges, bundles, groups, twins } ) { - rando = (await ethers.getSigners())[10]; // random account making the calls + rando = (await getSigners())[10]; // random account making the calls const [ accountContractState, @@ -756,7 +773,7 @@ async function getAccountContractState(accountHandler, { DRs, sellers, buyers, a } for (const seller of sellers) { - const sellerAddress = seller.wallet.address; + const sellerAddress = seller.wallet; const sellerAuthToken = seller.authToken; sellerByAddressState.push(await getSeller(accountHandlerRando, sellerAddress, { getBy: "address" })); @@ -767,7 +784,7 @@ async function getAccountContractState(accountHandler, { DRs, sellers, buyers, a const otherAccounts = [...DRs, ...agents, ...buyers]; for (const account of otherAccounts) { - const accountAddress = account.wallet.address; + const accountAddress = account.wallet; sellerByAddressState.push(await getSeller(accountHandlerRando, accountAddress, { getBy: "address" })); DRbyAddressState.push(await getDisputeResolver(accountHandlerRando, accountAddress, { getBy: "address" })); @@ -1033,18 +1050,18 @@ async function getMetaTxPrivateContractState(protocolDiamondAddress) { */ // starting slot - const metaTxStorageSlot = keccak256(ethers.utils.toUtf8Bytes("boson.protocol.metaTransactions")); - const metaTxStorageSlotNumber = ethers.BigNumber.from(metaTxStorageSlot); + const metaTxStorageSlot = keccak256(toUtf8Bytes("boson.protocol.metaTransactions")); + const metaTxStorageSlotNumber = BigInt(metaTxStorageSlot); // current sender address + isMetaTransaction (they are packed since they are shorter than one slot) // should be always be 0x - const inTransactionInfo = await getStorageAt(protocolDiamondAddress, metaTxStorageSlotNumber.add("0")); + const inTransactionInfo = await getStorageAt(protocolDiamondAddress, metaTxStorageSlotNumber + 0n); // domain separator - const domainSeparator = await getStorageAt(protocolDiamondAddress, metaTxStorageSlotNumber.add("1")); + const domainSeparator = await getStorageAt(protocolDiamondAddress, metaTxStorageSlotNumber + 1n); // cached chain id - const cachedChainId = await getStorageAt(protocolDiamondAddress, metaTxStorageSlotNumber.add("3")); + const cachedChainId = await getStorageAt(protocolDiamondAddress, metaTxStorageSlotNumber + 3n); // input type const inputTypeKeys = [ @@ -1061,7 +1078,7 @@ async function getMetaTxPrivateContractState(protocolDiamondAddress) { const inputTypesState = []; for (const inputTypeKey of inputTypeKeys) { - const storageSlot = getMappingStoragePosition(metaTxStorageSlotNumber.add("4"), inputTypeKey, paddingType.NONE); + const storageSlot = getMappingStoragePosition(metaTxStorageSlotNumber + 4n, inputTypeKey, paddingType.NONE); inputTypesState.push(await getStorageAt(protocolDiamondAddress, storageSlot)); } @@ -1077,11 +1094,11 @@ async function getMetaTxPrivateContractState(protocolDiamondAddress) { const hashInfoState = []; for (const hashInfoType of Object.values(hashInfoTypes)) { - const storageSlot = getMappingStoragePosition(metaTxStorageSlotNumber.add("5"), hashInfoType, paddingType.START); + const storageSlot = getMappingStoragePosition(metaTxStorageSlotNumber + 5n, hashInfoType, paddingType.START); // get also hashFunction hashInfoState.push({ typeHash: await getStorageAt(protocolDiamondAddress, storageSlot), - functionPointer: await getStorageAt(protocolDiamondAddress, ethers.BigNumber.from(storageSlot).add(1)), + functionPointer: await getStorageAt(protocolDiamondAddress, BigInt(storageSlot) + 1), }); } const isAllowlistedState = {}; @@ -1108,7 +1125,7 @@ async function getMetaTxPrivateContractState(protocolDiamondAddress) { const selectors = await getMetaTransactionsHandlerFacetInitArgs(facets); for (const selector of Object.values(selectors)) { - const storageSlot = getMappingStoragePosition(metaTxStorageSlotNumber.add("6"), selector, paddingType.START); + const storageSlot = getMappingStoragePosition(metaTxStorageSlotNumber + 6n, selector, paddingType.START); isAllowlistedState[selector] = await getStorageAt(protocolDiamondAddress, storageSlot); } @@ -1127,15 +1144,15 @@ async function getProtocolStatusPrivateContractState(protocolDiamondAddress) { */ // starting slot - const protocolStatusStorageSlot = keccak256(ethers.utils.toUtf8Bytes("boson.protocol.initializers")); - const protocolStatusStorageSlotNumber = ethers.BigNumber.from(protocolStatusStorageSlot); + const protocolStatusStorageSlot = keccak256(toUtf8Bytes("boson.protocol.initializers")); + const protocolStatusStorageSlotNumber = BigInt(protocolStatusStorageSlot); // pause scenario - const pauseScenario = await getStorageAt(protocolDiamondAddress, protocolStatusStorageSlotNumber.add("0")); + const pauseScenario = await getStorageAt(protocolDiamondAddress, protocolStatusStorageSlotNumber + 0n); // reentrancy status // default: NOT_ENTERED = 1 - const reentrancyStatus = await getStorageAt(protocolDiamondAddress, protocolStatusStorageSlotNumber.add("1")); + const reentrancyStatus = await getStorageAt(protocolDiamondAddress, protocolStatusStorageSlotNumber + 1n); // initializedInterfaces if (!preUpgradeInterfaceIds) { @@ -1145,11 +1162,7 @@ async function getProtocolStatusPrivateContractState(protocolDiamondAddress) { const initializedInterfacesState = []; for (const interfaceId of Object.values(preUpgradeInterfaceIds)) { - const storageSlot = getMappingStoragePosition( - protocolStatusStorageSlotNumber.add("2"), - interfaceId, - paddingType.END - ); + const storageSlot = getMappingStoragePosition(protocolStatusStorageSlotNumber + 2n, interfaceId, paddingType.END); initializedInterfacesState.push(await getStorageAt(protocolDiamondAddress, storageSlot)); } @@ -1159,7 +1172,7 @@ async function getProtocolStatusPrivateContractState(protocolDiamondAddress) { const initializedVersionsState = []; for (const version of preUpgradeVersions) { - const storageSlot = getMappingStoragePosition(protocolStatusStorageSlotNumber.add("3"), version, paddingType.END); + const storageSlot = getMappingStoragePosition(protocolStatusStorageSlotNumber + 3n, version, paddingType.END); initializedVersionsState.push(await getStorageAt(protocolDiamondAddress, storageSlot)); } @@ -1210,8 +1223,8 @@ async function getProtocolLookupsPrivateContractState( */ // starting slot - const protocolLookupsSlot = keccak256(ethers.utils.toUtf8Bytes("boson.protocol.lookups")); - const protocolLookupsSlotNumber = ethers.BigNumber.from(protocolLookupsSlot); + const protocolLookupsSlot = keccak256(toUtf8Bytes("boson.protocol.lookups")); + const protocolLookupsSlotNumber = BigInt(protocolLookupsSlot); // exchangeIdsByOffer and groupIdByOffer let exchangeIdsByOfferState = []; @@ -1220,13 +1233,11 @@ async function getProtocolLookupsPrivateContractState( const id = Number(offer.offer.id); // exchangeIdsByOffer let exchangeIdsByOffer = []; - const arraySlot = ethers.BigNumber.from( - getMappingStoragePosition(protocolLookupsSlotNumber.add("0"), id, paddingType.START) - ); - const arrayLength = ethers.BigNumber.from(await getStorageAt(protocolDiamondAddress, arraySlot)).toNumber(); - const arrayStart = ethers.BigNumber.from(keccak256(arraySlot)); - for (let i = 0; i < arrayLength; i++) { - exchangeIdsByOffer.push(await getStorageAt(protocolDiamondAddress, arrayStart.add(i))); + const arraySlot = BigInt(getMappingStoragePosition(protocolLookupsSlotNumber + 0n, id, paddingType.START)); + const arrayLength = await getStorageAt(protocolDiamondAddress, arraySlot); + const arrayStart = keccak256(arraySlot); + for (let i = 0n; i < arrayLength; i++) { + exchangeIdsByOffer.push(await getStorageAt(protocolDiamondAddress, arrayStart + i)); } exchangeIdsByOfferState.push(exchangeIdsByOffer); @@ -1234,7 +1245,7 @@ async function getProtocolLookupsPrivateContractState( groupIdByOfferState.push( await getStorageAt( protocolDiamondAddress, - getMappingStoragePosition(protocolLookupsSlotNumber.add("3"), id, paddingType.START) + getMappingStoragePosition(protocolLookupsSlotNumber + 3n, id, paddingType.START) ) ); } @@ -1247,13 +1258,13 @@ async function getProtocolLookupsPrivateContractState( const accounts = [...sellers, ...DRs, ...agents, ...buyers]; for (const account of accounts) { - const accountAddress = account.wallet.address; + const accountAddress = account.wallet; // buyerIdByWallet buyerIdByWallet.push( await getStorageAt( protocolDiamondAddress, - getMappingStoragePosition(protocolLookupsSlotNumber.add("8"), accountAddress, paddingType.START) + getMappingStoragePosition(protocolLookupsSlotNumber + 8n, accountAddress, paddingType.START) ) ); @@ -1261,13 +1272,13 @@ async function getProtocolLookupsPrivateContractState( agentIdByWallet.push( await getStorageAt( protocolDiamondAddress, - getMappingStoragePosition(protocolLookupsSlotNumber.add("13"), accountAddress, paddingType.START) + getMappingStoragePosition(protocolLookupsSlotNumber + 13n, accountAddress, paddingType.START) ) ); // conditionalCommitsByAddress - const firstMappingStorageSlot = ethers.BigNumber.from( - getMappingStoragePosition(protocolLookupsSlotNumber.add("19"), accountAddress, paddingType.START) + const firstMappingStorageSlot = BigInt( + getMappingStoragePosition(protocolLookupsSlotNumber + 19n, accountAddress, paddingType.START) ); let commitsPerGroup = []; for (const group of groups) { @@ -1294,32 +1305,30 @@ async function getProtocolLookupsPrivateContractState( // loop over all ids even where no data is expected for (const id of accountIds) { // disputeResolverFeeTokenIndex - let firstMappingStorageSlot = ethers.BigNumber.from( - getMappingStoragePosition(protocolLookupsSlotNumber.add("12"), id, paddingType.START) + let firstMappingStorageSlot = BigInt( + getMappingStoragePosition(protocolLookupsSlotNumber + 12n, id, paddingType.START) ); disputeResolverFeeTokenIndex.push({ native: await getStorageAt( protocolDiamondAddress, - getMappingStoragePosition(firstMappingStorageSlot, ethers.constants.AddressZero, paddingType.START) + getMappingStoragePosition(firstMappingStorageSlot, ZeroAddress, paddingType.START) ), mockToken: await getStorageAt( protocolDiamondAddress, - getMappingStoragePosition(firstMappingStorageSlot, mockToken.address, paddingType.START) + getMappingStoragePosition(firstMappingStorageSlot, await mockToken.getAddress(), paddingType.START) ), }); // tokenIndexByAccount - firstMappingStorageSlot = ethers.BigNumber.from( - getMappingStoragePosition(protocolLookupsSlotNumber.add("16"), id, paddingType.START) - ); + firstMappingStorageSlot = BigInt(getMappingStoragePosition(protocolLookupsSlotNumber + 16n, id, paddingType.START)); tokenIndexByAccount.push({ native: await getStorageAt( protocolDiamondAddress, - getMappingStoragePosition(firstMappingStorageSlot, ethers.constants.AddressZero, paddingType.START) + getMappingStoragePosition(firstMappingStorageSlot, ZeroAddress, paddingType.START) ), mockToken: await getStorageAt( protocolDiamondAddress, - getMappingStoragePosition(firstMappingStorageSlot, mockToken.address, paddingType.START) + getMappingStoragePosition(firstMappingStorageSlot, await mockToken.getAddress(), paddingType.START) ), }); @@ -1327,7 +1336,7 @@ async function getProtocolLookupsPrivateContractState( cloneAddress.push( await getStorageAt( protocolDiamondAddress, - getMappingStoragePosition(protocolLookupsSlotNumber.add("17"), id, paddingType.START) + getMappingStoragePosition(protocolLookupsSlotNumber + 17n, id, paddingType.START) ) ); @@ -1335,7 +1344,7 @@ async function getProtocolLookupsPrivateContractState( voucherCount.push( await getStorageAt( protocolDiamondAddress, - getMappingStoragePosition(protocolLookupsSlotNumber.add("18"), id, paddingType.START) + getMappingStoragePosition(protocolLookupsSlotNumber + 18n, id, paddingType.START) ) ); } @@ -1343,20 +1352,24 @@ async function getProtocolLookupsPrivateContractState( // twinRangesBySeller let twinRangesBySeller = []; for (const id of accountIds) { - const firstMappingStorageSlot = ethers.BigNumber.from( - getMappingStoragePosition(protocolLookupsSlotNumber.add("22"), id, paddingType.START) + const firstMappingStorageSlot = BigInt( + getMappingStoragePosition(protocolLookupsSlotNumber + 22n, id, paddingType.START) ); let ranges = {}; for (let mockTwin of mockTwinTokens) { - ranges[mockTwin.address] = []; - const arraySlot = getMappingStoragePosition(firstMappingStorageSlot, mockTwin.address, paddingType.START); - const arrayLength = ethers.BigNumber.from(await getStorageAt(protocolDiamondAddress, arraySlot)).toNumber(); - const arrayStart = ethers.BigNumber.from(keccak256(arraySlot)); - for (let i = 0; i < arrayLength * 2; i = i + 2) { + ranges[await mockTwin.getAddress()] = []; + const arraySlot = getMappingStoragePosition( + firstMappingStorageSlot, + await mockTwin.getAddress(), + paddingType.START + ); + const arrayLength = await getStorageAt(protocolDiamondAddress, arraySlot); + const arrayStart = keccak256(arraySlot); + for (let i = 0; i < arrayLength * 2n; i = i + 2n) { // each BosonTypes.TokenRange has length 2 - ranges[mockTwin.address].push({ - start: await getStorageAt(protocolDiamondAddress, arrayStart.add(i)), - end: await getStorageAt(protocolDiamondAddress, arrayStart.add(i + 1)), + ranges[await mockTwin.getAddress()].push({ + start: await getStorageAt(protocolDiamondAddress, arrayStart + i), + end: await getStorageAt(protocolDiamondAddress, arrayStart + i + 1n), }); } } @@ -1366,17 +1379,21 @@ async function getProtocolLookupsPrivateContractState( // twinIdsByTokenAddressAndBySeller let twinIdsByTokenAddressAndBySeller = []; for (const id of accountIds) { - const firstMappingStorageSlot = ethers.BigNumber.from( - getMappingStoragePosition(protocolLookupsSlotNumber.add("23"), id, paddingType.START) + const firstMappingStorageSlot = BigInt( + getMappingStoragePosition(protocolLookupsSlotNumber + 23n, id, paddingType.START) ); let twinIds = {}; for (let mockTwin of mockTwinTokens) { - twinIds[mockTwin.address] = []; - const arraySlot = getMappingStoragePosition(firstMappingStorageSlot, mockTwin.address, paddingType.START); - const arrayLength = ethers.BigNumber.from(await getStorageAt(protocolDiamondAddress, arraySlot)).toNumber(); - const arrayStart = ethers.BigNumber.from(keccak256(arraySlot)); + twinIds[await mockTwin.getAddress()] = []; + const arraySlot = getMappingStoragePosition( + firstMappingStorageSlot, + await mockTwin.getAddress(), + paddingType.START + ); + const arrayLength = await getStorageAt(protocolDiamondAddress, arraySlot); + const arrayStart = keccak256(arraySlot); for (let i = 0; i < arrayLength; i++) { - twinIds[mockTwin.address].push(await getStorageAt(protocolDiamondAddress, arrayStart.add(i))); + twinIds[await mockTwin.getAddress()].push(await getStorageAt(protocolDiamondAddress, arrayStart + i)); } } twinIdsByTokenAddressAndBySeller.push(twinIds); @@ -1385,23 +1402,15 @@ async function getProtocolLookupsPrivateContractState( // allowedSellerIndex let allowedSellerIndex = []; for (const DR of DRs) { - const firstMappingStorageSlot = ethers.BigNumber.from( - getMappingStoragePosition( - protocolLookupsSlotNumber.add("26"), - ethers.BigNumber.from(DR.disputeResolver.id).toHexString(), - paddingType.START - ) + const firstMappingStorageSlot = BigInt( + getMappingStoragePosition(protocolLookupsSlotNumber + 26n, BigInt(DR.disputeResolver.id), paddingType.START) ); let sellerStatus = []; for (const seller of sellers) { sellerStatus.push( await getStorageAt( protocolDiamondAddress, - getMappingStoragePosition( - firstMappingStorageSlot, - ethers.BigNumber.from(seller.seller.id).toHexString(), - paddingType.START - ) + getMappingStoragePosition(firstMappingStorageSlot, BigInt(seller.seller.id), paddingType.START) ) ); } @@ -1412,9 +1421,7 @@ async function getProtocolLookupsPrivateContractState( let offerIdIndexByGroup = []; for (const group of groups) { const id = group.id; - const firstMappingStorageSlot = ethers.BigNumber.from( - getMappingStoragePosition(protocolLookupsSlotNumber.add("28"), id, paddingType.START) - ); + const firstMappingStorageSlot = BigInt(getMappingStoragePosition(protocolLookupsSlotNumber, id, paddingType.START)); let offerInidices = []; for (const offer of offers) { const id2 = Number(offer.offer.id); @@ -1436,37 +1443,31 @@ async function getProtocolLookupsPrivateContractState( // Although pending address/auth token update is not yet defined in 2.0.0, we can check that storage slots are empty for (const id of accountIds) { // pendingAddressUpdatesBySeller - let structStorageSlot = ethers.BigNumber.from( - getMappingStoragePosition(protocolLookupsSlotNumber.add("29"), id, paddingType.START) - ); + let structStorageSlot = BigInt(getMappingStoragePosition(protocolLookupsSlotNumber + 29n, id, paddingType.START)); let structFields = []; - for (let i = 0; i < 5; i++) { + for (let i = 0n; i < 5n; i++) { // BosonTypes.Seller has 6 fields, but last bool is packed in one slot with previous field - structFields.push(await getStorageAt(protocolDiamondAddress, structStorageSlot.add(i))); + structFields.push(await getStorageAt(protocolDiamondAddress, structStorageSlot + i)); } pendingAddressUpdatesBySeller.push(structFields); // pendingAuthTokenUpdatesBySeller - structStorageSlot = ethers.BigNumber.from( - getMappingStoragePosition(protocolLookupsSlotNumber.add("30"), id, paddingType.START) - ); + structStorageSlot = BigInt(getMappingStoragePosition(protocolLookupsSlotNumber + 30n, id, paddingType.START)); structFields = []; - for (let i = 0; i < 2; i++) { + for (let i = 0n; i < 2n; i++) { // BosonTypes.AuthToken has 2 fields - structFields.push(await getStorageAt(protocolDiamondAddress, structStorageSlot.add(i))); + structFields.push(await getStorageAt(protocolDiamondAddress, structStorageSlot + i)); } pendingAuthTokenUpdatesBySeller.push(structFields); // pendingAddressUpdatesByDisputeResolver - structStorageSlot = ethers.BigNumber.from( - getMappingStoragePosition(protocolLookupsSlotNumber.add("31"), id, paddingType.START) - ); + structStorageSlot = BigInt(getMappingStoragePosition(protocolLookupsSlotNumber + 31n, id, paddingType.START)); structFields = []; - for (let i = 0; i < 8; i++) { + for (let i = 0n; i < 8n; i++) { // BosonTypes.DisputeResolver has 8 fields - structFields.push(await getStorageAt(protocolDiamondAddress, structStorageSlot.add(i))); + structFields.push(await getStorageAt(protocolDiamondAddress, structStorageSlot + i)); } - structFields[6] = await getStorageAt(protocolDiamondAddress, keccak256(structStorageSlot.add(6))); // represents field string metadataUri. Technically this value represents the length of the string, but since it should be 0, we don't do further decoding + structFields[6] = await getStorageAt(protocolDiamondAddress, keccak256(structStorageSlot + 6n)); // represents field string metadataUri. Technically this value represents the length of the string, but since it should be 0, we don't do further decoding pendingAddressUpdatesByDisputeResolver.push(structFields); } @@ -1571,13 +1572,13 @@ async function populateVoucherContract( let nextAccountId = await accountHandler.getNextAccountId(); for (const entity of entities) { - const wallet = ethers.Wallet.createRandom(); - const connectedWallet = wallet.connect(ethers.provider); + const wallet = Wallet.createRandom(); + const connectedWallet = wallet.connect(provider); //Fund the new wallet let tx = { - to: connectedWallet.address, + to: await connectedWallet.getAddress(), // Convert currency unit from ether to wei - value: ethers.utils.parseEther("10"), + value: parseEther("10"), }; await deployer.sendTransaction(tx); @@ -1585,16 +1586,16 @@ async function populateVoucherContract( switch (entity) { case entityType.DR: { const disputeResolver = mockDisputeResolver( - wallet.address, - wallet.address, - wallet.address, - wallet.address, + await wallet.getAddress(), + await wallet.getAddress(), + await wallet.getAddress(), + await wallet.getAddress(), true, true ); const disputeResolverFees = [ - new DisputeResolverFee(ethers.constants.AddressZero, "Native", "0"), - new DisputeResolverFee(mockToken.address, "MockToken", "0"), + new DisputeResolverFee(ZeroAddress, "Native", "0"), + new DisputeResolverFee(await mockToken.getAddress(), "MockToken", "0"), ]; const sellerAllowList = []; @@ -1618,9 +1619,17 @@ async function populateVoucherContract( break; } case entityType.SELLER: { - const seller = mockSeller(wallet.address, wallet.address, wallet.address, wallet.address, true, undefined, { - refreshModule: true, - }); + const seller = mockSeller( + await wallet.getAddress(), + await wallet.getAddress(), + await wallet.getAddress(), + await wallet.getAddress(), + true, + undefined, + { + refreshModule: true, + } + ); const id = (seller.id = nextAccountId.toString()); let authToken = mockAuthToken(); @@ -1629,8 +1638,8 @@ async function populateVoucherContract( await accountHandler.connect(connectedWallet).createSeller(seller, authToken, voucherInitValues); // calculate voucher contract address and cast it to contract instance - const voucherContractAddress = calculateContractAddress(accountHandler.address, voucherIndex++); - const bosonVoucher = await ethers.getContractAt("BosonVoucher", voucherContractAddress); + const voucherContractAddress = calculateContractAddress(await accountHandler.getAddress(), voucherIndex++); + const bosonVoucher = await getContractAt("BosonVoucher", voucherContractAddress); sellers.push({ wallet: connectedWallet, @@ -1644,13 +1653,13 @@ async function populateVoucherContract( bosonVouchers.push(bosonVoucher); // mint mock token to sellers just in case they need them - await mockToken.mint(connectedWallet.address, "10000000000"); + await mockToken.mint(await connectedWallet.getAddress(), "10000000000"); await mockToken.connect(connectedWallet).approve(protocolDiamondAddress, "10000000000"); break; } case entityType.BUYER: { // no need to explicitly create buyer, since it's done automatically during commitToOffer - const buyer = mockBuyer(wallet.address); + const buyer = mockBuyer(await wallet.getAddress()); buyer.id = nextAccountId.toString(); buyers.push({ wallet: connectedWallet, id: buyer.id, buyer }); break; @@ -1662,7 +1671,7 @@ async function populateVoucherContract( } // create offers - first seller has 5 offers, second 4, third 3 etc - let offerId = (await offerHandler.getNextOfferId()).toNumber(); + let offerId = Number(await offerHandler.getNextOfferId()); for (let i = 0; i < sellers.length; i++) { for (let j = i; j >= 0; j--) { // Mock offer, offerDates and offerDurations @@ -1678,17 +1687,13 @@ async function populateVoucherContract( // Default offer is in native token. Change every other to mock token if (offerId % 2 == 0) { - offer.exchangeToken = mockToken.address; + offer.exchangeToken = await mockToken.getAddress(); } // Set unique offer dates based on offer id const now = offerDates.validFrom; - offerDates.validFrom = ethers.BigNumber.from(now) - .add(oneMonth + offerId * 1000) - .toString(); - offerDates.validUntil = ethers.BigNumber.from(now) - .add(oneMonth * 6 * (offerId + 1)) - .toString(); + offerDates.validFrom = (BigInt(now) + oneMonth + BigInt(offerId) * 1000n).toString(); + offerDates.validUntil = (BigInt(now) + oneMonth * 6n * BigInt(offerId + 1)).toString(); // Set unique offerDurations based on offer id offerDurations.disputePeriod = `${(offerId + 1) * oneMonth}`; @@ -1708,8 +1713,8 @@ async function populateVoucherContract( sellers[j].offerIds.push(offerId); // Deposit seller funds so the commit will succeed - const sellerPool = ethers.BigNumber.from(offer.quantityAvailable).mul(offer.price).toString(); - const msgValue = offer.exchangeToken == ethers.constants.AddressZero ? sellerPool : "0"; + const sellerPool = BigInt(offer.quantityAvailable) * BigInt(offer.price); + const msgValue = offer.exchangeToken == ZeroAddress ? sellerPool : "0"; await fundsHandler .connect(sellers[j].wallet) .depositFunds(sellers[j].seller.id, offer.exchangeToken, sellerPool, { value: msgValue }); @@ -1720,22 +1725,24 @@ async function populateVoucherContract( // commit to some offers: first buyer commit to 1 offer, second to 2, third to 3 etc await setNextBlockTimestamp(Number(offers[offers.length - 1].offerDates.validFrom)); // When latest offer is valid, also other offers are valid - let exchangeId = (await exchangeHandler.getNextExchangeId()).toNumber(); + let exchangeId = Number(await exchangeHandler.getNextExchangeId()); for (let i = 0; i < buyers.length; i++) { for (let j = i; j < buyers.length; j++) { const offer = offers[i + j].offer; // some offers will be picked multiple times, some never. const offerPrice = offer.price; const buyerWallet = buyers[j].wallet; let msgValue; - if (offer.exchangeToken == ethers.constants.AddressZero) { + if (offer.exchangeToken == ZeroAddress) { msgValue = offerPrice; } else { // approve token transfer msgValue = 0; await mockToken.connect(buyerWallet).approve(protocolDiamondAddress, offerPrice); - await mockToken.mint(buyerWallet.address, offerPrice); + await mockToken.mint(await buyerWallet.getAddress(), offerPrice); } - await exchangeHandler.connect(buyerWallet).commitToOffer(buyerWallet.address, offer.id, { value: msgValue }); + await exchangeHandler + .connect(buyerWallet) + .commitToOffer(await buyerWallet.getAddress(), offer.id, { value: msgValue }); exchanges.push({ exchangeId: exchangeId, offerId: offer.id, buyerIndex: j }); exchangeId++; } @@ -1782,7 +1789,7 @@ async function getVoucherContractState({ bosonVouchers, exchanges, sellers, buye // balanceOf(address owner) // isApprovedForAll(address owner, address assistant) - const addresses = [...sellers, ...buyers].map((acc) => acc.wallet.address); + const addresses = [...sellers, ...buyers].map((acc) => acc.wallet); const balanceOf = await Promise.all(addresses.map((address) => bosonVoucher.balanceOf(address))); const isApprovedForAll = await Promise.all( addresses.map((address1) => diff --git a/test/util/utils.js b/test/util/utils.js index 0447b5562..6c8cafe03 100644 --- a/test/util/utils.js +++ b/test/util/utils.js @@ -1,17 +1,31 @@ const { ethers } = require("hardhat"); -const { utils, provider, BigNumber } = ethers; +const { + getAddress, + provider, + keccak256, + encodeRlp, + getSigners, + parseUnits, + getContractAt, + toBeArray, + isHexString, + zeroPadValue, + Interface, + toUtf8Bytes, +} = ethers; const { getFacets } = require("../../scripts/config/facet-deploy.js"); -const { keccak256, RLP } = utils; const { oneWeek, oneMonth, maxPriorityFeePerGas } = require("./constants"); const Role = require("../../scripts/domain/Role"); +const { toHexString } = require("../../scripts/util/utils.js"); const { expect } = require("chai"); const Offer = require("../../scripts/domain/Offer"); +const { zeroPadBytes } = require("ethers"); function getEvent(receipt, factory, eventName) { let found = false; const eventFragment = factory.interface.fragments.filter((e) => e.name == eventName); - const iface = new utils.Interface(eventFragment); + const iface = new Interface(eventFragment); for (const log in receipt.logs) { const topics = receipt.logs[log].topics; @@ -23,8 +37,9 @@ function getEvent(receipt, factory, eventName) { // CHECK IF TOPIC CORRESPONDS TO THE EVENT GIVEN TO FN const event = iface.getEvent(encodedTopic); - if (event.name == eventName) { + if (event && event.name == eventName) { found = true; + const eventArgs = iface.parseLog(receipt.logs[log]).args; return eventArgs; } @@ -46,7 +61,7 @@ function eventEmittedWithArgs(receipt, factory, eventName, args) { let match = false; const eventFragment = factory.interface.fragments.filter((e) => e.name == eventName); - const iface = new utils.Interface(eventFragment); + const iface = new Interface(eventFragment); for (const log in receipt.logs) { const topics = receipt.logs[log].topics; @@ -106,7 +121,7 @@ function compareArgs(eventArgs, args) { disputeResolutionTermsStruct, offerFeesStruct, agentId, - assistant.address, + await assistant.getAddress(), ); * * @param {*} returnedOffer @@ -125,7 +140,7 @@ async function setNextBlockTimestamp(timestamp) { } function getSignatureParameters(signature) { - if (!utils.isHexString(signature)) { + if (!isHexString(signature)) { throw new Error('Given value "'.concat(signature, '" is not a valid hex string.')); } @@ -175,10 +190,10 @@ async function prepareDataSignatureParameters( if (type == "Protocol") { //hardhat default chain id is 31337 - domainData.salt = utils.hexZeroPad(BigNumber.from(31337).toHexString(), 32); + domainData.salt = zeroPadValue(toHexString(31337n), 32); } else { const { chainId } = await provider.getNetwork(); - domainData.chainId = chainId; + domainData.chainId = chainId.toString(); } // Prepare the types @@ -196,7 +211,7 @@ async function prepareDataSignatureParameters( }); // Sign the data - const signature = await provider.send("eth_signTypedData_v4", [user.address, dataToSign]); + const signature = await provider.send("eth_signTypedData_v4", [await user.getAddress(), dataToSign]); // Collect the Signature components const { r, s, v } = getSignatureParameters(signature); @@ -210,28 +225,29 @@ async function prepareDataSignatureParameters( } function calculateVoucherExpiry(block, voucherRedeemableFromDate, voucherValidDuration) { - const startDate = BigNumber.from(block.timestamp).gte(BigNumber.from(voucherRedeemableFromDate)) - ? BigNumber.from(block.timestamp) - : BigNumber.from(voucherRedeemableFromDate); - return startDate.add(BigNumber.from(voucherValidDuration)).toString(); + const startDate = + BigInt(block.timestamp) > BigInt(voucherRedeemableFromDate) + ? BigInt(block.timestamp) + : BigInt(voucherRedeemableFromDate); + return (startDate + BigInt(voucherValidDuration)).toString(); } function applyPercentage(base, percentage) { - return BigNumber.from(base).mul(percentage).div("10000").toString(); + return ((BigInt(base) * BigInt(percentage)) / BigInt(10000)).toString(); } function calculateContractAddress(senderAddress, senderNonce) { - const nonce = BigNumber.from(senderNonce); - const nonceHex = nonce.eq(0) ? "0x" : nonce.toHexString(); + const nonce = BigInt(senderNonce); + const nonceHex = nonce == 0n ? "0x" : toBeArray(nonce); const input_arr = [senderAddress, nonceHex]; - const rlp_encoded = RLP.encode(input_arr); + const rlp_encoded = encodeRlp(input_arr); const contract_address_long = keccak256(rlp_encoded); const contract_address = "0x" + contract_address_long.substring(26); //Trim the first 24 characters. - return utils.getAddress(contract_address); + return getAddress(contract_address); } const paddingType = { @@ -244,16 +260,16 @@ function getMappingStoragePosition(slot, key, padding = paddingType.NONE) { let keyBuffer; switch (padding) { case paddingType.NONE: - keyBuffer = utils.toUtf8Bytes(key); + keyBuffer = toUtf8Bytes(key); break; case paddingType.START: - keyBuffer = Buffer.from(utils.hexZeroPad(key, 32).toString().slice(2), "hex"); + keyBuffer = Buffer.from(zeroPadBytes(key, 32).toString().slice(2), "hex"); break; case paddingType.END: keyBuffer = Buffer.from(key.slice(2).padEnd(64, "0"), "hex"); // assume key is prefixed with 0x break; } - const pBuffer = Buffer.from(slot.toHexString().slice(2), "hex"); + const pBuffer = Buffer.from(toHexString(slot).slice(2), "hex"); return keccak256(Buffer.concat([keyBuffer, pBuffer])); } @@ -268,7 +284,7 @@ async function getFacetsWithArgs(facetNames, config) { function objectToArray(input) { // If the input is not an object, return it as-is - if (BigNumber.isBigNumber(input) || typeof input !== "object" || input === null) { + if (typeof input !== "object" || input === null) { return input; } @@ -315,23 +331,23 @@ async function setupTestEnvironment(contracts, { bosonTokenAddress, forwarderAdd "MetaTransactionsHandlerFacet", ]; - const signers = await ethers.getSigners(); + const signers = await getSigners(); const [deployer, protocolTreasury, bosonToken, pauser] = signers; // Deploy the Protocol Diamond const [protocolDiamond, , , , accessController] = await deployProtocolDiamond(maxPriorityFeePerGas); // Temporarily grant UPGRADER role to deployer account - await accessController.grantRole(Role.UPGRADER, deployer.address); + await accessController.grantRole(Role.UPGRADER, await deployer.getAddress()); // Grant PROTOCOL role to ProtocolDiamond address and renounces admin - await accessController.grantRole(Role.PROTOCOL, protocolDiamond.address); + await accessController.grantRole(Role.PROTOCOL, await protocolDiamond.getAddress()); // Grant PAUSER role to pauser account - await accessController.grantRole(Role.PAUSER, pauser.address); + await accessController.grantRole(Role.PAUSER, await pauser.getAddress()); // Deploy the Protocol client implementation/proxy pairs (currently just the Boson Voucher) - const protocolClientArgs = [protocolDiamond.address]; + const protocolClientArgs = [await protocolDiamond.getAddress()]; const [implementations, beacons, proxies, clients] = await deployProtocolClients( protocolClientArgs, maxPriorityFeePerGas, @@ -344,17 +360,17 @@ async function setupTestEnvironment(contracts, { bosonTokenAddress, forwarderAdd // set protocolFees const protocolFeePercentage = "200"; // 2 % - const protocolFeeFlatBoson = ethers.utils.parseUnits("0.01", "ether").toString(); + const protocolFeeFlatBoson = parseUnits("0.01", "ether").toString(); const buyerEscalationDepositPercentage = "1000"; // 10% // Add config Handler, so ids start at 1, and so voucher address can be found const protocolConfig = [ // Protocol addresses { - treasury: protocolTreasury.address, - token: bosonTokenAddress || bosonToken.address, - voucherBeacon: beacon.address, - beaconProxy: proxy.address, + treasury: await protocolTreasury.getAddress(), + token: bosonTokenAddress || (await bosonToken.getAddress()), + voucherBeacon: await beacon.getAddress(), + beaconProxy: await proxy.getAddress(), }, // Protocol limits { @@ -385,11 +401,11 @@ async function setupTestEnvironment(contracts, { bosonTokenAddress, forwarderAdd const facetsToDeploy = await getFacetsWithArgs(facetNames, protocolConfig); // Cut the protocol handler facets into the Diamond - await deployAndCutFacets(protocolDiamond.address, facetsToDeploy, maxPriorityFeePerGas); + await deployAndCutFacets(await protocolDiamond.getAddress(), facetsToDeploy, maxPriorityFeePerGas); let contractInstances = {}; for (const contract of Object.keys(contracts)) { - contractInstances[contract] = await ethers.getContractAt(contracts[contract], protocolDiamond.address); + contractInstances[contract] = await getContractAt(contracts[contract], await protocolDiamond.getAddress()); } const extraReturnValues = { accessController, bosonVoucher, voucherImplementation, beacon }; @@ -398,21 +414,21 @@ async function setupTestEnvironment(contracts, { bosonTokenAddress, forwarderAdd signers: signers.slice(3), contractInstances, protocolConfig, - diamondAddress: protocolDiamond.address, + diamondAddress: await protocolDiamond.getAddress(), extraReturnValues, }; } async function getSnapshot() { - return await ethers.provider.send("evm_snapshot", []); + return await provider.send("evm_snapshot", []); } async function revertToSnapshot(snapshotId) { - return await ethers.provider.send("evm_revert", [snapshotId]); + return await provider.send("evm_revert", [snapshotId]); } function deriveTokenId(offerId, exchangeId) { - return ethers.BigNumber.from(offerId).shl(128).add(exchangeId); + return (BigInt(offerId) << 128n) + BigInt(exchangeId); } exports.setNextBlockTimestamp = setNextBlockTimestamp;