From 722ac6028ee92e20b4c33f1c1a97181c72f76a2e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Aug 2023 12:21:31 +0000 Subject: [PATCH 1/4] build(deps): bump @openzeppelin/contracts-upgradeable Bumps [@openzeppelin/contracts-upgradeable](https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable) from 4.9.2 to 4.9.3. - [Release notes](https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/releases) - [Changelog](https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/v4.9.3/CHANGELOG.md) - [Commits](https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/compare/v4.9.2...v4.9.3) --- updated-dependencies: - dependency-name: "@openzeppelin/contracts-upgradeable" dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- package-lock.json | 14 +++++++------- package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index 3d15b987..e469deb5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "license": "MIT", "dependencies": { "@openzeppelin/contracts": "^4.9.3", - "@openzeppelin/contracts-upgradeable": "^4.9.2", + "@openzeppelin/contracts-upgradeable": "^4.9.3", "@primitivefi/hardhat-dodoc": "^0.2.3", "hardhat": "^2.17.1", "keccak256": "^1.0.6", @@ -1515,9 +1515,9 @@ "integrity": "sha512-He3LieZ1pP2TNt5JbkPA4PNT9WC3gOTOlDcFGJW4Le4QKqwmiNJCRt44APfxMxvq7OugU/cqYuPcSBzOw38DAg==" }, "node_modules/@openzeppelin/contracts-upgradeable": { - "version": "4.9.2", - "resolved": "https://registry.npmjs.org/@openzeppelin/contracts-upgradeable/-/contracts-upgradeable-4.9.2.tgz", - "integrity": "sha512-siviV3PZV/fHfPaoIC51rf1Jb6iElkYWnNYZ0leO23/ukXuvOyoC/ahy8jqiV7g+++9Nuo3n/rk5ajSN/+d/Sg==" + "version": "4.9.3", + "resolved": "https://registry.npmjs.org/@openzeppelin/contracts-upgradeable/-/contracts-upgradeable-4.9.3.tgz", + "integrity": "sha512-jjaHAVRMrE4UuZNfDwjlLGDxTHWIOwTJS2ldnc278a0gevfXfPr8hxKEVBGFBE96kl2G3VHDZhUimw/+G3TG2A==" }, "node_modules/@openzeppelin/hardhat-upgrades": { "version": "1.27.0", @@ -12393,9 +12393,9 @@ "integrity": "sha512-He3LieZ1pP2TNt5JbkPA4PNT9WC3gOTOlDcFGJW4Le4QKqwmiNJCRt44APfxMxvq7OugU/cqYuPcSBzOw38DAg==" }, "@openzeppelin/contracts-upgradeable": { - "version": "4.9.2", - "resolved": "https://registry.npmjs.org/@openzeppelin/contracts-upgradeable/-/contracts-upgradeable-4.9.2.tgz", - "integrity": "sha512-siviV3PZV/fHfPaoIC51rf1Jb6iElkYWnNYZ0leO23/ukXuvOyoC/ahy8jqiV7g+++9Nuo3n/rk5ajSN/+d/Sg==" + "version": "4.9.3", + "resolved": "https://registry.npmjs.org/@openzeppelin/contracts-upgradeable/-/contracts-upgradeable-4.9.3.tgz", + "integrity": "sha512-jjaHAVRMrE4UuZNfDwjlLGDxTHWIOwTJS2ldnc278a0gevfXfPr8hxKEVBGFBE96kl2G3VHDZhUimw/+G3TG2A==" }, "@openzeppelin/hardhat-upgrades": { "version": "1.27.0", diff --git a/package.json b/package.json index 97e5838d..00d2133e 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,7 @@ }, "dependencies": { "@openzeppelin/contracts": "^4.9.3", - "@openzeppelin/contracts-upgradeable": "^4.9.2", + "@openzeppelin/contracts-upgradeable": "^4.9.3", "@primitivefi/hardhat-dodoc": "^0.2.3", "hardhat": "^2.17.1", "keccak256": "^1.0.6", From 514014280017a1cf81939969cdc567c6dba0aca8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 28 Aug 2023 20:04:14 +0000 Subject: [PATCH 2/4] build(deps-dev): bump @types/node from 20.4.6 to 20.5.7 Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 20.4.6 to 20.5.7. - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) --- updated-dependencies: - dependency-name: "@types/node" dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- package-lock.json | 14 +++++++------- package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index 3d15b987..ab99db90 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,7 +23,7 @@ "@openzeppelin/hardhat-upgrades": "^1.27.0", "@types/chai": "^4.3.5", "@types/mocha": "^10.0.1", - "@types/node": "^20.4.6", + "@types/node": "^20.5.7", "@typescript-eslint/eslint-plugin": "^4.33.0", "@typescript-eslint/parser": "^4.33.0", "dotenv": "^16.3.1", @@ -2051,9 +2051,9 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.4.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.6.tgz", - "integrity": "sha512-q0RkvNgMweWWIvSMDiXhflGUKMdIxBo2M2tYM/0kEGDueQByFzK4KZAgu5YHGFNxziTlppNpTIBcqHQAxlfHdA==" + "version": "20.5.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.5.7.tgz", + "integrity": "sha512-dP7f3LdZIysZnmvP3ANJYTSwg+wLLl8p7RqniVlV7j+oXSXAbt9h0WIBFmJy5inWZoX9wZN6eXx+YXd9Rh3RBA==" }, "node_modules/@types/pbkdf2": { "version": "3.1.0", @@ -12812,9 +12812,9 @@ "dev": true }, "@types/node": { - "version": "20.4.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.6.tgz", - "integrity": "sha512-q0RkvNgMweWWIvSMDiXhflGUKMdIxBo2M2tYM/0kEGDueQByFzK4KZAgu5YHGFNxziTlppNpTIBcqHQAxlfHdA==" + "version": "20.5.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.5.7.tgz", + "integrity": "sha512-dP7f3LdZIysZnmvP3ANJYTSwg+wLLl8p7RqniVlV7j+oXSXAbt9h0WIBFmJy5inWZoX9wZN6eXx+YXd9Rh3RBA==" }, "@types/pbkdf2": { "version": "3.1.0", diff --git a/package.json b/package.json index 97e5838d..439cb4c5 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "@openzeppelin/hardhat-upgrades": "^1.27.0", "@types/chai": "^4.3.5", "@types/mocha": "^10.0.1", - "@types/node": "^20.4.6", + "@types/node": "^20.5.7", "@typescript-eslint/eslint-plugin": "^4.33.0", "@typescript-eslint/parser": "^4.33.0", "dotenv": "^16.3.1", From 7db01cbb09e90fe7f5aac54647e2c4f44acb6370 Mon Sep 17 00:00:00 2001 From: Zero Ekkusu <94782988+ZeroEkkusu@users.noreply.github.com> Date: Fri, 1 Sep 2023 11:41:27 +0200 Subject: [PATCH 3/4] feat: discard hardfork --- .github/workflows/ci.yml | 12 - README.md | 4 +- contracts/child/EIP1559Burn.sol | 4 +- contracts/child/governance/ChildGovernor.sol | 10 +- .../hardfork/ForkParamsHardforkProxy.sol | 17 - .../hardfork/NetworkParamsHardforkProxy.sol | 25 - contracts/child/validator/README.md | 6 - contracts/child/validator/RewardPool.sol | 8 +- contracts/child/validator/ValidatorSet.sol | 52 +- .../contracts-upgradeable/README.md | 9 - .../extensions/ERC20PermitUpgradeable.sol | 115 - .../extensions/ERC20VotesUpgradeable.sol | 308 --- .../utils/cryptography/EIP712Upgradeable.sol | 208 -- .../legacy-compat/LegacyStateVars.sol | 20 - .../hardfork/RewardPoolHardforkProxy.sol | 25 - .../hardfork/ValidatorSetHardforkProxy.sol | 25 - contracts/lib/AccessList.sol | 18 +- contracts/lib/EIP712MetaTransaction.sol | 4 +- contracts/lib/GenesisProxy.sol | 22 - contracts/lib/ProxyBase.sol | 33 - contracts/root/ExitHelper.sol | 2 +- .../root/staking/CustomSupernetManager.sol | 58 +- contracts/root/staking/StakeManager.sol | 20 +- .../root/staking/StakeManagerChildData.sol | 23 +- .../StakeManagerLegacyCompatStorage.sol | 47 - .../root/staking/StakeManagerStakingData.sol | 44 +- contracts/root/staking/SupernetManager.sol | 6 +- .../proxy/hardfork/ForkParamsHardforkProxy.md | 84 - .../hardfork/NetworkParamsHardforkProxy.md | 85 - docs/child/validator/ValidatorSet.md | 3 +- .../legacy-compat/LegacyStateVars.md | 12 - .../proxy/hardfork/RewardPoolHardforkProxy.md | 85 - .../hardfork/ValidatorSetHardforkProxy.md | 85 - docs/lib/GenesisProxy.md | 85 - docs/lib/ProxyBase.md | 64 - .../StakeManagerLegacyCompatStorage.md | 12 - test/forge/hardfork/Hardfork.t.sol | 360 --- test/forge/hardfork/deployed/ForkParams.sol | 169 -- .../forge/hardfork/deployed/NetworkParams.sol | 200 -- test/forge/hardfork/deployed/RewardPool.sol | 957 -------- test/forge/hardfork/deployed/ValidatorSet.sol | 2105 ----------------- .../root/staking/CustomSupernetManager.t.sol | 24 +- 42 files changed, 142 insertions(+), 5313 deletions(-) delete mode 100644 contracts/child/proxy/hardfork/ForkParamsHardforkProxy.sol delete mode 100644 contracts/child/proxy/hardfork/NetworkParamsHardforkProxy.sol delete mode 100644 contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/README.md delete mode 100644 contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol delete mode 100644 contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol delete mode 100644 contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol delete mode 100644 contracts/child/validator/legacy-compat/LegacyStateVars.sol delete mode 100644 contracts/child/validator/proxy/hardfork/RewardPoolHardforkProxy.sol delete mode 100644 contracts/child/validator/proxy/hardfork/ValidatorSetHardforkProxy.sol delete mode 100644 contracts/lib/GenesisProxy.sol delete mode 100644 contracts/lib/ProxyBase.sol delete mode 100644 contracts/root/staking/StakeManagerLegacyCompatStorage.sol delete mode 100644 docs/child/proxy/hardfork/ForkParamsHardforkProxy.md delete mode 100644 docs/child/proxy/hardfork/NetworkParamsHardforkProxy.md delete mode 100644 docs/child/validator/legacy-compat/LegacyStateVars.md delete mode 100644 docs/child/validator/proxy/hardfork/RewardPoolHardforkProxy.md delete mode 100644 docs/child/validator/proxy/hardfork/ValidatorSetHardforkProxy.md delete mode 100644 docs/lib/GenesisProxy.md delete mode 100644 docs/lib/ProxyBase.md delete mode 100644 docs/root/staking/StakeManagerLegacyCompatStorage.md delete mode 100644 test/forge/hardfork/Hardfork.t.sol delete mode 100644 test/forge/hardfork/deployed/ForkParams.sol delete mode 100644 test/forge/hardfork/deployed/NetworkParams.sol delete mode 100644 test/forge/hardfork/deployed/RewardPool.sol delete mode 100644 test/forge/hardfork/deployed/ValidatorSet.sol diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4459ffa9..232a212f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,18 +7,6 @@ on: branches: [main, dev] jobs: - maintenance: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Install Node modules - uses: actions/setup-node@v3 - with: - node-version: "18.x" - cache: "npm" - - run: npm ci - - name: Check modified OpenZeppelin contracts - run: node scripts/maintenance/checkModifiedOpenZeppelinContracts.js tests: runs-on: ubuntu-latest steps: diff --git a/README.md b/README.md index d57f1694..69cc8160 100644 --- a/README.md +++ b/README.md @@ -162,9 +162,7 @@ forge install Deploying these contracts in the context of a production blockchain is out of the scope of this repo, as it requires a client that has support of the Edge specification integrated. At current, Edge maintains its own client [here](https://github.com/0xPolygon/polygon-edge), which can be consulted. -One point that is worth emphasizing in this context is that from the perspective of launching a Supernet is understanding genesis contracts. Another is that for at least the time being, the decision has been made to proxify all genesis contracts in order to facilitate upgrades/updates without necessitating a hardfork or regenesis. A basic proxy for this task has been provided in [`contracts/lib/BasicGenesisProxy.sol`](/contracts/lib/BasicGenesisProxy.sol). - -**Important:** If you have to hardfork, the `RewardPool` and `ValidatorSet` contracts have their own custom proxies. This stems from an incident in which Supernets were deployed without proxifying the genesis contracts. These contracts already had historical state, which complicated simply hardforking their bytecode into being a proxy. The proxy contracts supplied for them (in [`contracts/child/validator/proxy/hardfork`](/contracts/child/validator/proxy/hardfork)) have been tailored to facilitate storage compatability between the legacy and current versions of these contracts. +One point that is worth emphasizing in this context is that from the perspective of launching a Supernet is understanding genesis contracts. Another is that for at least the time being, the decision has been made to proxify all genesis contracts in order to facilitate upgrades/updates without necessitating a hardfork or regenesis. All deployment scripts in `script/deployment` use OpenZeppelin's `TransparentUpgradeableProxy`. ### Environment Setup diff --git a/contracts/child/EIP1559Burn.sol b/contracts/child/EIP1559Burn.sol index 65a80f9f..8a4b8add 100644 --- a/contracts/child/EIP1559Burn.sol +++ b/contracts/child/EIP1559Burn.sol @@ -13,7 +13,7 @@ import "../interfaces/child/IChildERC20Predicate.sol"; contract EIP1559Burn is Initializable { IChildERC20Predicate public childERC20Predicate; address public burnDestination; - IChildERC20 private constant NATIVE_TOKEN = IChildERC20(0x0000000000000000000000000000000000001010); + IChildERC20 private constant _NATIVE_TOKEN = IChildERC20(0x0000000000000000000000000000000000001010); event NativeTokenBurnt(address indexed burner, uint256 amount); @@ -42,7 +42,7 @@ contract EIP1559Burn is Initializable { uint256 balance = address(this).balance; - childERC20Predicate.withdrawTo(NATIVE_TOKEN, burnDestination, balance); + childERC20Predicate.withdrawTo(_NATIVE_TOKEN, burnDestination, balance); // slither-disable-next-line reentrancy-events emit NativeTokenBurnt(msg.sender, balance); } diff --git a/contracts/child/governance/ChildGovernor.sol b/contracts/child/governance/ChildGovernor.sol index b4bf280c..6d8e7203 100644 --- a/contracts/child/governance/ChildGovernor.sol +++ b/contracts/child/governance/ChildGovernor.sol @@ -16,7 +16,7 @@ contract ChildGovernor is GovernorVotesQuorumFractionUpgradeable, GovernorTimelockControlUpgradeable { - NetworkParams internal networkParams; + NetworkParams internal _networkParams; function initialize( IVotesUpgradeable token_, @@ -29,23 +29,23 @@ contract ChildGovernor is __GovernorVotes_init(token_); __GovernorVotesQuorumFraction_init(quorumNumerator_); - networkParams = NetworkParams(networkParams_); + _networkParams = NetworkParams(networkParams_); } // TODO: adjust values for block time of child chain function votingDelay() public view override returns (uint256) { - return networkParams.votingDelay(); + return _networkParams.votingDelay(); } function votingPeriod() public view override returns (uint256) { - return networkParams.votingPeriod(); + return _networkParams.votingPeriod(); } // END TODO function proposalThreshold() public view override returns (uint256) { - return networkParams.proposalThreshold(); + return _networkParams.proposalThreshold(); } // The functions below are overrides required by Solidity. diff --git a/contracts/child/proxy/hardfork/ForkParamsHardforkProxy.sol b/contracts/child/proxy/hardfork/ForkParamsHardforkProxy.sol deleted file mode 100644 index 82c5e385..00000000 --- a/contracts/child/proxy/hardfork/ForkParamsHardforkProxy.sol +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "contracts/lib/ProxyBase.sol"; -import {ForkParams} from "contracts/child/ForkParams.sol"; - -/// @notice ForkParams-specific proxy for hardfork migration -/// @dev If starting fresh, use GenesisProxy instead -contract ForkParamsHardforkProxy is ProxyBase { - function setUpProxy(address logic, address admin) external { - _setUpProxy(logic, admin, ""); - - ForkParams forkParams = ForkParams(address(this)); - forkParams.initialize(forkParams.owner()); - } -} diff --git a/contracts/child/proxy/hardfork/NetworkParamsHardforkProxy.sol b/contracts/child/proxy/hardfork/NetworkParamsHardforkProxy.sol deleted file mode 100644 index 3db000e3..00000000 --- a/contracts/child/proxy/hardfork/NetworkParamsHardforkProxy.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "contracts/lib/ProxyBase.sol"; -import {NetworkParams} from "contracts/child/NetworkParams.sol"; - -/// @notice NetworkParams-specific proxy for hardfork migration -/// @dev If starting fresh, use GenesisProxy instead -contract NetworkParamsHardforkProxy is ProxyBase { - function setUpProxy(address logic, address admin, NetworkParams.InitParams memory initParams) external { - _setUpProxy(logic, admin, ""); - - // slither-disable-next-line assembly - assembly { - sstore(0, 0) - sstore(1, 0) - sstore(2, 0) - sstore(3, 0) - sstore(4, 0) - } - - NetworkParams(address(this)).initialize(initParams); - } -} diff --git a/contracts/child/validator/README.md b/contracts/child/validator/README.md index 158159d9..18c9322a 100644 --- a/contracts/child/validator/README.md +++ b/contracts/child/validator/README.md @@ -11,9 +11,3 @@ This contract manages the distribution of assets as rewards for validators valid ## ValidatorSet Manages most direct validator tasks, such as committing epochs or announcing intent to unstake. - -## `proxy/hardfork/` and `legacy-compat/` - -`RewardPool` and `ValidatorSet` are both intended to be genesis contracts, as in they are intended to be instantiated at the genesis of the chain, as opposed to traditionally deployed. In Edge's earlier stages, the decision has been made to proxify all genesis contracts, as to say that a proxy will be deployed for each at genesis, pointing towards its implementation. This should allow updates to genesis contracts without needing a hardfork or regenesis. The `proxy/hardfork/` directory contains proxies for `RewardPool` and `ValidatorSet`, in case you have to hardfork. A specific proxy was needed for each due to a situation that arose from production Supernets which had not proxified, but then needed to update to a newer version. These custom proxies were created so that they would be able to continue using the historical state of `RewardPool` and `ValidatorSet`. A more generic proxy for the rest of the genesis contracts (which do not create state) can be found in [`contracts/lib/BasicGenesisProxy.sol`](../../lib/BasicGenesisProxy.sol). - -`legacy-compat/` serves a similar purpose. In the migrated contracts there were some variables and functions that changed. This directory contains contracts from OpenZeppelin which we have tailored in order to synchronize the storage slots of the older and newer versions of `RewardPool` and `ValidatorSet`. diff --git a/contracts/child/validator/RewardPool.sol b/contracts/child/validator/RewardPool.sol index 2d347a7f..b62a7759 100644 --- a/contracts/child/validator/RewardPool.sol +++ b/contracts/child/validator/RewardPool.sol @@ -15,13 +15,11 @@ contract RewardPool is IRewardPool, System, Initializable { IERC20Upgradeable public rewardToken; address public rewardWallet; IValidatorSet public validatorSet; - // slither-disable-next-line unused-state,naming-convention - uint256[1] private __legacy_compat_gap; mapping(uint256 => uint256) public paidRewardPerEpoch; mapping(address => uint256) public pendingRewards; - NetworkParams internal networkParams; + NetworkParams internal _networkParams; function initialize( address newRewardToken, @@ -38,7 +36,7 @@ contract RewardPool is IRewardPool, System, Initializable { rewardWallet = newRewardWallet; validatorSet = IValidatorSet(newValidatorSet); - networkParams = NetworkParams(networkParamsAddr); + _networkParams = NetworkParams(networkParamsAddr); } /** @@ -49,7 +47,7 @@ contract RewardPool is IRewardPool, System, Initializable { uint256 totalBlocks = validatorSet.totalBlocks(epochId); require(totalBlocks != 0, "EPOCH_NOT_COMMITTED"); // slither-disable-next-line divide-before-multiply - uint256 reward = (networkParams.epochReward() * totalBlocks) / epochSize; + uint256 reward = (_networkParams.epochReward() * totalBlocks) / epochSize; // TODO disincentivize long epoch times uint256 totalSupply = validatorSet.totalSupplyAt(epochId); diff --git a/contracts/child/validator/ValidatorSet.sol b/contracts/child/validator/ValidatorSet.sol index 3a1386b7..bebd9c89 100644 --- a/contracts/child/validator/ValidatorSet.sol +++ b/contracts/child/validator/ValidatorSet.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.19; -import "./legacy-compat/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol"; import "../../lib/WithdrawalQueue.sol"; import "../../interfaces/child/validator/IValidatorSet.sol"; import "../../interfaces/IStateSender.sol"; @@ -12,25 +12,23 @@ import "../System.sol"; contract ValidatorSet is IValidatorSet, ERC20VotesUpgradeable, System { using WithdrawalQueueLib for WithdrawalQueue; - bytes32 private constant STAKE_SIG = keccak256("STAKE"); - bytes32 private constant UNSTAKE_SIG = keccak256("UNSTAKE"); - bytes32 private constant SLASH_SIG = keccak256("SLASH"); + bytes32 private constant _STAKE_SIG = keccak256("STAKE"); + bytes32 private constant _UNSTAKE_SIG = keccak256("UNSTAKE"); + bytes32 private constant _SLASH_SIG = keccak256("SLASH"); uint256 public constant SLASHING_PERCENTAGE = 50; // to be read through NetworkParams later uint256 public constant SLASH_INCENTIVE_PERCENTAGE = 30; // exitor reward, to be read through NetworkParams later - IStateSender private stateSender; - address private stateReceiver; - address private rootChainManager; - // slither-disable-next-line unused-state,naming-convention - uint256[1] private __legacy_compat_gap; + IStateSender private _stateSender; + address private _stateReceiver; + address private _rootChainManager; uint256 public currentEpochId; mapping(uint256 => Epoch) public epochs; uint256[] public epochEndBlocks; - mapping(address => WithdrawalQueue) private withdrawals; + mapping(address => WithdrawalQueue) private _withdrawals; - NetworkParams private networkParams; + NetworkParams private _networkParams; mapping(uint256 => uint256) private _commitBlockNumbers; mapping(uint256 => bool) public slashProcessed; @@ -47,10 +45,10 @@ contract ValidatorSet is IValidatorSet, ERC20VotesUpgradeable, System { "INVALID_INPUT" ); __ERC20_init("ValidatorSet", "VSET"); - stateSender = IStateSender(newStateSender); - stateReceiver = newStateReceiver; - rootChainManager = newRootChainManager; - networkParams = NetworkParams(newNetworkParams); + _stateSender = IStateSender(newStateSender); + _stateReceiver = newStateReceiver; + _rootChainManager = newRootChainManager; + _networkParams = NetworkParams(newNetworkParams); for (uint256 i = 0; i < initialValidators.length; ) { _stake(initialValidators[i].addr, initialValidators[i].stake); unchecked { @@ -80,18 +78,18 @@ contract ValidatorSet is IValidatorSet, ERC20VotesUpgradeable, System { * @inheritdoc IValidatorSet */ function slash(address[] calldata validators) external onlySystemCall { - stateSender.syncState( - rootChainManager, - abi.encode(SLASH_SIG, validators, SLASHING_PERCENTAGE, SLASH_INCENTIVE_PERCENTAGE) + _stateSender.syncState( + _rootChainManager, + abi.encode(_SLASH_SIG, validators, SLASHING_PERCENTAGE, SLASH_INCENTIVE_PERCENTAGE) ); } function onStateReceive(uint256 /*counter*/, address sender, bytes calldata data) external override { - require(msg.sender == stateReceiver && sender == rootChainManager, "INVALID_SENDER"); - if (bytes32(data[:32]) == STAKE_SIG) { + require(msg.sender == _stateReceiver && sender == _rootChainManager, "INVALID_SENDER"); + if (bytes32(data[:32]) == _STAKE_SIG) { (address validator, uint256 amount) = abi.decode(data[32:], (address, uint256)); _stake(validator, amount); - } else if (bytes32(data[:32]) == SLASH_SIG) { + } else if (bytes32(data[:32]) == _SLASH_SIG) { (, uint256 exitEventId, address[] memory validatorsToSlash, ) = abi.decode( data, (bytes32, uint256, address[], uint256) @@ -112,11 +110,11 @@ contract ValidatorSet is IValidatorSet, ERC20VotesUpgradeable, System { * @inheritdoc IValidatorSet */ function withdraw() external { - WithdrawalQueue storage queue = withdrawals[msg.sender]; + WithdrawalQueue storage queue = _withdrawals[msg.sender]; (uint256 amount, uint256 newHead) = queue.withdrawable(currentEpochId); queue.head = newHead; emit Withdrawal(msg.sender, amount); - stateSender.syncState(rootChainManager, abi.encode(UNSTAKE_SIG, msg.sender, amount)); + _stateSender.syncState(_rootChainManager, abi.encode(_UNSTAKE_SIG, msg.sender, amount)); } /** @@ -124,14 +122,14 @@ contract ValidatorSet is IValidatorSet, ERC20VotesUpgradeable, System { */ // slither-disable-next-line unused-return function withdrawable(address account) external view returns (uint256 amount) { - (amount, ) = withdrawals[account].withdrawable(currentEpochId); + (amount, ) = _withdrawals[account].withdrawable(currentEpochId); } /** * @inheritdoc IValidatorSet */ function pendingWithdrawals(address account) external view returns (uint256) { - return withdrawals[account].pending(currentEpochId); + return _withdrawals[account].pending(currentEpochId); } /** @@ -151,7 +149,7 @@ contract ValidatorSet is IValidatorSet, ERC20VotesUpgradeable, System { } function _registerWithdrawal(address account, uint256 amount) internal { - withdrawals[account].append(amount, currentEpochId + networkParams.withdrawalWaitPeriod()); + _withdrawals[account].append(amount, currentEpochId + _networkParams.withdrawalWaitPeriod()); emit WithdrawalRegistered(account, amount); } @@ -162,7 +160,7 @@ contract ValidatorSet is IValidatorSet, ERC20VotesUpgradeable, System { for (uint256 i = 0; i < length; ) { _burn(validatorsToSlash[i], balanceOf(validatorsToSlash[i])); // unstake validator // slither-disable-next-line mapping-deletion - delete withdrawals[validatorsToSlash[i]]; // remove pending withdrawals + delete _withdrawals[validatorsToSlash[i]]; // remove pending withdrawals unchecked { ++i; } diff --git a/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/README.md b/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/README.md deleted file mode 100644 index 530da6e6..00000000 --- a/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/README.md +++ /dev/null @@ -1,9 +0,0 @@ -### Changes - -- The `__gap`s have been trimmed down in all contracts -- `LegacyStateVars` have been injected into `EIP712Upgradeable` -- The import paths have been adjusted - -### Checks - -See the [script](../../../../../../scripts/maintenance/checkModifiedOpenZeppelinContracts.js) diff --git a/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol b/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol deleted file mode 100644 index 1d636509..00000000 --- a/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol +++ /dev/null @@ -1,115 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Permit.sol) -// customized by Polygon in order to synchronize storage slots between contracts - -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; -import "../../../utils/cryptography/EIP712Upgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; - -/** - * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in - * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. - * - * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by - * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't - * need to send a transaction, and thus is not required to hold Ether at all. - * - * _Available since v3.4._ - * - * @custom:storage-size 51 - */ -abstract contract ERC20PermitUpgradeable is - Initializable, - ERC20Upgradeable, - IERC20PermitUpgradeable, - EIP712Upgradeable -{ - using CountersUpgradeable for CountersUpgradeable.Counter; - - mapping(address => CountersUpgradeable.Counter) private _nonces; - - // solhint-disable-next-line var-name-mixedcase - bytes32 private constant _PERMIT_TYPEHASH = - keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); - /** - * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`. - * However, to ensure consistency with the upgradeable transpiler, we will continue - * to reserve a slot. - * @custom:oz-renamed-from _PERMIT_TYPEHASH - */ - // solhint-disable-next-line var-name-mixedcase - bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT; - - /** - * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. - * - * It's a good idea to use the same `name` that is defined as the ERC20 token name. - */ - function __ERC20Permit_init(string memory name) internal onlyInitializing { - __EIP712_init_unchained(name, "1"); - } - - function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {} - - /** - * @dev See {IERC20Permit-permit}. - */ - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual override { - require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); - - bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); - - bytes32 hash = _hashTypedDataV4(structHash); - - address signer = ECDSAUpgradeable.recover(hash, v, r, s); - require(signer == owner, "ERC20Permit: invalid signature"); - - _approve(owner, spender, value); - } - - /** - * @dev See {IERC20Permit-nonces}. - */ - function nonces(address owner) public view virtual override returns (uint256) { - return _nonces[owner].current(); - } - - /** - * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. - */ - // solhint-disable-next-line func-name-mixedcase - function DOMAIN_SEPARATOR() external view override returns (bytes32) { - return _domainSeparatorV4(); - } - - /** - * @dev "Consume a nonce": return the current value and increment. - * - * _Available since v4.1._ - */ - function _useNonce(address owner) internal virtual returns (uint256 current) { - CountersUpgradeable.Counter storage nonce = _nonces[owner]; - current = nonce.current(); - nonce.increment(); - } - - /** - * @dev This empty reserved space is put in place to allow future versions to add new - * variables without shifting down storage in the inheritance chain. - * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps - */ - uint256[49 - 36] private __gap; -} diff --git a/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol b/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol deleted file mode 100644 index 1b02706e..00000000 --- a/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol +++ /dev/null @@ -1,308 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Votes.sol) -// customized by Polygon in order to synchronize storage slots between contracts - -pragma solidity ^0.8.0; - -import "./ERC20PermitUpgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/interfaces/IERC5805Upgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; - -/** - * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, - * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. - * - * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. - * - * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either - * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting - * power can be queried through the public accessors {getVotes} and {getPastVotes}. - * - * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it - * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. - * - * _Available since v4.2._ - */ -abstract contract ERC20VotesUpgradeable is Initializable, ERC20PermitUpgradeable, IERC5805Upgradeable { - function __ERC20Votes_init() internal onlyInitializing {} - - function __ERC20Votes_init_unchained() internal onlyInitializing {} - - struct Checkpoint { - uint32 fromBlock; - uint224 votes; - } - - bytes32 private constant _DELEGATION_TYPEHASH = - keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); - - mapping(address => address) private _delegates; - mapping(address => Checkpoint[]) private _checkpoints; - Checkpoint[] private _totalSupplyCheckpoints; - - /** - * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting). - */ - function clock() public view virtual override returns (uint48) { - return SafeCastUpgradeable.toUint48(block.number); - } - - /** - * @dev Description of the clock - */ - // solhint-disable-next-line func-name-mixedcase - function CLOCK_MODE() public view virtual override returns (string memory) { - // Check that the clock was not modified - require(clock() == block.number, "ERC20Votes: broken clock mode"); - return "mode=blocknumber&from=default"; - } - - /** - * @dev Get the `pos`-th checkpoint for `account`. - */ - function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { - return _checkpoints[account][pos]; - } - - /** - * @dev Get number of checkpoints for `account`. - */ - function numCheckpoints(address account) public view virtual returns (uint32) { - return SafeCastUpgradeable.toUint32(_checkpoints[account].length); - } - - /** - * @dev Get the address `account` is currently delegating to. - */ - function delegates(address account) public view virtual override returns (address) { - return _delegates[account]; - } - - /** - * @dev Gets the current votes balance for `account` - */ - function getVotes(address account) public view virtual override returns (uint256) { - uint256 pos = _checkpoints[account].length; - unchecked { - return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; - } - } - - /** - * @dev Retrieve the number of votes for `account` at the end of `timepoint`. - * - * Requirements: - * - * - `timepoint` must be in the past - */ - function getPastVotes(address account, uint256 timepoint) public view virtual override returns (uint256) { - require(timepoint < clock(), "ERC20Votes: future lookup"); - return _checkpointsLookup(_checkpoints[account], timepoint); - } - - /** - * @dev Retrieve the `totalSupply` at the end of `timepoint`. Note, this value is the sum of all balances. - * It is NOT the sum of all the delegated votes! - * - * Requirements: - * - * - `timepoint` must be in the past - */ - function getPastTotalSupply(uint256 timepoint) public view virtual override returns (uint256) { - require(timepoint < clock(), "ERC20Votes: future lookup"); - return _checkpointsLookup(_totalSupplyCheckpoints, timepoint); - } - - /** - * @dev Lookup a value in a list of (sorted) checkpoints. - */ - function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) { - // We run a binary search to look for the last (most recent) checkpoint taken before (or at) `timepoint`. - // - // Initially we check if the block is recent to narrow the search range. - // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). - // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. - // - If the middle checkpoint is after `timepoint`, we look in [low, mid) - // - If the middle checkpoint is before or equal to `timepoint`, we look in [mid+1, high) - // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not - // out of bounds (in which case we're looking too far in the past and the result is 0). - // Note that if the latest checkpoint available is exactly for `timepoint`, we end up with an index that is - // past the end of the array, so we technically don't find a checkpoint after `timepoint`, but it works out - // the same. - uint256 length = ckpts.length; - - uint256 low = 0; - uint256 high = length; - - if (length > 5) { - uint256 mid = length - MathUpgradeable.sqrt(length); - if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { - high = mid; - } else { - low = mid + 1; - } - } - - while (low < high) { - uint256 mid = MathUpgradeable.average(low, high); - if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { - high = mid; - } else { - low = mid + 1; - } - } - - unchecked { - return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes; - } - } - - /** - * @dev Delegate votes from the sender to `delegatee`. - */ - function delegate(address delegatee) public virtual override { - _delegate(_msgSender(), delegatee); - } - - /** - * @dev Delegates votes from signer to `delegatee` - */ - function delegateBySig( - address delegatee, - uint256 nonce, - uint256 expiry, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual override { - require(block.timestamp <= expiry, "ERC20Votes: signature expired"); - address signer = ECDSAUpgradeable.recover( - _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), - v, - r, - s - ); - require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); - _delegate(signer, delegatee); - } - - /** - * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). - */ - function _maxSupply() internal view virtual returns (uint224) { - return type(uint224).max; - } - - /** - * @dev Snapshots the totalSupply after it has been increased. - */ - function _mint(address account, uint256 amount) internal virtual override { - super._mint(account, amount); - require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); - - _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); - } - - /** - * @dev Snapshots the totalSupply after it has been decreased. - */ - function _burn(address account, uint256 amount) internal virtual override { - super._burn(account, amount); - - _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); - } - - /** - * @dev Move voting power when tokens are transferred. - * - * Emits a {IVotes-DelegateVotesChanged} event. - */ - function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual override { - super._afterTokenTransfer(from, to, amount); - - _moveVotingPower(delegates(from), delegates(to), amount); - } - - /** - * @dev Change delegation for `delegator` to `delegatee`. - * - * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}. - */ - function _delegate(address delegator, address delegatee) internal virtual { - address currentDelegate = delegates(delegator); - uint256 delegatorBalance = balanceOf(delegator); - _delegates[delegator] = delegatee; - - emit DelegateChanged(delegator, currentDelegate, delegatee); - - _moveVotingPower(currentDelegate, delegatee, delegatorBalance); - } - - function _moveVotingPower(address src, address dst, uint256 amount) private { - if (src != dst && amount > 0) { - if (src != address(0)) { - (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); - emit DelegateVotesChanged(src, oldWeight, newWeight); - } - - if (dst != address(0)) { - (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); - emit DelegateVotesChanged(dst, oldWeight, newWeight); - } - } - } - - function _writeCheckpoint( - Checkpoint[] storage ckpts, - function(uint256, uint256) view returns (uint256) op, - uint256 delta - ) private returns (uint256 oldWeight, uint256 newWeight) { - uint256 pos = ckpts.length; - - unchecked { - Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1); - - oldWeight = oldCkpt.votes; - newWeight = op(oldWeight, delta); - - if (pos > 0 && oldCkpt.fromBlock == clock()) { - _unsafeAccess(ckpts, pos - 1).votes = SafeCastUpgradeable.toUint224(newWeight); - } else { - ckpts.push( - Checkpoint({ - fromBlock: SafeCastUpgradeable.toUint32(clock()), - votes: SafeCastUpgradeable.toUint224(newWeight) - }) - ); - } - } - } - - function _add(uint256 a, uint256 b) private pure returns (uint256) { - return a + b; - } - - function _subtract(uint256 a, uint256 b) private pure returns (uint256) { - return a - b; - } - - /** - * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. - */ - function _unsafeAccess(Checkpoint[] storage ckpts, uint256 pos) private pure returns (Checkpoint storage result) { - assembly { - mstore(0, ckpts.slot) - result.slot := add(keccak256(0, 0x20), pos) - } - } - - /** - * @dev This empty reserved space is put in place to allow future versions to add new - * variables without shifting down storage in the inheritance chain. - * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps - */ - uint256[47 - 35] private __gap; -} diff --git a/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol b/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol deleted file mode 100644 index d819d499..00000000 --- a/contracts/child/validator/legacy-compat/@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol +++ /dev/null @@ -1,208 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol) -// customized by Polygon in order to synchronize storage slots between contracts - -pragma solidity ^0.8.8; - -import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/interfaces/IERC5267Upgradeable.sol"; -import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; - -import {LegacyStateVars} from "../../../../LegacyStateVars.sol"; - -/** - * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. - * - * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, - * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding - * they need in their contracts using a combination of `abi.encode` and `keccak256`. - * - * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding - * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA - * ({_hashTypedDataV4}). - * - * The implementation of the domain separator was designed to be as efficient as possible while still properly updating - * the chain id to protect against replay attacks on an eventual fork of the chain. - * - * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method - * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. - * - * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain - * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the - * separator from the immutable values, which is cheaper than accessing a cached version in cold storage. - * - * _Available since v3.4._ - * - * @custom:storage-size 52 - */ -abstract contract EIP712Upgradeable is Initializable, IERC5267Upgradeable, LegacyStateVars { - bytes32 private constant _TYPE_HASH = - keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); - - /// @custom:oz-renamed-from _HASHED_NAME - bytes32 private _hashedName; - /// @custom:oz-renamed-from _HASHED_VERSION - bytes32 private _hashedVersion; - - string private _name; - string private _version; - - /** - * @dev Initializes the domain separator and parameter caches. - * - * The meaning of `name` and `version` is specified in - * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: - * - * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. - * - `version`: the current major version of the signing domain. - * - * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart - * contract upgrade]. - */ - function __EIP712_init(string memory name, string memory version) internal onlyInitializing { - __EIP712_init_unchained(name, version); - } - - function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing { - _name = name; - _version = version; - - // Reset prior values in storage if upgrading - _hashedName = 0; - _hashedVersion = 0; - } - - /** - * @dev Returns the domain separator for the current chain. - */ - function _domainSeparatorV4() internal view returns (bytes32) { - return _buildDomainSeparator(); - } - - function _buildDomainSeparator() private view returns (bytes32) { - return keccak256(abi.encode(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this))); - } - - /** - * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this - * function returns the hash of the fully encoded EIP712 message for this domain. - * - * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: - * - * ```solidity - * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( - * keccak256("Mail(address to,string contents)"), - * mailTo, - * keccak256(bytes(mailContents)) - * ))); - * address signer = ECDSA.recover(digest, signature); - * ``` - */ - function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { - return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); - } - - /** - * @dev See {EIP-5267}. - * - * _Available since v4.9._ - */ - function eip712Domain() - public - view - virtual - override - returns ( - bytes1 fields, - string memory name, - string memory version, - uint256 chainId, - address verifyingContract, - bytes32 salt, - uint256[] memory extensions - ) - { - // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized - // and the EIP712 domain is not reliable, as it will be missing name and version. - require(_hashedName == 0 && _hashedVersion == 0, "EIP712: Uninitialized"); - - return ( - hex"0f", // 01111 - _EIP712Name(), - _EIP712Version(), - block.chainid, - address(this), - bytes32(0), - new uint256[](0) - ); - } - - /** - * @dev The name parameter for the EIP712 domain. - * - * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs - * are a concern. - */ - function _EIP712Name() internal view virtual returns (string memory) { - return _name; - } - - /** - * @dev The version parameter for the EIP712 domain. - * - * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs - * are a concern. - */ - function _EIP712Version() internal view virtual returns (string memory) { - return _version; - } - - /** - * @dev The hash of the name parameter for the EIP712 domain. - * - * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead. - */ - function _EIP712NameHash() internal view returns (bytes32) { - string memory name = _EIP712Name(); - if (bytes(name).length > 0) { - return keccak256(bytes(name)); - } else { - // If the name is empty, the contract may have been upgraded without initializing the new storage. - // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design. - bytes32 hashedName = _hashedName; - if (hashedName != 0) { - return hashedName; - } else { - return keccak256(""); - } - } - } - - /** - * @dev The hash of the version parameter for the EIP712 domain. - * - * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead. - */ - function _EIP712VersionHash() internal view returns (bytes32) { - string memory version = _EIP712Version(); - if (bytes(version).length > 0) { - return keccak256(bytes(version)); - } else { - // If the version is empty, the contract may have been upgraded without initializing the new storage. - // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design. - bytes32 hashedVersion = _hashedVersion; - if (hashedVersion != 0) { - return hashedVersion; - } else { - return keccak256(""); - } - } - } - - /** - * @dev This empty reserved space is put in place to allow future versions to add new - * variables without shifting down storage in the inheritance chain. - * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps - */ - uint256[48 - 36] private __gap; -} diff --git a/contracts/child/validator/legacy-compat/LegacyStateVars.sol b/contracts/child/validator/legacy-compat/LegacyStateVars.sol deleted file mode 100644 index df029d0e..00000000 --- a/contracts/child/validator/legacy-compat/LegacyStateVars.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import {CountersUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; - -abstract contract LegacyStateVars { - // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a - // Snapshot struct, but that would impede usage of functions that work on an array. - struct Snapshots { - uint256[] ids; - uint256[] values; - } - - mapping(address => Snapshots) private _accountBalanceSnapshots; - Snapshots private _totalSupplySnapshots; - - // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. - CountersUpgradeable.Counter private _currentSnapshotId; -} diff --git a/contracts/child/validator/proxy/hardfork/RewardPoolHardforkProxy.sol b/contracts/child/validator/proxy/hardfork/RewardPoolHardforkProxy.sol deleted file mode 100644 index 99e4960c..00000000 --- a/contracts/child/validator/proxy/hardfork/RewardPoolHardforkProxy.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "contracts/lib/ProxyBase.sol"; - -/// @notice RewardPool-specific proxy for hardfork migration -/// @dev If starting fresh, use GenesisProxy instead -contract RewardPoolHardforkProxy is ProxyBase { - /// @notice function for initializing proxy for the RewardPool genesis contract - /// @dev meant to be deployed during genesis - /// @param logic the address of the implementation (logic) contract for the reward pool - /// @param admin the address that has permission to update what address contains the implementation - /// @param newNetworkParams address of genesis contract NetworkParams - function setUpProxy(address logic, address admin, address newNetworkParams) external { - _setUpProxy(logic, admin, ""); - - // this writes the address of NetworkParams to storage - // this is performed in assembly for contracts migrating from not being proxified - // slither-disable-next-line assembly - assembly { - sstore(56, newNetworkParams) - } - } -} diff --git a/contracts/child/validator/proxy/hardfork/ValidatorSetHardforkProxy.sol b/contracts/child/validator/proxy/hardfork/ValidatorSetHardforkProxy.sol deleted file mode 100644 index 3a0cf434..00000000 --- a/contracts/child/validator/proxy/hardfork/ValidatorSetHardforkProxy.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "contracts/lib/ProxyBase.sol"; - -/// @notice ValidatorSet-specific proxy for hardfork migration -/// @dev If starting fresh, use GenesisProxy instead -contract ValidatorSetHardforkProxy is ProxyBase { - /// @notice function for initializing proxy for the ValidatorSet genesis contract - /// @dev meant to be deployed during genesis - /// @param logic the address of the implementation (logic) contract for the validator set - /// @param admin the address that has permission to update what address contains the implementation - /// @param newNetworkParams address of genesis contract NetworkParams - function setUpProxy(address logic, address admin, address newNetworkParams) external { - _setUpProxy(logic, admin, ""); - - // this writes the address of NetworkParams to storage - // this is performed in assembly for contracts migrating from not being proxified - // slither-disable-next-line assembly - assembly { - sstore(209, newNetworkParams) - } - } -} diff --git a/contracts/lib/AccessList.sol b/contracts/lib/AccessList.sol index b5572123..f465c9d0 100644 --- a/contracts/lib/AccessList.sol +++ b/contracts/lib/AccessList.sol @@ -11,24 +11,24 @@ import {System} from "../child/System.sol"; @notice Checks the access lists to see if an address is allowed and not blocked */ contract AccessList is Ownable2StepUpgradeable, System { - bool private useAllowList; - bool private useBlockList; + bool private _useAllowList; + bool private _useBlockList; event AllowListUsageSet(uint256 indexed block, bool indexed status); event BlockListUsageSet(uint256 indexed block, bool indexed status); function setAllowList(bool newUseAllowList) external onlyOwner { - useAllowList = newUseAllowList; + _useAllowList = newUseAllowList; emit AllowListUsageSet(block.number, newUseAllowList); } function setBlockList(bool newUseBlockList) external onlyOwner { - useBlockList = newUseBlockList; + _useBlockList = newUseBlockList; emit BlockListUsageSet(block.number, newUseBlockList); } function _checkAccessList() internal view { - if (useAllowList) { + if (_useAllowList) { // solhint-disable avoid-low-level-calls // slither-disable-next-line low-level-calls (bool allowSuccess, bytes memory allowlistRes) = ALLOWLIST_PRECOMPILE.staticcall{gas: READ_ADDRESSLIST_GAS}( @@ -36,7 +36,7 @@ contract AccessList is Ownable2StepUpgradeable, System { ); require(allowSuccess && abi.decode(allowlistRes, (uint256)) > 0, "DISALLOWED_SENDER"); } - if (useBlockList) { + if (_useBlockList) { // slither-disable-next-line low-level-calls (bool blockSuccess, bytes memory blocklistRes) = BLOCKLIST_PRECOMPILE.staticcall{gas: READ_ADDRESSLIST_GAS}( abi.encodeWithSelector(IAddressList.readAddressList.selector, msg.sender) @@ -45,9 +45,9 @@ contract AccessList is Ownable2StepUpgradeable, System { } } - function _initializeAccessList(bool _useAllowList, bool _useBlockList) internal { - useAllowList = _useAllowList; - useBlockList = _useBlockList; + function _initializeAccessList(bool __useAllowList, bool __useBlockList) internal { + _useAllowList = __useAllowList; + _useBlockList = __useBlockList; } // slither-disable-next-line unused-state,naming-convention diff --git a/contracts/lib/EIP712MetaTransaction.sol b/contracts/lib/EIP712MetaTransaction.sol index 7c345ba6..b88da50b 100644 --- a/contracts/lib/EIP712MetaTransaction.sol +++ b/contracts/lib/EIP712MetaTransaction.sol @@ -5,7 +5,7 @@ import "./EIP712Upgradeable.sol"; // solhint-disable reason-string contract EIP712MetaTransaction is EIP712Upgradeable { - bytes32 private constant META_TRANSACTION_TYPEHASH = + bytes32 private constant _META_TRANSACTION_TYPEHASH = keccak256(bytes("MetaTransaction(uint256 nonce,address from,bytes functionSignature)")); event MetaTransactionExecuted(address userAddress, address relayerAddress, bytes functionSignature); @@ -96,7 +96,7 @@ contract EIP712MetaTransaction is EIP712Upgradeable { function _hashMetaTransaction(MetaTransaction memory metaTx) private pure returns (bytes32) { return keccak256( - abi.encode(META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature)) + abi.encode(_META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature)) ); } diff --git a/contracts/lib/GenesisProxy.sol b/contracts/lib/GenesisProxy.sol deleted file mode 100644 index 3b01f464..00000000 --- a/contracts/lib/GenesisProxy.sol +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./ProxyBase.sol"; - -/** - @title GenesisProxy - @author Polygon Technology - @notice wrapper for OpenZeppelin's Transparent Upgreadable Proxy, intended for use during genesis for genesis contracts - @notice one GenesisProxy should be deployed for each genesis contract, but there are exceptions if hardforking - see below - @dev If hardforking, for ValidatorSet, RewardPool, ForkParams, and NetworkParams, use the respective dedicated HardforkProxy instead - */ -contract GenesisProxy is ProxyBase { - /// @notice function for initializing proxy - /// @param logic the address of the implementation (logic) contract for the genesis contract - /// @param admin the address that has permission to update what address contains the implementation - /// @param data raw calldata for the intialization of the genesis contract (if required) - function setUpProxy(address logic, address admin, bytes memory data) external { - _setUpProxy(logic, admin, data); - } -} diff --git a/contracts/lib/ProxyBase.sol b/contracts/lib/ProxyBase.sol deleted file mode 100644 index b8ad7f2a..00000000 --- a/contracts/lib/ProxyBase.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; - -abstract contract ProxyBase is TransparentUpgradeableProxy { - // Required by compiler. Not meant to be used in the traditional way. - constructor() TransparentUpgradeableProxy(address(this), msg.sender, "") {} - - function _setUpProxy(address logic, address admin, bytes memory data) internal { - bytes32 setUpState; - bytes32 setUpSlot = keccak256("ProxyBase _setUpProxy setUpSlot"); - - // slither-disable-next-line assembly - assembly { - setUpState := sload(setUpSlot) - } - - require(setUpState == "", "ProxyBase: Already set up."); - - // TransparentUpgradeableProxy - _changeAdmin(admin); - - // ERC1967Proxy - _upgradeToAndCall(logic, data, false); - - // slither-disable-next-line assembly - assembly { - sstore(setUpSlot, 0x01) - } - } -} diff --git a/contracts/root/ExitHelper.sol b/contracts/root/ExitHelper.sol index fe4bc29b..dd0bd630 100644 --- a/contracts/root/ExitHelper.sol +++ b/contracts/root/ExitHelper.sol @@ -100,5 +100,5 @@ contract ExitHelper is IExitHelper, Initializable { } // slither-disable-next-line unused-state,naming-convention - uint256[49] private __gap; + uint256[50] private __gap; } diff --git a/contracts/root/staking/CustomSupernetManager.sol b/contracts/root/staking/CustomSupernetManager.sol index 54d7ee23..528a0de0 100644 --- a/contracts/root/staking/CustomSupernetManager.sol +++ b/contracts/root/staking/CustomSupernetManager.sol @@ -14,15 +14,15 @@ contract CustomSupernetManager is ICustomSupernetManager, Ownable2StepUpgradeabl using SafeERC20 for IERC20; using GenesisLib for GenesisSet; - bytes32 private constant STAKE_SIG = keccak256("STAKE"); - bytes32 private constant UNSTAKE_SIG = keccak256("UNSTAKE"); - bytes32 private constant SLASH_SIG = keccak256("SLASH"); + bytes32 private constant _STAKE_SIG = keccak256("STAKE"); + bytes32 private constant _UNSTAKE_SIG = keccak256("UNSTAKE"); + bytes32 private constant _SLASH_SIG = keccak256("SLASH"); - IBLS private bls; - IStateSender private stateSender; - IERC20 private matic; - address private childValidatorSet; - address private exitHelper; + IBLS private _bls; + IStateSender private _stateSender; + IERC20 private _matic; + address private _childValidatorSet; + address private _exitHelper; bytes32 public domain; @@ -54,11 +54,11 @@ contract CustomSupernetManager is ICustomSupernetManager, Ownable2StepUpgradeabl "INVALID_INPUT" ); __SupernetManager_init(newStakeManager); - bls = IBLS(newBls); - stateSender = IStateSender(newStateSender); - matic = IERC20(newMatic); - childValidatorSet = newChildValidatorSet; - exitHelper = newExitHelper; + _bls = IBLS(newBls); + _stateSender = IStateSender(newStateSender); + _matic = IERC20(newMatic); + _childValidatorSet = newChildValidatorSet; + _exitHelper = newExitHelper; domain = keccak256(abi.encodePacked(newDomain)); __Ownable2Step_init(); } @@ -108,19 +108,19 @@ contract CustomSupernetManager is ICustomSupernetManager, Ownable2StepUpgradeabl * @inheritdoc ICustomSupernetManager */ function withdrawSlashedStake(address to) external onlyOwner { - uint256 balance = matic.balanceOf(address(this)); - matic.safeTransfer(to, balance); + uint256 balance = _matic.balanceOf(address(this)); + _matic.safeTransfer(to, balance); } /** * @inheritdoc ICustomSupernetManager */ function onL2StateReceive(uint256 /*id*/, address sender, bytes calldata data) external { - if (msg.sender != exitHelper || sender != childValidatorSet) revert Unauthorized("exitHelper"); - if (bytes32(data[:32]) == UNSTAKE_SIG) { + if (msg.sender != _exitHelper || sender != _childValidatorSet) revert Unauthorized("_exitHelper"); + if (bytes32(data[:32]) == _UNSTAKE_SIG) { (address validator, uint256 amount) = abi.decode(data[32:], (address, uint256)); _unstake(validator, amount); - } else if (bytes32(data[:32]) == SLASH_SIG) { + } else if (bytes32(data[:32]) == _SLASH_SIG) { (, address[] memory validatorsToSlash, uint256 slashingPercentage, uint256 slashIncentivePercentage) = abi .decode(data, (bytes32, address[], uint256, uint256)); _slash(id, validatorsToSlash, slashingPercentage, slashIncentivePercentage); @@ -146,7 +146,7 @@ contract CustomSupernetManager is ICustomSupernetManager, Ownable2StepUpgradeabl if (_genesis.gatheringGenesisValidators()) { _genesis.insert(validator, amount); } else if (_genesis.completed()) { - stateSender.syncState(childValidatorSet, abi.encode(STAKE_SIG, validator, amount)); + _stateSender.syncState(_childValidatorSet, abi.encode(_STAKE_SIG, validator, amount)); } else { revert Unauthorized("Wait for genesis"); } @@ -154,7 +154,7 @@ contract CustomSupernetManager is ICustomSupernetManager, Ownable2StepUpgradeabl function _unstake(address validator, uint256 amount) internal { // slither-disable-next-line reentrancy-benign,reentrancy-events - stakeManager.releaseStakeOf(validator, amount); + _stakeManager.releaseStakeOf(validator, amount); _removeIfValidatorUnstaked(validator); } @@ -167,9 +167,9 @@ contract CustomSupernetManager is ICustomSupernetManager, Ownable2StepUpgradeabl uint256 length = validatorsToSlash.length; uint256 totalSlashedAmount; for (uint256 i = 0; i < length; ) { - uint256 slashedAmount = (stakeManager.stakeOf(validatorsToSlash[i], id) * slashingPercentage) / 100; + uint256 slashedAmount = (_stakeManager.stakeOf(validatorsToSlash[i], id) * slashingPercentage) / 100; // slither-disable-next-line reentrancy-benign,reentrancy-events,reentrancy-no-eth - stakeManager.slashStakeOf(validatorsToSlash[i], slashedAmount); + _stakeManager.slashStakeOf(validatorsToSlash[i], slashedAmount); _removeIfValidatorUnstaked(validatorsToSlash[i]); totalSlashedAmount += slashedAmount; unchecked { @@ -179,12 +179,12 @@ contract CustomSupernetManager is ICustomSupernetManager, Ownable2StepUpgradeabl // contract will always have enough balance since slashStakeOf returns entire slashed amt uint256 rewardAmount = (totalSlashedAmount * slashIncentivePercentage) / 100; - matic.safeTransfer(IExitHelper(exitHelper).caller(), rewardAmount); + _matic.safeTransfer(IExitHelper(_exitHelper).caller(), rewardAmount); // complete slashing on child chain - stateSender.syncState( - childValidatorSet, - abi.encode(SLASH_SIG, exitEventId, validatorsToSlash, slashingPercentage) + _stateSender.syncState( + _childValidatorSet, + abi.encode(_SLASH_SIG, exitEventId, validatorsToSlash, slashingPercentage) ); } @@ -196,14 +196,14 @@ contract CustomSupernetManager is ICustomSupernetManager, Ownable2StepUpgradeabl /// @dev signature verification succeeds if signature and pubkey are empty if (signature[0] == 0 && signature[1] == 0) revert InvalidSignature(signer); // slither-disable-next-line calls-loop - (bool result, bool callSuccess) = bls.verifySingle(signature, pubkey, _message(signer)); + (bool result, bool callSuccess) = _bls.verifySingle(signature, pubkey, _message(signer)); if (!callSuccess || !result) revert InvalidSignature(signer); } /// @notice Message to sign for registration function _message(address signer) internal view returns (uint256[2] memory) { // slither-disable-next-line calls-loop - return bls.hashToPoint(domain, abi.encodePacked(signer, address(this), block.chainid)); + return _bls.hashToPoint(domain, abi.encodePacked(signer, address(this), block.chainid)); } function _addToWhitelist(address validator) internal { @@ -217,7 +217,7 @@ contract CustomSupernetManager is ICustomSupernetManager, Ownable2StepUpgradeabl } function _removeIfValidatorUnstaked(address validator) internal { - if (stakeManager.stakeOf(validator, id) == 0) { + if (_stakeManager.stakeOf(validator, id) == 0) { validators[validator].isActive = false; emit ValidatorDeactivated(validator); } diff --git a/contracts/root/staking/StakeManager.sol b/contracts/root/staking/StakeManager.sol index 4f483d3b..f08d04e7 100644 --- a/contracts/root/staking/StakeManager.sol +++ b/contracts/root/staking/StakeManager.sol @@ -5,22 +5,16 @@ import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../interfaces/root/staking/IStakeManager.sol"; -// the next import is to facilitate storage compatibility across versions of StakeManager -import {StakeManagerLegacyCompatStorage} from "./StakeManagerLegacyCompatStorage.sol"; import "./StakeManagerChildData.sol"; import "./StakeManagerStakingData.sol"; -contract StakeManager is - IStakeManager, - Initializable, - StakeManagerLegacyCompatStorage, - StakeManagerChildData, - StakeManagerStakingData -{ +contract StakeManager is IStakeManager, Initializable, StakeManagerChildData, StakeManagerStakingData { using SafeERC20 for IERC20; + IERC20 internal _stakingToken; + function initialize(address newStakingToken) public initializer { - stakingToken = IERC20(newStakingToken); + _stakingToken = IERC20(newStakingToken); } /** @@ -38,9 +32,9 @@ contract StakeManager is * @inheritdoc IStakeManager */ function stakeFor(uint256 id, uint256 amount) external { - require(id != 0 && id <= counter, "StakeManager: INVALID_ID"); + require(id != 0 && id <= _counter, "StakeManager: INVALID_ID"); // slither-disable-next-line reentrancy-benign,reentrancy-events - stakingToken.safeTransferFrom(msg.sender, address(this), amount); + _stakingToken.safeTransferFrom(msg.sender, address(this), amount); // calling the library directly once fixes the coverage issue // https://github.com/foundry-rs/foundry/issues/4854#issuecomment-1528897219 _addStake(msg.sender, id, amount); @@ -132,7 +126,7 @@ contract StakeManager is function _withdrawStake(address validator, address to, uint256 amount) private { _withdrawStake(validator, amount); // slither-disable-next-line reentrancy-events - stakingToken.safeTransfer(to, amount); + _stakingToken.safeTransfer(to, amount); emit StakeWithdrawn(validator, to, amount); } diff --git a/contracts/root/staking/StakeManagerChildData.sol b/contracts/root/staking/StakeManagerChildData.sol index f7eea08b..51062d2d 100644 --- a/contracts/root/staking/StakeManagerChildData.sol +++ b/contracts/root/staking/StakeManagerChildData.sol @@ -1,15 +1,20 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.19; -// the next import is to facilitate storage compatibility across versions of StakeManager -import {StakeManagerLegacyCompatStorage} from "./StakeManagerLegacyCompatStorage.sol"; - /** * @title StakeManagerChildData * @notice Holds data to allow look-up between child chain manager contract address and child chain id. * Note that this is contract is designed to be included in StakeManager. It is upgradeable. */ -abstract contract StakeManagerChildData is StakeManagerLegacyCompatStorage { +abstract contract StakeManagerChildData { + // Highest child chain id allocated thus far. Child chain id 0x00 is an invalid id. + uint256 internal _counter; + // child chain id to child chain manager contract address. + mapping(uint256 => address) private _managers; + // child chain manager contract address to child chain id. + // slither-disable-next-line naming-convention + mapping(address => uint256) internal _ids; + /** * @notice Register a child chain manager contract and allocate a child chain id. * @param manager Child chain manager contract address. @@ -18,9 +23,9 @@ abstract contract StakeManagerChildData is StakeManagerLegacyCompatStorage { function _registerChild(address manager) internal returns (uint256 id) { require(manager != address(0), "StakeManagerChildData: INVALID_ADDRESS"); unchecked { - id = ++counter; + id = ++_counter; } - __managers[id] = manager; + _managers[id] = manager; _ids[manager] = id; } @@ -30,7 +35,7 @@ abstract contract StakeManagerChildData is StakeManagerLegacyCompatStorage { * @return manager Child chain manager contract address. */ function _managerOf(uint256 id) internal view returns (address manager) { - manager = __managers[id]; + manager = _managers[id]; require(manager != address(0), "StakeManagerChildData: INVALID_ID"); } @@ -43,4 +48,8 @@ abstract contract StakeManagerChildData is StakeManagerLegacyCompatStorage { id = _ids[manager]; require(id != 0, "StakeManagerChildData: INVALID_MANAGER"); } + + // Storage gap + // slither-disable-next-line unused-state,naming-convention + uint256[50] private __gap; } diff --git a/contracts/root/staking/StakeManagerLegacyCompatStorage.sol b/contracts/root/staking/StakeManagerLegacyCompatStorage.sol deleted file mode 100644 index d905e6a0..00000000 --- a/contracts/root/staking/StakeManagerLegacyCompatStorage.sol +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity 0.8.19; - -import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; - -abstract contract StakeManagerLegacyCompatStorage { - // StakeManager - - IERC20 internal stakingToken; - - // StakeManagerChildData - - // Highest child chain id allocated thus far. Child chain id 0x00 is an invalid id. - uint256 internal counter; - // child chain id to child chain manager contract address. - // slither-disable-next-line naming-convention - mapping(uint256 => address) internal __managers; - // child chain manager contract address to child chain id. - // slither-disable-next-line naming-convention - mapping(address => uint256) internal _ids; - - // StakeManagerStakingData - - // slither-disable-next-line naming-convention - uint256 internal _totalStake; - // validator => child => amount - // slither-disable-next-line naming-convention - mapping(address => mapping(uint256 => uint256)) internal __stakes; - // child chain id => total stake - // slither-disable-next-line naming-convention - mapping(uint256 => uint256) internal __totalStakePerChild; - // validator address => stake across all child chains. - // slither-disable-next-line naming-convention - mapping(address => uint256) internal __totalStakes; - // validator address => withdrawable stake. - // slither-disable-next-line naming-convention - mapping(address => uint256) internal __withdrawableStakes; - - // Storage gaps - - // slither-disable-next-line unused-state,naming-convention - uint256[50] private __StakeManagerChildData_gap; - - // slither-disable-next-line unused-state,naming-convention - uint256[50] private __StakeManagerStakingData_gap; -} diff --git a/contracts/root/staking/StakeManagerStakingData.sol b/contracts/root/staking/StakeManagerStakingData.sol index 9e10966c..9d1b9042 100644 --- a/contracts/root/staking/StakeManagerStakingData.sol +++ b/contracts/root/staking/StakeManagerStakingData.sol @@ -1,47 +1,59 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.19; -// the next import is to facilitate storage compatibility across versions of StakeManager -import {StakeManagerLegacyCompatStorage} from "./StakeManagerLegacyCompatStorage.sol"; - /** * @title StakeManagerStakingData * @notice Holds all staking related data. * Note that this is contract is designed to be included in StakeManager. It is upgradeable. */ -abstract contract StakeManagerStakingData is StakeManagerLegacyCompatStorage { +abstract contract StakeManagerStakingData { + // slither-disable-next-line naming-convention + uint256 internal _totalStake; + // validator => child => amount + mapping(address => mapping(uint256 => uint256)) private _stakes; + // child chain id => total stake + mapping(uint256 => uint256) private _totalStakePerChild; + // validator address => stake across all child chains. + mapping(address => uint256) private _totalStakes; + // validator address => withdrawable stake. + mapping(address => uint256) private _withdrawableStakes; + function _addStake(address validator, uint256 id, uint256 amount) internal { - __stakes[validator][id] += amount; - __totalStakePerChild[id] += amount; - __totalStakes[validator] += amount; + _stakes[validator][id] += amount; + _totalStakePerChild[id] += amount; + _totalStakes[validator] += amount; _totalStake += amount; } function _removeStake(address validator, uint256 id, uint256 amount) internal { - __stakes[validator][id] -= amount; - __totalStakePerChild[id] -= amount; - __totalStakes[validator] -= amount; + _stakes[validator][id] -= amount; + _totalStakePerChild[id] -= amount; + _totalStakes[validator] -= amount; _totalStake -= amount; - __withdrawableStakes[validator] += amount; + _withdrawableStakes[validator] += amount; } function _withdrawStake(address validator, uint256 amount) internal { - __withdrawableStakes[validator] -= amount; + _withdrawableStakes[validator] -= amount; } function _withdrawableStakeOf(address validator) internal view returns (uint256 amount) { - amount = __withdrawableStakes[validator]; + amount = _withdrawableStakes[validator]; } function _totalStakeOfChild(uint256 id) internal view returns (uint256 amount) { - amount = __totalStakePerChild[id]; + amount = _totalStakePerChild[id]; } function _stakeOf(address validator, uint256 id) internal view returns (uint256 amount) { - amount = __stakes[validator][id]; + amount = _stakes[validator][id]; } function _totalStakeOf(address validator) internal view returns (uint256 amount) { - amount = __totalStakes[validator]; + amount = _totalStakes[validator]; } + + // Storage gap + // slither-disable-next-line unused-state,naming-convention + uint256[50] private __gap; } diff --git a/contracts/root/staking/SupernetManager.sol b/contracts/root/staking/SupernetManager.sol index 2295c398..fc273312 100644 --- a/contracts/root/staking/SupernetManager.sol +++ b/contracts/root/staking/SupernetManager.sol @@ -6,17 +6,17 @@ import "../../interfaces/root/staking/IStakeManager.sol"; import "../../interfaces/root/staking/ISupernetManager.sol"; abstract contract SupernetManager is ISupernetManager, Initializable { - IStakeManager internal stakeManager; + IStakeManager internal _stakeManager; uint256 public id; modifier onlyStakeManager() { - require(msg.sender == address(stakeManager), "SupernetManager: ONLY_STAKE_MANAGER"); + require(msg.sender == address(_stakeManager), "SupernetManager: ONLY_STAKE_MANAGER"); _; } // slither-disable-next-line naming-convention function __SupernetManager_init(address newStakeManager) internal onlyInitializing { - stakeManager = IStakeManager(newStakeManager); + _stakeManager = IStakeManager(newStakeManager); } function onInit(uint256 id_) external onlyStakeManager { diff --git a/docs/child/proxy/hardfork/ForkParamsHardforkProxy.md b/docs/child/proxy/hardfork/ForkParamsHardforkProxy.md deleted file mode 100644 index b5e2c33c..00000000 --- a/docs/child/proxy/hardfork/ForkParamsHardforkProxy.md +++ /dev/null @@ -1,84 +0,0 @@ -# ForkParamsHardforkProxy - - - - - -ForkParams-specific proxy for hardfork migration - -*If starting fresh, use GenesisProxy instead* - -## Methods - -### setUpProxy - -```solidity -function setUpProxy(address logic, address admin) external nonpayable -``` - - - - - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| logic | address | undefined | -| admin | address | undefined | - - - -## Events - -### AdminChanged - -```solidity -event AdminChanged(address previousAdmin, address newAdmin) -``` - - - -*Emitted when the admin account has changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| previousAdmin | address | undefined | -| newAdmin | address | undefined | - -### BeaconUpgraded - -```solidity -event BeaconUpgraded(address indexed beacon) -``` - - - -*Emitted when the beacon is changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| beacon `indexed` | address | undefined | - -### Upgraded - -```solidity -event Upgraded(address indexed implementation) -``` - - - -*Emitted when the implementation is upgraded.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| implementation `indexed` | address | undefined | - - - diff --git a/docs/child/proxy/hardfork/NetworkParamsHardforkProxy.md b/docs/child/proxy/hardfork/NetworkParamsHardforkProxy.md deleted file mode 100644 index f7c5be3f..00000000 --- a/docs/child/proxy/hardfork/NetworkParamsHardforkProxy.md +++ /dev/null @@ -1,85 +0,0 @@ -# NetworkParamsHardforkProxy - - - - - -NetworkParams-specific proxy for hardfork migration - -*If starting fresh, use GenesisProxy instead* - -## Methods - -### setUpProxy - -```solidity -function setUpProxy(address logic, address admin, NetworkParams.InitParams initParams) external nonpayable -``` - - - - - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| logic | address | undefined | -| admin | address | undefined | -| initParams | NetworkParams.InitParams | undefined | - - - -## Events - -### AdminChanged - -```solidity -event AdminChanged(address previousAdmin, address newAdmin) -``` - - - -*Emitted when the admin account has changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| previousAdmin | address | undefined | -| newAdmin | address | undefined | - -### BeaconUpgraded - -```solidity -event BeaconUpgraded(address indexed beacon) -``` - - - -*Emitted when the beacon is changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| beacon `indexed` | address | undefined | - -### Upgraded - -```solidity -event Upgraded(address indexed implementation) -``` - - - -*Emitted when the implementation is upgraded.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| implementation `indexed` | address | undefined | - - - diff --git a/docs/child/validator/ValidatorSet.md b/docs/child/validator/ValidatorSet.md index 720da5c6..77ef0e50 100644 --- a/docs/child/validator/ValidatorSet.md +++ b/docs/child/validator/ValidatorSet.md @@ -1117,7 +1117,7 @@ event NewEpoch(uint256 indexed id, uint256 indexed startBlock, uint256 indexed e ### Slashed ```solidity -event Slashed(uint256 indexed exitId, address[] validators, uint256[] amounts) +event Slashed(uint256 indexed exitId, address[] validators) ``` @@ -1130,7 +1130,6 @@ event Slashed(uint256 indexed exitId, address[] validators, uint256[] amounts) |---|---|---| | exitId `indexed` | uint256 | undefined | | validators | address[] | undefined | -| amounts | uint256[] | undefined | ### Transfer diff --git a/docs/child/validator/legacy-compat/LegacyStateVars.md b/docs/child/validator/legacy-compat/LegacyStateVars.md deleted file mode 100644 index 0e5317ff..00000000 --- a/docs/child/validator/legacy-compat/LegacyStateVars.md +++ /dev/null @@ -1,12 +0,0 @@ -# LegacyStateVars - - - - - - - - - - - diff --git a/docs/child/validator/proxy/hardfork/RewardPoolHardforkProxy.md b/docs/child/validator/proxy/hardfork/RewardPoolHardforkProxy.md deleted file mode 100644 index 9703833b..00000000 --- a/docs/child/validator/proxy/hardfork/RewardPoolHardforkProxy.md +++ /dev/null @@ -1,85 +0,0 @@ -# RewardPoolHardforkProxy - - - - - -RewardPool-specific proxy for hardfork migration - -*If starting fresh, use GenesisProxy instead* - -## Methods - -### setUpProxy - -```solidity -function setUpProxy(address logic, address admin, address newNetworkParams) external nonpayable -``` - -function for initializing proxy for the RewardPool genesis contract - -*meant to be deployed during genesis* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| logic | address | the address of the implementation (logic) contract for the reward pool | -| admin | address | the address that has permission to update what address contains the implementation | -| newNetworkParams | address | address of genesis contract NetworkParams | - - - -## Events - -### AdminChanged - -```solidity -event AdminChanged(address previousAdmin, address newAdmin) -``` - - - -*Emitted when the admin account has changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| previousAdmin | address | undefined | -| newAdmin | address | undefined | - -### BeaconUpgraded - -```solidity -event BeaconUpgraded(address indexed beacon) -``` - - - -*Emitted when the beacon is changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| beacon `indexed` | address | undefined | - -### Upgraded - -```solidity -event Upgraded(address indexed implementation) -``` - - - -*Emitted when the implementation is upgraded.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| implementation `indexed` | address | undefined | - - - diff --git a/docs/child/validator/proxy/hardfork/ValidatorSetHardforkProxy.md b/docs/child/validator/proxy/hardfork/ValidatorSetHardforkProxy.md deleted file mode 100644 index ff658d53..00000000 --- a/docs/child/validator/proxy/hardfork/ValidatorSetHardforkProxy.md +++ /dev/null @@ -1,85 +0,0 @@ -# ValidatorSetHardforkProxy - - - - - -ValidatorSet-specific proxy for hardfork migration - -*If starting fresh, use GenesisProxy instead* - -## Methods - -### setUpProxy - -```solidity -function setUpProxy(address logic, address admin, address newNetworkParams) external nonpayable -``` - -function for initializing proxy for the ValidatorSet genesis contract - -*meant to be deployed during genesis* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| logic | address | the address of the implementation (logic) contract for the validator set | -| admin | address | the address that has permission to update what address contains the implementation | -| newNetworkParams | address | address of genesis contract NetworkParams | - - - -## Events - -### AdminChanged - -```solidity -event AdminChanged(address previousAdmin, address newAdmin) -``` - - - -*Emitted when the admin account has changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| previousAdmin | address | undefined | -| newAdmin | address | undefined | - -### BeaconUpgraded - -```solidity -event BeaconUpgraded(address indexed beacon) -``` - - - -*Emitted when the beacon is changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| beacon `indexed` | address | undefined | - -### Upgraded - -```solidity -event Upgraded(address indexed implementation) -``` - - - -*Emitted when the implementation is upgraded.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| implementation `indexed` | address | undefined | - - - diff --git a/docs/lib/GenesisProxy.md b/docs/lib/GenesisProxy.md deleted file mode 100644 index 682e1076..00000000 --- a/docs/lib/GenesisProxy.md +++ /dev/null @@ -1,85 +0,0 @@ -# GenesisProxy - -*Polygon Technology* - -> GenesisProxy - -wrapper for OpenZeppelin's Transparent Upgreadable Proxy, intended for use during genesis for genesis contractsone GenesisProxy should be deployed for each genesis contract, but there are exceptions if hardforking - see below - -*If hardforking, for ValidatorSet, RewardPool, ForkParams, and NetworkParams, use the respective dedicated HardforkProxy instead* - -## Methods - -### setUpProxy - -```solidity -function setUpProxy(address logic, address admin, bytes data) external nonpayable -``` - -function for initializing proxy - - - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| logic | address | the address of the implementation (logic) contract for the genesis contract | -| admin | address | the address that has permission to update what address contains the implementation | -| data | bytes | raw calldata for the intialization of the genesis contract (if required) | - - - -## Events - -### AdminChanged - -```solidity -event AdminChanged(address previousAdmin, address newAdmin) -``` - - - -*Emitted when the admin account has changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| previousAdmin | address | undefined | -| newAdmin | address | undefined | - -### BeaconUpgraded - -```solidity -event BeaconUpgraded(address indexed beacon) -``` - - - -*Emitted when the beacon is changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| beacon `indexed` | address | undefined | - -### Upgraded - -```solidity -event Upgraded(address indexed implementation) -``` - - - -*Emitted when the implementation is upgraded.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| implementation `indexed` | address | undefined | - - - diff --git a/docs/lib/ProxyBase.md b/docs/lib/ProxyBase.md deleted file mode 100644 index c3b893c9..00000000 --- a/docs/lib/ProxyBase.md +++ /dev/null @@ -1,64 +0,0 @@ -# ProxyBase - - - - - - - - - - -## Events - -### AdminChanged - -```solidity -event AdminChanged(address previousAdmin, address newAdmin) -``` - - - -*Emitted when the admin account has changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| previousAdmin | address | undefined | -| newAdmin | address | undefined | - -### BeaconUpgraded - -```solidity -event BeaconUpgraded(address indexed beacon) -``` - - - -*Emitted when the beacon is changed.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| beacon `indexed` | address | undefined | - -### Upgraded - -```solidity -event Upgraded(address indexed implementation) -``` - - - -*Emitted when the implementation is upgraded.* - -#### Parameters - -| Name | Type | Description | -|---|---|---| -| implementation `indexed` | address | undefined | - - - diff --git a/docs/root/staking/StakeManagerLegacyCompatStorage.md b/docs/root/staking/StakeManagerLegacyCompatStorage.md deleted file mode 100644 index 28c3399d..00000000 --- a/docs/root/staking/StakeManagerLegacyCompatStorage.md +++ /dev/null @@ -1,12 +0,0 @@ -# StakeManagerLegacyCompatStorage - - - - - - - - - - - diff --git a/test/forge/hardfork/Hardfork.t.sol b/test/forge/hardfork/Hardfork.t.sol deleted file mode 100644 index d9fdd637..00000000 --- a/test/forge/hardfork/Hardfork.t.sol +++ /dev/null @@ -1,360 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.19; - -import "@utils/Test.sol"; - -import {NetworkParams} from "contracts/child/NetworkParams.sol"; - -import {ValidatorSet as Old_ValidatorSet, ValidatorInit as Old_ValidatorInit} from "./deployed/ValidatorSet.sol"; -import {ValidatorSet, ValidatorInit} from "contracts/child/validator/ValidatorSet.sol"; -import {ValidatorSetHardforkProxy} from "contracts/child/validator/proxy/hardfork/ValidatorSetHardforkProxy.sol"; - -import {RewardPool as Old_RewardPool} from "./deployed/RewardPool.sol"; -import {RewardPool} from "contracts/child/validator/RewardPool.sol"; -import {RewardPoolHardforkProxy} from "contracts/child/validator/proxy/hardfork/RewardPoolHardforkProxy.sol"; - -import {NetworkParams as Old_NetworkParams} from "./deployed/NetworkParams.sol"; -import {NetworkParams} from "contracts/child/NetworkParams.sol"; -import {NetworkParamsHardforkProxy} from "contracts/child/proxy/hardfork/NetworkParamsHardforkProxy.sol"; - -import {ForkParams as Old_ForkParams} from "./deployed/ForkParams.sol"; -import {ForkParams} from "contracts/child/ForkParams.sol"; -import {ForkParamsHardforkProxy} from "contracts/child/proxy/hardfork/ForkParamsHardforkProxy.sol"; - -/// @notice Checks if all modified OpenZeppelin contracts are up-to-date. -contract Hardfork_ModifiedOpenZeppelinContractsCheck is Test { - function test_CheckModifiedOpenZeppelinContracts() public { - string[] memory cmd = new string[](2); - cmd[0] = "node"; - cmd[1] = "scripts/maintenance/checkModifiedOpenZeppelinContracts.js"; - - bytes memory out = vm.ffi(cmd); - - require(out.length > 0, "Script contains errors."); - - bytes32 ok = keccak256("All modified OpenZeppelin contracts up-to-date."); - - require(keccak256(out) == ok, string(out)); - } -} - -abstract contract Initialized is Test { - // Actors. - address internal immutable ADMIN = makeAddr("ADMIN"); - address internal immutable VALIDATOR_A = makeAddr("VALIDATOR_A"); - address internal immutable VALIDATOR_B = makeAddr("VALIDATOR_B"); - - // Other required contracts. - address internal stateSender; - address internal stateReceiver; - address internal rootChainManager; - // - address internal rewardToken; - address internal rewardWallet; - - // Old versions. - Old_ValidatorSet internal old_validatorSet; - bytes32 constant EXPECTED_STORAGE_START_VS = bytes32(uint256(201)); - // - Old_RewardPool internal old_rewardPool; - bytes32 constant EXPECTED_STORAGE_START_RP = bytes32(uint256(50)); - // - Old_NetworkParams internal old_networkParams; - // - Old_ForkParams internal old_forkParams; - - /// @notice Deploys or mocks other required contracts. - /// @dev Called by `setUp`. - function _setUp_OtherContracts() internal virtual { - stateSender = makeAddr("stateSender"); - stateReceiver = makeAddr("stateReceiver"); - rootChainManager = makeAddr("rootChainManager"); - // - rewardToken = makeAddr("newRewardToken"); - rewardWallet = makeAddr("newRewardWallet"); - } - - function setUp() public virtual { - _setUp_OtherContracts(); - - old_validatorSet = new Old_ValidatorSet(); - // - old_rewardPool = new Old_RewardPool(); - // - old_networkParams = new Old_NetworkParams(address(1), 1, 1, 1, 1); - // - old_forkParams = new Old_ForkParams(ADMIN); - - // Simulate initializations without proxies! - - Old_ValidatorInit[] memory initialValidators = new Old_ValidatorInit[](2); - initialValidators[0] = Old_ValidatorInit({addr: VALIDATOR_A, stake: 300}); - initialValidators[1] = Old_ValidatorInit({addr: VALIDATOR_B, stake: 100}); - - old_validatorSet.initialize(stateSender, stateReceiver, rootChainManager, 1, initialValidators); - // - old_rewardPool.initialize(rewardToken, rewardWallet, address(old_validatorSet), 1); - } -} - -contract HardforkTest_Initialized is Initialized { - /// @dev Do not use the already deployed contract for this test. - function test_Old_ValidatorSet_OGStorageStart() public { - old_validatorSet = new Old_ValidatorSet(); - Old_ValidatorInit[] memory initialValidators = new Old_ValidatorInit[](2); - initialValidators[0] = Old_ValidatorInit({addr: VALIDATOR_A, stake: 300}); - initialValidators[1] = Old_ValidatorInit({addr: VALIDATOR_B, stake: 100}); - old_validatorSet.initialize(stateSender, stateReceiver, rootChainManager, 1, initialValidators); - - assertEq(vm.load(address(old_validatorSet), EXPECTED_STORAGE_START_VS), bytes32(uint256(uint160(stateSender)))); - } - - /// @dev Do not use the already deployed contract for this test. - function test_Old_RewardPool_OGStorageStart() public { - old_rewardPool = new Old_RewardPool(); - old_rewardPool.initialize(rewardToken, rewardWallet, address(old_validatorSet), 1); - - assertEq( - vm.load(address(old_rewardPool), EXPECTED_STORAGE_START_RP), - bytes32(bytes.concat(hex"00000000000000000000", abi.encodePacked(rewardToken), hex"0001")) - ); - } - - function test_Old_NetworkParams_StorageSlots() public { - for (uint i; i < 4; i++) { - assertNotEq(vm.load(address(old_networkParams), bytes32(i)), bytes32(uint256(0))); - } - } - - function test_Old_ForkParams_StorageSlots() public { - assertEq(old_forkParams.owner(), ADMIN); - } -} - -abstract contract StateContaining is Initialized { - function setUp() public virtual override { - super.setUp(); - } -} - -contract HardforkTest_StateContaining is StateContaining {} - -abstract contract Hardforked is StateContaining { - // New versions. - ValidatorSet internal validatorSet; - RewardPool internal rewardPool; - NetworkParams internal networkParams; - ForkParams internal forkParams; - - // Helpers. - address internal validatorSetProxyAddr; - ValidatorSet internal validatorSetViaProxy; - // - address internal rewardPoolProxyAddr; - RewardPool internal rewardPoolViaProxy; - // - address internal networkParamsProxyAddr; - NetworkParams internal networkParamsViaProxy; - // - address internal forkParamsProxyAddr; - ForkParams internal forkParamsViaProxy; - - function setUp() public virtual override { - super.setUp(); - - // Hardfork! - - // 1. Deploy new logic. - validatorSet = new ValidatorSet(); - // - rewardPool = new RewardPool(); - // - networkParams = new NetworkParams(); - // - forkParams = new ForkParams(); - - // 2. Replace contracts with proxies. - deployCodeTo("ValidatorSetHardforkProxy.sol", address(old_validatorSet)); - // - deployCodeTo("RewardPoolHardforkProxy.sol", address(old_rewardPool)); - // - deployCodeTo("NetworkParamsHardforkProxy.sol", address(old_networkParams)); - // - deployCodeTo("ForkParamsHardforkProxy.sol", address(old_forkParams)); - - validatorSetProxyAddr = address(old_validatorSet); - // - rewardPoolProxyAddr = address(old_rewardPool); - // - networkParamsProxyAddr = address(old_networkParams); - // - forkParamsProxyAddr = address(old_forkParams); - - // 3. Set up proxies. - ValidatorSetHardforkProxy(payable(validatorSetProxyAddr)).setUpProxy( - address(validatorSet), - ADMIN, - address(networkParams) - ); - // - RewardPoolHardforkProxy(payable(rewardPoolProxyAddr)).setUpProxy( - address(rewardPool), - ADMIN, - address(networkParams) - ); - // - NetworkParamsHardforkProxy(payable(networkParamsProxyAddr)).setUpProxy( - address(networkParams), - ADMIN, - NetworkParams.InitParams({ - newOwner: ADMIN, - newCheckpointBlockInterval: 2, - newEpochSize: 2, - newEpochReward: 2, - newSprintSize: 2, - newMinValidatorSetSize: 2, - newMaxValidatorSetSize: 2, - newWithdrawalWaitPeriod: 2, - newBlockTime: 2, - newBlockTimeDrift: 2, - newVotingDelay: 2, - newVotingPeriod: 2, - newProposalThreshold: 2 - }) - ); - // - ForkParamsHardforkProxy(payable(forkParamsProxyAddr)).setUpProxy(address(forkParams), ADMIN); - - validatorSetViaProxy = ValidatorSet(validatorSetProxyAddr); - // - rewardPoolViaProxy = RewardPool(rewardPoolProxyAddr); - // - networkParamsViaProxy = NetworkParams(networkParamsProxyAddr); - // - forkParams = ForkParams(forkParamsProxyAddr); - } -} - -contract HardforkTest_Hardforked is Hardforked { - function test_ValidatorSetHardforkProxy_RevertOn_setUpProxy() public { - vm.expectRevert("ProxyBase: Already set up."); - - ValidatorSetHardforkProxy(payable(validatorSetProxyAddr)).setUpProxy(address(0), address(0), address(0)); - } - - function test_ValidatorSet_RevertOn_initialize() public { - vm.expectRevert("Initializable: contract is already initialized"); - - validatorSetViaProxy.initialize( - stateSender, - stateReceiver, - rootChainManager, - address(networkParams), - new ValidatorInit[](0) - ); - } - - function test_ValidatorSet_networkParams() public { - assertEq( - vm.load(validatorSetProxyAddr, bytes32(uint256(209))), - bytes32(uint256(uint160(address(networkParams)))) - ); - } - - /// @dev Do not use the already deployed contract for this test. - function test_ValidatorSet_OGStorageStart() public { - validatorSet = new ValidatorSet(); - ValidatorInit[] memory initialValidators = new ValidatorInit[](2); - initialValidators[0] = ValidatorInit({addr: VALIDATOR_A, stake: 300}); - initialValidators[1] = ValidatorInit({addr: VALIDATOR_B, stake: 100}); - validatorSet.initialize( - stateSender, - stateReceiver, - rootChainManager, - address(networkParams), - initialValidators - ); - - assertEq(vm.load(address(validatorSet), EXPECTED_STORAGE_START_VS), bytes32(uint256(uint160(stateSender)))); - } - - function test_RewardPoolHardforkProxy_RevertOn_setUpProxy() public { - vm.expectRevert("ProxyBase: Already set up."); - - RewardPoolHardforkProxy(payable(rewardPoolProxyAddr)).setUpProxy(address(0), address(0), address(0)); - } - - function test_RewardPool_RevertOn_initialize() public { - vm.expectRevert("Initializable: contract is already initialized"); - - rewardPoolViaProxy.initialize( - address(rewardToken), - rewardWallet, - address(validatorSetViaProxy), - address(networkParams) - ); - } - - function test_RewardPool_networkParams() public { - assertEq(vm.load(rewardPoolProxyAddr, bytes32(uint256(56))), bytes32(uint256(uint160(address(networkParams))))); - } - - /// @dev Do not use the already deployed contract for this test. - function test_RewardPool_OGStorageStart() public { - rewardPool = new RewardPool(); - rewardPool.initialize(address(rewardToken), rewardWallet, address(validatorSet), address(networkParams)); - - assertEq( - vm.load(rewardPoolProxyAddr, EXPECTED_STORAGE_START_RP), - bytes32(bytes.concat(hex"00000000000000000000", abi.encodePacked(rewardToken), hex"0001")) - ); - } - - function test_NetworkParamsHardforkProxy_RevertOn_setUpProxy() public { - NetworkParams.InitParams memory initParams; - - vm.expectRevert("ProxyBase: Already set up."); - - NetworkParamsHardforkProxy(payable(networkParamsProxyAddr)).setUpProxy(address(0), address(0), initParams); - } - - function test_NetworkParams_RevertOn_initialize() public { - NetworkParams.InitParams memory initParams; - - vm.expectRevert("Initializable: contract is already initialized"); - - networkParamsViaProxy.initialize(initParams); - } - - function test_NetworkParams_StorageSlots() public { - assertEq(networkParamsViaProxy.owner(), ADMIN); - assertEq(networkParamsViaProxy.checkpointBlockInterval(), 2); - assertEq(networkParamsViaProxy.epochSize(), 2); - assertEq(networkParamsViaProxy.epochReward(), 2); - assertEq(networkParamsViaProxy.sprintSize(), 2); - assertEq(networkParamsViaProxy.minValidatorSetSize(), 2); - assertEq(networkParamsViaProxy.maxValidatorSetSize(), 2); - assertEq(networkParamsViaProxy.withdrawalWaitPeriod(), 2); - assertEq(networkParamsViaProxy.blockTime(), 2); - assertEq(networkParamsViaProxy.blockTimeDrift(), 2); - assertEq(networkParamsViaProxy.votingDelay(), 2); - assertEq(networkParamsViaProxy.votingPeriod(), 2); - assertEq(networkParamsViaProxy.proposalThreshold(), 2); - } - - function test_ForkParamsHardforkProxy_RevertOn_setUpProxy() public { - vm.expectRevert("ProxyBase: Already set up."); - - ForkParamsHardforkProxy(payable(address(old_forkParams))).setUpProxy(address(0), address(0)); - } - - function test_ForkParams_RevertOn_initialize() public { - vm.expectRevert("Initializable: contract is already initialized"); - - forkParams.initialize(address(0)); - } - - function test_ForkParams_StorageSlots() public { - assertEq(forkParams.owner(), ADMIN); - } -} diff --git a/test/forge/hardfork/deployed/ForkParams.sol b/test/forge/hardfork/deployed/ForkParams.sol deleted file mode 100644 index 9f205987..00000000 --- a/test/forge/hardfork/deployed/ForkParams.sol +++ /dev/null @@ -1,169 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.19; - -// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) - -// OpenZeppelin Contracts v4.4.1 (utils/Context.sol) - -/** - * @dev Provides information about the current execution context, including the - * sender of the transaction and its data. While these are generally available - * via msg.sender and msg.data, they should not be accessed in such a direct - * manner, since when dealing with meta-transactions the account sending and - * paying for execution may not be the actual sender (as far as an application - * is concerned). - * - * This contract is only required for intermediate, library-like contracts. - */ -abstract contract Context { - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } -} - -/** - * @dev Contract module which provides a basic access control mechanism, where - * there is an account (an owner) that can be granted exclusive access to - * specific functions. - * - * By default, the owner account will be the one that deploys the contract. This - * can later be changed with {transferOwnership}. - * - * This module is used through inheritance. It will make available the modifier - * `onlyOwner`, which can be applied to your functions to restrict their use to - * the owner. - */ -abstract contract Ownable is Context { - address private _owner; - - event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); - - /** - * @dev Initializes the contract setting the deployer as the initial owner. - */ - constructor() { - _transferOwnership(_msgSender()); - } - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - _checkOwner(); - _; - } - - /** - * @dev Returns the address of the current owner. - */ - function owner() public view virtual returns (address) { - return _owner; - } - - /** - * @dev Throws if the sender is not the owner. - */ - function _checkOwner() internal view virtual { - require(owner() == _msgSender(), "Ownable: caller is not the owner"); - } - - /** - * @dev Leaves the contract without owner. It will not be possible to call - * `onlyOwner` functions. Can only be called by the current owner. - * - * NOTE: Renouncing ownership will leave the contract without an owner, - * thereby disabling any functionality that is only available to the owner. - */ - function renounceOwnership() public virtual onlyOwner { - _transferOwnership(address(0)); - } - - /** - * @dev Transfers ownership of the contract to a new account (`newOwner`). - * Can only be called by the current owner. - */ - function transferOwnership(address newOwner) public virtual onlyOwner { - require(newOwner != address(0), "Ownable: new owner is the zero address"); - _transferOwnership(newOwner); - } - - /** - * @dev Transfers ownership of the contract to a new account (`newOwner`). - * Internal function without access restriction. - */ - function _transferOwnership(address newOwner) internal virtual { - address oldOwner = _owner; - _owner = newOwner; - emit OwnershipTransferred(oldOwner, newOwner); - } -} - -/** - @title ForkParams - @author Polygon Technology (@QEDK) - @notice Configurable softfork features that are read by the client on each epoch - @dev The contract allows for configurable softfork parameters without genesis updation - */ -contract ForkParams is Ownable { - mapping(bytes32 => uint256) public featureToBlockNumber; // keccak256("FEATURE_NAME") -> blockNumber - - event NewFeature(bytes32 indexed feature, uint256 indexed block); - event UpdatedFeature(bytes32 indexed feature, uint256 indexed block); - - /** - * @notice constructor function to set the owner - * @param newOwner address to transfer the ownership to - */ - constructor(address newOwner) { - _transferOwnership(newOwner); - } - - /** - * @notice function to add a new feature at a block number - * @dev block number must be set in the future and feature must already not be scheduled - * @param blockNumber block number to schedule the feature - * @param feature feature name to schedule - */ - function addNewFeature(uint256 blockNumber, string calldata feature) external onlyOwner { - require(blockNumber >= block.number, "ForkParams: INVALID_BLOCK"); - bytes32 featureHash = keccak256(abi.encode(feature)); - require(featureToBlockNumber[featureHash] == 0, "ForkParams: FEATURE_EXISTS"); - featureToBlockNumber[featureHash] = blockNumber; - - emit NewFeature(featureHash, blockNumber); - } - - /** - * @notice function to update the block number for a feature - * @dev block number must be set in the future and feature must already be scheduled - * @param newBlockNumber new block number to schedule the feature at - * @param feature feature name to schedule - */ - function updateFeatureBlock(uint256 newBlockNumber, string calldata feature) external onlyOwner { - bytes32 featureHash = keccak256(abi.encode(feature)); - uint256 featureBlock = featureToBlockNumber[featureHash]; - require(featureBlock != 0, "ForkParams: NONEXISTENT_FEATURE"); - require(newBlockNumber >= block.number && block.number < featureBlock, "ForkParams: INVALID_BLOCK"); - featureToBlockNumber[featureHash] = newBlockNumber; - - emit UpdatedFeature(featureHash, newBlockNumber); - } - - /** - * @notice function to check if a feature is activated - * @dev returns true if feature is activated, false if feature is scheduled in the future and reverts if feature does not exists - * @param feature feature name to check for activation - */ - function isFeatureActivated(string calldata feature) external view returns (bool) { - uint256 featureBlock = featureToBlockNumber[keccak256(abi.encode(feature))]; - require(featureBlock != 0, "ForkParams: NONEXISTENT_FEATURE"); - if (block.number >= featureBlock) { - return true; - } - return false; - } -} diff --git a/test/forge/hardfork/deployed/NetworkParams.sol b/test/forge/hardfork/deployed/NetworkParams.sol deleted file mode 100644 index bff71211..00000000 --- a/test/forge/hardfork/deployed/NetworkParams.sol +++ /dev/null @@ -1,200 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.19; - -// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) - -// OpenZeppelin Contracts v4.4.1 (utils/Context.sol) - -/** - * @dev Provides information about the current execution context, including the - * sender of the transaction and its data. While these are generally available - * via msg.sender and msg.data, they should not be accessed in such a direct - * manner, since when dealing with meta-transactions the account sending and - * paying for execution may not be the actual sender (as far as an application - * is concerned). - * - * This contract is only required for intermediate, library-like contracts. - */ -abstract contract Context { - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } -} - -/** - * @dev Contract module which provides a basic access control mechanism, where - * there is an account (an owner) that can be granted exclusive access to - * specific functions. - * - * By default, the owner account will be the one that deploys the contract. This - * can later be changed with {transferOwnership}. - * - * This module is used through inheritance. It will make available the modifier - * `onlyOwner`, which can be applied to your functions to restrict their use to - * the owner. - */ -abstract contract Ownable is Context { - address private _owner; - - event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); - - /** - * @dev Initializes the contract setting the deployer as the initial owner. - */ - constructor() { - _transferOwnership(_msgSender()); - } - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - _checkOwner(); - _; - } - - /** - * @dev Returns the address of the current owner. - */ - function owner() public view virtual returns (address) { - return _owner; - } - - /** - * @dev Throws if the sender is not the owner. - */ - function _checkOwner() internal view virtual { - require(owner() == _msgSender(), "Ownable: caller is not the owner"); - } - - /** - * @dev Leaves the contract without owner. It will not be possible to call - * `onlyOwner` functions. Can only be called by the current owner. - * - * NOTE: Renouncing ownership will leave the contract without an owner, - * thereby disabling any functionality that is only available to the owner. - */ - function renounceOwnership() public virtual onlyOwner { - _transferOwnership(address(0)); - } - - /** - * @dev Transfers ownership of the contract to a new account (`newOwner`). - * Can only be called by the current owner. - */ - function transferOwnership(address newOwner) public virtual onlyOwner { - require(newOwner != address(0), "Ownable: new owner is the zero address"); - _transferOwnership(newOwner); - } - - /** - * @dev Transfers ownership of the contract to a new account (`newOwner`). - * Internal function without access restriction. - */ - function _transferOwnership(address newOwner) internal virtual { - address oldOwner = _owner; - _owner = newOwner; - emit OwnershipTransferred(oldOwner, newOwner); - } -} - -/** - @title NetworkParams - @author Polygon Technology (@QEDK) - @notice Configurable network parameters that are read by the client on each epoch - @dev The contract allows for configurable network parameters without the need for a hardfork - */ -contract NetworkParams is Ownable { - uint256 public blockGasLimit; - uint256 public checkpointBlockInterval; // in blocks - uint256 public minStake; // in wei - uint256 public maxValidatorSetSize; - - event NewBlockGasLimit(uint256 indexed value); - event NewCheckpointBlockInterval(uint256 indexed value); - event NewMinStake(uint256 indexed value); - event NewMaxValdidatorSetSize(uint256 indexed value); - - /** - * @notice initializer for NetworkParams, sets the initial set of values for the network - * @dev disallows setting of zero values for sanity check purposes - * @param newOwner address of the contract controller to be set at deployment - * @param newBlockGasLimit initial block gas limit - * @param newCheckpointBlockInterval initial checkpoint interval - * @param newMinStake initial minimum stake - * @param newMaxValidatorSetSize initial max validator set size - */ - constructor( - address newOwner, - uint256 newBlockGasLimit, - uint256 newCheckpointBlockInterval, - uint256 newMinStake, - uint256 newMaxValidatorSetSize - ) { - require( - newOwner != address(0) && - newBlockGasLimit != 0 && - newMinStake != 0 && - newCheckpointBlockInterval != 0 && - newMaxValidatorSetSize != 0, - "NetworkParams: INVALID_INPUT" - ); - blockGasLimit = newBlockGasLimit; - checkpointBlockInterval = newCheckpointBlockInterval; - minStake = newMinStake; - maxValidatorSetSize = newMaxValidatorSetSize; - _transferOwnership(newOwner); - } - - /** - * @notice function to set new block gas limit - * @dev disallows setting of a zero value for sanity check purposes - * @param newBlockGasLimit new block gas limit - */ - function setNewBlockGasLimit(uint256 newBlockGasLimit) external onlyOwner { - require(newBlockGasLimit != 0, "NetworkParams: INVALID_BLOCK_GAS_LIMIT"); - blockGasLimit = newBlockGasLimit; - - emit NewBlockGasLimit(newBlockGasLimit); - } - - /** - * @notice function to set new checkpoint block interval - * @dev disallows setting of a zero value for sanity check purposes - * @param newCheckpointBlockInterval new checkpoint block interval - */ - function setNewCheckpointBlockInterval(uint256 newCheckpointBlockInterval) external onlyOwner { - require(newCheckpointBlockInterval != 0, "NetworkParams: INVALID_CHECKPOINT_INTERVAL"); - checkpointBlockInterval = newCheckpointBlockInterval; - - emit NewCheckpointBlockInterval(newCheckpointBlockInterval); - } - - /** - * @notice function to set new minimum stake - * @dev disallows setting of a zero value for sanity check purposes - * @param newMinStake new minimum stake - */ - function setNewMinStake(uint256 newMinStake) external onlyOwner { - require(newMinStake != 0, "NetworkParams: INVALID_MIN_STAKE"); - minStake = newMinStake; - - emit NewMinStake(newMinStake); - } - - /** - * @notice function to set new maximum validator set size - * @dev disallows setting of a zero value for sanity check purposes - * @param newMaxValidatorSetSize new maximum validator set size - */ - function setNewMaxValidatorSetSize(uint256 newMaxValidatorSetSize) external onlyOwner { - require(newMaxValidatorSetSize != 0, "NetworkParams: INVALID_MAX_VALIDATOR_SET_SIZE"); - maxValidatorSetSize = newMaxValidatorSetSize; - - emit NewMaxValdidatorSetSize(newMaxValidatorSetSize); - } -} diff --git a/test/forge/hardfork/deployed/RewardPool.sol b/test/forge/hardfork/deployed/RewardPool.sol deleted file mode 100644 index 7315a47f..00000000 --- a/test/forge/hardfork/deployed/RewardPool.sol +++ /dev/null @@ -1,957 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.19; - -// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) - -// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) - -/** - * @dev Collection of functions related to the address type - */ -library AddressUpgradeable { - /** - * @dev Returns true if `account` is a contract. - * - * [IMPORTANT] - * ==== - * It is unsafe to assume that an address for which this function returns - * false is an externally-owned account (EOA) and not a contract. - * - * Among others, `isContract` will return false for the following - * types of addresses: - * - * - an externally-owned account - * - a contract in construction - * - an address where a contract will be created - * - an address where a contract lived, but was destroyed - * - * Furthermore, `isContract` will also return true if the target contract within - * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, - * which only has an effect at the end of a transaction. - * ==== - * - * [IMPORTANT] - * ==== - * You shouldn't rely on `isContract` to protect against flash loan attacks! - * - * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets - * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract - * constructor. - * ==== - */ - function isContract(address account) internal view returns (bool) { - // This method relies on extcodesize/address.code.length, which returns 0 - // for contracts in construction, since the code is only stored at the end - // of the constructor execution. - - return account.code.length > 0; - } - - /** - * @dev Replacement for Solidity's `transfer`: sends `amount` wei to - * `recipient`, forwarding all available gas and reverting on errors. - * - * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost - * of certain opcodes, possibly making contracts go over the 2300 gas limit - * imposed by `transfer`, making them unable to receive funds via - * `transfer`. {sendValue} removes this limitation. - * - * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. - * - * IMPORTANT: because control is transferred to `recipient`, care must be - * taken to not create reentrancy vulnerabilities. Consider using - * {ReentrancyGuard} or the - * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. - */ - function sendValue(address payable recipient, uint256 amount) internal { - require(address(this).balance >= amount, "Address: insufficient balance"); - - (bool success, ) = recipient.call{value: amount}(""); - require(success, "Address: unable to send value, recipient may have reverted"); - } - - /** - * @dev Performs a Solidity function call using a low level `call`. A - * plain `call` is an unsafe replacement for a function call: use this - * function instead. - * - * If `target` reverts with a revert reason, it is bubbled up by this - * function (like regular Solidity function calls). - * - * Returns the raw returned data. To convert to the expected return value, - * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. - * - * Requirements: - * - * - `target` must be a contract. - * - calling `target` with `data` must not revert. - * - * _Available since v3.1._ - */ - function functionCall(address target, bytes memory data) internal returns (bytes memory) { - return functionCallWithValue(target, data, 0, "Address: low-level call failed"); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with - * `errorMessage` as a fallback revert reason when `target` reverts. - * - * _Available since v3.1._ - */ - function functionCall( - address target, - bytes memory data, - string memory errorMessage - ) internal returns (bytes memory) { - return functionCallWithValue(target, data, 0, errorMessage); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], - * but also transferring `value` wei to `target`. - * - * Requirements: - * - * - the calling contract must have an ETH balance of at least `value`. - * - the called Solidity function must be `payable`. - * - * _Available since v3.1._ - */ - function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { - return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); - } - - /** - * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but - * with `errorMessage` as a fallback revert reason when `target` reverts. - * - * _Available since v3.1._ - */ - function functionCallWithValue( - address target, - bytes memory data, - uint256 value, - string memory errorMessage - ) internal returns (bytes memory) { - require(address(this).balance >= value, "Address: insufficient balance for call"); - (bool success, bytes memory returndata) = target.call{value: value}(data); - return verifyCallResultFromTarget(target, success, returndata, errorMessage); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], - * but performing a static call. - * - * _Available since v3.3._ - */ - function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { - return functionStaticCall(target, data, "Address: low-level static call failed"); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], - * but performing a static call. - * - * _Available since v3.3._ - */ - function functionStaticCall( - address target, - bytes memory data, - string memory errorMessage - ) internal view returns (bytes memory) { - (bool success, bytes memory returndata) = target.staticcall(data); - return verifyCallResultFromTarget(target, success, returndata, errorMessage); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], - * but performing a delegate call. - * - * _Available since v3.4._ - */ - function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { - return functionDelegateCall(target, data, "Address: low-level delegate call failed"); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], - * but performing a delegate call. - * - * _Available since v3.4._ - */ - function functionDelegateCall( - address target, - bytes memory data, - string memory errorMessage - ) internal returns (bytes memory) { - (bool success, bytes memory returndata) = target.delegatecall(data); - return verifyCallResultFromTarget(target, success, returndata, errorMessage); - } - - /** - * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling - * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. - * - * _Available since v4.8._ - */ - function verifyCallResultFromTarget( - address target, - bool success, - bytes memory returndata, - string memory errorMessage - ) internal view returns (bytes memory) { - if (success) { - if (returndata.length == 0) { - // only check isContract if the call was successful and the return data is empty - // otherwise we already know that it was a contract - require(isContract(target), "Address: call to non-contract"); - } - return returndata; - } else { - _revert(returndata, errorMessage); - } - } - - /** - * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the - * revert reason or using the provided one. - * - * _Available since v4.3._ - */ - function verifyCallResult( - bool success, - bytes memory returndata, - string memory errorMessage - ) internal pure returns (bytes memory) { - if (success) { - return returndata; - } else { - _revert(returndata, errorMessage); - } - } - - function _revert(bytes memory returndata, string memory errorMessage) private pure { - // Look for revert reason and bubble it up if present - if (returndata.length > 0) { - // The easiest way to bubble the revert reason is using memory via assembly - /// @solidity memory-safe-assembly - assembly { - let returndata_size := mload(returndata) - revert(add(32, returndata), returndata_size) - } - } else { - revert(errorMessage); - } - } -} - -/** - * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed - * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an - * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer - * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. - * - * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be - * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in - * case an upgrade adds a module that needs to be initialized. - * - * For example: - * - * [.hljs-theme-light.nopadding] - * ```solidity - * contract MyToken is ERC20Upgradeable { - * function initialize() initializer public { - * __ERC20_init("MyToken", "MTK"); - * } - * } - * - * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { - * function initializeV2() reinitializer(2) public { - * __ERC20Permit_init("MyToken"); - * } - * } - * ``` - * - * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as - * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. - * - * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure - * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. - * - * [CAUTION] - * ==== - * Avoid leaving a contract uninitialized. - * - * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation - * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke - * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: - * - * [.hljs-theme-light.nopadding] - * ``` - * /// @custom:oz-upgrades-unsafe-allow constructor - * constructor() { - * _disableInitializers(); - * } - * ``` - * ==== - */ -abstract contract Initializable { - /** - * @dev Indicates that the contract has been initialized. - * @custom:oz-retyped-from bool - */ - uint8 private _initialized; - - /** - * @dev Indicates that the contract is in the process of being initialized. - */ - bool private _initializing; - - /** - * @dev Triggered when the contract has been initialized or reinitialized. - */ - event Initialized(uint8 version); - - /** - * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, - * `onlyInitializing` functions can be used to initialize parent contracts. - * - * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a - * constructor. - * - * Emits an {Initialized} event. - */ - modifier initializer() { - bool isTopLevelCall = !_initializing; - require( - (isTopLevelCall && _initialized < 1) || - (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), - "Initializable: contract is already initialized" - ); - _initialized = 1; - if (isTopLevelCall) { - _initializing = true; - } - _; - if (isTopLevelCall) { - _initializing = false; - emit Initialized(1); - } - } - - /** - * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the - * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be - * used to initialize parent contracts. - * - * A reinitializer may be used after the original initialization step. This is essential to configure modules that - * are added through upgrades and that require initialization. - * - * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` - * cannot be nested. If one is invoked in the context of another, execution will revert. - * - * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in - * a contract, executing them in the right order is up to the developer or operator. - * - * WARNING: setting the version to 255 will prevent any future reinitialization. - * - * Emits an {Initialized} event. - */ - modifier reinitializer(uint8 version) { - require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); - _initialized = version; - _initializing = true; - _; - _initializing = false; - emit Initialized(version); - } - - /** - * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the - * {initializer} and {reinitializer} modifiers, directly or indirectly. - */ - modifier onlyInitializing() { - require(_initializing, "Initializable: contract is not initializing"); - _; - } - - /** - * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. - * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized - * to any version. It is recommended to use this to lock implementation contracts that are designed to be called - * through proxies. - * - * Emits an {Initialized} event the first time it is successfully executed. - */ - function _disableInitializers() internal virtual { - require(!_initializing, "Initializable: contract is initializing"); - if (_initialized != type(uint8).max) { - _initialized = type(uint8).max; - emit Initialized(type(uint8).max); - } - } - - /** - * @dev Returns the highest version that has been initialized. See {reinitializer}. - */ - function _getInitializedVersion() internal view returns (uint8) { - return _initialized; - } - - /** - * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. - */ - function _isInitializing() internal view returns (bool) { - return _initializing; - } -} - -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) - -/** - * @dev Interface of the ERC20 standard as defined in the EIP. - */ -interface IERC20Upgradeable { - /** - * @dev Emitted when `value` tokens are moved from one account (`from`) to - * another (`to`). - * - * Note that `value` may be zero. - */ - event Transfer(address indexed from, address indexed to, uint256 value); - - /** - * @dev Emitted when the allowance of a `spender` for an `owner` is set by - * a call to {approve}. `value` is the new allowance. - */ - event Approval(address indexed owner, address indexed spender, uint256 value); - - /** - * @dev Returns the amount of tokens in existence. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns the amount of tokens owned by `account`. - */ - function balanceOf(address account) external view returns (uint256); - - /** - * @dev Moves `amount` tokens from the caller's account to `to`. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transfer(address to, uint256 amount) external returns (bool); - - /** - * @dev Returns the remaining number of tokens that `spender` will be - * allowed to spend on behalf of `owner` through {transferFrom}. This is - * zero by default. - * - * This value changes when {approve} or {transferFrom} are called. - */ - function allowance(address owner, address spender) external view returns (uint256); - - /** - * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * IMPORTANT: Beware that changing an allowance with this method brings the risk - * that someone may use both the old and the new allowance by unfortunate - * transaction ordering. One possible solution to mitigate this race - * condition is to first reduce the spender's allowance to 0 and set the - * desired value afterwards: - * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 - * - * Emits an {Approval} event. - */ - function approve(address spender, uint256 amount) external returns (bool); - - /** - * @dev Moves `amount` tokens from `from` to `to` using the - * allowance mechanism. `amount` is then deducted from the caller's - * allowance. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transferFrom(address from, address to, uint256 amount) external returns (bool); -} - -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol) - -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol) - -/** - * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in - * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. - * - * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by - * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't - * need to send a transaction, and thus is not required to hold Ether at all. - */ -interface IERC20PermitUpgradeable { - /** - * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, - * given ``owner``'s signed approval. - * - * IMPORTANT: The same issues {IERC20-approve} has related to transaction - * ordering also apply here. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `deadline` must be a timestamp in the future. - * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` - * over the EIP712-formatted function arguments. - * - the signature must use ``owner``'s current nonce (see {nonces}). - * - * For more information on the signature format, see the - * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP - * section]. - */ - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external; - - /** - * @dev Returns the current nonce for `owner`. This value must be - * included whenever a signature is generated for {permit}. - * - * Every successful call to {permit} increases ``owner``'s nonce by one. This - * prevents a signature from being used multiple times. - */ - function nonces(address owner) external view returns (uint256); - - /** - * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. - */ - // solhint-disable-next-line func-name-mixedcase - function DOMAIN_SEPARATOR() external view returns (bytes32); -} - -/** - * @title SafeERC20 - * @dev Wrappers around ERC20 operations that throw on failure (when the token - * contract returns false). Tokens that return no value (and instead revert or - * throw on failure) are also supported, non-reverting calls are assumed to be - * successful. - * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, - * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. - */ -library SafeERC20Upgradeable { - using AddressUpgradeable for address; - - /** - * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, - * non-reverting calls are assumed to be successful. - */ - function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { - _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); - } - - /** - * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the - * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. - */ - function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { - _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); - } - - /** - * @dev Deprecated. This function has issues similar to the ones found in - * {IERC20-approve}, and its usage is discouraged. - * - * Whenever possible, use {safeIncreaseAllowance} and - * {safeDecreaseAllowance} instead. - */ - function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { - // safeApprove should only be called when setting an initial allowance, - // or when resetting it to zero. To increase and decrease it, use - // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' - require( - (value == 0) || (token.allowance(address(this), spender) == 0), - "SafeERC20: approve from non-zero to non-zero allowance" - ); - _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); - } - - /** - * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, - * non-reverting calls are assumed to be successful. - */ - function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { - uint256 oldAllowance = token.allowance(address(this), spender); - _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); - } - - /** - * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, - * non-reverting calls are assumed to be successful. - */ - function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { - unchecked { - uint256 oldAllowance = token.allowance(address(this), spender); - require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); - _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); - } - } - - /** - * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, - * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to - * 0 before setting it to a non-zero value. - */ - function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal { - bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); - - if (!_callOptionalReturnBool(token, approvalCall)) { - _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); - _callOptionalReturn(token, approvalCall); - } - } - - /** - * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. - * Revert on invalid signature. - */ - function safePermit( - IERC20PermitUpgradeable token, - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) internal { - uint256 nonceBefore = token.nonces(owner); - token.permit(owner, spender, value, deadline, v, r, s); - uint256 nonceAfter = token.nonces(owner); - require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); - } - - /** - * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement - * on the return value: the return value is optional (but if data is returned, it must not be false). - * @param token The token targeted by the call. - * @param data The call data (encoded using abi.encode or one of its variants). - */ - function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { - // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since - // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that - // the target address contains contract code and also asserts for success in the low-level call. - - bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); - require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); - } - - /** - * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement - * on the return value: the return value is optional (but if data is returned, it must not be false). - * @param token The token targeted by the call. - * @param data The call data (encoded using abi.encode or one of its variants). - * - * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. - */ - function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) { - // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since - // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false - // and not revert is the subcall reverts. - - (bool success, bytes memory returndata) = address(token).call(data); - return - success && - (returndata.length == 0 || abi.decode(returndata, (bool))) && - AddressUpgradeable.isContract(address(token)); - } -} - -error Unauthorized(string only); -error StakeRequirement(string src, string msg); -error InvalidSignature(address signer); - -contract System { - // pre-compiled contracts - // slither-disable too-many-digits - address public constant NATIVE_TRANSFER_PRECOMPILE = 0x0000000000000000000000000000000000002020; - address public constant VALIDATOR_PKCHECK_PRECOMPILE = 0x0000000000000000000000000000000000002030; - address public constant ALLOWLIST_PRECOMPILE = 0x0200000000000000000000000000000000000004; - address public constant BLOCKLIST_PRECOMPILE = 0x0300000000000000000000000000000000000004; - - // internal addrs - address public constant SYSTEM = 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE; - - // pre-compiled gas consumption - uint256 public constant NATIVE_TRANSFER_PRECOMPILE_GAS = 21000; - uint256 public constant VALIDATOR_PKCHECK_PRECOMPILE_GAS = 150000; - uint256 public constant READ_ADDRESSLIST_GAS = 5000; - - // genesis contracts - address public constant NATIVE_TOKEN_CONTRACT = 0x0000000000000000000000000000000000001010; - - modifier onlySystemCall() { - if (msg.sender != SYSTEM) revert Unauthorized("SYSTEMCALL"); - _; - } - - // slither-disable-next-line unused-state,naming-convention - uint256[50] private __gap; -} - -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) - -/** - * @dev Interface of the ERC20 standard as defined in the EIP. - */ -interface IERC20 { - /** - * @dev Emitted when `value` tokens are moved from one account (`from`) to - * another (`to`). - * - * Note that `value` may be zero. - */ - event Transfer(address indexed from, address indexed to, uint256 value); - - /** - * @dev Emitted when the allowance of a `spender` for an `owner` is set by - * a call to {approve}. `value` is the new allowance. - */ - event Approval(address indexed owner, address indexed spender, uint256 value); - - /** - * @dev Returns the amount of tokens in existence. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns the amount of tokens owned by `account`. - */ - function balanceOf(address account) external view returns (uint256); - - /** - * @dev Moves `amount` tokens from the caller's account to `to`. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transfer(address to, uint256 amount) external returns (bool); - - /** - * @dev Returns the remaining number of tokens that `spender` will be - * allowed to spend on behalf of `owner` through {transferFrom}. This is - * zero by default. - * - * This value changes when {approve} or {transferFrom} are called. - */ - function allowance(address owner, address spender) external view returns (uint256); - - /** - * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * IMPORTANT: Beware that changing an allowance with this method brings the risk - * that someone may use both the old and the new allowance by unfortunate - * transaction ordering. One possible solution to mitigate this race - * condition is to first reduce the spender's allowance to 0 and set the - * desired value afterwards: - * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 - * - * Emits an {Approval} event. - */ - function approve(address spender, uint256 amount) external returns (bool); - - /** - * @dev Moves `amount` tokens from `from` to `to` using the - * allowance mechanism. `amount` is then deducted from the caller's - * allowance. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transferFrom(address from, address to, uint256 amount) external returns (bool); -} - -interface IStateReceiver { - function onStateReceive(uint256 counter, address sender, bytes calldata data) external; -} - -struct ValidatorInit { - address addr; - uint256 stake; -} - -struct Epoch { - uint256 startBlock; - uint256 endBlock; - bytes32 epochRoot; -} - -/** - @title IValidatorSet - @author Polygon Technology (@gretzke) - @notice Manages voting power for validators and commits epochs for child chains - @dev Voting power is synced between the stake manager on root on stake and unstake actions - */ -interface IValidatorSet is IStateReceiver { - event NewEpoch(uint256 indexed id, uint256 indexed startBlock, uint256 indexed endBlock, bytes32 epochRoot); - event Slashed(uint256 indexed validator, uint256 amount); - event WithdrawalRegistered(address indexed account, uint256 amount); - event Withdrawal(address indexed account, uint256 amount); - - /// @notice commits a new epoch - /// @dev system call - function commitEpoch(uint256 id, Epoch calldata epoch) external; - - /// @notice allows a validator to announce their intention to withdraw a given amount of tokens - /// @dev initializes a waiting period before the tokens can be withdrawn - function unstake(uint256 amount) external; - - /// @notice allows a validator to complete a withdrawal - /// @dev calls the bridge to release the funds on root - function withdraw() external; - - /// @notice amount of blocks in an epoch - /// @dev when an epoch is committed a multiple of this number of blocks must be committed - // slither-disable-next-line naming-convention - function EPOCH_SIZE() external view returns (uint256); - - /// @notice total amount of blocks in a given epoch - function totalBlocks(uint256 epochId) external view returns (uint256 length); - - /// @notice returns a validator balance for a given epoch - function balanceOfAt(address account, uint256 epochNumber) external view returns (uint256); - - /// @notice returns the total supply for a given epoch - function totalSupplyAt(uint256 epochNumber) external view returns (uint256); - - /** - * @notice Calculates how much can be withdrawn for account in this epoch. - * @param account The account to calculate amount for - * @return Amount withdrawable (in MATIC wei) - */ - function withdrawable(address account) external view returns (uint256); - - /** - * @notice Calculates how much is yet to become withdrawable for account. - * @param account The account to calculate amount for - * @return Amount not yet withdrawable (in MATIC wei) - */ - function pendingWithdrawals(address account) external view returns (uint256); -} - -struct Uptime { - address validator; - uint256 signedBlocks; -} - -/** - @title IRewardPool - @author Polygon Technology (@gretzke) - @notice Distributes rewards to validators for committed epochs - */ -interface IRewardPool { - event RewardDistributed(uint256 indexed epochId, uint256 totalReward); - - /// @notice distributes reward for the given epoch - /// @dev transfers funds from sender to this contract - /// @param uptime uptime data for every validator - function distributeRewardFor(uint256 epochId, Uptime[] calldata uptime) external; - - /// @notice withdraws pending rewards for the sender (validator) - function withdrawReward() external; - - /// @notice returns the total reward paid for the given epoch - function paidRewardPerEpoch(uint256 epochId) external view returns (uint256); - - /// @notice returns the pending reward for the given account - function pendingRewards(address account) external view returns (uint256); -} - -contract RewardPool is IRewardPool, System, Initializable { - using SafeERC20Upgradeable for IERC20Upgradeable; - - IERC20Upgradeable public rewardToken; - address public rewardWallet; - IValidatorSet public validatorSet; - uint256 public baseReward; - - mapping(uint256 => uint256) public paidRewardPerEpoch; - mapping(address => uint256) public pendingRewards; - - function initialize( - address newRewardToken, - address newRewardWallet, - address newValidatorSet, - uint256 newBaseReward - ) public initializer { - require( - newRewardToken != address(0) && newRewardWallet != address(0) && newValidatorSet != address(0), - "ZERO_ADDRESS" - ); - - rewardToken = IERC20Upgradeable(newRewardToken); - rewardWallet = newRewardWallet; - validatorSet = IValidatorSet(newValidatorSet); - baseReward = newBaseReward; - } - - /** - * @inheritdoc IRewardPool - */ - function distributeRewardFor(uint256 epochId, Uptime[] calldata uptime) external onlySystemCall { - require(paidRewardPerEpoch[epochId] == 0, "REWARD_ALREADY_DISTRIBUTED"); - uint256 totalBlocks = validatorSet.totalBlocks(epochId); - require(totalBlocks != 0, "EPOCH_NOT_COMMITTED"); - uint256 epochSize = validatorSet.EPOCH_SIZE(); - // slither-disable-next-line divide-before-multiply - uint256 reward = (baseReward * totalBlocks) / epochSize; - - uint256 totalSupply = validatorSet.totalSupplyAt(epochId); - uint256 length = uptime.length; - uint256 totalReward = 0; - for (uint256 i = 0; i < length; i++) { - Uptime memory data = uptime[i]; - require(data.signedBlocks <= totalBlocks, "SIGNED_BLOCKS_EXCEEDS_TOTAL"); - // slither-disable-next-line calls-loop - uint256 balance = validatorSet.balanceOfAt(data.validator, epochId); - // slither-disable-next-line divide-before-multiply - uint256 validatorReward = (reward * balance * data.signedBlocks) / (totalSupply * totalBlocks); - pendingRewards[data.validator] += validatorReward; - totalReward += validatorReward; - } - paidRewardPerEpoch[epochId] = totalReward; - _transferRewards(totalReward); - emit RewardDistributed(epochId, totalReward); - } - - /** - * @inheritdoc IRewardPool - */ - function withdrawReward() external { - uint256 pendingReward = pendingRewards[msg.sender]; - pendingRewards[msg.sender] = 0; - rewardToken.safeTransfer(msg.sender, pendingReward); - } - - /// @dev this method can be overridden to add logic depending on the reward token - function _transferRewards(uint256 amount) internal virtual { - // slither-disable-next-line arbitrary-send-erc20 - rewardToken.safeTransferFrom(rewardWallet, address(this), amount); - } -} diff --git a/test/forge/hardfork/deployed/ValidatorSet.sol b/test/forge/hardfork/deployed/ValidatorSet.sol deleted file mode 100644 index bb723fa8..00000000 --- a/test/forge/hardfork/deployed/ValidatorSet.sol +++ /dev/null @@ -1,2105 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.19; - -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Snapshot.sol) - -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) - -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) - -/** - * @dev Interface of the ERC20 standard as defined in the EIP. - */ -interface IERC20Upgradeable { - /** - * @dev Emitted when `value` tokens are moved from one account (`from`) to - * another (`to`). - * - * Note that `value` may be zero. - */ - event Transfer(address indexed from, address indexed to, uint256 value); - - /** - * @dev Emitted when the allowance of a `spender` for an `owner` is set by - * a call to {approve}. `value` is the new allowance. - */ - event Approval(address indexed owner, address indexed spender, uint256 value); - - /** - * @dev Returns the amount of tokens in existence. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns the amount of tokens owned by `account`. - */ - function balanceOf(address account) external view returns (uint256); - - /** - * @dev Moves `amount` tokens from the caller's account to `to`. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transfer(address to, uint256 amount) external returns (bool); - - /** - * @dev Returns the remaining number of tokens that `spender` will be - * allowed to spend on behalf of `owner` through {transferFrom}. This is - * zero by default. - * - * This value changes when {approve} or {transferFrom} are called. - */ - function allowance(address owner, address spender) external view returns (uint256); - - /** - * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * IMPORTANT: Beware that changing an allowance with this method brings the risk - * that someone may use both the old and the new allowance by unfortunate - * transaction ordering. One possible solution to mitigate this race - * condition is to first reduce the spender's allowance to 0 and set the - * desired value afterwards: - * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 - * - * Emits an {Approval} event. - */ - function approve(address spender, uint256 amount) external returns (bool); - - /** - * @dev Moves `amount` tokens from `from` to `to` using the - * allowance mechanism. `amount` is then deducted from the caller's - * allowance. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transferFrom(address from, address to, uint256 amount) external returns (bool); -} - -// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) - -/** - * @dev Interface for the optional metadata functions from the ERC20 standard. - * - * _Available since v4.1._ - */ -interface IERC20MetadataUpgradeable is IERC20Upgradeable { - /** - * @dev Returns the name of the token. - */ - function name() external view returns (string memory); - - /** - * @dev Returns the symbol of the token. - */ - function symbol() external view returns (string memory); - - /** - * @dev Returns the decimals places of the token. - */ - function decimals() external view returns (uint8); -} - -// OpenZeppelin Contracts v4.4.1 (utils/Context.sol) - -// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) - -// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) - -/** - * @dev Collection of functions related to the address type - */ -library AddressUpgradeable { - /** - * @dev Returns true if `account` is a contract. - * - * [IMPORTANT] - * ==== - * It is unsafe to assume that an address for which this function returns - * false is an externally-owned account (EOA) and not a contract. - * - * Among others, `isContract` will return false for the following - * types of addresses: - * - * - an externally-owned account - * - a contract in construction - * - an address where a contract will be created - * - an address where a contract lived, but was destroyed - * - * Furthermore, `isContract` will also return true if the target contract within - * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, - * which only has an effect at the end of a transaction. - * ==== - * - * [IMPORTANT] - * ==== - * You shouldn't rely on `isContract` to protect against flash loan attacks! - * - * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets - * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract - * constructor. - * ==== - */ - function isContract(address account) internal view returns (bool) { - // This method relies on extcodesize/address.code.length, which returns 0 - // for contracts in construction, since the code is only stored at the end - // of the constructor execution. - - return account.code.length > 0; - } - - /** - * @dev Replacement for Solidity's `transfer`: sends `amount` wei to - * `recipient`, forwarding all available gas and reverting on errors. - * - * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost - * of certain opcodes, possibly making contracts go over the 2300 gas limit - * imposed by `transfer`, making them unable to receive funds via - * `transfer`. {sendValue} removes this limitation. - * - * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. - * - * IMPORTANT: because control is transferred to `recipient`, care must be - * taken to not create reentrancy vulnerabilities. Consider using - * {ReentrancyGuard} or the - * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. - */ - function sendValue(address payable recipient, uint256 amount) internal { - require(address(this).balance >= amount, "Address: insufficient balance"); - - (bool success, ) = recipient.call{value: amount}(""); - require(success, "Address: unable to send value, recipient may have reverted"); - } - - /** - * @dev Performs a Solidity function call using a low level `call`. A - * plain `call` is an unsafe replacement for a function call: use this - * function instead. - * - * If `target` reverts with a revert reason, it is bubbled up by this - * function (like regular Solidity function calls). - * - * Returns the raw returned data. To convert to the expected return value, - * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. - * - * Requirements: - * - * - `target` must be a contract. - * - calling `target` with `data` must not revert. - * - * _Available since v3.1._ - */ - function functionCall(address target, bytes memory data) internal returns (bytes memory) { - return functionCallWithValue(target, data, 0, "Address: low-level call failed"); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with - * `errorMessage` as a fallback revert reason when `target` reverts. - * - * _Available since v3.1._ - */ - function functionCall( - address target, - bytes memory data, - string memory errorMessage - ) internal returns (bytes memory) { - return functionCallWithValue(target, data, 0, errorMessage); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], - * but also transferring `value` wei to `target`. - * - * Requirements: - * - * - the calling contract must have an ETH balance of at least `value`. - * - the called Solidity function must be `payable`. - * - * _Available since v3.1._ - */ - function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { - return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); - } - - /** - * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but - * with `errorMessage` as a fallback revert reason when `target` reverts. - * - * _Available since v3.1._ - */ - function functionCallWithValue( - address target, - bytes memory data, - uint256 value, - string memory errorMessage - ) internal returns (bytes memory) { - require(address(this).balance >= value, "Address: insufficient balance for call"); - (bool success, bytes memory returndata) = target.call{value: value}(data); - return verifyCallResultFromTarget(target, success, returndata, errorMessage); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], - * but performing a static call. - * - * _Available since v3.3._ - */ - function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { - return functionStaticCall(target, data, "Address: low-level static call failed"); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], - * but performing a static call. - * - * _Available since v3.3._ - */ - function functionStaticCall( - address target, - bytes memory data, - string memory errorMessage - ) internal view returns (bytes memory) { - (bool success, bytes memory returndata) = target.staticcall(data); - return verifyCallResultFromTarget(target, success, returndata, errorMessage); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], - * but performing a delegate call. - * - * _Available since v3.4._ - */ - function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { - return functionDelegateCall(target, data, "Address: low-level delegate call failed"); - } - - /** - * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], - * but performing a delegate call. - * - * _Available since v3.4._ - */ - function functionDelegateCall( - address target, - bytes memory data, - string memory errorMessage - ) internal returns (bytes memory) { - (bool success, bytes memory returndata) = target.delegatecall(data); - return verifyCallResultFromTarget(target, success, returndata, errorMessage); - } - - /** - * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling - * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. - * - * _Available since v4.8._ - */ - function verifyCallResultFromTarget( - address target, - bool success, - bytes memory returndata, - string memory errorMessage - ) internal view returns (bytes memory) { - if (success) { - if (returndata.length == 0) { - // only check isContract if the call was successful and the return data is empty - // otherwise we already know that it was a contract - require(isContract(target), "Address: call to non-contract"); - } - return returndata; - } else { - _revert(returndata, errorMessage); - } - } - - /** - * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the - * revert reason or using the provided one. - * - * _Available since v4.3._ - */ - function verifyCallResult( - bool success, - bytes memory returndata, - string memory errorMessage - ) internal pure returns (bytes memory) { - if (success) { - return returndata; - } else { - _revert(returndata, errorMessage); - } - } - - function _revert(bytes memory returndata, string memory errorMessage) private pure { - // Look for revert reason and bubble it up if present - if (returndata.length > 0) { - // The easiest way to bubble the revert reason is using memory via assembly - /// @solidity memory-safe-assembly - assembly { - let returndata_size := mload(returndata) - revert(add(32, returndata), returndata_size) - } - } else { - revert(errorMessage); - } - } -} - -/** - * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed - * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an - * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer - * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. - * - * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be - * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in - * case an upgrade adds a module that needs to be initialized. - * - * For example: - * - * [.hljs-theme-light.nopadding] - * ```solidity - * contract MyToken is ERC20Upgradeable { - * function initialize() initializer public { - * __ERC20_init("MyToken", "MTK"); - * } - * } - * - * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { - * function initializeV2() reinitializer(2) public { - * __ERC20Permit_init("MyToken"); - * } - * } - * ``` - * - * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as - * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. - * - * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure - * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. - * - * [CAUTION] - * ==== - * Avoid leaving a contract uninitialized. - * - * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation - * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke - * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: - * - * [.hljs-theme-light.nopadding] - * ``` - * /// @custom:oz-upgrades-unsafe-allow constructor - * constructor() { - * _disableInitializers(); - * } - * ``` - * ==== - */ -abstract contract Initializable { - /** - * @dev Indicates that the contract has been initialized. - * @custom:oz-retyped-from bool - */ - uint8 private _initialized; - - /** - * @dev Indicates that the contract is in the process of being initialized. - */ - bool private _initializing; - - /** - * @dev Triggered when the contract has been initialized or reinitialized. - */ - event Initialized(uint8 version); - - /** - * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, - * `onlyInitializing` functions can be used to initialize parent contracts. - * - * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a - * constructor. - * - * Emits an {Initialized} event. - */ - modifier initializer() { - bool isTopLevelCall = !_initializing; - require( - (isTopLevelCall && _initialized < 1) || - (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), - "Initializable: contract is already initialized" - ); - _initialized = 1; - if (isTopLevelCall) { - _initializing = true; - } - _; - if (isTopLevelCall) { - _initializing = false; - emit Initialized(1); - } - } - - /** - * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the - * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be - * used to initialize parent contracts. - * - * A reinitializer may be used after the original initialization step. This is essential to configure modules that - * are added through upgrades and that require initialization. - * - * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` - * cannot be nested. If one is invoked in the context of another, execution will revert. - * - * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in - * a contract, executing them in the right order is up to the developer or operator. - * - * WARNING: setting the version to 255 will prevent any future reinitialization. - * - * Emits an {Initialized} event. - */ - modifier reinitializer(uint8 version) { - require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); - _initialized = version; - _initializing = true; - _; - _initializing = false; - emit Initialized(version); - } - - /** - * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the - * {initializer} and {reinitializer} modifiers, directly or indirectly. - */ - modifier onlyInitializing() { - require(_initializing, "Initializable: contract is not initializing"); - _; - } - - /** - * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. - * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized - * to any version. It is recommended to use this to lock implementation contracts that are designed to be called - * through proxies. - * - * Emits an {Initialized} event the first time it is successfully executed. - */ - function _disableInitializers() internal virtual { - require(!_initializing, "Initializable: contract is initializing"); - if (_initialized != type(uint8).max) { - _initialized = type(uint8).max; - emit Initialized(type(uint8).max); - } - } - - /** - * @dev Returns the highest version that has been initialized. See {reinitializer}. - */ - function _getInitializedVersion() internal view returns (uint8) { - return _initialized; - } - - /** - * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. - */ - function _isInitializing() internal view returns (bool) { - return _initializing; - } -} - -/** - * @dev Provides information about the current execution context, including the - * sender of the transaction and its data. While these are generally available - * via msg.sender and msg.data, they should not be accessed in such a direct - * manner, since when dealing with meta-transactions the account sending and - * paying for execution may not be the actual sender (as far as an application - * is concerned). - * - * This contract is only required for intermediate, library-like contracts. - */ -abstract contract ContextUpgradeable is Initializable { - function __Context_init() internal onlyInitializing {} - - function __Context_init_unchained() internal onlyInitializing {} - - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } - - /** - * @dev This empty reserved space is put in place to allow future versions to add new - * variables without shifting down storage in the inheritance chain. - * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps - */ - uint256[50] private __gap; -} - -/** - * @dev Implementation of the {IERC20} interface. - * - * This implementation is agnostic to the way tokens are created. This means - * that a supply mechanism has to be added in a derived contract using {_mint}. - * For a generic mechanism see {ERC20PresetMinterPauser}. - * - * TIP: For a detailed writeup see our guide - * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How - * to implement supply mechanisms]. - * - * The default value of {decimals} is 18. To change this, you should override - * this function so it returns a different value. - * - * We have followed general OpenZeppelin Contracts guidelines: functions revert - * instead returning `false` on failure. This behavior is nonetheless - * conventional and does not conflict with the expectations of ERC20 - * applications. - * - * Additionally, an {Approval} event is emitted on calls to {transferFrom}. - * This allows applications to reconstruct the allowance for all accounts just - * by listening to said events. Other implementations of the EIP may not emit - * these events, as it isn't required by the specification. - * - * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} - * functions have been added to mitigate the well-known issues around setting - * allowances. See {IERC20-approve}. - */ -contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { - mapping(address => uint256) private _balances; - - mapping(address => mapping(address => uint256)) private _allowances; - - uint256 private _totalSupply; - - string private _name; - string private _symbol; - - /** - * @dev Sets the values for {name} and {symbol}. - * - * All two of these values are immutable: they can only be set once during - * construction. - */ - function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { - __ERC20_init_unchained(name_, symbol_); - } - - function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { - _name = name_; - _symbol = symbol_; - } - - /** - * @dev Returns the name of the token. - */ - function name() public view virtual override returns (string memory) { - return _name; - } - - /** - * @dev Returns the symbol of the token, usually a shorter version of the - * name. - */ - function symbol() public view virtual override returns (string memory) { - return _symbol; - } - - /** - * @dev Returns the number of decimals used to get its user representation. - * For example, if `decimals` equals `2`, a balance of `505` tokens should - * be displayed to a user as `5.05` (`505 / 10 ** 2`). - * - * Tokens usually opt for a value of 18, imitating the relationship between - * Ether and Wei. This is the default value returned by this function, unless - * it's overridden. - * - * NOTE: This information is only used for _display_ purposes: it in - * no way affects any of the arithmetic of the contract, including - * {IERC20-balanceOf} and {IERC20-transfer}. - */ - function decimals() public view virtual override returns (uint8) { - return 18; - } - - /** - * @dev See {IERC20-totalSupply}. - */ - function totalSupply() public view virtual override returns (uint256) { - return _totalSupply; - } - - /** - * @dev See {IERC20-balanceOf}. - */ - function balanceOf(address account) public view virtual override returns (uint256) { - return _balances[account]; - } - - /** - * @dev See {IERC20-transfer}. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - the caller must have a balance of at least `amount`. - */ - function transfer(address to, uint256 amount) public virtual override returns (bool) { - address owner = _msgSender(); - _transfer(owner, to, amount); - return true; - } - - /** - * @dev See {IERC20-allowance}. - */ - function allowance(address owner, address spender) public view virtual override returns (uint256) { - return _allowances[owner][spender]; - } - - /** - * @dev See {IERC20-approve}. - * - * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on - * `transferFrom`. This is semantically equivalent to an infinite approval. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function approve(address spender, uint256 amount) public virtual override returns (bool) { - address owner = _msgSender(); - _approve(owner, spender, amount); - return true; - } - - /** - * @dev See {IERC20-transferFrom}. - * - * Emits an {Approval} event indicating the updated allowance. This is not - * required by the EIP. See the note at the beginning of {ERC20}. - * - * NOTE: Does not update the allowance if the current allowance - * is the maximum `uint256`. - * - * Requirements: - * - * - `from` and `to` cannot be the zero address. - * - `from` must have a balance of at least `amount`. - * - the caller must have allowance for ``from``'s tokens of at least - * `amount`. - */ - function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { - address spender = _msgSender(); - _spendAllowance(from, spender, amount); - _transfer(from, to, amount); - return true; - } - - /** - * @dev Atomically increases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { - address owner = _msgSender(); - _approve(owner, spender, allowance(owner, spender) + addedValue); - return true; - } - - /** - * @dev Atomically decreases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `spender` must have allowance for the caller of at least - * `subtractedValue`. - */ - function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { - address owner = _msgSender(); - uint256 currentAllowance = allowance(owner, spender); - require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); - unchecked { - _approve(owner, spender, currentAllowance - subtractedValue); - } - - return true; - } - - /** - * @dev Moves `amount` of tokens from `from` to `to`. - * - * This internal function is equivalent to {transfer}, and can be used to - * e.g. implement automatic token fees, slashing mechanisms, etc. - * - * Emits a {Transfer} event. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `from` must have a balance of at least `amount`. - */ - function _transfer(address from, address to, uint256 amount) internal virtual { - require(from != address(0), "ERC20: transfer from the zero address"); - require(to != address(0), "ERC20: transfer to the zero address"); - - _beforeTokenTransfer(from, to, amount); - - uint256 fromBalance = _balances[from]; - require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); - unchecked { - _balances[from] = fromBalance - amount; - // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by - // decrementing then incrementing. - _balances[to] += amount; - } - - emit Transfer(from, to, amount); - - _afterTokenTransfer(from, to, amount); - } - - /** @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. - * - * Emits a {Transfer} event with `from` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - */ - function _mint(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: mint to the zero address"); - - _beforeTokenTransfer(address(0), account, amount); - - _totalSupply += amount; - unchecked { - // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. - _balances[account] += amount; - } - emit Transfer(address(0), account, amount); - - _afterTokenTransfer(address(0), account, amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, reducing the - * total supply. - * - * Emits a {Transfer} event with `to` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - * - `account` must have at least `amount` tokens. - */ - function _burn(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: burn from the zero address"); - - _beforeTokenTransfer(account, address(0), amount); - - uint256 accountBalance = _balances[account]; - require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); - unchecked { - _balances[account] = accountBalance - amount; - // Overflow not possible: amount <= accountBalance <= totalSupply. - _totalSupply -= amount; - } - - emit Transfer(account, address(0), amount); - - _afterTokenTransfer(account, address(0), amount); - } - - /** - * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. - * - * This internal function is equivalent to `approve`, and can be used to - * e.g. set automatic allowances for certain subsystems, etc. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `owner` cannot be the zero address. - * - `spender` cannot be the zero address. - */ - function _approve(address owner, address spender, uint256 amount) internal virtual { - require(owner != address(0), "ERC20: approve from the zero address"); - require(spender != address(0), "ERC20: approve to the zero address"); - - _allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } - - /** - * @dev Updates `owner` s allowance for `spender` based on spent `amount`. - * - * Does not update the allowance amount in case of infinite allowance. - * Revert if not enough allowance is available. - * - * Might emit an {Approval} event. - */ - function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { - uint256 currentAllowance = allowance(owner, spender); - if (currentAllowance != type(uint256).max) { - require(currentAllowance >= amount, "ERC20: insufficient allowance"); - unchecked { - _approve(owner, spender, currentAllowance - amount); - } - } - } - - /** - * @dev Hook that is called before any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * will be transferred to `to`. - * - when `from` is zero, `amount` tokens will be minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens will be burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} - - /** - * @dev Hook that is called after any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * has been transferred to `to`. - * - when `from` is zero, `amount` tokens have been minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens have been burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} - - /** - * @dev This empty reserved space is put in place to allow future versions to add new - * variables without shifting down storage in the inheritance chain. - * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps - */ - uint256[45] private __gap; -} - -// OpenZeppelin Contracts (last updated v4.9.0) (utils/Arrays.sol) - -// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol) -// This file was procedurally generated from scripts/generate/templates/StorageSlot.js. - -/** - * @dev Library for reading and writing primitive types to specific storage slots. - * - * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. - * This library helps with reading and writing to such slots without the need for inline assembly. - * - * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. - * - * Example usage to set ERC1967 implementation slot: - * ```solidity - * contract ERC1967 { - * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; - * - * function _getImplementation() internal view returns (address) { - * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; - * } - * - * function _setImplementation(address newImplementation) internal { - * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); - * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; - * } - * } - * ``` - * - * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._ - * _Available since v4.9 for `string`, `bytes`._ - */ -library StorageSlotUpgradeable { - struct AddressSlot { - address value; - } - - struct BooleanSlot { - bool value; - } - - struct Bytes32Slot { - bytes32 value; - } - - struct Uint256Slot { - uint256 value; - } - - struct StringSlot { - string value; - } - - struct BytesSlot { - bytes value; - } - - /** - * @dev Returns an `AddressSlot` with member `value` located at `slot`. - */ - function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `BooleanSlot` with member `value` located at `slot`. - */ - function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. - */ - function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `Uint256Slot` with member `value` located at `slot`. - */ - function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `StringSlot` with member `value` located at `slot`. - */ - function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `StringSlot` representation of the string storage pointer `store`. - */ - function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := store.slot - } - } - - /** - * @dev Returns an `BytesSlot` with member `value` located at `slot`. - */ - function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. - */ - function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := store.slot - } - } -} - -// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) - -/** - * @dev Standard math utilities missing in the Solidity language. - */ -library MathUpgradeable { - enum Rounding { - Down, // Toward negative infinity - Up, // Toward infinity - Zero // Toward zero - } - - /** - * @dev Returns the largest of two numbers. - */ - function max(uint256 a, uint256 b) internal pure returns (uint256) { - return a > b ? a : b; - } - - /** - * @dev Returns the smallest of two numbers. - */ - function min(uint256 a, uint256 b) internal pure returns (uint256) { - return a < b ? a : b; - } - - /** - * @dev Returns the average of two numbers. The result is rounded towards - * zero. - */ - function average(uint256 a, uint256 b) internal pure returns (uint256) { - // (a + b) / 2 can overflow. - return (a & b) + (a ^ b) / 2; - } - - /** - * @dev Returns the ceiling of the division of two numbers. - * - * This differs from standard division with `/` in that it rounds up instead - * of rounding down. - */ - function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { - // (a + b - 1) / b can overflow on addition, so we distribute. - return a == 0 ? 0 : (a - 1) / b + 1; - } - - /** - * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 - * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) - * with further edits by Uniswap Labs also under MIT license. - */ - function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { - unchecked { - // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use - // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 - // variables such that product = prod1 * 2^256 + prod0. - uint256 prod0; // Least significant 256 bits of the product - uint256 prod1; // Most significant 256 bits of the product - assembly { - let mm := mulmod(x, y, not(0)) - prod0 := mul(x, y) - prod1 := sub(sub(mm, prod0), lt(mm, prod0)) - } - - // Handle non-overflow cases, 256 by 256 division. - if (prod1 == 0) { - // Solidity will revert if denominator == 0, unlike the div opcode on its own. - // The surrounding unchecked block does not change this fact. - // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. - return prod0 / denominator; - } - - // Make sure the result is less than 2^256. Also prevents denominator == 0. - require(denominator > prod1, "Math: mulDiv overflow"); - - /////////////////////////////////////////////// - // 512 by 256 division. - /////////////////////////////////////////////// - - // Make division exact by subtracting the remainder from [prod1 prod0]. - uint256 remainder; - assembly { - // Compute remainder using mulmod. - remainder := mulmod(x, y, denominator) - - // Subtract 256 bit number from 512 bit number. - prod1 := sub(prod1, gt(remainder, prod0)) - prod0 := sub(prod0, remainder) - } - - // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. - // See https://cs.stackexchange.com/q/138556/92363. - - // Does not overflow because the denominator cannot be zero at this stage in the function. - uint256 twos = denominator & (~denominator + 1); - assembly { - // Divide denominator by twos. - denominator := div(denominator, twos) - - // Divide [prod1 prod0] by twos. - prod0 := div(prod0, twos) - - // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. - twos := add(div(sub(0, twos), twos), 1) - } - - // Shift in bits from prod1 into prod0. - prod0 |= prod1 * twos; - - // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such - // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for - // four bits. That is, denominator * inv = 1 mod 2^4. - uint256 inverse = (3 * denominator) ^ 2; - - // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works - // in modular arithmetic, doubling the correct bits in each step. - inverse *= 2 - denominator * inverse; // inverse mod 2^8 - inverse *= 2 - denominator * inverse; // inverse mod 2^16 - inverse *= 2 - denominator * inverse; // inverse mod 2^32 - inverse *= 2 - denominator * inverse; // inverse mod 2^64 - inverse *= 2 - denominator * inverse; // inverse mod 2^128 - inverse *= 2 - denominator * inverse; // inverse mod 2^256 - - // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. - // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is - // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 - // is no longer required. - result = prod0 * inverse; - return result; - } - } - - /** - * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. - */ - function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { - uint256 result = mulDiv(x, y, denominator); - if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { - result += 1; - } - return result; - } - - /** - * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. - * - * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). - */ - function sqrt(uint256 a) internal pure returns (uint256) { - if (a == 0) { - return 0; - } - - // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. - // - // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have - // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. - // - // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` - // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` - // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` - // - // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. - uint256 result = 1 << (log2(a) >> 1); - - // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, - // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at - // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision - // into the expected uint128 result. - unchecked { - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - return min(result, a / result); - } - } - - /** - * @notice Calculates sqrt(a), following the selected rounding direction. - */ - function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = sqrt(a); - return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); - } - } - - /** - * @dev Return the log in base 2, rounded down, of a positive value. - * Returns 0 if given 0. - */ - function log2(uint256 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >> 128 > 0) { - value >>= 128; - result += 128; - } - if (value >> 64 > 0) { - value >>= 64; - result += 64; - } - if (value >> 32 > 0) { - value >>= 32; - result += 32; - } - if (value >> 16 > 0) { - value >>= 16; - result += 16; - } - if (value >> 8 > 0) { - value >>= 8; - result += 8; - } - if (value >> 4 > 0) { - value >>= 4; - result += 4; - } - if (value >> 2 > 0) { - value >>= 2; - result += 2; - } - if (value >> 1 > 0) { - result += 1; - } - } - return result; - } - - /** - * @dev Return the log in base 2, following the selected rounding direction, of a positive value. - * Returns 0 if given 0. - */ - function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = log2(value); - return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); - } - } - - /** - * @dev Return the log in base 10, rounded down, of a positive value. - * Returns 0 if given 0. - */ - function log10(uint256 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >= 10 ** 64) { - value /= 10 ** 64; - result += 64; - } - if (value >= 10 ** 32) { - value /= 10 ** 32; - result += 32; - } - if (value >= 10 ** 16) { - value /= 10 ** 16; - result += 16; - } - if (value >= 10 ** 8) { - value /= 10 ** 8; - result += 8; - } - if (value >= 10 ** 4) { - value /= 10 ** 4; - result += 4; - } - if (value >= 10 ** 2) { - value /= 10 ** 2; - result += 2; - } - if (value >= 10 ** 1) { - result += 1; - } - } - return result; - } - - /** - * @dev Return the log in base 10, following the selected rounding direction, of a positive value. - * Returns 0 if given 0. - */ - function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = log10(value); - return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); - } - } - - /** - * @dev Return the log in base 256, rounded down, of a positive value. - * Returns 0 if given 0. - * - * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. - */ - function log256(uint256 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >> 128 > 0) { - value >>= 128; - result += 16; - } - if (value >> 64 > 0) { - value >>= 64; - result += 8; - } - if (value >> 32 > 0) { - value >>= 32; - result += 4; - } - if (value >> 16 > 0) { - value >>= 16; - result += 2; - } - if (value >> 8 > 0) { - result += 1; - } - } - return result; - } - - /** - * @dev Return the log in base 256, following the selected rounding direction, of a positive value. - * Returns 0 if given 0. - */ - function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = log256(value); - return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); - } - } -} - -/** - * @dev Collection of functions related to array types. - */ -library ArraysUpgradeable { - using StorageSlotUpgradeable for bytes32; - - /** - * @dev Searches a sorted `array` and returns the first index that contains - * a value greater or equal to `element`. If no such index exists (i.e. all - * values in the array are strictly less than `element`), the array length is - * returned. Time complexity O(log n). - * - * `array` is expected to be sorted in ascending order, and to contain no - * repeated elements. - */ - function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { - if (array.length == 0) { - return 0; - } - - uint256 low = 0; - uint256 high = array.length; - - while (low < high) { - uint256 mid = MathUpgradeable.average(low, high); - - // Note that mid will always be strictly less than high (i.e. it will be a valid array index) - // because Math.average rounds down (it does integer division with truncation). - if (unsafeAccess(array, mid).value > element) { - high = mid; - } else { - low = mid + 1; - } - } - - // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. - if (low > 0 && unsafeAccess(array, low - 1).value == element) { - return low - 1; - } else { - return low; - } - } - - /** - * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. - * - * WARNING: Only use if you are certain `pos` is lower than the array length. - */ - function unsafeAccess( - address[] storage arr, - uint256 pos - ) internal pure returns (StorageSlotUpgradeable.AddressSlot storage) { - bytes32 slot; - // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` - // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. - - /// @solidity memory-safe-assembly - assembly { - mstore(0, arr.slot) - slot := add(keccak256(0, 0x20), pos) - } - return slot.getAddressSlot(); - } - - /** - * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. - * - * WARNING: Only use if you are certain `pos` is lower than the array length. - */ - function unsafeAccess( - bytes32[] storage arr, - uint256 pos - ) internal pure returns (StorageSlotUpgradeable.Bytes32Slot storage) { - bytes32 slot; - // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` - // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. - - /// @solidity memory-safe-assembly - assembly { - mstore(0, arr.slot) - slot := add(keccak256(0, 0x20), pos) - } - return slot.getBytes32Slot(); - } - - /** - * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. - * - * WARNING: Only use if you are certain `pos` is lower than the array length. - */ - function unsafeAccess( - uint256[] storage arr, - uint256 pos - ) internal pure returns (StorageSlotUpgradeable.Uint256Slot storage) { - bytes32 slot; - // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` - // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. - - /// @solidity memory-safe-assembly - assembly { - mstore(0, arr.slot) - slot := add(keccak256(0, 0x20), pos) - } - return slot.getUint256Slot(); - } -} - -// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) - -/** - * @title Counters - * @author Matt Condon (@shrugs) - * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number - * of elements in a mapping, issuing ERC721 ids, or counting request ids. - * - * Include with `using Counters for Counters.Counter;` - */ -library CountersUpgradeable { - struct Counter { - // This variable should never be directly accessed by users of the library: interactions must be restricted to - // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add - // this feature: see https://github.com/ethereum/solidity/issues/4637 - uint256 _value; // default: 0 - } - - function current(Counter storage counter) internal view returns (uint256) { - return counter._value; - } - - function increment(Counter storage counter) internal { - unchecked { - counter._value += 1; - } - } - - function decrement(Counter storage counter) internal { - uint256 value = counter._value; - require(value > 0, "Counter: decrement overflow"); - unchecked { - counter._value = value - 1; - } - } - - function reset(Counter storage counter) internal { - counter._value = 0; - } -} - -/** - * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and - * total supply at the time are recorded for later access. - * - * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. - * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different - * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be - * used to create an efficient ERC20 forking mechanism. - * - * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a - * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot - * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id - * and the account address. - * - * NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it - * return `block.number` will trigger the creation of snapshot at the beginning of each new block. When overriding this - * function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract. - * - * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient - * alternative consider {ERC20Votes}. - * - * ==== Gas Costs - * - * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log - * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much - * smaller since identical balances in subsequent snapshots are stored as a single entry. - * - * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is - * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent - * transfers will have normal cost until the next snapshot, and so on. - */ - -abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable { - function __ERC20Snapshot_init() internal onlyInitializing {} - - function __ERC20Snapshot_init_unchained() internal onlyInitializing {} - - // Inspired by Jordi Baylina's MiniMeToken to record historical balances: - // https://github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol - - using ArraysUpgradeable for uint256[]; - using CountersUpgradeable for CountersUpgradeable.Counter; - - // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a - // Snapshot struct, but that would impede usage of functions that work on an array. - struct Snapshots { - uint256[] ids; - uint256[] values; - } - - mapping(address => Snapshots) private _accountBalanceSnapshots; - Snapshots private _totalSupplySnapshots; - - // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. - CountersUpgradeable.Counter private _currentSnapshotId; - - /** - * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. - */ - event Snapshot(uint256 id); - - /** - * @dev Creates a new snapshot and returns its snapshot id. - * - * Emits a {Snapshot} event that contains the same id. - * - * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a - * set of accounts, for example using {AccessControl}, or it may be open to the public. - * - * [WARNING] - * ==== - * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, - * you must consider that it can potentially be used by attackers in two ways. - * - * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow - * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target - * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs - * section above. - * - * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. - * ==== - */ - function _snapshot() internal virtual returns (uint256) { - _currentSnapshotId.increment(); - - uint256 currentId = _getCurrentSnapshotId(); - emit Snapshot(currentId); - return currentId; - } - - /** - * @dev Get the current snapshotId - */ - function _getCurrentSnapshotId() internal view virtual returns (uint256) { - return _currentSnapshotId.current(); - } - - /** - * @dev Retrieves the balance of `account` at the time `snapshotId` was created. - */ - function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { - (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); - - return snapshotted ? value : balanceOf(account); - } - - /** - * @dev Retrieves the total supply at the time `snapshotId` was created. - */ - function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256) { - (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); - - return snapshotted ? value : totalSupply(); - } - - // Update balance and/or total supply snapshots before the values are modified. This is implemented - // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. - function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { - super._beforeTokenTransfer(from, to, amount); - - if (from == address(0)) { - // mint - _updateAccountSnapshot(to); - _updateTotalSupplySnapshot(); - } else if (to == address(0)) { - // burn - _updateAccountSnapshot(from); - _updateTotalSupplySnapshot(); - } else { - // transfer - _updateAccountSnapshot(from); - _updateAccountSnapshot(to); - } - } - - function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { - require(snapshotId > 0, "ERC20Snapshot: id is 0"); - require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id"); - - // When a valid snapshot is queried, there are three possibilities: - // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never - // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds - // to this id is the current one. - // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the - // requested id, and its value is the one to return. - // c) More snapshots were created after the requested one, and the queried value was later modified. There will be - // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is - // larger than the requested one. - // - // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if - // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does - // exactly this. - - uint256 index = snapshots.ids.findUpperBound(snapshotId); - - if (index == snapshots.ids.length) { - return (false, 0); - } else { - return (true, snapshots.values[index]); - } - } - - function _updateAccountSnapshot(address account) private { - _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); - } - - function _updateTotalSupplySnapshot() private { - _updateSnapshot(_totalSupplySnapshots, totalSupply()); - } - - function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { - uint256 currentId = _getCurrentSnapshotId(); - if (_lastSnapshotId(snapshots.ids) < currentId) { - snapshots.ids.push(currentId); - snapshots.values.push(currentValue); - } - } - - function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { - if (ids.length == 0) { - return 0; - } else { - return ids[ids.length - 1]; - } - } - - /** - * @dev This empty reserved space is put in place to allow future versions to add new - * variables without shifting down storage in the inheritance chain. - * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps - */ - uint256[46] private __gap; -} - -// NOTE: Renamed Withdrawal to Withdrawal_Struct because of a conflict with the event of the same name when flattened. - -/** - * @notice data type for withdrawals - * @param amount the amount to withdraw - * @param epoch the epoch of the withdrawal - */ -struct Withdrawal_Struct { - uint256 amount; - uint256 epoch; -} - -/** - * @notice data type for managing the withdrawal queue - * @param head earliest unprocessed index - * (which is also the most recently filled witrhdrawal) - * @param tail index of most recent withdrawal - * (which is also the total number of submitted withdrawals) - * @param withdrawals Withdrawal structs by index - */ -struct WithdrawalQueue { - uint256 head; - uint256 tail; - mapping(uint256 => Withdrawal_Struct) withdrawals; -} - -/** - * @title Withdrawal Queue Lib - * @author Polygon Technology (Daniel Gretzke @gretzke) - * @notice queue for withdrawals - */ -library WithdrawalQueueLib { - /** - * @notice update queue with new withdrawal data - * @dev if there is already a withdrawal for the epoch being submitted, - * the amount will be added to that epoch; otherwise, a new withdrawal - * struct will be created in the queue - * @param self the WithdrawalQueue struct - * @param amount the amount to withdraw - * @param epoch the epoch to withdraw - */ - function append(WithdrawalQueue storage self, uint256 amount, uint256 epoch) internal { - require(amount != 0, "WithdrawalQueueLib: INVALID_AMOUNT"); - uint256 head = self.head; - uint256 tail = self.tail; - - // first element in empty list - if (tail == head) { - self.withdrawals[tail] = Withdrawal_Struct(amount, epoch); - self.tail++; - return; - } - - uint256 latestEpoch = self.withdrawals[tail - 1].epoch; - assert(epoch >= latestEpoch); - if (latestEpoch < epoch) { - // new withdrawal for next epoch - self.withdrawals[tail] = Withdrawal_Struct(amount, epoch); - self.tail++; - } else { - // adding to existing withdrawal for next epoch - self.withdrawals[tail - 1].amount += amount; - } - } - - /** - * @notice returns the length between the head and tail of the queue - * (which is the amount of unprocessed withdrawals) - * @param self the WithdrawalQueue struct - * @return uint256 the length between head and tail (unproceesed withdrawals) - */ - // slither-disable-next-line dead-code - function length(WithdrawalQueue storage self) internal view returns (uint256) { - return self.tail - self.head; - } - - /** - * @notice returns the amount withdrawable through a specified epoch - * and new head index at that point - * @dev meant to be used with the current epoch being passed in - * @param self the WithdrawalQueue struct - * @param currentEpoch the epoch to check until - * @return amount the amount withdrawable through the specified epoch - * @return newHead the head of the queue once these withdrawals have been processed - */ - function withdrawable( - WithdrawalQueue storage self, - uint256 currentEpoch - ) internal view returns (uint256 amount, uint256 newHead) { - for (newHead = self.head; newHead < self.tail; newHead++) { - Withdrawal_Struct memory withdrawal = self.withdrawals[newHead]; - if (withdrawal.epoch > currentEpoch) return (amount, newHead); - amount += withdrawal.amount; - } - } - - /** - * @notice returns the amount withdrawable beyond a specified epoch - * @dev meant to be used with the current epoch being passed in - * @param self the WithdrawalQueue struct - * @param currentEpoch the epoch to check from - * @return amount the amount withdrawable from beyond the specified epoch - */ - function pending(WithdrawalQueue storage self, uint256 currentEpoch) internal view returns (uint256 amount) { - uint256 tail = self.tail; - if (tail == 0) return 0; - for (uint256 i = tail - 1; i >= self.head; i--) { - Withdrawal_Struct memory withdrawal = self.withdrawals[i]; - if (withdrawal.epoch <= currentEpoch) break; - amount += withdrawal.amount; - if (i == 0) break; - } - } -} - -interface IStateReceiver { - function onStateReceive(uint256 counter, address sender, bytes calldata data) external; -} - -struct ValidatorInit { - address addr; - uint256 stake; -} - -struct Epoch { - uint256 startBlock; - uint256 endBlock; - bytes32 epochRoot; -} - -/** - @title IValidatorSet - @author Polygon Technology (@gretzke) - @notice Manages voting power for validators and commits epochs for child chains - @dev Voting power is synced between the stake manager on root on stake and unstake actions - */ -interface IValidatorSet is IStateReceiver { - event NewEpoch(uint256 indexed id, uint256 indexed startBlock, uint256 indexed endBlock, bytes32 epochRoot); - event Slashed(uint256 indexed validator, uint256 amount); - event WithdrawalRegistered(address indexed account, uint256 amount); - event Withdrawal(address indexed account, uint256 amount); - - /// @notice commits a new epoch - /// @dev system call - function commitEpoch(uint256 id, Epoch calldata epoch) external; - - /// @notice allows a validator to announce their intention to withdraw a given amount of tokens - /// @dev initializes a waiting period before the tokens can be withdrawn - function unstake(uint256 amount) external; - - /// @notice allows a validator to complete a withdrawal - /// @dev calls the bridge to release the funds on root - function withdraw() external; - - /// @notice amount of blocks in an epoch - /// @dev when an epoch is committed a multiple of this number of blocks must be committed - // slither-disable-next-line naming-convention - function EPOCH_SIZE() external view returns (uint256); - - /// @notice total amount of blocks in a given epoch - function totalBlocks(uint256 epochId) external view returns (uint256 length); - - /// @notice returns a validator balance for a given epoch - function balanceOfAt(address account, uint256 epochNumber) external view returns (uint256); - - /// @notice returns the total supply for a given epoch - function totalSupplyAt(uint256 epochNumber) external view returns (uint256); - - /** - * @notice Calculates how much can be withdrawn for account in this epoch. - * @param account The account to calculate amount for - * @return Amount withdrawable (in MATIC wei) - */ - function withdrawable(address account) external view returns (uint256); - - /** - * @notice Calculates how much is yet to become withdrawable for account. - * @param account The account to calculate amount for - * @return Amount not yet withdrawable (in MATIC wei) - */ - function pendingWithdrawals(address account) external view returns (uint256); -} - -interface IStateSender { - function syncState(address receiver, bytes calldata data) external; -} - -error Unauthorized(string only); -error StakeRequirement(string src, string msg); -error InvalidSignature(address signer); - -contract System { - // pre-compiled contracts - // slither-disable too-many-digits - address public constant NATIVE_TRANSFER_PRECOMPILE = 0x0000000000000000000000000000000000002020; - address public constant VALIDATOR_PKCHECK_PRECOMPILE = 0x0000000000000000000000000000000000002030; - address public constant ALLOWLIST_PRECOMPILE = 0x0200000000000000000000000000000000000004; - address public constant BLOCKLIST_PRECOMPILE = 0x0300000000000000000000000000000000000004; - - // internal addrs - address public constant SYSTEM = 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE; - - // pre-compiled gas consumption - uint256 public constant NATIVE_TRANSFER_PRECOMPILE_GAS = 21000; - uint256 public constant VALIDATOR_PKCHECK_PRECOMPILE_GAS = 150000; - uint256 public constant READ_ADDRESSLIST_GAS = 5000; - - // genesis contracts - address public constant NATIVE_TOKEN_CONTRACT = 0x0000000000000000000000000000000000001010; - - modifier onlySystemCall() { - if (msg.sender != SYSTEM) revert Unauthorized("SYSTEMCALL"); - _; - } - - // slither-disable-next-line unused-state,naming-convention - uint256[50] private __gap; -} - -contract ValidatorSet is IValidatorSet, ERC20SnapshotUpgradeable, System { - using WithdrawalQueueLib for WithdrawalQueue; - - bytes32 private constant STAKE_SIG = keccak256("STAKE"); - bytes32 private constant UNSTAKE_SIG = keccak256("UNSTAKE"); - bytes32 private constant SLASH_SIG = keccak256("SLASH"); - uint256 public constant WITHDRAWAL_WAIT_PERIOD = 1; - - IStateSender private stateSender; - address private stateReceiver; - address private rootChainManager; - // slither-disable-next-line naming-convention - uint256 public EPOCH_SIZE; - - uint256 public currentEpochId; - - mapping(uint256 => Epoch) public epochs; - uint256[] public epochEndBlocks; - mapping(address => WithdrawalQueue) internal withdrawals; - - function initialize( - address newStateSender, - address newStateReceiver, - address newRootChainManager, - uint256 newEpochSize, - ValidatorInit[] memory initialValidators - ) public initializer { - require( - newStateSender != address(0) && - newStateReceiver != address(0) && - newRootChainManager != address(0) && - newEpochSize != 0, - "INVALID_INPUT" - ); - __ERC20_init("ValidatorSet", "VSET"); - stateSender = IStateSender(newStateSender); - stateReceiver = newStateReceiver; - rootChainManager = newRootChainManager; - EPOCH_SIZE = newEpochSize; - for (uint256 i = 0; i < initialValidators.length; ) { - _stake(initialValidators[i].addr, initialValidators[i].stake); - unchecked { - ++i; - } - } - epochEndBlocks.push(0); - currentEpochId = 1; - } - - /** - * @inheritdoc IValidatorSet - */ - function commitEpoch(uint256 id, Epoch calldata epoch) external onlySystemCall { - uint256 newEpochId = currentEpochId++; - require(id == newEpochId, "UNEXPECTED_EPOCH_ID"); - require(epoch.endBlock > epoch.startBlock, "NO_BLOCKS_COMMITTED"); - require((epoch.endBlock - epoch.startBlock + 1) % EPOCH_SIZE == 0, "EPOCH_MUST_BE_DIVISIBLE_BY_EPOCH_SIZE"); - require(epochs[newEpochId - 1].endBlock + 1 == epoch.startBlock, "INVALID_START_BLOCK"); - epochs[newEpochId] = epoch; - epochEndBlocks.push(epoch.endBlock); - emit NewEpoch(id, epoch.startBlock, epoch.endBlock, epoch.epochRoot); - } - - function onStateReceive(uint256 /*counter*/, address sender, bytes calldata data) external override { - require(msg.sender == stateReceiver && sender == rootChainManager, "INVALID_SENDER"); - if (bytes32(data[:32]) == STAKE_SIG) { - (address validator, uint256 amount) = abi.decode(data[32:], (address, uint256)); - _stake(validator, amount); - } - } - - /** - * @inheritdoc IValidatorSet - */ - function unstake(uint256 amount) external { - _burn(msg.sender, amount); - _registerWithdrawal(msg.sender, amount); - } - - /** - * @inheritdoc IValidatorSet - */ - function withdraw() external { - WithdrawalQueue storage queue = withdrawals[msg.sender]; - (uint256 amount, uint256 newHead) = queue.withdrawable(currentEpochId); - queue.head = newHead; - emit Withdrawal(msg.sender, amount); - stateSender.syncState(rootChainManager, abi.encode(UNSTAKE_SIG, msg.sender, amount)); - } - - /** - * @inheritdoc IValidatorSet - */ - function withdrawable(address account) external view returns (uint256 amount) { - (amount, ) = withdrawals[account].withdrawable(currentEpochId); - } - - /** - * @inheritdoc IValidatorSet - */ - function pendingWithdrawals(address account) external view returns (uint256) { - return withdrawals[account].pending(currentEpochId); - } - - /** - * @inheritdoc IValidatorSet - */ - function totalBlocks(uint256 epochId) external view returns (uint256 length) { - uint256 endBlock = epochs[epochId].endBlock; - length = endBlock == 0 ? 0 : endBlock - epochs[epochId].startBlock + 1; - } - - function _registerWithdrawal(address account, uint256 amount) internal { - withdrawals[account].append(amount, currentEpochId + WITHDRAWAL_WAIT_PERIOD); - emit WithdrawalRegistered(account, amount); - } - - /// @dev no public facing slashing function implemented yet - // slither-disable-next-line dead-code - function _slash(address validator) internal { - // unstake validator - _burn(validator, balanceOf(validator)); - // remove pending withdrawals - // slither-disable-next-line mapping-deletion - delete withdrawals[validator]; - // slash validator - stateSender.syncState(rootChainManager, abi.encode(SLASH_SIG, validator)); - } - - function _stake(address validator, uint256 amount) internal { - _mint(validator, amount); - } - - /// @dev the epoch number is also the snapshot id - function _getCurrentSnapshotId() internal view override returns (uint256) { - return currentEpochId; - } - - function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { - require(from == address(0) || to == address(0), "TRANSFER_FORBIDDEN"); - super._beforeTokenTransfer(from, to, amount); - } - - function balanceOfAt( - address account, - uint256 epochNumber - ) public view override(ERC20SnapshotUpgradeable, IValidatorSet) returns (uint256) { - return super.balanceOfAt(account, epochNumber); - } - - function totalSupplyAt( - uint256 epochNumber - ) public view override(ERC20SnapshotUpgradeable, IValidatorSet) returns (uint256) { - return super.totalSupplyAt(epochNumber); - } -} diff --git a/test/forge/root/staking/CustomSupernetManager.t.sol b/test/forge/root/staking/CustomSupernetManager.t.sol index 83797d23..1f9d1091 100644 --- a/test/forge/root/staking/CustomSupernetManager.t.sol +++ b/test/forge/root/staking/CustomSupernetManager.t.sol @@ -353,12 +353,12 @@ contract CustomSupernetManager_Unstake is EnabledStaking { event ValidatorDeactivated(address indexed validator); function test_RevertNotCalledByExitHelper() public { - vm.expectRevert(abi.encodeWithSelector(Unauthorized.selector, "exitHelper")); + vm.expectRevert(abi.encodeWithSelector(Unauthorized.selector, "_exitHelper")); supernetManager.onL2StateReceive(1, childValidatorSet, ""); } function test_RevertChildValidatorSetNotSender() public { - vm.expectRevert(abi.encodeWithSelector(Unauthorized.selector, "exitHelper")); + vm.expectRevert(abi.encodeWithSelector(Unauthorized.selector, "_exitHelper")); vm.prank(exitHelper); supernetManager.onL2StateReceive(1, alice, ""); } @@ -411,7 +411,12 @@ contract CustomSupernetManager_Slash is EnabledStaking { emit ValidatorDeactivated(address(this)); // emits state sync event to complete slashing on child chain vm.expectEmit(true, true, true, true); - emit StateSynced(exitEventId, address(supernetManager), childValidatorSet, abi.encode(SLASH_SIG, exitEventId, validatorsToSlash, slashingPercentage)); + emit StateSynced( + exitEventId, + address(supernetManager), + childValidatorSet, + abi.encode(SLASH_SIG, exitEventId, validatorsToSlash, slashingPercentage) + ); vm.store(exitHelper, callerSlotOnExitHelper, bytes32(uint256(uint160(mev)))); // simulate caller of exit() vm.prank(exitHelper); supernetManager.onL2StateReceive(exitEventId, childValidatorSet, callData); @@ -426,7 +431,6 @@ contract CustomSupernetManager_Slash is EnabledStaking { assertEq(supernetManager.getValidator(address(this)).isActive, false, "should deactivate"); } - function test_SlashIncentiveDistribution() external { uint256 exitEventId = 1; address[] memory validatorsToSlash = new address[](1); @@ -466,16 +470,8 @@ contract CustomSupernetManager_Slash is EnabledStaking { assertEq(stakeManager.stakeOf(address(this), 1), 0, "should unstake all"); assertEq(stakeManager.stakeOf(alice, 1), 0, "should unstake all"); - assertEq( - stakeManager.withdrawableStake(address(this)), - amount - thisSlashedAmount, - "should slash" - ); - assertEq( - stakeManager.withdrawableStake(alice), - aliceStakedAmount - aliceSlashedAmount, - "should slash" - ); + assertEq(stakeManager.withdrawableStake(address(this)), amount - thisSlashedAmount, "should slash"); + assertEq(stakeManager.withdrawableStake(alice), aliceStakedAmount - aliceSlashedAmount, "should slash"); assertEq(supernetManager.getValidator(address(this)).isActive, false, "should deactivate"); assertEq(supernetManager.getValidator(alice).isActive, false, "should deactivate"); uint256 exitorReward = ((thisSlashedAmount + aliceSlashedAmount) * slashIncentivePercentage) / 100; From bcd6b4132dfada22f7205c3786d48fa4ad8ad7aa Mon Sep 17 00:00:00 2001 From: gretzke Date: Fri, 1 Sep 2023 17:05:50 +0200 Subject: [PATCH 4/4] slither fixes --- .github/workflows/ci.yml | 1 - contracts/child/governance/ChildGovernor.sol | 6 +++--- contracts/child/validator/RewardPool.sol | 2 +- contracts/root/staking/StakeManager.sol | 2 +- contracts/root/staking/StakeManagerChildData.sol | 1 + contracts/root/staking/SupernetManager.sol | 1 + docs/child/governance/ChildGovernor.md | 4 ++-- lib/forge-std | 2 +- 8 files changed, 10 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 232a212f..6f75a2a8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,7 +70,6 @@ jobs: with: node-version: "18.x" cache: "npm" - - run: rm foundry.toml - uses: crytic/slither-action@v0.3.0 with: node-version: 18 diff --git a/contracts/child/governance/ChildGovernor.sol b/contracts/child/governance/ChildGovernor.sol index 6d8e7203..6f8828dc 100644 --- a/contracts/child/governance/ChildGovernor.sol +++ b/contracts/child/governance/ChildGovernor.sol @@ -16,20 +16,20 @@ contract ChildGovernor is GovernorVotesQuorumFractionUpgradeable, GovernorTimelockControlUpgradeable { - NetworkParams internal _networkParams; + NetworkParams private _networkParams; function initialize( IVotesUpgradeable token_, TimelockControllerUpgradeable timelock_, uint256 quorumNumerator_, - address networkParams_ + address networkParams ) public initializer { __Governor_init("ChildGovernor"); __GovernorTimelockControl_init(timelock_); __GovernorVotes_init(token_); __GovernorVotesQuorumFraction_init(quorumNumerator_); - _networkParams = NetworkParams(networkParams_); + _networkParams = NetworkParams(networkParams); } // TODO: adjust values for block time of child chain diff --git a/contracts/child/validator/RewardPool.sol b/contracts/child/validator/RewardPool.sol index b62a7759..72b7fa95 100644 --- a/contracts/child/validator/RewardPool.sol +++ b/contracts/child/validator/RewardPool.sol @@ -19,7 +19,7 @@ contract RewardPool is IRewardPool, System, Initializable { mapping(uint256 => uint256) public paidRewardPerEpoch; mapping(address => uint256) public pendingRewards; - NetworkParams internal _networkParams; + NetworkParams private _networkParams; function initialize( address newRewardToken, diff --git a/contracts/root/staking/StakeManager.sol b/contracts/root/staking/StakeManager.sol index f08d04e7..3df3abfc 100644 --- a/contracts/root/staking/StakeManager.sol +++ b/contracts/root/staking/StakeManager.sol @@ -11,7 +11,7 @@ import "./StakeManagerStakingData.sol"; contract StakeManager is IStakeManager, Initializable, StakeManagerChildData, StakeManagerStakingData { using SafeERC20 for IERC20; - IERC20 internal _stakingToken; + IERC20 private _stakingToken; function initialize(address newStakingToken) public initializer { _stakingToken = IERC20(newStakingToken); diff --git a/contracts/root/staking/StakeManagerChildData.sol b/contracts/root/staking/StakeManagerChildData.sol index 51062d2d..2f3d9d24 100644 --- a/contracts/root/staking/StakeManagerChildData.sol +++ b/contracts/root/staking/StakeManagerChildData.sol @@ -8,6 +8,7 @@ pragma solidity 0.8.19; */ abstract contract StakeManagerChildData { // Highest child chain id allocated thus far. Child chain id 0x00 is an invalid id. + // slither-disable-next-line naming-convention uint256 internal _counter; // child chain id to child chain manager contract address. mapping(uint256 => address) private _managers; diff --git a/contracts/root/staking/SupernetManager.sol b/contracts/root/staking/SupernetManager.sol index fc273312..052d4ac0 100644 --- a/contracts/root/staking/SupernetManager.sol +++ b/contracts/root/staking/SupernetManager.sol @@ -6,6 +6,7 @@ import "../../interfaces/root/staking/IStakeManager.sol"; import "../../interfaces/root/staking/ISupernetManager.sol"; abstract contract SupernetManager is ISupernetManager, Initializable { + // slither-disable-next-line naming-convention IStakeManager internal _stakeManager; uint256 public id; diff --git a/docs/child/governance/ChildGovernor.md b/docs/child/governance/ChildGovernor.md index 2b372958..51e2b156 100644 --- a/docs/child/governance/ChildGovernor.md +++ b/docs/child/governance/ChildGovernor.md @@ -472,7 +472,7 @@ function hashProposal(address[] targets, uint256[] values, bytes[] calldatas, by ### initialize ```solidity -function initialize(contract IVotesUpgradeable token_, contract TimelockControllerUpgradeable timelock_, uint256 quorumNumerator_, address networkParams_) external nonpayable +function initialize(contract IVotesUpgradeable token_, contract TimelockControllerUpgradeable timelock_, uint256 quorumNumerator_, address networkParams) external nonpayable ``` @@ -486,7 +486,7 @@ function initialize(contract IVotesUpgradeable token_, contract TimelockControll | token_ | contract IVotesUpgradeable | undefined | | timelock_ | contract TimelockControllerUpgradeable | undefined | | quorumNumerator_ | uint256 | undefined | -| networkParams_ | address | undefined | +| networkParams | address | undefined | ### name diff --git a/lib/forge-std b/lib/forge-std index 1cefc0e4..aea0b268 160000 --- a/lib/forge-std +++ b/lib/forge-std @@ -1 +1 @@ -Subproject commit 1cefc0e4e3d2a1f604c654004c90bd6701b2b5e2 +Subproject commit aea0b2685bebc883c09f5554d7fb481e85d0564d