Commit 20380ee6 by github-actions

Transpile 3ab0e5e5

parent e48b7beb
...@@ -8,8 +8,8 @@ jobs: ...@@ -8,8 +8,8 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
- uses: actions/setup-node@v2 - uses: actions/setup-node@v3
with: with:
node-version: 12.x node-version: 12.x
- uses: actions/cache@v2 - uses: actions/cache@v2
......
...@@ -12,8 +12,8 @@ jobs: ...@@ -12,8 +12,8 @@ jobs:
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
- uses: actions/setup-node@v2 - uses: actions/setup-node@v3
with: with:
node-version: 12.x node-version: 12.x
- uses: actions/cache@v2 - uses: actions/cache@v2
......
...@@ -6,6 +6,14 @@ ...@@ -6,6 +6,14 @@
* `EnumerableMap`: add new `AddressToUintMap` map type. ([#3150](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3150)) * `EnumerableMap`: add new `AddressToUintMap` map type. ([#3150](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3150))
* `ERC1155`: Add a `_afterTokenTransfer` hook for improved extensibility. ([#3166](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3166)) * `ERC1155`: Add a `_afterTokenTransfer` hook for improved extensibility. ([#3166](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3166))
* `DoubleEndedQueue`: a new data structure that supports efficient push and pop to both front and back, useful for FIFO and LIFO queues. ([#3153](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3153)) * `DoubleEndedQueue`: a new data structure that supports efficient push and pop to both front and back, useful for FIFO and LIFO queues. ([#3153](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3153))
* `Governor`: improved security of `onlyGovernance` modifier when using an external executor contract (e.g. a timelock) that can operate without necessarily going through the governance protocol. ([#3147](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3147))
* `Governor`: Add a way to parameterize votes. This can be used to implement voting systems such as fractionalized voting, ERC721 based voting, or any number of other systems. The `params` argument added to `_countVote` method, and included in the newly added `_getVotes` method, can be used by counting and voting modules respectively for such purposes.
### Breaking changes
* `Governor`: Adds internal virtual `_getVotes` method that must be implemented; this is a breaking change for existing concrete extensions to `Governor`. To fix this on an existing voting module extension, rename `getVotes` to `_getVotes` and add a `bytes memory` argument. ([#3043](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3043))
* `Governor`: Adds `params` parameter to internal virtual `_countVote ` method; this is a breaking change for existing concrete extensions to `Governor`. To fix this on an existing counting module extension, add a `bytes memory` argument to `_countVote`. ([#3043](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3043))
* `Governor`: Does not emit `VoteCast` event when params data is non-empty; instead emits `VoteCastWithParams` event. To fix this on an integration that consumes the `VoteCast` event, also fetch/monitor `VoteCastWithParams` events. ([#3043](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3043))
## 4.5.0 (2022-02-09) ## 4.5.0 (2022-02-09)
......
...@@ -27,6 +27,10 @@ It follows all of the rules for [Writing Upgradeable Contracts]: constructors ar ...@@ -27,6 +27,10 @@ It follows all of the rules for [Writing Upgradeable Contracts]: constructors ar
$ npm install @openzeppelin/contracts-upgradeable $ npm install @openzeppelin/contracts-upgradeable
``` ```
OpenZeppelin Contracts features a [stable API](https://docs.openzeppelin.com/contracts/releases-stability#api-stability), which means your contracts won't break unexpectedly when upgrading to a newer minor version.
An alternative to npm is to use the GitHub repository `openzeppelin/openzeppelin-contracts` to retrieve the contracts. When doing this, make sure to specify the tag for a release such as `v4.5.0`, instead of using the `master` branch.
### Usage ### Usage
The package replicates the structure of the main OpenZeppelin Contracts package, but every file and contract has the suffix `Upgradeable`. The package replicates the structure of the main OpenZeppelin Contracts package, but every file and contract has the suffix `Upgradeable`.
......
...@@ -54,13 +54,28 @@ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable { ...@@ -54,13 +54,28 @@ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable {
event ProposalExecuted(uint256 proposalId); event ProposalExecuted(uint256 proposalId);
/** /**
* @dev Emitted when a vote is cast. * @dev Emitted when a vote is cast without params.
* *
* Note: `support` values should be seen as buckets. There interpretation depends on the voting module used. * Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used.
*/ */
event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason); event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason);
/** /**
* @dev Emitted when a vote is cast with params.
*
* Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used.
* `params` are additional encoded parameters. Their intepepretation also depends on the voting module used.
*/
event VoteCastWithParams(
address indexed voter,
uint256 proposalId,
uint8 support,
uint256 weight,
string reason,
bytes params
);
/**
* @notice module:core * @notice module:core
* @dev Name of the governor instance (used in building the ERC712 domain separator). * @dev Name of the governor instance (used in building the ERC712 domain separator).
*/ */
...@@ -84,6 +99,12 @@ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable { ...@@ -84,6 +99,12 @@ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable {
* - `quorum=bravo` means that only For votes are counted towards quorum. * - `quorum=bravo` means that only For votes are counted towards quorum.
* - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
* *
* If a counting module makes use of encoded `params`, it should include this under a `params` key with a unique
* name that describes the behavior. For example:
*
* - `params=fractional` might refer to a scheme where votes are divided fractionally between for/against/abstain.
* - `params=erc721` might refer to a scheme where specific NFTs are delegated to vote.
*
* NOTE: The string can be decoded by the standard * NOTE: The string can be decoded by the standard
* https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`]
* JavaScript class. * JavaScript class.
...@@ -158,6 +179,16 @@ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable { ...@@ -158,6 +179,16 @@ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable {
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256); function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256);
/** /**
* @notice module:reputation
* @dev Voting power of an `account` at a specific `blockNumber` given additional encoded parameters.
*/
function getVotesWithParams(
address account,
uint256 blockNumber,
bytes memory params
) public view virtual returns (uint256);
/**
* @notice module:voting * @notice module:voting
* @dev Returns weither `account` has cast a vote on `proposalId`. * @dev Returns weither `account` has cast a vote on `proposalId`.
*/ */
...@@ -210,7 +241,19 @@ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable { ...@@ -210,7 +241,19 @@ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable {
) public virtual returns (uint256 balance); ) public virtual returns (uint256 balance);
/** /**
* @dev Cast a vote using the user cryptographic signature. * @dev Cast a vote with a reason and additional encoded parameters
*
* Emits a {VoteCast} event.
*/
function castVoteWithReasonAndParams(
uint256 proposalId,
uint8 support,
string calldata reason,
bytes memory params
) public virtual returns (uint256 balance);
/**
* @dev Cast a vote using the user's cryptographic signature.
* *
* Emits a {VoteCast} event. * Emits a {VoteCast} event.
*/ */
...@@ -223,6 +266,21 @@ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable { ...@@ -223,6 +266,21 @@ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable {
) public virtual returns (uint256 balance); ) public virtual returns (uint256 balance);
/** /**
* @dev Cast a vote with a reason and additional encoded parameters using the user's cryptographic signature.
*
* Emits a {VoteCast} event.
*/
function castVoteWithReasonAndParamsBySig(
uint256 proposalId,
uint8 support,
string calldata reason,
bytes memory params,
uint8 v,
bytes32 r,
bytes32 s
) public virtual returns (uint256 balance);
/**
* @dev This empty reserved space is put in place to allow future versions to add new * @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. * variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
......
...@@ -271,7 +271,8 @@ abstract contract GovernorCompatibilityBravoUpgradeable is Initializable, IGover ...@@ -271,7 +271,8 @@ abstract contract GovernorCompatibilityBravoUpgradeable is Initializable, IGover
uint256 proposalId, uint256 proposalId,
address account, address account,
uint8 support, uint8 support,
uint256 weight uint256 weight,
bytes memory // params
) internal virtual override { ) internal virtual override {
ProposalDetails storage details = _proposalDetails[proposalId]; ProposalDetails storage details = _proposalDetails[proposalId];
Receipt storage receipt = details.receipts[account]; Receipt storage receipt = details.receipts[account];
......
...@@ -92,7 +92,8 @@ abstract contract GovernorCountingSimpleUpgradeable is Initializable, GovernorUp ...@@ -92,7 +92,8 @@ abstract contract GovernorCountingSimpleUpgradeable is Initializable, GovernorUp
uint256 proposalId, uint256 proposalId,
address account, address account,
uint8 support, uint8 support,
uint256 weight uint256 weight,
bytes memory // params
) internal virtual override { ) internal virtual override {
ProposalVote storage proposalvote = _proposalVotes[proposalId]; ProposalVote storage proposalvote = _proposalVotes[proposalId];
......
...@@ -62,9 +62,10 @@ abstract contract GovernorPreventLateQuorumUpgradeable is Initializable, Governo ...@@ -62,9 +62,10 @@ abstract contract GovernorPreventLateQuorumUpgradeable is Initializable, Governo
uint256 proposalId, uint256 proposalId,
address account, address account,
uint8 support, uint8 support,
string memory reason string memory reason,
bytes memory params
) internal virtual override returns (uint256) { ) internal virtual override returns (uint256) {
uint256 result = super._castVote(proposalId, account, support, reason); uint256 result = super._castVote(proposalId, account, support, reason, params);
TimersUpgradeable.BlockNumber storage extendedDeadline = _extendedDeadlines[proposalId]; TimersUpgradeable.BlockNumber storage extendedDeadline = _extendedDeadlines[proposalId];
......
...@@ -24,9 +24,13 @@ abstract contract GovernorVotesCompUpgradeable is Initializable, GovernorUpgrade ...@@ -24,9 +24,13 @@ abstract contract GovernorVotesCompUpgradeable is Initializable, GovernorUpgrade
} }
/** /**
* Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}). * Read the voting weight from the token's built in snapshot mechanism (see {Governor-_getVotes}).
*/ */
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { function _getVotes(
address account,
uint256 blockNumber,
bytes memory /*params*/
) internal view virtual override returns (uint256) {
return token.getPriorVotes(account, blockNumber); return token.getPriorVotes(account, blockNumber);
} }
......
...@@ -24,9 +24,13 @@ abstract contract GovernorVotesUpgradeable is Initializable, GovernorUpgradeable ...@@ -24,9 +24,13 @@ abstract contract GovernorVotesUpgradeable is Initializable, GovernorUpgradeable
} }
/** /**
* Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}). * Read the voting weight from the token's built in snapshot mechanism (see {Governor-_getVotes}).
*/ */
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { function _getVotes(
address account,
uint256 blockNumber,
bytes memory /*params*/
) internal view virtual override returns (uint256) {
return token.getPastVotes(account, blockNumber); return token.getPastVotes(account, blockNumber);
} }
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
pragma solidity ^0.8.0; pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol"; import "../utils/introspection/IERC165Upgradeable.sol";
/** /**
* @dev Interface for the NFT Royalty Standard. * @dev Interface for the NFT Royalty Standard.
......
...@@ -36,16 +36,6 @@ contract GovernorCompMockUpgradeable is Initializable, GovernorVotesCompUpgradea ...@@ -36,16 +36,6 @@ contract GovernorCompMockUpgradeable is Initializable, GovernorVotesCompUpgradea
return _cancel(targets, values, calldatas, salt); return _cancel(targets, values, calldatas, salt);
} }
function getVotes(address account, uint256 blockNumber)
public
view
virtual
override(IGovernorUpgradeable, GovernorVotesCompUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
/** /**
* @dev This empty reserved space is put in place to allow future versions to add new * @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. * variables without shifting down storage in the inheritance chain.
......
...@@ -135,16 +135,6 @@ contract GovernorCompatibilityBravoMockUpgradeable is ...@@ -135,16 +135,6 @@ contract GovernorCompatibilityBravoMockUpgradeable is
return super._cancel(targets, values, calldatas, salt); return super._cancel(targets, values, calldatas, salt);
} }
function getVotes(address account, uint256 blockNumber)
public
view
virtual
override(IGovernorUpgradeable, GovernorVotesCompUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function _executor() internal view virtual override(GovernorUpgradeable, GovernorTimelockCompoundUpgradeable) returns (address) { function _executor() internal view virtual override(GovernorUpgradeable, GovernorTimelockCompoundUpgradeable) returns (address) {
return super._executor(); return super._executor();
} }
......
...@@ -45,16 +45,6 @@ contract GovernorMockUpgradeable is ...@@ -45,16 +45,6 @@ contract GovernorMockUpgradeable is
return _cancel(targets, values, calldatas, salt); return _cancel(targets, values, calldatas, salt);
} }
function getVotes(address account, uint256 blockNumber)
public
view
virtual
override(IGovernorUpgradeable, GovernorVotesUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function proposalThreshold() public view override(GovernorUpgradeable, GovernorSettingsUpgradeable) returns (uint256) { function proposalThreshold() public view override(GovernorUpgradeable, GovernorSettingsUpgradeable) returns (uint256) {
return super.proposalThreshold(); return super.proposalThreshold();
} }
......
...@@ -65,9 +65,10 @@ contract GovernorPreventLateQuorumMockUpgradeable is ...@@ -65,9 +65,10 @@ contract GovernorPreventLateQuorumMockUpgradeable is
uint256 proposalId, uint256 proposalId,
address account, address account,
uint8 support, uint8 support,
string memory reason string memory reason,
bytes memory params
) internal virtual override(GovernorUpgradeable, GovernorPreventLateQuorumUpgradeable) returns (uint256) { ) internal virtual override(GovernorUpgradeable, GovernorPreventLateQuorumUpgradeable) returns (uint256) {
return super._castVote(proposalId, account, support, reason); return super._castVote(proposalId, account, support, reason, params);
} }
/** /**
......
...@@ -103,16 +103,6 @@ contract GovernorTimelockCompoundMockUpgradeable is ...@@ -103,16 +103,6 @@ contract GovernorTimelockCompoundMockUpgradeable is
return super._cancel(targets, values, calldatas, salt); return super._cancel(targets, values, calldatas, salt);
} }
function getVotes(address account, uint256 blockNumber)
public
view
virtual
override(IGovernorUpgradeable, GovernorVotesUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function _executor() internal view virtual override(GovernorUpgradeable, GovernorTimelockCompoundUpgradeable) returns (address) { function _executor() internal view virtual override(GovernorUpgradeable, GovernorTimelockCompoundUpgradeable) returns (address) {
return super._executor(); return super._executor();
} }
......
...@@ -103,20 +103,12 @@ contract GovernorTimelockControlMockUpgradeable is ...@@ -103,20 +103,12 @@ contract GovernorTimelockControlMockUpgradeable is
return super._cancel(targets, values, calldatas, descriptionHash); return super._cancel(targets, values, calldatas, descriptionHash);
} }
function getVotes(address account, uint256 blockNumber)
public
view
virtual
override(IGovernorUpgradeable, GovernorVotesUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function _executor() internal view virtual override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (address) { function _executor() internal view virtual override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (address) {
return super._executor(); return super._executor();
} }
function nonGovernanceFunction() external {}
/** /**
* @dev This empty reserved space is put in place to allow future versions to add new * @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. * variables without shifting down storage in the inheritance chain.
......
...@@ -36,16 +36,6 @@ contract GovernorVoteMocksUpgradeable is Initializable, GovernorVotesUpgradeable ...@@ -36,16 +36,6 @@ contract GovernorVoteMocksUpgradeable is Initializable, GovernorVotesUpgradeable
return _cancel(targets, values, calldatas, salt); return _cancel(targets, values, calldatas, salt);
} }
function getVotes(address account, uint256 blockNumber)
public
view
virtual
override(IGovernorUpgradeable, GovernorVotesUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
/** /**
* @dev This empty reserved space is put in place to allow future versions to add new * @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. * variables without shifting down storage in the inheritance chain.
......
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../governance/extensions/GovernorCountingSimpleUpgradeable.sol";
import "../governance/extensions/GovernorVotesUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract GovernorWithParamsMockUpgradeable is Initializable, GovernorVotesUpgradeable, GovernorCountingSimpleUpgradeable {
event CountParams(uint256 uintParam, string strParam);
function __GovernorWithParamsMock_init(string memory name_, IVotesUpgradeable token_) internal onlyInitializing {
__EIP712_init_unchained(name_, version());
__Governor_init_unchained(name_);
__GovernorVotes_init_unchained(token_);
}
function __GovernorWithParamsMock_init_unchained(string memory, IVotesUpgradeable) internal onlyInitializing {}
function quorum(uint256) public pure override returns (uint256) {
return 0;
}
function votingDelay() public pure override returns (uint256) {
return 4;
}
function votingPeriod() public pure override returns (uint256) {
return 16;
}
function _getVotes(
address account,
uint256 blockNumber,
bytes memory params
) internal view virtual override(GovernorUpgradeable, GovernorVotesUpgradeable) returns (uint256) {
uint256 reduction = 0;
// If the user provides parameters, we reduce the voting weight by the amount of the integer param
if (params.length > 0) {
(reduction, ) = abi.decode(params, (uint256, string));
}
// reverts on overflow
return super._getVotes(account, blockNumber, params) - reduction;
}
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight,
bytes memory params
) internal virtual override(GovernorUpgradeable, GovernorCountingSimpleUpgradeable) {
if (params.length > 0) {
(uint256 _uintParam, string memory _strParam) = abi.decode(params, (uint256, string));
emit CountParams(_uintParam, _strParam);
}
return super._countVote(proposalId, account, support, weight, params);
}
function cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 salt
) public returns (uint256 proposalId) {
return _cancel(targets, values, calldatas, salt);
}
/**
* @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;
}
...@@ -40,6 +40,13 @@ contract MyGovernor1UpgradeableWithInit is MyGovernor1Upgradeable { ...@@ -40,6 +40,13 @@ contract MyGovernor1UpgradeableWithInit is MyGovernor1Upgradeable {
__MyGovernor1_init(_token, _timelock); __MyGovernor1_init(_token, _timelock);
} }
} }
import "./GovernorWithParamsMockUpgradeable.sol";
contract GovernorWithParamsMockUpgradeableWithInit is GovernorWithParamsMockUpgradeable {
constructor(string memory name_, IVotesUpgradeable token_) payable initializer {
__GovernorWithParamsMock_init(name_, token_);
}
}
import "./GovernorVoteMockUpgradeable.sol"; import "./GovernorVoteMockUpgradeable.sol";
contract GovernorVoteMocksUpgradeableWithInit is GovernorVoteMocksUpgradeable { contract GovernorVoteMocksUpgradeableWithInit is GovernorVoteMocksUpgradeable {
......
...@@ -44,15 +44,6 @@ contract MyGovernor1Upgradeable is ...@@ -44,15 +44,6 @@ contract MyGovernor1Upgradeable is
return super.quorum(blockNumber); return super.quorum(blockNumber);
} }
function getVotes(address account, uint256 blockNumber)
public
view
override(IGovernorUpgradeable, GovernorVotesUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function state(uint256 proposalId) public view override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (ProposalState) { function state(uint256 proposalId) public view override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (ProposalState) {
return super.state(proposalId); return super.state(proposalId);
} }
......
...@@ -50,15 +50,6 @@ contract MyGovernor2Upgradeable is ...@@ -50,15 +50,6 @@ contract MyGovernor2Upgradeable is
return super.quorum(blockNumber); return super.quorum(blockNumber);
} }
function getVotes(address account, uint256 blockNumber)
public
view
override(IGovernorUpgradeable, GovernorVotesUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function state(uint256 proposalId) public view override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (ProposalState) { function state(uint256 proposalId) public view override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (ProposalState) {
return super.state(proposalId); return super.state(proposalId);
} }
......
...@@ -48,15 +48,6 @@ contract MyGovernorUpgradeable is ...@@ -48,15 +48,6 @@ contract MyGovernorUpgradeable is
return super.quorum(blockNumber); return super.quorum(blockNumber);
} }
function getVotes(address account, uint256 blockNumber)
public
view
override(IGovernorUpgradeable, GovernorVotesUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function state(uint256 proposalId) function state(uint256 proposalId)
public public
view view
......
...@@ -186,9 +186,9 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -186,9 +186,9 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
emit TransferSingle(operator, from, to, id, amount); emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
_afterTokenTransfer(operator, from, to, ids, amounts, data); _afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
} }
/** /**
...@@ -229,9 +229,9 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -229,9 +229,9 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
emit TransferBatch(operator, from, to, ids, amounts); emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
_afterTokenTransfer(operator, from, to, ids, amounts, data); _afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
} }
/** /**
...@@ -285,9 +285,9 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -285,9 +285,9 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
_balances[id][to] += amount; _balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount); emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data); _afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
} }
/** /**
...@@ -318,9 +318,9 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -318,9 +318,9 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
emit TransferBatch(operator, address(0), to, ids, amounts); emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data); _afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
} }
/** /**
......
...@@ -185,7 +185,7 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl ...@@ -185,7 +185,7 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl
*/ */
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender(); address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue); _approve(owner, spender, allowance(owner, spender) + addedValue);
return true; return true;
} }
...@@ -205,7 +205,7 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl ...@@ -205,7 +205,7 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl
*/ */
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender(); address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender]; uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked { unchecked {
_approve(owner, spender, currentAllowance - subtractedValue); _approve(owner, spender, currentAllowance - subtractedValue);
......
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
pragma solidity ^0.8.0; pragma solidity ^0.8.0;
import "../../../interfaces/IERC3156Upgradeable.sol"; import "../../../interfaces/IERC3156FlashBorrowerUpgradeable.sol";
import "../../../interfaces/IERC3156FlashLenderUpgradeable.sol";
import "../ERC20Upgradeable.sol"; import "../ERC20Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol"; import "../../../proxy/utils/Initializable.sol";
...@@ -27,7 +28,7 @@ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, ...@@ -27,7 +28,7 @@ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable,
/** /**
* @dev Returns the maximum amount of tokens available for loan. * @dev Returns the maximum amount of tokens available for loan.
* @param token The address of the token that is requested. * @param token The address of the token that is requested.
* @return The amont of token that can be loaned. * @return The amount of token that can be loaned.
*/ */
function maxFlashLoan(address token) public view virtual override returns (uint256) { function maxFlashLoan(address token) public view virtual override returns (uint256) {
return token == address(this) ? type(uint256).max - ERC20Upgradeable.totalSupply() : 0; return token == address(this) ? type(uint256).max - ERC20Upgradeable.totalSupply() : 0;
...@@ -60,7 +61,7 @@ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, ...@@ -60,7 +61,7 @@ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable,
* supported. * supported.
* @param amount The amount of tokens to be loaned. * @param amount The amount of tokens to be loaned.
* @param data An arbitrary datafield that is passed to the receiver. * @param data An arbitrary datafield that is passed to the receiver.
* @return `true` is the flash loan was successful. * @return `true` if the flash loan was successful.
*/ */
// This function can reenter, but it doesn't pose a risk because it always preserves the property that the amount // This function can reenter, but it doesn't pose a risk because it always preserves the property that the amount
// minted at the beginning is always recovered and burned at the end, or else the entire function will revert. // minted at the beginning is always recovered and burned at the end, or else the entire function will revert.
......
...@@ -23,7 +23,7 @@ import "../../../proxy/utils/Initializable.sol"; ...@@ -23,7 +23,7 @@ import "../../../proxy/utils/Initializable.sol";
* and the account address. * and the account address.
* *
* NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it * 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 begining of each new block. When overridding this * 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. * 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 * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient
......
...@@ -46,7 +46,7 @@ abstract contract ERC20WrapperUpgradeable is Initializable, ERC20Upgradeable { ...@@ -46,7 +46,7 @@ abstract contract ERC20WrapperUpgradeable is Initializable, ERC20Upgradeable {
} }
/** /**
* @dev Mint wrapped token to cover any underlyingTokens that would have been transfered by mistake. Internal * @dev Mint wrapped token to cover any underlyingTokens that would have been transferred by mistake. Internal
* function that can be exposed with access control if desired. * function that can be exposed with access control if desired.
*/ */
function _recover(address account) internal virtual returns (uint256) { function _recover(address account) internal virtual returns (uint256) {
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -41,6 +41,7 @@ contract('Governor', function (accounts) { ...@@ -41,6 +41,7 @@ contract('Governor', function (accounts) {
shouldSupportInterfaces([ shouldSupportInterfaces([
'ERC165', 'ERC165',
'Governor', 'Governor',
'GovernorWithParams',
]); ]);
it('deployment check', async function () { it('deployment check', async function () {
......
...@@ -48,6 +48,7 @@ contract('GovernorTimelockCompound', function (accounts) { ...@@ -48,6 +48,7 @@ contract('GovernorTimelockCompound', function (accounts) {
shouldSupportInterfaces([ shouldSupportInterfaces([
'ERC165', 'ERC165',
'Governor', 'Governor',
'GovernorWithParams',
'GovernorTimelock', 'GovernorTimelock',
]); ]);
......
const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); const { constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai'); const { expect } = require('chai');
const Enums = require('../../helpers/enums'); const Enums = require('../../helpers/enums');
...@@ -31,7 +31,7 @@ contract('GovernorTimelockControl', function (accounts) { ...@@ -31,7 +31,7 @@ contract('GovernorTimelockControl', function (accounts) {
this.timelock = await Timelock.new(3600, [], []); this.timelock = await Timelock.new(3600, [], []);
this.mock = await Governor.new(name, this.token.address, 4, 16, this.timelock.address, 0); this.mock = await Governor.new(name, this.token.address, 4, 16, this.timelock.address, 0);
this.receiver = await CallReceiver.new(); this.receiver = await CallReceiver.new();
// normal setup: governor is proposer, everyone is executor, timelock is its own admin // normal setup: governor and admin are proposers, everyone is executor, timelock is its own admin
await this.timelock.grantRole(await this.timelock.PROPOSER_ROLE(), this.mock.address); await this.timelock.grantRole(await this.timelock.PROPOSER_ROLE(), this.mock.address);
await this.timelock.grantRole(await this.timelock.PROPOSER_ROLE(), admin); await this.timelock.grantRole(await this.timelock.PROPOSER_ROLE(), admin);
await this.timelock.grantRole(await this.timelock.EXECUTOR_ROLE(), constants.ZERO_ADDRESS); await this.timelock.grantRole(await this.timelock.EXECUTOR_ROLE(), constants.ZERO_ADDRESS);
...@@ -43,6 +43,7 @@ contract('GovernorTimelockControl', function (accounts) { ...@@ -43,6 +43,7 @@ contract('GovernorTimelockControl', function (accounts) {
shouldSupportInterfaces([ shouldSupportInterfaces([
'ERC165', 'ERC165',
'Governor', 'Governor',
'GovernorWithParams',
'GovernorTimelock', 'GovernorTimelock',
]); ]);
...@@ -338,6 +339,32 @@ contract('GovernorTimelockControl', function (accounts) { ...@@ -338,6 +339,32 @@ contract('GovernorTimelockControl', function (accounts) {
); );
}); });
it('protected against other proposers', async function () {
await this.timelock.schedule(
this.mock.address,
web3.utils.toWei('0'),
this.mock.contract.methods.relay(...this.call).encodeABI(),
constants.ZERO_BYTES32,
constants.ZERO_BYTES32,
3600,
{ from: admin },
);
await time.increase(3600);
await expectRevert(
this.timelock.execute(
this.mock.address,
web3.utils.toWei('0'),
this.mock.contract.methods.relay(...this.call).encodeABI(),
constants.ZERO_BYTES32,
constants.ZERO_BYTES32,
{ from: admin },
),
'TimelockController: underlying transaction reverted',
);
});
describe('using workflow', function () { describe('using workflow', function () {
beforeEach(async function () { beforeEach(async function () {
this.settings = { this.settings = {
...@@ -461,4 +488,33 @@ contract('GovernorTimelockControl', function (accounts) { ...@@ -461,4 +488,33 @@ contract('GovernorTimelockControl', function (accounts) {
runGovernorWorkflow(); runGovernorWorkflow();
}); });
}); });
describe('clear queue of pending governor calls', function () {
beforeEach(async function () {
this.settings = {
proposal: [
[ this.mock.address ],
[ web3.utils.toWei('0') ],
[ this.mock.contract.methods.nonGovernanceFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 3600 },
},
};
});
afterEach(async function () {
expectEvent(
this.receipts.execute,
'ProposalExecuted',
{ proposalId: this.id },
);
});
runGovernorWorkflow();
});
}); });
const { BN, constants, expectEvent } = require('@openzeppelin/test-helpers');
const { web3 } = require('@openzeppelin/test-helpers/src/setup');
const Enums = require('../../helpers/enums');
const ethSigUtil = require('eth-sig-util');
const Wallet = require('ethereumjs-wallet').default;
const { EIP712Domain } = require('../../helpers/eip712');
const { fromRpcSig } = require('ethereumjs-util');
const { runGovernorWorkflow } = require('../GovernorWorkflow.behavior');
const { expect } = require('chai');
const Token = artifacts.require('ERC20VotesCompMock');
const Governor = artifacts.require('GovernorWithParamsMock');
const CallReceiver = artifacts.require('CallReceiverMock');
contract('GovernorWithParams', function (accounts) {
const [owner, proposer, voter1, voter2, voter3, voter4] = accounts;
const name = 'OZ-Governor';
const version = '1';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100');
const votingDelay = new BN(4);
const votingPeriod = new BN(16);
beforeEach(async function () {
this.owner = owner;
this.token = await Token.new(tokenName, tokenSymbol);
this.mock = await Governor.new(name, this.token.address);
this.receiver = await CallReceiver.new();
await this.token.mint(owner, tokenSupply);
await this.token.delegate(voter1, { from: voter1 });
await this.token.delegate(voter2, { from: voter2 });
await this.token.delegate(voter3, { from: voter3 });
await this.token.delegate(voter4, { from: voter4 });
});
it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
});
describe('nominal is unaffected', function () {
beforeEach(async function () {
this.settings = {
proposal: [
[this.receiver.address],
[0],
[this.receiver.contract.methods.mockFunction().encodeABI()],
'<proposal description>',
],
proposer,
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('1'), support: Enums.VoteType.For, reason: 'This is nice' },
{ voter: voter2, weight: web3.utils.toWei('7'), support: Enums.VoteType.For },
{ voter: voter3, weight: web3.utils.toWei('5'), support: Enums.VoteType.Against },
{ voter: voter4, weight: web3.utils.toWei('2'), support: Enums.VoteType.Abstain },
],
};
});
afterEach(async function () {
expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.id, voter1)).to.be.equal(true);
expect(await this.mock.hasVoted(this.id, voter2)).to.be.equal(true);
await this.mock.proposalVotes(this.id).then((result) => {
for (const [key, value] of Object.entries(Enums.VoteType)) {
expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal(
Object.values(this.settings.voters)
.filter(({ support }) => support === value)
.reduce((acc, { weight }) => acc.add(new BN(weight)), new BN('0')),
);
}
});
const startBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay);
const endBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay).add(votingPeriod);
expect(await this.mock.proposalSnapshot(this.id)).to.be.bignumber.equal(startBlock);
expect(await this.mock.proposalDeadline(this.id)).to.be.bignumber.equal(endBlock);
expectEvent(this.receipts.propose, 'ProposalCreated', {
proposalId: this.id,
proposer,
targets: this.settings.proposal[0],
// values: this.settings.proposal[1].map(value => new BN(value)),
signatures: this.settings.proposal[2].map(() => ''),
calldatas: this.settings.proposal[2],
startBlock,
endBlock,
description: this.settings.proposal[3],
});
this.receipts.castVote.filter(Boolean).forEach((vote) => {
const { voter } = vote.logs.filter(({ event }) => event === 'VoteCast').find(Boolean).args;
expectEvent(
vote,
'VoteCast',
this.settings.voters.find(({ address }) => address === voter),
);
});
expectEvent(this.receipts.execute, 'ProposalExecuted', { proposalId: this.id });
await expectEvent.inTransaction(this.receipts.execute.transactionHash, this.receiver, 'MockFunctionCalled');
});
runGovernorWorkflow();
});
describe('Voting with params is properly supported', function () {
const voter2Weight = web3.utils.toWei('1.0');
beforeEach(async function () {
this.settings = {
proposal: [
[this.receiver.address],
[0],
[this.receiver.contract.methods.mockFunction().encodeABI()],
'<proposal description>',
],
proposer,
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('0.2'), support: Enums.VoteType.Against },
{ voter: voter2, weight: voter2Weight }, // do not actually vote, only getting tokenss
],
steps: {
wait: { enable: false },
execute: { enable: false },
},
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
const uintParam = new BN(1);
const strParam = 'These are my params';
const reducedWeight = new BN(voter2Weight).sub(uintParam);
const params = web3.eth.abi.encodeParameters(['uint256', 'string'], [uintParam, strParam]);
const tx = await this.mock.castVoteWithReasonAndParams(this.id, Enums.VoteType.For, '', params, { from: voter2 });
expectEvent(tx, 'CountParams', { uintParam, strParam });
expectEvent(tx, 'VoteCastWithParams', { voter: voter2, weight: reducedWeight, params });
const votes = await this.mock.proposalVotes(this.id);
expect(votes.forVotes).to.be.bignumber.equal(reducedWeight);
});
runGovernorWorkflow();
});
describe('Voting with params by signature is properly supported', function () {
const voterBySig = Wallet.generate(); // generate voter by signature wallet
const sigVoterWeight = web3.utils.toWei('1.0');
beforeEach(async function () {
this.chainId = await web3.eth.getChainId();
this.voter = web3.utils.toChecksumAddress(voterBySig.getAddressString());
// use delegateBySig to enable vote delegation sig voting wallet
const { v, r, s } = fromRpcSig(
ethSigUtil.signTypedMessage(voterBySig.getPrivateKey(), {
data: {
types: {
EIP712Domain,
Delegation: [
{ name: 'delegatee', type: 'address' },
{ name: 'nonce', type: 'uint256' },
{ name: 'expiry', type: 'uint256' },
],
},
domain: { name: tokenName, version: '1', chainId: this.chainId, verifyingContract: this.token.address },
primaryType: 'Delegation',
message: { delegatee: this.voter, nonce: 0, expiry: constants.MAX_UINT256 },
},
}),
);
await this.token.delegateBySig(this.voter, 0, constants.MAX_UINT256, v, r, s);
this.settings = {
proposal: [
[this.receiver.address],
[0],
[this.receiver.contract.methods.mockFunction().encodeABI()],
'<proposal description>',
],
proposer,
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('0.2'), support: Enums.VoteType.Against },
{ voter: this.voter, weight: sigVoterWeight }, // do not actually vote, only getting tokens
],
steps: {
wait: { enable: false },
execute: { enable: false },
},
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
const reason = 'This is my reason';
const uintParam = new BN(1);
const strParam = 'These are my params';
const reducedWeight = new BN(sigVoterWeight).sub(uintParam);
const params = web3.eth.abi.encodeParameters(['uint256', 'string'], [uintParam, strParam]);
// prepare signature for vote by signature
const { v, r, s } = fromRpcSig(
ethSigUtil.signTypedMessage(voterBySig.getPrivateKey(), {
data: {
types: {
EIP712Domain,
ExtendedBallot: [
{ name: 'proposalId', type: 'uint256' },
{ name: 'support', type: 'uint8' },
{ name: 'reason', type: 'string' },
{ name: 'params', type: 'bytes' },
],
},
domain: { name, version, chainId: this.chainId, verifyingContract: this.mock.address },
primaryType: 'ExtendedBallot',
message: { proposalId: this.id, support: Enums.VoteType.For, reason, params },
},
}),
);
const tx = await this.mock.castVoteWithReasonAndParamsBySig(this.id, Enums.VoteType.For, reason, params, v, r, s);
expectEvent(tx, 'CountParams', { uintParam, strParam });
expectEvent(tx, 'VoteCastWithParams', { voter: this.voter, weight: reducedWeight, params });
const votes = await this.mock.proposalVotes(this.id);
expect(votes.forVotes).to.be.bignumber.equal(reducedWeight);
});
runGovernorWorkflow();
});
});
...@@ -69,6 +69,28 @@ const INTERFACES = { ...@@ -69,6 +69,28 @@ const INTERFACES = {
'castVoteWithReason(uint256,uint8,string)', 'castVoteWithReason(uint256,uint8,string)',
'castVoteBySig(uint256,uint8,uint8,bytes32,bytes32)', 'castVoteBySig(uint256,uint8,uint8,bytes32,bytes32)',
], ],
GovernorWithParams: [
'name()',
'version()',
'COUNTING_MODE()',
'hashProposal(address[],uint256[],bytes[],bytes32)',
'state(uint256)',
'proposalSnapshot(uint256)',
'proposalDeadline(uint256)',
'votingDelay()',
'votingPeriod()',
'quorum(uint256)',
'getVotes(address,uint256)',
'getVotesWithParams(address,uint256,bytes)',
'hasVoted(uint256,address)',
'propose(address[],uint256[],bytes[],string)',
'execute(address[],uint256[],bytes[],bytes32)',
'castVote(uint256,uint8)',
'castVoteWithReason(uint256,uint8,string)',
'castVoteWithReasonAndParams(uint256,uint8,string,bytes)',
'castVoteBySig(uint256,uint8,uint8,bytes32,bytes32)',
'castVoteWithReasonAndParamsBySig(uint256,uint8,string,bytes,uint8,bytes32,bytes32)',
],
GovernorTimelock: [ GovernorTimelock: [
'timelock()', 'timelock()',
'proposalEta(uint256)', 'proposalEta(uint256)',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment