diff --git a/CHANGELOG.md b/CHANGELOG.md index 0733af7cb91..bb6a58dce1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ * `Governor`: add a relay function to help recover assets sent to a governor that is not its own executor (e.g. when using a timelock). ([#2926](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2926)) * `GovernorPreventLateQuorum`: add new module to ensure a minimum voting duration is available after the quorum is reached. ([#2973](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2973)) * `ERC721`: improved revert reason when transferring from wrong owner. ([#2975](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2975)) + * `Votes`: Added a base contract for vote tracking with delegation. ([#2944](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2944)) + * `ERC721Votes`: Added an extension of ERC721 enabled with vote tracking and delegation. ([#2944](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2944)) ## 4.4.1 (2021-12-10) diff --git a/contracts/governance/IGovernor.sol b/contracts/governance/IGovernor.sol index 50d9d9952df..d5dc08cd661 100644 --- a/contracts/governance/IGovernor.sol +++ b/contracts/governance/IGovernor.sol @@ -193,7 +193,7 @@ abstract contract IGovernor is IERC165 { function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); /** - * @dev Cast a with a reason + * @dev Cast a vote with a reason * * Emits a {VoteCast} event. */ diff --git a/contracts/governance/README.adoc b/contracts/governance/README.adoc index d94bde71e96..58daf56e70d 100644 --- a/contracts/governance/README.adoc +++ b/contracts/governance/README.adoc @@ -84,6 +84,10 @@ NOTE: Functions of the `Governor` contract do not include access control. If you {{GovernorProposalThreshold}} +== Utils + +{{Votes}} + == Timelock In a governance system, the {TimelockController} contract is in charge of introducing a delay between a proposal and its execution. It can be used with or without a {Governor}. diff --git a/contracts/governance/extensions/GovernorVotes.sol b/contracts/governance/extensions/GovernorVotes.sol index d1719ca149a..bdca8c935bd 100644 --- a/contracts/governance/extensions/GovernorVotes.sol +++ b/contracts/governance/extensions/GovernorVotes.sol @@ -4,18 +4,17 @@ pragma solidity ^0.8.0; import "../Governor.sol"; -import "../../token/ERC20/extensions/ERC20Votes.sol"; -import "../../utils/math/Math.sol"; +import "../utils/IVotes.sol"; /** - * @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token. + * @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token, or since v4.5 an {ERC721Votes} token. * * _Available since v4.3._ */ abstract contract GovernorVotes is Governor { - ERC20Votes public immutable token; + IVotes public immutable token; - constructor(ERC20Votes tokenAddress) { + constructor(IVotes tokenAddress) { token = tokenAddress; } diff --git a/contracts/governance/utils/IVotes.sol b/contracts/governance/utils/IVotes.sol new file mode 100644 index 00000000000..d277a610127 --- /dev/null +++ b/contracts/governance/utils/IVotes.sol @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts v4.4.0 (interfaces/IVotes.sol) +pragma solidity ^0.8.0; + +/** + * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. + * + * _Available since v4.5._ + */ +interface IVotes { + /** + * @dev Emitted when an account changes their delegate. + */ + event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); + + /** + * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes. + */ + event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); + + /** + * @dev Returns the current amount of votes that `account` has. + */ + function getVotes(address account) external view returns (uint256); + + /** + * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`). + */ + function getPastVotes(address account, uint256 blockNumber) external view returns (uint256); + + /** + * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`). + * + * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. + * Votes that have not been delegated are still part of total supply, even though they would not participate in a + * vote. + */ + function getPastTotalSupply(uint256 blockNumber) external view returns (uint256); + + /** + * @dev Returns the delegate that `account` has chosen. + */ + function delegates(address account) external view returns (address); + + /** + * @dev Delegates votes from the sender to `delegatee`. + */ + function delegate(address delegatee) external; + + /** + * @dev Delegates votes from signer to `delegatee`. + */ + function delegateBySig( + address delegatee, + uint256 nonce, + uint256 expiry, + uint8 v, + bytes32 r, + bytes32 s + ) external; +} diff --git a/contracts/governance/utils/Votes.sol b/contracts/governance/utils/Votes.sol new file mode 100644 index 00000000000..89eaf175285 --- /dev/null +++ b/contracts/governance/utils/Votes.sol @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "../../utils/Context.sol"; +import "../../utils/Counters.sol"; +import "../../utils/Checkpoints.sol"; +import "../../utils/cryptography/draft-EIP712.sol"; +import "./IVotes.sol"; + +/** + * @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be + * transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of + * "representative" that will pool delegated voting units from different accounts and can then use it to vote in + * decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to + * delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative. + * + * This contract is often combined with a token contract such that voting units correspond to token units. For an + * example, see {ERC721Votes}. + * + * The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed + * at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the + * cost of this history tracking optional. + * + * When using this module the derived contract must implement {_getVotingUnits} (for example, make it return + * {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the + * previous example, it would be included in {ERC721-_beforeTokenTransfer}). + * + * _Available since v4.5._ + */ +abstract contract Votes is IVotes, Context, EIP712 { + using Checkpoints for Checkpoints.History; + using Counters for Counters.Counter; + + bytes32 private constant _DELEGATION_TYPEHASH = + keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); + + mapping(address => address) private _delegation; + mapping(address => Checkpoints.History) private _delegateCheckpoints; + Checkpoints.History private _totalCheckpoints; + + mapping(address => Counters.Counter) private _nonces; + + /** + * @dev Returns the current amount of votes that `account` has. + */ + function getVotes(address account) public view virtual override returns (uint256) { + return _delegateCheckpoints[account].latest(); + } + + /** + * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`). + * + * Requirements: + * + * - `blockNumber` must have been already mined + */ + function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { + return _delegateCheckpoints[account].getAtBlock(blockNumber); + } + + /** + * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`). + * + * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. + * Votes that have not been delegated are still part of total supply, even though they would not participate in a + * vote. + * + * Requirements: + * + * - `blockNumber` must have been already mined + */ + function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) { + require(blockNumber < block.number, "Votes: block not yet mined"); + return _totalCheckpoints.getAtBlock(blockNumber); + } + + /** + * @dev Returns the current total supply of votes. + */ + function _getTotalSupply() internal view virtual returns (uint256) { + return _totalCheckpoints.latest(); + } + + /** + * @dev Returns the delegate that `account` has chosen. + */ + function delegates(address account) public view virtual override returns (address) { + return _delegation[account]; + } + + /** + * @dev Delegates votes from the sender to `delegatee`. + */ + function delegate(address delegatee) public virtual override { + address account = _msgSender(); + _delegate(account, 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, "Votes: signature expired"); + address signer = ECDSA.recover( + _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), + v, + r, + s + ); + require(nonce == _useNonce(signer), "Votes: invalid nonce"); + _delegate(signer, delegatee); + } + + /** + * @dev Delegate all of `account`'s voting units to `delegatee`. + * + * Emits events {DelegateChanged} and {DelegateVotesChanged}. + */ + function _delegate(address account, address delegatee) internal virtual { + address oldDelegate = delegates(account); + _delegation[account] = delegatee; + + emit DelegateChanged(account, oldDelegate, delegatee); + _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account)); + } + + /** + * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to` + * should be zero. Total supply of voting units will be adjusted with mints and burns. + */ + function _transferVotingUnits( + address from, + address to, + uint256 amount + ) internal virtual { + if (from == address(0)) { + _totalCheckpoints.push(_add, amount); + } + if (to == address(0)) { + _totalCheckpoints.push(_subtract, amount); + } + _moveDelegateVotes(delegates(from), delegates(to), amount); + } + + /** + * @dev Moves delegated votes from one delegate to another. + */ + function _moveDelegateVotes( + address from, + address to, + uint256 amount + ) private { + if (from != to && amount > 0) { + if (from != address(0)) { + (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[from].push(_subtract, amount); + emit DelegateVotesChanged(from, oldValue, newValue); + } + if (to != address(0)) { + (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[to].push(_add, amount); + emit DelegateVotesChanged(to, oldValue, newValue); + } + } + } + + 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 Consumes a nonce. + * + * Returns the current value and increments nonce. + */ + function _useNonce(address owner) internal virtual returns (uint256 current) { + Counters.Counter storage nonce = _nonces[owner]; + current = nonce.current(); + nonce.increment(); + } + + /** + * @dev Returns an address nonce. + */ + function nonces(address owner) public view virtual returns (uint256) { + return _nonces[owner].current(); + } + + /** + * @dev Returns the contract's {EIP712} domain separator. + */ + // solhint-disable-next-line func-name-mixedcase + function DOMAIN_SEPARATOR() external view returns (bytes32) { + return _domainSeparatorV4(); + } + + /** + * @dev Must return the voting units held by an account. + */ + function _getVotingUnits(address) internal virtual returns (uint256); +} diff --git a/contracts/mocks/CheckpointsImpl.sol b/contracts/mocks/CheckpointsImpl.sol new file mode 100644 index 00000000000..5b9ec0acbd7 --- /dev/null +++ b/contracts/mocks/CheckpointsImpl.sol @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../utils/Checkpoints.sol"; + +contract CheckpointsImpl { + using Checkpoints for Checkpoints.History; + + Checkpoints.History private _totalCheckpoints; + + function latest() public view returns (uint256) { + return _totalCheckpoints.latest(); + } + + function getAtBlock(uint256 blockNumber) public view returns (uint256) { + return _totalCheckpoints.getAtBlock(blockNumber); + } + + function push(uint256 value) public returns (uint256, uint256) { + return _totalCheckpoints.push(value); + } +} diff --git a/contracts/mocks/ERC721VotesMock.sol b/contracts/mocks/ERC721VotesMock.sol new file mode 100644 index 00000000000..0755ace66ce --- /dev/null +++ b/contracts/mocks/ERC721VotesMock.sol @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../token/ERC721/extensions/draft-ERC721Votes.sol"; + +contract ERC721VotesMock is ERC721Votes { + constructor(string memory name, string memory symbol) ERC721(name, symbol) EIP712(name, "1") {} + + function getTotalSupply() public view returns (uint256) { + return _getTotalSupply(); + } + + function mint(address account, uint256 tokenId) public { + _mint(account, tokenId); + } + + function burn(uint256 tokenId) public { + _burn(tokenId); + } + + function getChainId() external view returns (uint256) { + return block.chainid; + } +} diff --git a/contracts/mocks/GovernorMock.sol b/contracts/mocks/GovernorMock.sol index cc96dcd2775..85233f55951 100644 --- a/contracts/mocks/GovernorMock.sol +++ b/contracts/mocks/GovernorMock.sol @@ -15,7 +15,7 @@ contract GovernorMock is { constructor( string memory name_, - ERC20Votes token_, + IVotes token_, uint256 votingDelay_, uint256 votingPeriod_, uint256 quorumNumerator_ diff --git a/contracts/mocks/GovernorPreventLateQuorumMock.sol b/contracts/mocks/GovernorPreventLateQuorumMock.sol index 412337c08d5..7de50a01f94 100644 --- a/contracts/mocks/GovernorPreventLateQuorumMock.sol +++ b/contracts/mocks/GovernorPreventLateQuorumMock.sol @@ -17,7 +17,7 @@ contract GovernorPreventLateQuorumMock is constructor( string memory name_, - ERC20Votes token_, + IVotes token_, uint256 votingDelay_, uint256 votingPeriod_, uint256 quorum_, diff --git a/contracts/mocks/GovernorTimelockCompoundMock.sol b/contracts/mocks/GovernorTimelockCompoundMock.sol index 848f4b409b3..aeba5b86a80 100644 --- a/contracts/mocks/GovernorTimelockCompoundMock.sol +++ b/contracts/mocks/GovernorTimelockCompoundMock.sol @@ -15,7 +15,7 @@ contract GovernorTimelockCompoundMock is { constructor( string memory name_, - ERC20Votes token_, + IVotes token_, uint256 votingDelay_, uint256 votingPeriod_, ICompoundTimelock timelock_, diff --git a/contracts/mocks/GovernorTimelockControlMock.sol b/contracts/mocks/GovernorTimelockControlMock.sol index 4d9e97fd522..97376c8253a 100644 --- a/contracts/mocks/GovernorTimelockControlMock.sol +++ b/contracts/mocks/GovernorTimelockControlMock.sol @@ -15,7 +15,7 @@ contract GovernorTimelockControlMock is { constructor( string memory name_, - ERC20Votes token_, + IVotes token_, uint256 votingDelay_, uint256 votingPeriod_, TimelockController timelock_, diff --git a/contracts/mocks/GovernorVoteMock.sol b/contracts/mocks/GovernorVoteMock.sol new file mode 100644 index 00000000000..23ccf6bc09c --- /dev/null +++ b/contracts/mocks/GovernorVoteMock.sol @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../governance/extensions/GovernorCountingSimple.sol"; +import "../governance/extensions/GovernorVotes.sol"; + +contract GovernorVoteMocks is GovernorVotes, GovernorCountingSimple { + constructor(string memory name_, IVotes token_) Governor(name_) GovernorVotes(token_) {} + + 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 cancel( + address[] memory targets, + uint256[] memory values, + bytes[] memory calldatas, + bytes32 salt + ) public returns (uint256 proposalId) { + return _cancel(targets, values, calldatas, salt); + } + + function getVotes(address account, uint256 blockNumber) + public + view + virtual + override(IGovernor, GovernorVotes) + returns (uint256) + { + return super.getVotes(account, blockNumber); + } +} diff --git a/contracts/mocks/VotesMock.sol b/contracts/mocks/VotesMock.sol new file mode 100644 index 00000000000..db06ee9a501 --- /dev/null +++ b/contracts/mocks/VotesMock.sol @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +import "../governance/utils/Votes.sol"; + +contract VotesMock is Votes { + mapping(address => uint256) private _balances; + mapping(uint256 => address) private _owners; + + constructor(string memory name) EIP712(name, "1") {} + + function getTotalSupply() public view returns (uint256) { + return _getTotalSupply(); + } + + function delegate(address account, address newDelegation) public { + return _delegate(account, newDelegation); + } + + function _getVotingUnits(address account) internal virtual override returns (uint256) { + return _balances[account]; + } + + function mint(address account, uint256 voteId) external { + _balances[account] += 1; + _owners[voteId] = account; + _transferVotingUnits(address(0), account, 1); + } + + function burn(uint256 voteId) external { + address owner = _owners[voteId]; + _balances[owner] -= 1; + _transferVotingUnits(owner, address(0), 1); + } + + function getChainId() external view returns (uint256) { + return block.chainid; + } +} diff --git a/contracts/mocks/wizard/MyGovernor1.sol b/contracts/mocks/wizard/MyGovernor1.sol index 72b486aa782..bd524ee55a2 100644 --- a/contracts/mocks/wizard/MyGovernor1.sol +++ b/contracts/mocks/wizard/MyGovernor1.sol @@ -14,7 +14,7 @@ contract MyGovernor1 is GovernorVotesQuorumFraction, GovernorCountingSimple { - constructor(ERC20Votes _token, TimelockController _timelock) + constructor(IVotes _token, TimelockController _timelock) Governor("MyGovernor") GovernorVotes(_token) GovernorVotesQuorumFraction(4) diff --git a/contracts/mocks/wizard/MyGovernor2.sol b/contracts/mocks/wizard/MyGovernor2.sol index 3f25b91bfe8..3a5c983e0b3 100644 --- a/contracts/mocks/wizard/MyGovernor2.sol +++ b/contracts/mocks/wizard/MyGovernor2.sol @@ -16,7 +16,7 @@ contract MyGovernor2 is GovernorVotesQuorumFraction, GovernorCountingSimple { - constructor(ERC20Votes _token, TimelockController _timelock) + constructor(IVotes _token, TimelockController _timelock) Governor("MyGovernor") GovernorVotes(_token) GovernorVotesQuorumFraction(4) diff --git a/contracts/mocks/wizard/MyGovernor3.sol b/contracts/mocks/wizard/MyGovernor3.sol index c2465751a79..835a893a3a4 100644 --- a/contracts/mocks/wizard/MyGovernor3.sol +++ b/contracts/mocks/wizard/MyGovernor3.sol @@ -14,7 +14,7 @@ contract MyGovernor is GovernorVotes, GovernorVotesQuorumFraction { - constructor(ERC20Votes _token, TimelockController _timelock) + constructor(IVotes _token, TimelockController _timelock) Governor("MyGovernor") GovernorVotes(_token) GovernorVotesQuorumFraction(4) diff --git a/contracts/token/ERC20/extensions/ERC20Votes.sol b/contracts/token/ERC20/extensions/ERC20Votes.sol index f4fd21d3e5b..6b0cf8372e1 100644 --- a/contracts/token/ERC20/extensions/ERC20Votes.sol +++ b/contracts/token/ERC20/extensions/ERC20Votes.sol @@ -5,6 +5,7 @@ pragma solidity ^0.8.0; import "./draft-ERC20Permit.sol"; import "../../../utils/math/Math.sol"; +import "../../../governance/utils/IVotes.sol"; import "../../../utils/math/SafeCast.sol"; import "../../../utils/cryptography/ECDSA.sol"; @@ -25,7 +26,7 @@ import "../../../utils/cryptography/ECDSA.sol"; * * _Available since v4.2._ */ -abstract contract ERC20Votes is ERC20Permit { +abstract contract ERC20Votes is IVotes, ERC20Permit { struct Checkpoint { uint32 fromBlock; uint224 votes; @@ -38,16 +39,6 @@ abstract contract ERC20Votes is ERC20Permit { mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; - /** - * @dev Emitted when an account changes their delegate. - */ - event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); - - /** - * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. - */ - event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); - /** * @dev Get the `pos`-th checkpoint for `account`. */ @@ -65,14 +56,14 @@ abstract contract ERC20Votes is ERC20Permit { /** * @dev Get the address `account` is currently delegating to. */ - function delegates(address account) public view virtual returns (address) { + 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 returns (uint256) { + function getVotes(address account) public view override returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } @@ -84,7 +75,7 @@ abstract contract ERC20Votes is ERC20Permit { * * - `blockNumber` must have been already mined */ - function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { + function getPastVotes(address account, uint256 blockNumber) public view override returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } @@ -97,7 +88,7 @@ abstract contract ERC20Votes is ERC20Permit { * * - `blockNumber` must have been already mined */ - function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { + function getPastTotalSupply(uint256 blockNumber) public view override returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } @@ -134,7 +125,7 @@ abstract contract ERC20Votes is ERC20Permit { /** * @dev Delegate votes from the sender to `delegatee`. */ - function delegate(address delegatee) public virtual { + function delegate(address delegatee) public virtual override { _delegate(_msgSender(), delegatee); } @@ -148,7 +139,7 @@ abstract contract ERC20Votes is ERC20Permit { uint8 v, bytes32 r, bytes32 s - ) public virtual { + ) public virtual override { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), diff --git a/contracts/token/ERC721/ERC721.sol b/contracts/token/ERC721/ERC721.sol index fd1617bbc40..0802a5f8d0e 100644 --- a/contracts/token/ERC721/ERC721.sol +++ b/contracts/token/ERC721/ERC721.sol @@ -287,6 +287,8 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); + + _afterTokenTransfer(address(0), to, tokenId); } /** @@ -311,6 +313,8 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); + + _afterTokenTransfer(owner, address(0), tokenId); } /** @@ -342,6 +346,8 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { _owners[tokenId] = to; emit Transfer(from, to, tokenId); + + _afterTokenTransfer(from, to, tokenId); } /** @@ -421,4 +427,21 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { address to, uint256 tokenId ) 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. + * - `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 tokenId + ) internal virtual {} } diff --git a/contracts/token/ERC721/README.adoc b/contracts/token/ERC721/README.adoc index f1122c53a99..90ec73783f0 100644 --- a/contracts/token/ERC721/README.adoc +++ b/contracts/token/ERC721/README.adoc @@ -15,6 +15,7 @@ Additionally there are multiple custom extensions, including: * designation of addresses that can pause token transfers for all users ({ERC721Pausable}). * destruction of own tokens ({ERC721Burnable}). +* support for voting and vote delegation ({ERC721Votes}) NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC721 (such as <>) and expose them as external functions in the way they prefer. On the other hand, xref:ROOT:erc721.adoc#Presets[ERC721 Presets] (such as {ERC721PresetMinterPauserAutoId}) are designed using opinionated patterns to provide developers with ready to use, deployable contracts. @@ -41,6 +42,8 @@ NOTE: This core set of contracts is designed to be unopinionated, allowing devel {{ERC721URIStorage}} +{{ERC721Votes}} + == Presets These contracts are preconfigured combinations of the above features. They can be used through inheritance or as models to copy and paste their source code. diff --git a/contracts/token/ERC721/extensions/draft-ERC721Votes.sol b/contracts/token/ERC721/extensions/draft-ERC721Votes.sol new file mode 100644 index 00000000000..45f1a307a47 --- /dev/null +++ b/contracts/token/ERC721/extensions/draft-ERC721Votes.sol @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/draft-ERC721Votes.sol) + +pragma solidity ^0.8.0; + +import "../ERC721.sol"; +import "../../../governance/utils/Votes.sol"; + +/** + * @dev Extension of ERC721 to support voting and delegation as implemented by {Votes}, where each individual NFT counts + * as 1 vote unit. + * + * Tokens do not count as votes until they are delegated, because votes must be tracked which incurs an additional cost + * on every transfer. Token holders can either delegate to a trusted representative who will decide how to make use of + * the votes in governance decisions, or they can delegate to themselves to be their own representative. + * + * _Available since v4.5._ + */ +abstract contract ERC721Votes is ERC721, Votes { + /** + * @dev Adjusts votes when tokens are transferred. + * + * Emits a {Votes-DelegateVotesChanged} event. + */ + function _afterTokenTransfer( + address from, + address to, + uint256 tokenId + ) internal virtual override { + _transferVotingUnits(from, to, 1); + super._afterTokenTransfer(from, to, tokenId); + } + + /** + * @dev Returns the balance of `account`. + */ + function _getVotingUnits(address account) internal virtual override returns (uint256) { + return balanceOf(account); + } +} diff --git a/contracts/utils/Checkpoints.sol b/contracts/utils/Checkpoints.sol new file mode 100644 index 00000000000..2d31539a6f1 --- /dev/null +++ b/contracts/utils/Checkpoints.sol @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "./math/Math.sol"; +import "./math/SafeCast.sol"; + +/** + * @dev This library defines the `History` struct, for checkpointing values as they change at different points in + * time, and later looking up past values by block number. See {Votes} as an example. + * + * To create a history of checkpoints define a variable type `Checkpoints.History` in your contract, and store a new + * checkpoint for the current transaction block using the {push} function. + * + * _Available since v4.5._ + */ +library Checkpoints { + struct Checkpoint { + uint32 _blockNumber; + uint224 _value; + } + + struct History { + Checkpoint[] _checkpoints; + } + + /** + * @dev Returns the value in the latest checkpoint, or zero if there are no checkpoints. + */ + function latest(History storage self) internal view returns (uint256) { + uint256 pos = self._checkpoints.length; + return pos == 0 ? 0 : self._checkpoints[pos - 1]._value; + } + + /** + * @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one + * before it is returned, or zero otherwise. + */ + function getAtBlock(History storage self, uint256 blockNumber) internal view returns (uint256) { + require(blockNumber < block.number, "Checkpoints: block not yet mined"); + + uint256 high = self._checkpoints.length; + uint256 low = 0; + while (low < high) { + uint256 mid = Math.average(low, high); + if (self._checkpoints[mid]._blockNumber > blockNumber) { + high = mid; + } else { + low = mid + 1; + } + } + return high == 0 ? 0 : self._checkpoints[high - 1]._value; + } + + /** + * @dev Pushes a value onto a History so that it is stored as the checkpoint for the current block. + * + * Returns previous value and new value. + */ + function push(History storage self, uint256 value) internal returns (uint256, uint256) { + uint256 pos = self._checkpoints.length; + uint256 old = latest(self); + if (pos > 0 && self._checkpoints[pos - 1]._blockNumber == block.number) { + self._checkpoints[pos - 1]._value = SafeCast.toUint224(value); + } else { + self._checkpoints.push( + Checkpoint({_blockNumber: SafeCast.toUint32(block.number), _value: SafeCast.toUint224(value)}) + ); + } + return (old, value); + } + + /** + * @dev Pushes a value onto a History, by updating the latest value using binary operation `op`. The new value will + * be set to `op(latest, delta)`. + * + * Returns previous value and new value. + */ + function push( + History storage self, + function(uint256, uint256) view returns (uint256) op, + uint256 delta + ) internal returns (uint256, uint256) { + return push(self, op(latest(self), delta)); + } +} diff --git a/contracts/utils/README.adoc b/contracts/utils/README.adoc index 4edcf923bb1..78f44b61858 100644 --- a/contracts/utils/README.adoc +++ b/contracts/utils/README.adoc @@ -86,6 +86,8 @@ Note that, in all cases, accounts simply _declare_ their interfaces, but they ar {{EnumerableSet}} +{{Checkpoints}} + == Libraries {{Create2}} diff --git a/docs/modules/ROOT/pages/erc721.adoc b/docs/modules/ROOT/pages/erc721.adoc index 8d28fad2e6e..14dbdc97606 100644 --- a/docs/modules/ROOT/pages/erc721.adoc +++ b/docs/modules/ROOT/pages/erc721.adoc @@ -1,6 +1,6 @@ = ERC721 -We've discussed how you can make a _fungible_ token using xref:erc20.adoc[ERC20], but what if not all tokens are alike? This comes up in situations like *real estate* or *collectibles*, where some items are valued more than others, due to their usefulness, rarity, etc. ERC721 is a standard for representing ownership of xref:tokens.adoc#different-kinds-of-tokens[_non-fungible_ tokens], that is, where each token is unique. +We've discussed how you can make a _fungible_ token using xref:erc20.adoc[ERC20], but what if not all tokens are alike? This comes up in situations like *real estate*, *voting rights*, or *collectibles*, where some items are valued more than others, due to their usefulness, rarity, etc. ERC721 is a standard for representing ownership of xref:tokens.adoc#different-kinds-of-tokens[_non-fungible_ tokens], that is, where each token is unique. ERC721 is a more complex standard than ERC20, with multiple optional extensions, and is split across a number of contracts. The OpenZeppelin Contracts provide flexibility regarding how these are combined, along with custom useful extensions. Check out the xref:api:token/ERC721.adoc[API Reference] to learn more about these. diff --git a/docs/modules/ROOT/pages/governance.adoc b/docs/modules/ROOT/pages/governance.adoc index 027301c1ba5..9f04ab5974e 100644 --- a/docs/modules/ROOT/pages/governance.adoc +++ b/docs/modules/ROOT/pages/governance.adoc @@ -119,13 +119,13 @@ contract MyToken is ERC20, ERC20Permit, ERC20Votes, ERC20Wrapper { } ``` -NOTE: Voting power could be determined in different ways: multiple ERC20 tokens, ERC721 tokens, sybil resistant identities, etc. All of these options are potentially supported by writing a custom Votes module for your Governor. +NOTE: Voting power could be determined in different ways: multiple ERC20 tokens, ERC721 tokens, sybil resistant identities, etc. All of these options are potentially supported by writing a custom Votes module for your Governor. The only other source of voting power available in OpenZeppelin Contracts currently is xref:api:token/ERC721.adoc#ERC721Votes[`ERC721Votes`]. === Governor -Initially, we will build a Governor without a timelock. The core logic is given by the Governor contract, but we still need to choose: 1) how voting power is determined, 2) how many votes are needed for quorum, and 3) what options people have when casting a vote and how those votes are counted. Each of these aspects is customizable by writing your own module, or more easily choosing one from OpenZeppelin Contracts. +Initially, we will build a Governor without a timelock. The core logic is given by the Governor contract, but we still need to choose: 1) how voting power is determined, 2) how many votes are needed for quorum, 3) what options people have when casting a vote and how those votes are counted, and 4) what type of token should be used to vote. Each of these aspects is customizable by writing your own module, or more easily choosing one from OpenZeppelin Contracts. -For 1) we will use the GovernorVotes module, which hooks to an ERC20Votes instance to determine the voting power of an account based on the token balance they hold when a proposal becomes active. This module requires as a constructor parameter the address of the token. +For 1) we will use the GovernorVotes module, which hooks to an IVotes instance to determine the voting power of an account based on the token balance they hold when a proposal becomes active. This module requires as a constructor parameter the address of the token. For 2) we will use GovernorVotesQuorumFraction which works together with ERC20Votes to define quorum as a percentage of the total supply at the block a proposal’s voting power is retrieved. This requires a constructor parameter to set the percentage. Most Governors nowadays use 4%, so we will initialize the module with parameter 4 (this indicates the percentage, resulting in 4%). @@ -152,7 +152,7 @@ import "./governance/extensions/GovernorVotesQuorumFraction.sol"; import "./governance/extensions/GovernorTimelockControl.sol"; contract MyGovernor is Governor, GovernorCompatibilityBravo, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockControl { - constructor(ERC20Votes _token, TimelockController _timelock) + constructor(IVotes _token, TimelockController _timelock) Governor("MyGovernor") GovernorVotes(_token) GovernorVotesQuorumFraction(4) @@ -294,7 +294,7 @@ This will create a new proposal, with a proposal id that is obtained by hashing === Cast a Vote -Once a proposal is active, stakeholders can cast their vote. This is done through a function in the Governor contract that users can invoke directly from a governance UI such as Tally. +Once a proposal is active, stakeholders can cast their vote. This is done through a function in the Governor contract that users can invoke directly from a governance UI such as Tally. image::tally-vote.png[Voting in Tally] diff --git a/test/governance/GovernorWorkflow.behavior.js b/test/governance/GovernorWorkflow.behavior.js index 3256792cca9..7bcaed06abf 100644 --- a/test/governance/GovernorWorkflow.behavior.js +++ b/test/governance/GovernorWorkflow.behavior.js @@ -31,6 +31,11 @@ function runGovernorWorkflow () { for (const voter of this.settings.voters) { if (voter.weight) { await this.token.transfer(voter.voter, voter.weight, { from: this.settings.tokenHolder }); + } else if (voter.nfts) { + for (const nft of voter.nfts) { + await this.token.transferFrom(this.settings.tokenHolder, voter.voter, nft, + { from: this.settings.tokenHolder }); + } } } } diff --git a/test/governance/extensions/GovernorERC721.test.js b/test/governance/extensions/GovernorERC721.test.js new file mode 100644 index 00000000000..3f89c02b4e0 --- /dev/null +++ b/test/governance/extensions/GovernorERC721.test.js @@ -0,0 +1,118 @@ +const { expectEvent } = require('@openzeppelin/test-helpers'); +const { BN } = require('bn.js'); +const Enums = require('../../helpers/enums'); + +const { + runGovernorWorkflow, +} = require('./../GovernorWorkflow.behavior'); + +const Token = artifacts.require('ERC721VotesMock'); +const Governor = artifacts.require('GovernorVoteMocks'); +const CallReceiver = artifacts.require('CallReceiverMock'); + +contract('GovernorERC721Mock', function (accounts) { + const [ owner, voter1, voter2, voter3, voter4 ] = accounts; + + const name = 'OZ-Governor'; + const tokenName = 'MockNFToken'; + const tokenSymbol = 'MTKN'; + const NFT0 = web3.utils.toWei('100'); + const NFT1 = web3.utils.toWei('10'); + const NFT2 = web3.utils.toWei('20'); + const NFT3 = web3.utils.toWei('30'); + const NFT4 = web3.utils.toWei('40'); + + // Must be the same as in contract + const ProposalState = { + Pending: new BN('0'), + Active: new BN('1'), + Canceled: new BN('2'), + Defeated: new BN('3'), + Succeeded: new BN('4'), + Queued: new BN('5'), + Expired: new BN('6'), + Executed: new BN('7'), + }; + + 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, NFT0); + await this.token.mint(owner, NFT1); + await this.token.mint(owner, NFT2); + await this.token.mint(owner, NFT3); + await this.token.mint(owner, NFT4); + + 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('4'); + expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); + expect(await this.mock.quorum(0)).to.be.bignumber.equal('0'); + }); + + describe('voting with ERC721 token', function () { + beforeEach(async function () { + this.settings = { + proposal: [ + [ this.receiver.address ], + [ web3.utils.toWei('0') ], + [ this.receiver.contract.methods.mockFunction().encodeABI() ], + '', + ], + tokenHolder: owner, + voters: [ + { voter: voter1, nfts: [NFT0], support: Enums.VoteType.For }, + { voter: voter2, nfts: [NFT1, NFT2], support: Enums.VoteType.For }, + { voter: voter3, nfts: [NFT3], support: Enums.VoteType.Against }, + { voter: voter4, nfts: [NFT4], support: Enums.VoteType.Abstain }, + ], + }; + }); + + afterEach(async function () { + expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false); + + for (const vote of this.receipts.castVote.filter(Boolean)) { + const { voter } = vote.logs.find(Boolean).args; + + expect(await this.mock.hasVoted(this.id, voter)).to.be.equal(true); + + expectEvent( + vote, + 'VoteCast', + this.settings.voters.find(({ address }) => address === voter), + ); + + if (voter === voter2) { + expect(await this.token.getVotes(voter, vote.blockNumber)).to.be.bignumber.equal('2'); + } else { + expect(await this.token.getVotes(voter, vote.blockNumber)).to.be.bignumber.equal('1'); + } + } + + 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, { nfts }) => acc.add(new BN(nfts.length)), + new BN('0'), + ), + ); + } + }); + + expect(await this.mock.state(this.id)).to.be.bignumber.equal(ProposalState.Executed); + }); + + runGovernorWorkflow(); + }); +}); diff --git a/test/governance/utils/Votes.behavior.js b/test/governance/utils/Votes.behavior.js new file mode 100644 index 00000000000..17b49eaa9d1 --- /dev/null +++ b/test/governance/utils/Votes.behavior.js @@ -0,0 +1,344 @@ +const { constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); + +const { MAX_UINT256, ZERO_ADDRESS } = constants; + +const { fromRpcSig } = require('ethereumjs-util'); +const ethSigUtil = require('eth-sig-util'); +const Wallet = require('ethereumjs-wallet').default; + +const { EIP712Domain, domainSeparator } = require('../../helpers/eip712'); + +const Delegation = [ + { name: 'delegatee', type: 'address' }, + { name: 'nonce', type: 'uint256' }, + { name: 'expiry', type: 'uint256' }, +]; + +const version = '1'; + +function shouldBehaveLikeVotes () { + describe('run votes workflow', function () { + it('initial nonce is 0', async function () { + expect(await this.votes.nonces(this.account1)).to.be.bignumber.equal('0'); + }); + + it('domain separator', async function () { + expect( + await this.votes.DOMAIN_SEPARATOR(), + ).to.equal( + await domainSeparator(this.name, version, this.chainId, this.votes.address), + ); + }); + + describe('delegation with signature', function () { + const delegator = Wallet.generate(); + const delegatorAddress = web3.utils.toChecksumAddress(delegator.getAddressString()); + const nonce = 0; + + const buildData = (chainId, verifyingContract, name, message) => ({ + data: { + primaryType: 'Delegation', + types: { EIP712Domain, Delegation }, + domain: { name, version, chainId, verifyingContract }, + message, + }, + }); + + beforeEach(async function () { + await this.votes.mint(delegatorAddress, this.NFT0); + }); + + it('accept signed delegation', async function () { + const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.votes.address, this.name, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + )); + + expect(await this.votes.delegates(delegatorAddress)).to.be.equal(ZERO_ADDRESS); + + const { receipt } = await this.votes.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); + expectEvent(receipt, 'DelegateChanged', { + delegator: delegatorAddress, + fromDelegate: ZERO_ADDRESS, + toDelegate: delegatorAddress, + }); + expectEvent(receipt, 'DelegateVotesChanged', { + delegate: delegatorAddress, + previousBalance: '0', + newBalance: '1', + }); + + expect(await this.votes.delegates(delegatorAddress)).to.be.equal(delegatorAddress); + + expect(await this.votes.getVotes(delegatorAddress)).to.be.bignumber.equal('1'); + expect(await this.votes.getPastVotes(delegatorAddress, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); + await time.advanceBlock(); + expect(await this.votes.getPastVotes(delegatorAddress, receipt.blockNumber)).to.be.bignumber.equal('1'); + }); + + it('rejects reused signature', async function () { + const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.votes.address, this.name, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + )); + + await this.votes.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s); + + await expectRevert( + this.votes.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s), + 'Votes: invalid nonce', + ); + }); + + it('rejects bad delegatee', async function () { + const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.votes.address, this.name, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + )); + + const { logs } = await this.votes.delegateBySig(this.account1Delegatee, nonce, MAX_UINT256, v, r, s); + const { args } = logs.find(({ event }) => event === 'DelegateChanged'); + expect(args.delegator).to.not.be.equal(delegatorAddress); + expect(args.fromDelegate).to.be.equal(ZERO_ADDRESS); + expect(args.toDelegate).to.be.equal(this.account1Delegatee); + }); + + it('rejects bad nonce', async function () { + const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.votes.address, this.name, { + delegatee: delegatorAddress, + nonce, + expiry: MAX_UINT256, + }), + )); + await expectRevert( + this.votes.delegateBySig(delegatorAddress, nonce + 1, MAX_UINT256, v, r, s), + 'Votes: invalid nonce', + ); + }); + + it('rejects expired permit', async function () { + const expiry = (await time.latest()) - time.duration.weeks(1); + const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage( + delegator.getPrivateKey(), + buildData(this.chainId, this.votes.address, this.name, { + delegatee: delegatorAddress, + nonce, + expiry, + }), + )); + + await expectRevert( + this.votes.delegateBySig(delegatorAddress, nonce, expiry, v, r, s), + 'Votes: signature expired', + ); + }); + }); + + describe('set delegation', function () { + describe('call', function () { + it('delegation with tokens', async function () { + await this.votes.mint(this.account1, this.NFT0); + expect(await this.votes.delegates(this.account1)).to.be.equal(ZERO_ADDRESS); + + const { receipt } = await this.votes.delegate(this.account1, { from: this.account1 }); + expectEvent(receipt, 'DelegateChanged', { + delegator: this.account1, + fromDelegate: ZERO_ADDRESS, + toDelegate: this.account1, + }); + expectEvent(receipt, 'DelegateVotesChanged', { + delegate: this.account1, + previousBalance: '0', + newBalance: '1', + }); + + expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1); + + expect(await this.votes.getVotes(this.account1)).to.be.bignumber.equal('1'); + expect(await this.votes.getPastVotes(this.account1, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); + await time.advanceBlock(); + expect(await this.votes.getPastVotes(this.account1, receipt.blockNumber)).to.be.bignumber.equal('1'); + }); + + it('delegation without tokens', async function () { + expect(await this.votes.delegates(this.account1)).to.be.equal(ZERO_ADDRESS); + + const { receipt } = await this.votes.delegate(this.account1, { from: this.account1 }); + expectEvent(receipt, 'DelegateChanged', { + delegator: this.account1, + fromDelegate: ZERO_ADDRESS, + toDelegate: this.account1, + }); + expectEvent.notEmitted(receipt, 'DelegateVotesChanged'); + + expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1); + }); + }); + }); + + describe('change delegation', function () { + beforeEach(async function () { + await this.votes.mint(this.account1, this.NFT0); + await this.votes.delegate(this.account1, { from: this.account1 }); + }); + + it('call', async function () { + expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1); + + const { receipt } = await this.votes.delegate(this.account1Delegatee, { from: this.account1 }); + expectEvent(receipt, 'DelegateChanged', { + delegator: this.account1, + fromDelegate: this.account1, + toDelegate: this.account1Delegatee, + }); + expectEvent(receipt, 'DelegateVotesChanged', { + delegate: this.account1, + previousBalance: '1', + newBalance: '0', + }); + expectEvent(receipt, 'DelegateVotesChanged', { + delegate: this.account1Delegatee, + previousBalance: '0', + newBalance: '1', + }); + const prevBlock = receipt.blockNumber - 1; + expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1Delegatee); + + expect(await this.votes.getVotes(this.account1)).to.be.bignumber.equal('0'); + expect(await this.votes.getVotes(this.account1Delegatee)).to.be.bignumber.equal('1'); + expect(await this.votes.getPastVotes(this.account1, receipt.blockNumber - 1)).to.be.bignumber.equal('1'); + expect(await this.votes.getPastVotes(this.account1Delegatee, prevBlock)).to.be.bignumber.equal('0'); + await time.advanceBlock(); + expect(await this.votes.getPastVotes(this.account1, receipt.blockNumber)).to.be.bignumber.equal('0'); + expect(await this.votes.getPastVotes(this.account1Delegatee, receipt.blockNumber)).to.be.bignumber.equal('1'); + }); + }); + + describe('getPastTotalSupply', function () { + beforeEach(async function () { + await this.votes.delegate(this.account1, { from: this.account1 }); + }); + + it('reverts if block number >= current block', async function () { + await expectRevert( + this.votes.getPastTotalSupply(5e10), + 'block not yet mined', + ); + }); + + it('returns 0 if there are no checkpoints', async function () { + expect(await this.votes.getPastTotalSupply(0)).to.be.bignumber.equal('0'); + }); + + it('returns the latest block if >= last checkpoint block', async function () { + const t1 = await this.votes.mint(this.account1, this.NFT0); + await time.advanceBlock(); + await time.advanceBlock(); + + expect(await this.votes.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); + expect(await this.votes.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('1'); + }); + + it('returns zero if < first checkpoint block', async function () { + await time.advanceBlock(); + const t2 = await this.votes.mint(this.account1, this.NFT1); + await time.advanceBlock(); + await time.advanceBlock(); + + expect(await this.votes.getPastTotalSupply(t2.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); + expect(await this.votes.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('1'); + }); + + it('generally returns the voting balance at the appropriate checkpoint', async function () { + const t1 = await this.votes.mint(this.account1, this.NFT1); + await time.advanceBlock(); + await time.advanceBlock(); + const t2 = await this.votes.burn(this.NFT1); + await time.advanceBlock(); + await time.advanceBlock(); + const t3 = await this.votes.mint(this.account1, this.NFT2); + await time.advanceBlock(); + await time.advanceBlock(); + const t4 = await this.votes.burn(this.NFT2); + await time.advanceBlock(); + await time.advanceBlock(); + const t5 = await this.votes.mint(this.account1, this.NFT3); + await time.advanceBlock(); + await time.advanceBlock(); + + expect(await this.votes.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); + expect(await this.votes.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal('1'); + expect(await this.votes.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('1'); + expect(await this.votes.getPastTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal('0'); + expect(await this.votes.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('0'); + expect(await this.votes.getPastTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal('1'); + expect(await this.votes.getPastTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal('1'); + expect(await this.votes.getPastTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal('0'); + expect(await this.votes.getPastTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal('0'); + expect(await this.votes.getPastTotalSupply(t5.receipt.blockNumber)).to.be.bignumber.equal('1'); + expect(await this.votes.getPastTotalSupply(t5.receipt.blockNumber + 1)).to.be.bignumber.equal('1'); + }); + }); + + // The following tests are a adaptation of + // https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js. + describe('Compound test suite', function () { + beforeEach(async function () { + await this.votes.mint(this.account1, this.NFT0); + await this.votes.mint(this.account1, this.NFT1); + await this.votes.mint(this.account1, this.NFT2); + await this.votes.mint(this.account1, this.NFT3); + }); + + describe('getPastVotes', function () { + it('reverts if block number >= current block', async function () { + await expectRevert( + this.votes.getPastVotes(this.account2, 5e10), + 'block not yet mined', + ); + }); + + it('returns 0 if there are no checkpoints', async function () { + expect(await this.votes.getPastVotes(this.account2, 0)).to.be.bignumber.equal('0'); + }); + + it('returns the latest block if >= last checkpoint block', async function () { + const t1 = await this.votes.delegate(this.account2, { from: this.account1 }); + await time.advanceBlock(); + await time.advanceBlock(); + const latest = await this.votes.getVotes(this.account2); + const nextBlock = t1.receipt.blockNumber + 1; + expect(await this.votes.getPastVotes(this.account2, t1.receipt.blockNumber)).to.be.bignumber.equal(latest); + expect(await this.votes.getPastVotes(this.account2, nextBlock)).to.be.bignumber.equal(latest); + }); + + it('returns zero if < first checkpoint block', async function () { + await time.advanceBlock(); + const t1 = await this.votes.delegate(this.account2, { from: this.account1 }); + await time.advanceBlock(); + await time.advanceBlock(); + + expect(await this.votes.getPastVotes(this.account2, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); + }); + }); + }); + }); +} + +module.exports = { + shouldBehaveLikeVotes, +}; diff --git a/test/governance/utils/Votes.test.js b/test/governance/utils/Votes.test.js new file mode 100644 index 00000000000..32b7d1dca57 --- /dev/null +++ b/test/governance/utils/Votes.test.js @@ -0,0 +1,61 @@ +const { expectRevert, BN } = require('@openzeppelin/test-helpers'); + +const { expect } = require('chai'); + +const { + shouldBehaveLikeVotes, +} = require('./Votes.behavior'); + +const Votes = artifacts.require('VotesMock'); + +contract('Votes', function (accounts) { + const [ account1, account2, account3 ] = accounts; + beforeEach(async function () { + this.name = 'My Vote'; + this.votes = await Votes.new(this.name); + }); + + it('starts with zero votes', async function () { + expect(await this.votes.getTotalSupply()).to.be.bignumber.equal('0'); + }); + + describe('performs voting operations', function () { + beforeEach(async function () { + this.tx1 = await this.votes.mint(account1, 1); + this.tx2 = await this.votes.mint(account2, 1); + this.tx3 = await this.votes.mint(account3, 1); + }); + + it('reverts if block number >= current block', async function () { + await expectRevert( + this.votes.getPastTotalSupply(this.tx3.receipt.blockNumber + 1), + 'Votes: block not yet mined', + ); + }); + + it('delegates', async function () { + await this.votes.delegate(account3, account2); + + expect(await this.votes.delegates(account3)).to.be.equal(account2); + }); + + it('returns total amount of votes', async function () { + expect(await this.votes.getTotalSupply()).to.be.bignumber.equal('3'); + }); + }); + + describe('performs voting workflow', function () { + beforeEach(async function () { + this.chainId = await this.votes.getChainId(); + this.account1 = account1; + this.account2 = account2; + this.account1Delegatee = account2; + this.NFT0 = new BN('10000000000000000000000000'); + this.NFT1 = new BN('10'); + this.NFT2 = new BN('20'); + this.NFT3 = new BN('30'); + }); + + shouldBehaveLikeVotes(); + }); +}); diff --git a/test/token/ERC721/extensions/ERC721Votes.test.js b/test/token/ERC721/extensions/ERC721Votes.test.js new file mode 100644 index 00000000000..6f001f20b4d --- /dev/null +++ b/test/token/ERC721/extensions/ERC721Votes.test.js @@ -0,0 +1,174 @@ +/* eslint-disable */ + +const { BN, expectEvent, time } = require('@openzeppelin/test-helpers'); +const { expect } = require('chai'); + +const { promisify } = require('util'); +const queue = promisify(setImmediate); + +const ERC721VotesMock = artifacts.require('ERC721VotesMock'); + +const { shouldBehaveLikeVotes } = require('../../../governance/utils/Votes.behavior'); + +contract('ERC721Votes', function (accounts) { + const [ account1, account2, account1Delegatee, other1, other2 ] = accounts; + this.name = 'My Vote'; + const symbol = 'MTKN'; + + beforeEach(async function () { + this.votes = await ERC721VotesMock.new(name, symbol); + + // We get the chain id from the contract because Ganache (used for coverage) does not return the same chain id + // from within the EVM as from the JSON RPC interface. + // See https://github.com/trufflesuite/ganache-core/issues/515 + this.chainId = await this.votes.getChainId(); + + this.NFT0 = new BN('10000000000000000000000000'); + this.NFT1 = new BN('10'); + this.NFT2 = new BN('20'); + this.NFT3 = new BN('30'); + }); + + describe('balanceOf', function () { + beforeEach(async function () { + await this.votes.mint(account1, this.NFT0); + await this.votes.mint(account1, this.NFT1); + await this.votes.mint(account1, this.NFT2); + await this.votes.mint(account1, this.NFT3); + }); + + it('grants to initial account', async function () { + expect(await this.votes.balanceOf(account1)).to.be.bignumber.equal('4'); + }); + }); + + describe('transfers', function () { + beforeEach(async function () { + await this.votes.mint(account1, this.NFT0); + }); + + it('no delegation', async function () { + const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); + expectEvent(receipt, 'Transfer', { from: account1, to: account2, tokenId: this.NFT0 }); + expectEvent.notEmitted(receipt, 'DelegateVotesChanged'); + + this.account1Votes = '0'; + this.account2Votes = '0'; + }); + + it('sender delegation', async function () { + await this.votes.delegate(account1, { from: account1 }); + + const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); + expectEvent(receipt, 'Transfer', { from: account1, to: account2, tokenId: this.NFT0 }); + expectEvent(receipt, 'DelegateVotesChanged', { delegate: account1, previousBalance: '1', newBalance: '0' }); + + const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); + expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); + + this.account1Votes = '0'; + this.account2Votes = '0'; + }); + + it('receiver delegation', async function () { + await this.votes.delegate(account2, { from: account2 }); + + const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); + expectEvent(receipt, 'Transfer', { from: account1, to: account2, tokenId: this.NFT0 }); + expectEvent(receipt, 'DelegateVotesChanged', { delegate: account2, previousBalance: '0', newBalance: '1' }); + + const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); + expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); + + this.account1Votes = '0'; + this.account2Votes = '1'; + }); + + it('full delegation', async function () { + await this.votes.delegate(account1, { from: account1 }); + await this.votes.delegate(account2, { from: account2 }); + + const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); + expectEvent(receipt, 'Transfer', { from: account1, to: account2, tokenId: this.NFT0 }); + expectEvent(receipt, 'DelegateVotesChanged', { delegate: account1, previousBalance: '1', newBalance: '0'}); + expectEvent(receipt, 'DelegateVotesChanged', { delegate: account2, previousBalance: '0', newBalance: '1' }); + + const { logIndex: transferLogIndex } = receipt.logs.find(({ event }) => event == 'Transfer'); + expect(receipt.logs.filter(({ event }) => event == 'DelegateVotesChanged').every(({ logIndex }) => transferLogIndex < logIndex)).to.be.equal(true); + + this.account1Votes = '0'; + this.account2Votes = '1'; + }); + + it('returns the same total supply on transfers', async function () { + await this.votes.delegate(account1, { from: account1 }); + + const { receipt } = await this.votes.transferFrom(account1, account2, this.NFT0, { from: account1 }); + + await time.advanceBlock(); + await time.advanceBlock(); + + expect(await this.votes.getPastTotalSupply(receipt.blockNumber - 1)).to.be.bignumber.equal('1'); + expect(await this.votes.getPastTotalSupply(receipt.blockNumber + 1)).to.be.bignumber.equal('1'); + + this.account1Votes = '0'; + this.account2Votes = '0'; + }); + + it('generally returns the voting balance at the appropriate checkpoint', async function () { + await this.votes.mint(account1, this.NFT1); + await this.votes.mint(account1, this.NFT2); + await this.votes.mint(account1, this.NFT3); + + const total = await this.votes.balanceOf(account1); + + const t1 = await this.votes.delegate(other1, { from: account1 }); + await time.advanceBlock(); + await time.advanceBlock(); + const t2 = await this.votes.transferFrom(account1, other2, this.NFT0, { from: account1 }); + await time.advanceBlock(); + await time.advanceBlock(); + const t3 = await this.votes.transferFrom(account1, other2, this.NFT2, { from: account1 }); + await time.advanceBlock(); + await time.advanceBlock(); + const t4 = await this.votes.transferFrom(other2, account1, this.NFT2, { from: other2 }); + await time.advanceBlock(); + await time.advanceBlock(); + + expect(await this.votes.getPastVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); + expect(await this.votes.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal(total); + expect(await this.votes.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal(total); + expect(await this.votes.getPastVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('3'); + expect(await this.votes.getPastVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal('3'); + expect(await this.votes.getPastVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('2'); + expect(await this.votes.getPastVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal('2'); + expect(await this.votes.getPastVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('3'); + expect(await this.votes.getPastVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal('3'); + + this.account1Votes = '0'; + this.account2Votes = '0'; + }); + + afterEach(async function () { + expect(await this.votes.getVotes(account1)).to.be.bignumber.equal(this.account1Votes); + expect(await this.votes.getVotes(account2)).to.be.bignumber.equal(this.account2Votes); + + // need to advance 2 blocks to see the effect of a transfer on "getPastVotes" + const blockNumber = await time.latestBlock(); + await time.advanceBlock(); + expect(await this.votes.getPastVotes(account1, blockNumber)).to.be.bignumber.equal(this.account1Votes); + expect(await this.votes.getPastVotes(account2, blockNumber)).to.be.bignumber.equal(this.account2Votes); + }); + }); + + describe('Voting workflow', function () { + beforeEach(async function () { + this.account1 = account1; + this.account1Delegatee = account1Delegatee; + this.account2 = account2; + this.name = 'My Vote'; + }); + + shouldBehaveLikeVotes(); + }); +}); diff --git a/test/utils/Checkpoints.test.js b/test/utils/Checkpoints.test.js new file mode 100644 index 00000000000..37f9013ecc8 --- /dev/null +++ b/test/utils/Checkpoints.test.js @@ -0,0 +1,59 @@ +const { expectRevert, time } = require('@openzeppelin/test-helpers'); + +const { expect } = require('chai'); + +const CheckpointsImpl = artifacts.require('CheckpointsImpl'); + +contract('Checkpoints', function (accounts) { + beforeEach(async function () { + this.checkpoint = await CheckpointsImpl.new(); + }); + + describe('without checkpoints', function () { + it('returns zero as latest value', async function () { + expect(await this.checkpoint.latest()).to.be.bignumber.equal('0'); + }); + + it('returns zero as past value', async function () { + await time.advanceBlock(); + expect(await this.checkpoint.getAtBlock(await web3.eth.getBlockNumber() - 1)).to.be.bignumber.equal('0'); + }); + }); + + describe('with checkpoints', function () { + beforeEach('pushing checkpoints', async function () { + this.tx1 = await this.checkpoint.push(1); + this.tx2 = await this.checkpoint.push(2); + await time.advanceBlock(); + this.tx3 = await this.checkpoint.push(3); + await time.advanceBlock(); + await time.advanceBlock(); + }); + + it('returns latest value', async function () { + expect(await this.checkpoint.latest()).to.be.bignumber.equal('3'); + }); + + it('returns past values', async function () { + expect(await this.checkpoint.getAtBlock(this.tx1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); + expect(await this.checkpoint.getAtBlock(this.tx1.receipt.blockNumber)).to.be.bignumber.equal('1'); + expect(await this.checkpoint.getAtBlock(this.tx2.receipt.blockNumber)).to.be.bignumber.equal('2'); + // Block with no new checkpoints + expect(await this.checkpoint.getAtBlock(this.tx2.receipt.blockNumber + 1)).to.be.bignumber.equal('2'); + expect(await this.checkpoint.getAtBlock(this.tx3.receipt.blockNumber)).to.be.bignumber.equal('3'); + expect(await this.checkpoint.getAtBlock(this.tx3.receipt.blockNumber + 1)).to.be.bignumber.equal('3'); + }); + + it('reverts if block number >= current block', async function () { + await expectRevert( + this.checkpoint.getAtBlock(await web3.eth.getBlockNumber()), + 'Checkpoints: block not yet mined', + ); + + await expectRevert( + this.checkpoint.getAtBlock(await web3.eth.getBlockNumber() + 1), + 'Checkpoints: block not yet mined', + ); + }); + }); +});