Commit 763144a7 by github-actions

Transpile 87bb8135

parent 508b94a1
{
"overrides": [
{
"files": "*.sol",
"options": {
"printWidth": 120,
"explicitTypes": "always"
}
}
]
}
{ {
"extends": "solhint:recommended",
"rules": { "rules": {
"func-order": "off", "no-unused-vars": "error",
"mark-callable-contracts": "off",
"no-empty-blocks": "off",
"compiler-version": "off",
"private-vars-leading-underscore": "error", "private-vars-leading-underscore": "error",
"reason-string": "off", "const-name-snakecase": "error",
"func-visibility": ["error", { "ignoreConstructors": true }] "contract-name-camelcase": "error",
"event-name-camelcase": "error",
"func-name-mixedcase": "error",
"func-param-name-mixedcase": "error",
"modifier-name-mixedcase": "error",
"private-vars-leading-underscore": "error",
"var-name-mixedcase": "error",
"imports-on-top": "error"
} }
} }
...@@ -2,7 +2,8 @@ ...@@ -2,7 +2,8 @@
## Unreleased ## Unreleased
* `ERC20Votes`: add a new extension of the `ERC20` token with support for voting snapshots and delegation. This extension is compatible with Compound's `Comp` token interface. ([#2632](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2632)) * `ERC20Votes`: add a new extension of the `ERC20` token with support for voting snapshots and delegation. ([#2632](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2632))
* `ERC20VotesComp`: Variant of `ERC20Votes` that is compatible with Compound's `Comp` token interface but restricts supply to `uint96`. ([#2706](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2706))
* Enumerables: Improve gas cost of removal in `EnumerableSet` and `EnumerableMap`. * Enumerables: Improve gas cost of removal in `EnumerableSet` and `EnumerableMap`.
* Enumerables: Improve gas cost of lookup in `EnumerableSet` and `EnumerableMap`. * Enumerables: Improve gas cost of lookup in `EnumerableSet` and `EnumerableMap`.
* `Counter`: add a reset method. ([#2678](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2678)) * `Counter`: add a reset method. ([#2678](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2678))
......
...@@ -11,6 +11,7 @@ import "../proxy/utils/Initializable.sol"; ...@@ -11,6 +11,7 @@ import "../proxy/utils/Initializable.sol";
*/ */
interface IAccessControlEnumerableUpgradeable { interface IAccessControlEnumerableUpgradeable {
function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMemberCount(bytes32 role) external view returns (uint256);
} }
...@@ -29,14 +30,13 @@ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessCo ...@@ -29,14 +30,13 @@ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessCo
} }
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping (bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/** /**
* @dev See {IERC165-supportsInterface}. * @dev See {IERC165-supportsInterface}.
*/ */
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
|| super.supportsInterface(interfaceId);
} }
/** /**
......
...@@ -12,9 +12,13 @@ import "../proxy/utils/Initializable.sol"; ...@@ -12,9 +12,13 @@ import "../proxy/utils/Initializable.sol";
*/ */
interface IAccessControlUpgradeable { interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool); function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32); function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external; function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external;
} }
...@@ -66,11 +70,11 @@ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, ...@@ -66,11 +70,11 @@ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable,
function __AccessControl_init_unchained() internal initializer { function __AccessControl_init_unchained() internal initializer {
} }
struct RoleData { struct RoleData {
mapping (address => bool) members; mapping(address => bool) members;
bytes32 adminRole; bytes32 adminRole;
} }
mapping (bytes32 => RoleData) private _roles; mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
...@@ -120,8 +124,7 @@ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, ...@@ -120,8 +124,7 @@ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable,
* @dev See {IERC165-supportsInterface}. * @dev See {IERC165-supportsInterface}.
*/ */
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
|| super.supportsInterface(interfaceId);
} }
/** /**
...@@ -139,13 +142,17 @@ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, ...@@ -139,13 +142,17 @@ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable,
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/ */
function _checkRole(bytes32 role, address account) internal view { function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) { if (!hasRole(role, account)) {
revert(string(abi.encodePacked( revert(
string(
abi.encodePacked(
"AccessControl: account ", "AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20), StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ", " is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32) StringsUpgradeable.toHexString(uint256(role), 32)
))); )
)
);
} }
} }
......
...@@ -4,6 +4,7 @@ pragma solidity ^0.8.0; ...@@ -4,6 +4,7 @@ pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol"; import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
/** /**
* @dev Contract module which provides a basic access control mechanism, where * @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to * there is an account (an owner) that can be granted exclusive access to
......
...@@ -45,7 +45,6 @@ contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { ...@@ -45,7 +45,6 @@ contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable {
} }
function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer {
// solhint-disable-next-line max-line-length
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees"); require(payees.length > 0, "PaymentSplitter: no payees");
...@@ -63,7 +62,7 @@ contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { ...@@ -63,7 +62,7 @@ contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable {
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions]. * functions].
*/ */
receive () external payable virtual { receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value); emit PaymentReceived(_msgSender(), msg.value);
} }
...@@ -110,7 +109,7 @@ contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { ...@@ -110,7 +109,7 @@ contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable {
require(_shares[account] > 0, "PaymentSplitter: account has no shares"); require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + _totalReleased; uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = totalReceived * _shares[account] / _totalShares - _released[account]; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account];
require(payment != 0, "PaymentSplitter: account is not due payment"); require(payment != 0, "PaymentSplitter: account is not due payment");
......
...@@ -32,7 +32,15 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -32,7 +32,15 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
/** /**
* @dev Emitted when a call is scheduled as part of operation `id`. * @dev Emitted when a call is scheduled as part of operation `id`.
*/ */
event CallScheduled(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay); event CallScheduled(
bytes32 indexed id,
uint256 indexed index,
address target,
uint256 value,
bytes data,
bytes32 predecessor,
uint256 delay
);
/** /**
* @dev Emitted when a call is performed as part of operation `id`. * @dev Emitted when a call is performed as part of operation `id`.
...@@ -52,14 +60,22 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -52,14 +60,22 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
/** /**
* @dev Initializes the contract with a given `minDelay`. * @dev Initializes the contract with a given `minDelay`.
*/ */
function __TimelockController_init(uint256 minDelay, address[] memory proposers, address[] memory executors) internal initializer { function __TimelockController_init(
uint256 minDelay,
address[] memory proposers,
address[] memory executors
) internal initializer {
__Context_init_unchained(); __Context_init_unchained();
__ERC165_init_unchained(); __ERC165_init_unchained();
__AccessControl_init_unchained(); __AccessControl_init_unchained();
__TimelockController_init_unchained(minDelay, proposers, executors); __TimelockController_init_unchained(minDelay, proposers, executors);
} }
function __TimelockController_init_unchained(uint256 minDelay, address[] memory proposers, address[] memory executors) internal initializer { function __TimelockController_init_unchained(
uint256 minDelay,
address[] memory proposers,
address[] memory executors
) internal initializer {
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
...@@ -120,7 +136,6 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -120,7 +136,6 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
*/ */
function isOperationReady(bytes32 id) public view virtual returns (bool ready) { function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
uint256 timestamp = getTimestamp(id); uint256 timestamp = getTimestamp(id);
// solhint-disable-next-line not-rely-on-time
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
} }
...@@ -152,7 +167,13 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -152,7 +167,13 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
* @dev Returns the identifier of an operation containing a single * @dev Returns the identifier of an operation containing a single
* transaction. * transaction.
*/ */
function hashOperation(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) { function hashOperation(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(target, value, data, predecessor, salt)); return keccak256(abi.encode(target, value, data, predecessor, salt));
} }
...@@ -160,7 +181,13 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -160,7 +181,13 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
* @dev Returns the identifier of an operation containing a batch of * @dev Returns the identifier of an operation containing a batch of
* transactions. * transactions.
*/ */
function hashOperationBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) { function hashOperationBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(targets, values, datas, predecessor, salt)); return keccak256(abi.encode(targets, values, datas, predecessor, salt));
} }
...@@ -173,7 +200,14 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -173,7 +200,14 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
* *
* - the caller must have the 'proposer' role. * - the caller must have the 'proposer' role.
*/ */
function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { function schedule(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt); bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay); _schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay);
...@@ -188,7 +222,14 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -188,7 +222,14 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
* *
* - the caller must have the 'proposer' role. * - the caller must have the 'proposer' role.
*/ */
function scheduleBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { function scheduleBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch");
...@@ -205,7 +246,6 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -205,7 +246,6 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
function _schedule(bytes32 id, uint256 delay) private { function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled"); require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay"); require(delay >= getMinDelay(), "TimelockController: insufficient delay");
// solhint-disable-next-line not-rely-on-time
_timestamps[id] = block.timestamp + delay; _timestamps[id] = block.timestamp + delay;
} }
...@@ -232,7 +272,13 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -232,7 +272,13 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
* *
* - the caller must have the 'executor' role. * - the caller must have the 'executor' role.
*/ */
function execute(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt); bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(predecessor); _beforeCall(predecessor);
_call(id, 0, target, value, data); _call(id, 0, target, value, data);
...@@ -248,7 +294,13 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -248,7 +294,13 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
* *
* - the caller must have the 'executor' role. * - the caller must have the 'executor' role.
*/ */
function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch");
...@@ -280,9 +332,14 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl ...@@ -280,9 +332,14 @@ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeabl
* *
* Emits a {CallExecuted} event. * Emits a {CallExecuted} event.
*/ */
function _call(bytes32 id, uint256 index, address target, uint256 value, bytes calldata data) private { function _call(
// solhint-disable-next-line avoid-low-level-calls bytes32 id,
(bool success,) = target.call{value: value}(data); uint256 index,
address target,
uint256 value,
bytes calldata data
) private {
(bool success, ) = target.call{value: value}(data);
require(success, "TimelockController: underlying transaction reverted"); require(success, "TimelockController: underlying transaction reverted");
emit CallExecuted(id, index, target, value, data); emit CallExecuted(id, index, target, value, data);
......
...@@ -37,9 +37,7 @@ interface IERC3156FlashLenderUpgradeable { ...@@ -37,9 +37,7 @@ interface IERC3156FlashLenderUpgradeable {
* @param token The loan currency. * @param token The loan currency.
* @return The amount of `token` that can be borrowed. * @return The amount of `token` that can be borrowed.
*/ */
function maxFlashLoan( function maxFlashLoan(address token) external view returns (uint256);
address token
) external view returns (uint256);
/** /**
* @dev The fee to be charged for a given loan. * @dev The fee to be charged for a given loan.
...@@ -47,10 +45,7 @@ interface IERC3156FlashLenderUpgradeable { ...@@ -47,10 +45,7 @@ interface IERC3156FlashLenderUpgradeable {
* @param amount The amount of tokens lent. * @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal. * @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/ */
function flashFee( function flashFee(address token, uint256 amount) external view returns (uint256);
address token,
uint256 amount
) external view returns (uint256);
/** /**
* @dev Initiate a flash loan. * @dev Initiate a flash loan.
...@@ -65,4 +60,4 @@ interface IERC3156FlashLenderUpgradeable { ...@@ -65,4 +60,4 @@ interface IERC3156FlashLenderUpgradeable {
uint256 amount, uint256 amount,
bytes calldata data bytes calldata data
) external returns (bool); ) external returns (bool);
} }
...@@ -20,14 +20,16 @@ abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable ...@@ -20,14 +20,16 @@ abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable
_trustedForwarder = trustedForwarder; _trustedForwarder = trustedForwarder;
} }
function isTrustedForwarder(address forwarder) public view virtual returns(bool) { function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return forwarder == _trustedForwarder; return forwarder == _trustedForwarder;
} }
function _msgSender() internal view virtual override returns (address sender) { function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) { if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`. // The assembly code is more direct than the Solidity version using `abi.decode`.
assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else { } else {
return super._msgSender(); return super._msgSender();
} }
...@@ -35,7 +37,7 @@ abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable ...@@ -35,7 +37,7 @@ abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable
function _msgData() internal view virtual override returns (bytes calldata) { function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) { if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length-20]; return msg.data[:msg.data.length - 20];
} else { } else {
return super._msgData(); return super._msgData();
} }
......
...@@ -21,7 +21,8 @@ contract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable { ...@@ -21,7 +21,8 @@ contract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {
bytes data; bytes data;
} }
bytes32 private constant TYPEHASH = keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)"); bytes32 private constant _TYPEHASH =
keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)");
mapping(address => uint256) private _nonces; mapping(address => uint256) private _nonces;
...@@ -37,24 +38,23 @@ contract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable { ...@@ -37,24 +38,23 @@ contract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {
} }
function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) { function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {
address signer = _hashTypedDataV4(keccak256(abi.encode( address signer = _hashTypedDataV4(
TYPEHASH, keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))
req.from, ).recover(signature);
req.to,
req.value,
req.gas,
req.nonce,
keccak256(req.data)
))).recover(signature);
return _nonces[req.from] == req.nonce && signer == req.from; return _nonces[req.from] == req.nonce && signer == req.from;
} }
function execute(ForwardRequest calldata req, bytes calldata signature) public payable returns (bool, bytes memory) { function execute(ForwardRequest calldata req, bytes calldata signature)
public
payable
returns (bool, bytes memory)
{
require(verify(req, signature), "MinimalForwarder: signature does not match request"); require(verify(req, signature), "MinimalForwarder: signature does not match request");
_nonces[req.from] = req.nonce + 1; _nonces[req.from] = req.nonce + 1;
// solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(
(bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(abi.encodePacked(req.data, req.from)); abi.encodePacked(req.data, req.from)
);
// Validate that the relayer has sent enough gas for the call. // Validate that the relayer has sent enough gas for the call.
// See https://ronan.eth.link/blog/ethereum-gas-dangers/ // See https://ronan.eth.link/blog/ethereum-gas-dangers/
assert(gasleft() > req.gas / 63); assert(gasleft() > req.gas / 63);
......
...@@ -29,7 +29,11 @@ contract AddressImplUpgradeable is Initializable { ...@@ -29,7 +29,11 @@ contract AddressImplUpgradeable is Initializable {
emit CallReturnValue(abi.decode(returnData, (string))); emit CallReturnValue(abi.decode(returnData, (string)));
} }
function functionCallWithValue(address target, bytes calldata data, uint256 value) external payable { function functionCallWithValue(
address target,
bytes calldata data,
uint256 value
) external payable {
bytes memory returnData = AddressUpgradeable.functionCallWithValue(target, data, value); bytes memory returnData = AddressUpgradeable.functionCallWithValue(target, data, value);
emit CallReturnValue(abi.decode(returnData, (string))); emit CallReturnValue(abi.decode(returnData, (string)));
} }
...@@ -40,6 +44,6 @@ contract AddressImplUpgradeable is Initializable { ...@@ -40,6 +44,6 @@ contract AddressImplUpgradeable is Initializable {
} }
// sendValue's tests require the contract to hold Ether // sendValue's tests require the contract to hold Ether
receive () external payable { } receive() external payable {}
uint256[49] private __gap; uint256[49] private __gap;
} }
...@@ -3,8 +3,7 @@ ...@@ -3,8 +3,7 @@
pragma solidity ^0.8.0; pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
contract BadBeaconNoImplUpgradeable is Initializable { contract BadBeaconNoImplUpgradeable is Initializable { function __BadBeaconNoImpl_init() internal initializer {
function __BadBeaconNoImpl_init() internal initializer {
__BadBeaconNoImpl_init_unchained(); __BadBeaconNoImpl_init_unchained();
} }
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
pragma solidity ^0.8.0; pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
/** /**
* @dev Implementation contract with an admin() function made to clash with * @dev Implementation contract with an admin() function made to clash with
* @dev TransparentUpgradeableProxy's to test correct functioning of the * @dev TransparentUpgradeableProxy's to test correct functioning of the
...@@ -16,7 +15,6 @@ contract ClashingImplementationUpgradeable is Initializable { ...@@ -16,7 +15,6 @@ contract ClashingImplementationUpgradeable is Initializable {
function __ClashingImplementation_init_unchained() internal initializer { function __ClashingImplementation_init_unchained() internal initializer {
} }
function admin() external pure returns (address) { function admin() external pure returns (address) {
return 0x0000000000000000000000000000000011111142; return 0x0000000000000000000000000000000011111142;
} }
......
...@@ -22,7 +22,11 @@ contract ClonesMockUpgradeable is Initializable { ...@@ -22,7 +22,11 @@ contract ClonesMockUpgradeable is Initializable {
_initAndEmit(implementation.clone(), initdata); _initAndEmit(implementation.clone(), initdata);
} }
function cloneDeterministic(address implementation, bytes32 salt, bytes calldata initdata) public payable { function cloneDeterministic(
address implementation,
bytes32 salt,
bytes calldata initdata
) public payable {
_initAndEmit(implementation.cloneDeterministic(salt), initdata); _initAndEmit(implementation.cloneDeterministic(salt), initdata);
} }
......
...@@ -38,7 +38,11 @@ contract ContextMockCallerUpgradeable is Initializable { ...@@ -38,7 +38,11 @@ contract ContextMockCallerUpgradeable is Initializable {
context.msgSender(); context.msgSender();
} }
function callData(ContextMockUpgradeable context, uint256 integerValue, string memory stringValue) public { function callData(
ContextMockUpgradeable context,
uint256 integerValue,
string memory stringValue
) public {
context.msgData(integerValue, stringValue); context.msgData(integerValue, stringValue);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -13,12 +13,15 @@ contract Create2ImplUpgradeable is Initializable { ...@@ -13,12 +13,15 @@ contract Create2ImplUpgradeable is Initializable {
function __Create2Impl_init_unchained() internal initializer { function __Create2Impl_init_unchained() internal initializer {
} }
function deploy(uint256 value, bytes32 salt, bytes memory code) public { function deploy(
uint256 value,
bytes32 salt,
bytes memory code
) public {
Create2Upgradeable.deploy(value, salt, code); Create2Upgradeable.deploy(value, salt, code);
} }
function deployERC1820Implementer(uint256 value, bytes32 salt) public { function deployERC1820Implementer(uint256 value, bytes32 salt) public {
// solhint-disable-next-line indent
Create2Upgradeable.deploy(value, salt, type(ERC1820ImplementerUpgradeable).creationCode); Create2Upgradeable.deploy(value, salt, type(ERC1820ImplementerUpgradeable).creationCode);
} }
...@@ -26,7 +29,11 @@ contract Create2ImplUpgradeable is Initializable { ...@@ -26,7 +29,11 @@ contract Create2ImplUpgradeable is Initializable {
return Create2Upgradeable.computeAddress(salt, codeHash); return Create2Upgradeable.computeAddress(salt, codeHash);
} }
function computeAddressWithDeployer(bytes32 salt, bytes32 codeHash, address deployer) public pure returns (address) { function computeAddressWithDeployer(
bytes32 salt,
bytes32 codeHash,
address deployer
) public pure returns (address) {
return Create2Upgradeable.computeAddress(salt, codeHash, deployer); return Create2Upgradeable.computeAddress(salt, codeHash, deployer);
} }
......
...@@ -41,7 +41,11 @@ contract DummyImplementationUpgradeable is Initializable { ...@@ -41,7 +41,11 @@ contract DummyImplementationUpgradeable is Initializable {
value = _value; value = _value;
} }
function initialize(uint256 _value, string memory _text, uint256[] memory _values) public { function initialize(
uint256 _value,
string memory _text,
uint256[] memory _values
) public {
value = _value; value = _value;
text = _text; text = _text;
values = _values; values = _values;
......
...@@ -18,12 +18,15 @@ contract EIP712ExternalUpgradeable is Initializable, EIP712Upgradeable { ...@@ -18,12 +18,15 @@ contract EIP712ExternalUpgradeable is Initializable, EIP712Upgradeable {
return _domainSeparatorV4(); return _domainSeparatorV4();
} }
function verify(bytes memory signature, address signer, address mailTo, string memory mailContents) external view { function verify(
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( bytes memory signature,
keccak256("Mail(address to,string contents)"), address signer,
mailTo, address mailTo,
keccak256(bytes(mailContents)) string memory mailContents
))); ) external view {
bytes32 digest = _hashTypedDataV4(
keccak256(abi.encode(keccak256("Mail(address to,string contents)"), mailTo, keccak256(bytes(mailContents))))
);
address recoveredSigner = ECDSAUpgradeable.recover(digest, signature); address recoveredSigner = ECDSAUpgradeable.recover(digest, signature);
require(recoveredSigner == signer); require(recoveredSigner == signer);
} }
......
...@@ -14,9 +14,14 @@ contract ERC1155BurnableMockUpgradeable is Initializable, ERC1155BurnableUpgrade ...@@ -14,9 +14,14 @@ contract ERC1155BurnableMockUpgradeable is Initializable, ERC1155BurnableUpgrade
__ERC1155BurnableMock_init_unchained(uri); __ERC1155BurnableMock_init_unchained(uri);
} }
function __ERC1155BurnableMock_init_unchained(string memory uri) internal initializer { } function __ERC1155BurnableMock_init_unchained(string memory uri) internal initializer {}
function mint(address to, uint256 id, uint256 value, bytes memory data) public { function mint(
address to,
uint256 id,
uint256 value,
bytes memory data
) public {
_mint(to, id, value, data); _mint(to, id, value, data);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -17,27 +17,43 @@ contract ERC1155MockUpgradeable is Initializable, ERC1155Upgradeable { ...@@ -17,27 +17,43 @@ contract ERC1155MockUpgradeable is Initializable, ERC1155Upgradeable {
__ERC1155Mock_init_unchained(uri); __ERC1155Mock_init_unchained(uri);
} }
function __ERC1155Mock_init_unchained(string memory uri) internal initializer { function __ERC1155Mock_init_unchained(string memory uri) internal initializer {}
// solhint-disable-previous-line no-empty-blocks
}
function setURI(string memory newuri) public { function setURI(string memory newuri) public {
_setURI(newuri); _setURI(newuri);
} }
function mint(address to, uint256 id, uint256 value, bytes memory data) public { function mint(
address to,
uint256 id,
uint256 value,
bytes memory data
) public {
_mint(to, id, value, data); _mint(to, id, value, data);
} }
function mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) public { function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public {
_mintBatch(to, ids, values, data); _mintBatch(to, ids, values, data);
} }
function burn(address owner, uint256 id, uint256 value) public { function burn(
address owner,
uint256 id,
uint256 value
) public {
_burn(owner, id, value); _burn(owner, id, value);
} }
function burnBatch(address owner, uint256[] memory ids, uint256[] memory values) public { function burnBatch(
address owner,
uint256[] memory ids,
uint256[] memory values
) public {
_burnBatch(owner, ids, values); _burnBatch(owner, ids, values);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -17,7 +17,7 @@ contract ERC1155PausableMockUpgradeable is Initializable, ERC1155MockUpgradeable ...@@ -17,7 +17,7 @@ contract ERC1155PausableMockUpgradeable is Initializable, ERC1155MockUpgradeable
__ERC1155PausableMock_init_unchained(uri); __ERC1155PausableMock_init_unchained(uri);
} }
function __ERC1155PausableMock_init_unchained(string memory uri) internal initializer { } function __ERC1155PausableMock_init_unchained(string memory uri) internal initializer {}
function pause() external { function pause() external {
_pause(); _pause();
...@@ -34,9 +34,7 @@ contract ERC1155PausableMockUpgradeable is Initializable, ERC1155MockUpgradeable ...@@ -34,9 +34,7 @@ contract ERC1155PausableMockUpgradeable is Initializable, ERC1155MockUpgradeable
uint256[] memory ids, uint256[] memory ids,
uint256[] memory amounts, uint256[] memory amounts,
bytes memory data bytes memory data
) ) internal virtual override(ERC1155Upgradeable, ERC1155PausableUpgradeable) {
internal virtual override(ERC1155Upgradeable, ERC1155PausableUpgradeable)
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data); super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -43,11 +43,7 @@ contract ERC1155ReceiverMockUpgradeable is Initializable, IERC1155ReceiverUpgrad ...@@ -43,11 +43,7 @@ contract ERC1155ReceiverMockUpgradeable is Initializable, IERC1155ReceiverUpgrad
uint256 id, uint256 id,
uint256 value, uint256 value,
bytes calldata data bytes calldata data
) ) external override returns (bytes4) {
external
override
returns(bytes4)
{
require(!_recReverts, "ERC1155ReceiverMock: reverting on receive"); require(!_recReverts, "ERC1155ReceiverMock: reverting on receive");
emit Received(operator, from, id, value, data, gasleft()); emit Received(operator, from, id, value, data, gasleft());
return _recRetval; return _recRetval;
...@@ -59,11 +55,7 @@ contract ERC1155ReceiverMockUpgradeable is Initializable, IERC1155ReceiverUpgrad ...@@ -59,11 +55,7 @@ contract ERC1155ReceiverMockUpgradeable is Initializable, IERC1155ReceiverUpgrad
uint256[] calldata ids, uint256[] calldata ids,
uint256[] calldata values, uint256[] calldata values,
bytes calldata data bytes calldata data
) ) external override returns (bytes4) {
external
override
returns(bytes4)
{
require(!_batReverts, "ERC1155ReceiverMock: reverting on batch receive"); require(!_batReverts, "ERC1155ReceiverMock: reverting on batch receive");
emit BatchReceived(operator, from, ids, values, data, gasleft()); emit BatchReceived(operator, from, ids, values, data, gasleft());
return _batRetval; return _batRetval;
......
...@@ -16,21 +16,39 @@ contract ERC1155SupplyMockUpgradeable is Initializable, ERC1155MockUpgradeable, ...@@ -16,21 +16,39 @@ contract ERC1155SupplyMockUpgradeable is Initializable, ERC1155MockUpgradeable,
__ERC1155SupplyMock_init_unchained(uri); __ERC1155SupplyMock_init_unchained(uri);
} }
function __ERC1155SupplyMock_init_unchained(string memory uri) internal initializer { } function __ERC1155SupplyMock_init_unchained(string memory uri) internal initializer {}
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual override(ERC1155Upgradeable, ERC1155SupplyUpgradeable) { function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual override(ERC1155Upgradeable, ERC1155SupplyUpgradeable) {
super._mint(account, id, amount, data); super._mint(account, id, amount, data);
} }
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual override(ERC1155Upgradeable, ERC1155SupplyUpgradeable) { function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override(ERC1155Upgradeable, ERC1155SupplyUpgradeable) {
super._mintBatch(to, ids, amounts, data); super._mintBatch(to, ids, amounts, data);
} }
function _burn(address account, uint256 id, uint256 amount) internal virtual override(ERC1155Upgradeable, ERC1155SupplyUpgradeable) { function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual override(ERC1155Upgradeable, ERC1155SupplyUpgradeable) {
super._burn(account, id, amount); super._burn(account, id, amount);
} }
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual override(ERC1155Upgradeable, ERC1155SupplyUpgradeable) { function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual override(ERC1155Upgradeable, ERC1155SupplyUpgradeable) {
super._burnBatch(account, ids, amounts); super._burnBatch(account, ids, amounts);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -5,8 +5,7 @@ pragma solidity ^0.8.0; ...@@ -5,8 +5,7 @@ pragma solidity ^0.8.0;
import "../utils/introspection/ERC165Upgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
contract ERC165MockUpgradeable is Initializable, ERC165Upgradeable { contract ERC165MockUpgradeable is Initializable, ERC165Upgradeable { function __ERC165Mock_init() internal initializer {
function __ERC165Mock_init() internal initializer {
__ERC165_init_unchained(); __ERC165_init_unchained();
__ERC165Mock_init_unchained(); __ERC165Mock_init_unchained();
} }
......
...@@ -6,14 +6,22 @@ import "../token/ERC20/extensions/ERC20CappedUpgradeable.sol"; ...@@ -6,14 +6,22 @@ import "../token/ERC20/extensions/ERC20CappedUpgradeable.sol";
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
contract ERC20CappedMockUpgradeable is Initializable, ERC20CappedUpgradeable { contract ERC20CappedMockUpgradeable is Initializable, ERC20CappedUpgradeable {
function __ERC20CappedMock_init(string memory name, string memory symbol, uint256 cap) internal initializer { function __ERC20CappedMock_init(
string memory name,
string memory symbol,
uint256 cap
) internal initializer {
__Context_init_unchained(); __Context_init_unchained();
__ERC20_init_unchained(name, symbol); __ERC20_init_unchained(name, symbol);
__ERC20Capped_init_unchained(cap); __ERC20Capped_init_unchained(cap);
__ERC20CappedMock_init_unchained(name, symbol, cap); __ERC20CappedMock_init_unchained(name, symbol, cap);
} }
function __ERC20CappedMock_init_unchained(string memory name, string memory symbol, uint256 cap) internal initializer { } function __ERC20CappedMock_init_unchained(
string memory name,
string memory symbol,
uint256 cap
) internal initializer {}
function mint(address to, uint256 tokenId) public { function mint(address to, uint256 tokenId) public {
_mint(to, tokenId); _mint(to, tokenId);
......
...@@ -8,13 +8,21 @@ import "../proxy/utils/Initializable.sol"; ...@@ -8,13 +8,21 @@ import "../proxy/utils/Initializable.sol";
contract ERC20DecimalsMockUpgradeable is Initializable, ERC20Upgradeable { contract ERC20DecimalsMockUpgradeable is Initializable, ERC20Upgradeable {
uint8 private _decimals; uint8 private _decimals;
function __ERC20DecimalsMock_init(string memory name_, string memory symbol_, uint8 decimals_) internal initializer { function __ERC20DecimalsMock_init(
string memory name_,
string memory symbol_,
uint8 decimals_
) internal initializer {
__Context_init_unchained(); __Context_init_unchained();
__ERC20_init_unchained(name_, symbol_); __ERC20_init_unchained(name_, symbol_);
__ERC20DecimalsMock_init_unchained(name_, symbol_, decimals_); __ERC20DecimalsMock_init_unchained(name_, symbol_, decimals_);
} }
function __ERC20DecimalsMock_init_unchained(string memory name_, string memory symbol_, uint8 decimals_) internal initializer { function __ERC20DecimalsMock_init_unchained(
string memory name_,
string memory symbol_,
uint8 decimals_
) internal initializer {
_decimals = decimals_; _decimals = decimals_;
} }
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
pragma solidity ^0.8.0; pragma solidity ^0.8.0;
import "../token/ERC20/extensions/ERC20FlashMintUpgradeable.sol"; import "../token/ERC20/extensions/ERC20FlashMintUpgradeable.sol";
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
......
...@@ -35,11 +35,19 @@ contract ERC20MockUpgradeable is Initializable, ERC20Upgradeable { ...@@ -35,11 +35,19 @@ contract ERC20MockUpgradeable is Initializable, ERC20Upgradeable {
_burn(account, amount); _burn(account, amount);
} }
function transferInternal(address from, address to, uint256 value) public { function transferInternal(
address from,
address to,
uint256 value
) public {
_transfer(from, to, value); _transfer(from, to, value);
} }
function approveInternal(address owner, address spender, uint256 value) public { function approveInternal(
address owner,
address spender,
uint256 value
) public {
_approve(owner, spender, value); _approve(owner, spender, value);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
pragma solidity ^0.8.0; pragma solidity ^0.8.0;
import "../token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol"; import "../token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol";
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
......
...@@ -5,7 +5,6 @@ pragma solidity ^0.8.0; ...@@ -5,7 +5,6 @@ pragma solidity ^0.8.0;
import "../token/ERC20/extensions/ERC20SnapshotUpgradeable.sol"; import "../token/ERC20/extensions/ERC20SnapshotUpgradeable.sol";
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
contract ERC20SnapshotMockUpgradeable is Initializable, ERC20SnapshotUpgradeable { contract ERC20SnapshotMockUpgradeable is Initializable, ERC20SnapshotUpgradeable {
function __ERC20SnapshotMock_init( function __ERC20SnapshotMock_init(
string memory name, string memory name,
......
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/extensions/ERC20VotesCompUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC20VotesCompMockUpgradeable is Initializable, ERC20VotesCompUpgradeable {
function __ERC20VotesCompMock_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
__ERC20Votes_init_unchained();
__ERC20VotesComp_init_unchained();
__ERC20VotesCompMock_init_unchained(name, symbol);
}
function __ERC20VotesCompMock_init_unchained(string memory name, string memory symbol) internal initializer {}
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
function burn(address account, uint256 amount) public {
_burn(account, amount);
}
function getChainId() external view returns (uint256) {
return block.chainid;
}
uint256[50] private __gap;
}
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
pragma solidity ^0.8.0; pragma solidity ^0.8.0;
import "../token/ERC20/extensions/ERC20VotesUpgradeable.sol"; import "../token/ERC20/extensions/ERC20VotesUpgradeable.sol";
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
......
...@@ -17,11 +17,11 @@ contract ERC2771ContextMockUpgradeable is Initializable, ContextMockUpgradeable, ...@@ -17,11 +17,11 @@ contract ERC2771ContextMockUpgradeable is Initializable, ContextMockUpgradeable,
function __ERC2771ContextMock_init_unchained(address trustedForwarder) internal initializer {} function __ERC2771ContextMock_init_unchained(address trustedForwarder) internal initializer {}
function _msgSender() internal override(ContextUpgradeable, ERC2771ContextUpgradeable) view virtual returns (address) { function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address) {
return ERC2771ContextUpgradeable._msgSender(); return ERC2771ContextUpgradeable._msgSender();
} }
function _msgData() internal override(ContextUpgradeable, ERC2771ContextUpgradeable) view virtual returns (bytes calldata) { function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) {
return ERC2771ContextUpgradeable._msgData(); return ERC2771ContextUpgradeable._msgData();
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
pragma solidity ^0.8.0; pragma solidity ^0.8.0;
import "../token/ERC20/IERC20Upgradeable.sol"; import "../token/ERC20/IERC20Upgradeable.sol";
import "../interfaces/IERC3156Upgradeable.sol"; import "../interfaces/IERC3156Upgradeable.sol";
import "../utils/AddressUpgradeable.sol"; import "../utils/AddressUpgradeable.sol";
...@@ -16,7 +15,7 @@ import "../proxy/utils/Initializable.sol"; ...@@ -16,7 +15,7 @@ import "../proxy/utils/Initializable.sol";
* live networks. * live networks.
*/ */
contract ERC3156FlashBorrowerMockUpgradeable is Initializable, IERC3156FlashBorrowerUpgradeable { contract ERC3156FlashBorrowerMockUpgradeable is Initializable, IERC3156FlashBorrowerUpgradeable {
bytes32 constant internal RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); bytes32 internal constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
bool _enableApprove; bool _enableApprove;
bool _enableReturn; bool _enableReturn;
...@@ -34,7 +33,7 @@ contract ERC3156FlashBorrowerMockUpgradeable is Initializable, IERC3156FlashBorr ...@@ -34,7 +33,7 @@ contract ERC3156FlashBorrowerMockUpgradeable is Initializable, IERC3156FlashBorr
} }
function onFlashLoan( function onFlashLoan(
address /*initiator*/, address, /*initiator*/
address token, address token,
uint256 amount, uint256 amount,
uint256 fee, uint256 fee,
...@@ -54,7 +53,7 @@ contract ERC3156FlashBorrowerMockUpgradeable is Initializable, IERC3156FlashBorr ...@@ -54,7 +53,7 @@ contract ERC3156FlashBorrowerMockUpgradeable is Initializable, IERC3156FlashBorr
IERC20Upgradeable(token).approve(token, amount + fee); IERC20Upgradeable(token).approve(token, amount + fee);
} }
return _enableReturn ? RETURN_VALUE : bytes32(0); return _enableReturn ? _RETURN_VALUE : bytes32(0);
} }
uint256[50] private __gap; uint256[50] private __gap;
} }
...@@ -14,7 +14,7 @@ contract ERC721BurnableMockUpgradeable is Initializable, ERC721BurnableUpgradeab ...@@ -14,7 +14,7 @@ contract ERC721BurnableMockUpgradeable is Initializable, ERC721BurnableUpgradeab
__ERC721BurnableMock_init_unchained(name, symbol); __ERC721BurnableMock_init_unchained(name, symbol);
} }
function __ERC721BurnableMock_init_unchained(string memory name, string memory symbol) internal initializer { } function __ERC721BurnableMock_init_unchained(string memory name, string memory symbol) internal initializer {}
function exists(uint256 tokenId) public view returns (bool) { function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId); return _exists(tokenId);
...@@ -28,7 +28,11 @@ contract ERC721BurnableMockUpgradeable is Initializable, ERC721BurnableUpgradeab ...@@ -28,7 +28,11 @@ contract ERC721BurnableMockUpgradeable is Initializable, ERC721BurnableUpgradeab
_safeMint(to, tokenId); _safeMint(to, tokenId);
} }
function safeMint(address to, uint256 tokenId, bytes memory _data) public { function safeMint(
address to,
uint256 tokenId,
bytes memory _data
) public {
_safeMint(to, tokenId, _data); _safeMint(to, tokenId, _data);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -20,7 +20,7 @@ contract ERC721EnumerableMockUpgradeable is Initializable, ERC721EnumerableUpgra ...@@ -20,7 +20,7 @@ contract ERC721EnumerableMockUpgradeable is Initializable, ERC721EnumerableUpgra
__ERC721EnumerableMock_init_unchained(name, symbol); __ERC721EnumerableMock_init_unchained(name, symbol);
} }
function __ERC721EnumerableMock_init_unchained(string memory name, string memory symbol) internal initializer { } function __ERC721EnumerableMock_init_unchained(string memory name, string memory symbol) internal initializer {}
function _baseURI() internal view virtual override returns (string memory) { function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI; return _baseTokenURI;
...@@ -46,7 +46,11 @@ contract ERC721EnumerableMockUpgradeable is Initializable, ERC721EnumerableUpgra ...@@ -46,7 +46,11 @@ contract ERC721EnumerableMockUpgradeable is Initializable, ERC721EnumerableUpgra
_safeMint(to, tokenId); _safeMint(to, tokenId);
} }
function safeMint(address to, uint256 tokenId, bytes memory _data) public { function safeMint(
address to,
uint256 tokenId,
bytes memory _data
) public {
_safeMint(to, tokenId, _data); _safeMint(to, tokenId, _data);
} }
......
...@@ -17,7 +17,7 @@ contract ERC721MockUpgradeable is Initializable, ERC721Upgradeable { ...@@ -17,7 +17,7 @@ contract ERC721MockUpgradeable is Initializable, ERC721Upgradeable {
__ERC721Mock_init_unchained(name, symbol); __ERC721Mock_init_unchained(name, symbol);
} }
function __ERC721Mock_init_unchained(string memory name, string memory symbol) internal initializer { } function __ERC721Mock_init_unchained(string memory name, string memory symbol) internal initializer {}
function baseURI() public view returns (string memory) { function baseURI() public view returns (string memory) {
return _baseURI(); return _baseURI();
...@@ -35,7 +35,11 @@ contract ERC721MockUpgradeable is Initializable, ERC721Upgradeable { ...@@ -35,7 +35,11 @@ contract ERC721MockUpgradeable is Initializable, ERC721Upgradeable {
_safeMint(to, tokenId); _safeMint(to, tokenId);
} }
function safeMint(address to, uint256 tokenId, bytes memory _data) public { function safeMint(
address to,
uint256 tokenId,
bytes memory _data
) public {
_safeMint(to, tokenId, _data); _safeMint(to, tokenId, _data);
} }
......
...@@ -19,7 +19,7 @@ contract ERC721PausableMockUpgradeable is Initializable, ERC721PausableUpgradeab ...@@ -19,7 +19,7 @@ contract ERC721PausableMockUpgradeable is Initializable, ERC721PausableUpgradeab
__ERC721PausableMock_init_unchained(name, symbol); __ERC721PausableMock_init_unchained(name, symbol);
} }
function __ERC721PausableMock_init_unchained(string memory name, string memory symbol) internal initializer { } function __ERC721PausableMock_init_unchained(string memory name, string memory symbol) internal initializer {}
function pause() external { function pause() external {
_pause(); _pause();
...@@ -41,7 +41,11 @@ contract ERC721PausableMockUpgradeable is Initializable, ERC721PausableUpgradeab ...@@ -41,7 +41,11 @@ contract ERC721PausableMockUpgradeable is Initializable, ERC721PausableUpgradeab
_safeMint(to, tokenId); _safeMint(to, tokenId);
} }
function safeMint(address to, uint256 tokenId, bytes memory _data) public { function safeMint(
address to,
uint256 tokenId,
bytes memory _data
) public {
_safeMint(to, tokenId, _data); _safeMint(to, tokenId, _data);
} }
......
...@@ -27,9 +27,12 @@ contract ERC721ReceiverMockUpgradeable is Initializable, IERC721ReceiverUpgradea ...@@ -27,9 +27,12 @@ contract ERC721ReceiverMockUpgradeable is Initializable, IERC721ReceiverUpgradea
_error = error; _error = error;
} }
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) function onERC721Received(
public override returns (bytes4) address operator,
{ address from,
uint256 tokenId,
bytes memory data
) public override returns (bytes4) {
if (_error == Error.RevertWithMessage) { if (_error == Error.RevertWithMessage) {
revert("ERC721ReceiverMock: reverting"); revert("ERC721ReceiverMock: reverting");
} else if (_error == Error.RevertWithoutMessage) { } else if (_error == Error.RevertWithoutMessage) {
......
...@@ -20,7 +20,7 @@ contract ERC721URIStorageMockUpgradeable is Initializable, ERC721URIStorageUpgra ...@@ -20,7 +20,7 @@ contract ERC721URIStorageMockUpgradeable is Initializable, ERC721URIStorageUpgra
__ERC721URIStorageMock_init_unchained(name, symbol); __ERC721URIStorageMock_init_unchained(name, symbol);
} }
function __ERC721URIStorageMock_init_unchained(string memory name, string memory symbol) internal initializer { } function __ERC721URIStorageMock_init_unchained(string memory name, string memory symbol) internal initializer {}
function _baseURI() internal view virtual override returns (string memory) { function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI; return _baseTokenURI;
...@@ -50,7 +50,11 @@ contract ERC721URIStorageMockUpgradeable is Initializable, ERC721URIStorageUpgra ...@@ -50,7 +50,11 @@ contract ERC721URIStorageMockUpgradeable is Initializable, ERC721URIStorageUpgra
_safeMint(to, tokenId); _safeMint(to, tokenId);
} }
function safeMint(address to, uint256 tokenId, bytes memory _data) public { function safeMint(
address to,
uint256 tokenId,
bytes memory _data
) public {
_safeMint(to, tokenId, _data); _safeMint(to, tokenId, _data);
} }
......
...@@ -31,7 +31,7 @@ contract ERC777MockUpgradeable is Initializable, ContextUpgradeable, ERC777Upgra ...@@ -31,7 +31,7 @@ contract ERC777MockUpgradeable is Initializable, ContextUpgradeable, ERC777Upgra
_mint(initialHolder, initialBalance, "", ""); _mint(initialHolder, initialBalance, "", "");
} }
function mintInternal ( function mintInternal(
address to, address to,
uint256 amount, uint256 amount,
bytes memory userData, bytes memory userData,
...@@ -40,7 +40,7 @@ contract ERC777MockUpgradeable is Initializable, ContextUpgradeable, ERC777Upgra ...@@ -40,7 +40,7 @@ contract ERC777MockUpgradeable is Initializable, ContextUpgradeable, ERC777Upgra
_mint(to, amount, userData, operatorData); _mint(to, amount, userData, operatorData);
} }
function mintInternalExtended ( function mintInternalExtended(
address to, address to,
uint256 amount, uint256 amount,
bytes memory userData, bytes memory userData,
...@@ -50,11 +50,20 @@ contract ERC777MockUpgradeable is Initializable, ContextUpgradeable, ERC777Upgra ...@@ -50,11 +50,20 @@ contract ERC777MockUpgradeable is Initializable, ContextUpgradeable, ERC777Upgra
_mint(to, amount, userData, operatorData, requireReceptionAck); _mint(to, amount, userData, operatorData, requireReceptionAck);
} }
function approveInternal(address holder, address spender, uint256 value) public { function approveInternal(
address holder,
address spender,
uint256 value
) public {
_approve(holder, spender, value); _approve(holder, spender, value);
} }
function _beforeTokenTransfer(address, address, address, uint256) internal override { function _beforeTokenTransfer(
address,
address,
address,
uint256
) internal override {
emit BeforeTokenTransfer(); emit BeforeTokenTransfer();
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -52,8 +52,8 @@ contract ERC777SenderRecipientMockUpgradeable is Initializable, ContextUpgradeab ...@@ -52,8 +52,8 @@ contract ERC777SenderRecipientMockUpgradeable is Initializable, ContextUpgradeab
IERC1820RegistryUpgradeable private _erc1820; IERC1820RegistryUpgradeable private _erc1820;
bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender");
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
function tokensToSend( function tokensToSend(
address operator, address operator,
...@@ -151,12 +151,21 @@ contract ERC777SenderRecipientMockUpgradeable is Initializable, ContextUpgradeab ...@@ -151,12 +151,21 @@ contract ERC777SenderRecipientMockUpgradeable is Initializable, ContextUpgradeab
_shouldRevertReceive = shouldRevert; _shouldRevertReceive = shouldRevert;
} }
function send(IERC777Upgradeable token, address to, uint256 amount, bytes memory data) public { function send(
IERC777Upgradeable token,
address to,
uint256 amount,
bytes memory data
) public {
// This is 777's send function, not the Solidity send function // This is 777's send function, not the Solidity send function
token.send(to, amount, data); // solhint-disable-line check-send-result token.send(to, amount, data); // solhint-disable-line check-send-result
} }
function burn(IERC777Upgradeable token, uint256 amount, bytes memory data) public { function burn(
IERC777Upgradeable token,
uint256 amount,
bytes memory data
) public {
token.burn(amount, data); token.burn(amount, data);
} }
uint256[49] private __gap; uint256[49] private __gap;
......
...@@ -40,7 +40,6 @@ contract EnumerableMapMockUpgradeable is Initializable { ...@@ -40,7 +40,6 @@ contract EnumerableMapMockUpgradeable is Initializable {
return _map.at(index); return _map.at(index);
} }
function tryGet(uint256 key) public view returns (bool, address) { function tryGet(uint256 key) public view returns (bool, address) {
return _map.tryGet(key); return _map.tryGet(key);
} }
......
...@@ -16,7 +16,7 @@ contract EtherReceiverMockUpgradeable is Initializable { ...@@ -16,7 +16,7 @@ contract EtherReceiverMockUpgradeable is Initializable {
_acceptEther = acceptEther; _acceptEther = acceptEther;
} }
receive () external payable { receive() external payable {
if (!_acceptEther) { if (!_acceptEther) {
revert(); revert();
} }
......
...@@ -9,7 +9,6 @@ import "../proxy/utils/Initializable.sol"; ...@@ -9,7 +9,6 @@ import "../proxy/utils/Initializable.sol";
* @dev This contract is a mock to test initializable functionality * @dev This contract is a mock to test initializable functionality
*/ */
contract InitializableMock is Initializable { contract InitializableMock is Initializable {
bool public initializerRan; bool public initializerRan;
uint256 public x; uint256 public x;
...@@ -32,5 +31,4 @@ contract InitializableMock is Initializable { ...@@ -32,5 +31,4 @@ contract InitializableMock is Initializable {
function fail() public pure { function fail() public pure {
require(false, "InitializableMock forced failure"); require(false, "InitializableMock forced failure");
} }
} }
...@@ -12,7 +12,11 @@ contract MerkleProofWrapperUpgradeable is Initializable { ...@@ -12,7 +12,11 @@ contract MerkleProofWrapperUpgradeable is Initializable {
function __MerkleProofWrapper_init_unchained() internal initializer { function __MerkleProofWrapper_init_unchained() internal initializer {
} }
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) public pure returns (bool) { function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) public pure returns (bool) {
return MerkleProofUpgradeable.verify(proof, root, leaf); return MerkleProofUpgradeable.verify(proof, root, leaf);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -12,14 +12,18 @@ contract MulticallTestUpgradeable is Initializable { ...@@ -12,14 +12,18 @@ contract MulticallTestUpgradeable is Initializable {
function __MulticallTest_init_unchained() internal initializer { function __MulticallTest_init_unchained() internal initializer {
} }
function testReturnValues(MulticallTokenMockUpgradeable multicallToken, address[] calldata recipients, uint256[] calldata amounts) external { function testReturnValues(
MulticallTokenMockUpgradeable multicallToken,
address[] calldata recipients,
uint256[] calldata amounts
) external {
bytes[] memory calls = new bytes[](recipients.length); bytes[] memory calls = new bytes[](recipients.length);
for (uint i = 0; i < recipients.length; i++) { for (uint256 i = 0; i < recipients.length; i++) {
calls[i] = abi.encodeWithSignature("transfer(address,uint256)", recipients[i], amounts[i]); calls[i] = abi.encodeWithSignature("transfer(address,uint256)", recipients[i], amounts[i]);
} }
bytes[] memory results = multicallToken.multicall(calls); bytes[] memory results = multicallToken.multicall(calls);
for (uint i = 0; i < results.length; i++) { for (uint256 i = 0; i < results.length; i++) {
require(abi.decode(results[i], (bool))); require(abi.decode(results[i], (bool)));
} }
} }
......
...@@ -32,7 +32,7 @@ contract SampleHuman is Initializable { ...@@ -32,7 +32,7 @@ contract SampleHuman is Initializable {
contract SampleMother is Initializable, SampleHuman { contract SampleMother is Initializable, SampleHuman {
uint256 public mother; uint256 public mother;
function initialize(uint256 value) public initializer virtual { function initialize(uint256 value) public virtual initializer {
SampleHuman.initialize(); SampleHuman.initialize();
mother = value; mother = value;
} }
...@@ -44,7 +44,7 @@ contract SampleMother is Initializable, SampleHuman { ...@@ -44,7 +44,7 @@ contract SampleMother is Initializable, SampleHuman {
contract SampleGramps is Initializable, SampleHuman { contract SampleGramps is Initializable, SampleHuman {
string public gramps; string public gramps;
function initialize(string memory value) public initializer virtual { function initialize(string memory value) public virtual initializer {
SampleHuman.initialize(); SampleHuman.initialize();
gramps = value; gramps = value;
} }
...@@ -68,7 +68,12 @@ contract SampleFather is Initializable, SampleGramps { ...@@ -68,7 +68,12 @@ contract SampleFather is Initializable, SampleGramps {
contract SampleChild is Initializable, SampleMother, SampleFather { contract SampleChild is Initializable, SampleMother, SampleFather {
uint256 public child; uint256 public child;
function initialize(uint256 _mother, string memory _gramps, uint256 _father, uint256 _child) public initializer { function initialize(
uint256 _mother,
string memory _gramps,
uint256 _father,
uint256 _child
) public initializer {
SampleMother.initialize(_mother); SampleMother.initialize(_mother);
SampleFather.initialize(_gramps, _father); SampleFather.initialize(_gramps, _father);
child = _child; child = _child;
......
...@@ -12,7 +12,7 @@ contract PullPaymentMockUpgradeable is Initializable, PullPaymentUpgradeable { ...@@ -12,7 +12,7 @@ contract PullPaymentMockUpgradeable is Initializable, PullPaymentUpgradeable {
__PullPaymentMock_init_unchained(); __PullPaymentMock_init_unchained();
} }
function __PullPaymentMock_init_unchained() internal initializer { } function __PullPaymentMock_init_unchained() internal initializer {}
// test helper function to call asyncTransfer // test helper function to call asyncTransfer
function callTransfer(address dest, uint256 amount) public { function callTransfer(address dest, uint256 amount) public {
......
...@@ -4,6 +4,7 @@ pragma solidity ^0.8.0; ...@@ -4,6 +4,7 @@ pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol"; import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
contract ReentrancyAttackUpgradeable is Initializable, ContextUpgradeable { contract ReentrancyAttackUpgradeable is Initializable, ContextUpgradeable {
function __ReentrancyAttack_init() internal initializer { function __ReentrancyAttack_init() internal initializer {
__Context_init_unchained(); __Context_init_unchained();
...@@ -13,8 +14,7 @@ contract ReentrancyAttackUpgradeable is Initializable, ContextUpgradeable { ...@@ -13,8 +14,7 @@ contract ReentrancyAttackUpgradeable is Initializable, ContextUpgradeable {
function __ReentrancyAttack_init_unchained() internal initializer { function __ReentrancyAttack_init_unchained() internal initializer {
} }
function callSender(bytes4 data) public { function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls (bool success, ) = _msgSender().call(abi.encodeWithSelector(data));
(bool success,) = _msgSender().call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call"); require(success, "ReentrancyAttack: failed call");
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -32,8 +32,7 @@ contract ReentrancyMockUpgradeable is Initializable, ReentrancyGuardUpgradeable ...@@ -32,8 +32,7 @@ contract ReentrancyMockUpgradeable is Initializable, ReentrancyGuardUpgradeable
function countThisRecursive(uint256 n) public nonReentrant { function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) { if (n > 0) {
_count(); _count();
// solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
(bool success,) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call"); require(success, "ReentrancyMock: failed call");
} }
} }
......
...@@ -5,61 +5,56 @@ pragma solidity ^0.8.0; ...@@ -5,61 +5,56 @@ pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol"; import "../proxy/utils/Initializable.sol";
contract Implementation1 is Initializable { contract Implementation1 is Initializable {
uint internal _value; uint256 internal _value;
function initialize() public initializer { function initialize() public initializer {}
}
function setValue(uint _number) public { function setValue(uint256 _number) public {
_value = _number; _value = _number;
} }
} }
contract Implementation2 is Initializable { contract Implementation2 is Initializable {
uint internal _value; uint256 internal _value;
function initialize() public initializer { function initialize() public initializer {}
}
function setValue(uint _number) public { function setValue(uint256 _number) public {
_value = _number; _value = _number;
} }
function getValue() public view returns (uint) { function getValue() public view returns (uint256) {
return _value; return _value;
} }
} }
contract Implementation3 is Initializable { contract Implementation3 is Initializable {
uint internal _value; uint256 internal _value;
function initialize() public initializer { function initialize() public initializer {}
}
function setValue(uint _number) public { function setValue(uint256 _number) public {
_value = _number; _value = _number;
} }
function getValue(uint _number) public view returns (uint) { function getValue(uint256 _number) public view returns (uint256) {
return _value + _number; return _value + _number;
} }
} }
contract Implementation4 is Initializable { contract Implementation4 is Initializable {
uint internal _value; uint256 internal _value;
function initialize() public initializer { function initialize() public initializer {}
}
function setValue(uint _number) public { function setValue(uint256 _number) public {
_value = _number; _value = _number;
} }
function getValue() public view returns (uint) { function getValue() public view returns (uint256) {
return _value; return _value;
} }
// solhint-disable-next-line payable-fallback
fallback() external { fallback() external {
_value = 1; _value = 1;
} }
......
...@@ -12,54 +12,62 @@ contract SafeCastMockUpgradeable is Initializable { ...@@ -12,54 +12,62 @@ contract SafeCastMockUpgradeable is Initializable {
function __SafeCastMock_init_unchained() internal initializer { function __SafeCastMock_init_unchained() internal initializer {
} }
using SafeCastUpgradeable for uint; using SafeCastUpgradeable for uint256;
using SafeCastUpgradeable for int; using SafeCastUpgradeable for int256;
function toUint256(int a) public pure returns (uint256) { function toUint256(int256 a) public pure returns (uint256) {
return a.toUint256(); return a.toUint256();
} }
function toInt256(uint a) public pure returns (int256) { function toUint224(uint256 a) public pure returns (uint224) {
return a.toInt256(); return a.toUint224();
} }
function toUint128(uint a) public pure returns (uint128) { function toUint128(uint256 a) public pure returns (uint128) {
return a.toUint128(); return a.toUint128();
} }
function toUint64(uint a) public pure returns (uint64) { function toUint96(uint256 a) public pure returns (uint96) {
return a.toUint96();
}
function toUint64(uint256 a) public pure returns (uint64) {
return a.toUint64(); return a.toUint64();
} }
function toUint32(uint a) public pure returns (uint32) { function toUint32(uint256 a) public pure returns (uint32) {
return a.toUint32(); return a.toUint32();
} }
function toUint16(uint a) public pure returns (uint16) { function toUint16(uint256 a) public pure returns (uint16) {
return a.toUint16(); return a.toUint16();
} }
function toUint8(uint a) public pure returns (uint8) { function toUint8(uint256 a) public pure returns (uint8) {
return a.toUint8(); return a.toUint8();
} }
function toInt128(int a) public pure returns (int128) { function toInt256(uint256 a) public pure returns (int256) {
return a.toInt256();
}
function toInt128(int256 a) public pure returns (int128) {
return a.toInt128(); return a.toInt128();
} }
function toInt64(int a) public pure returns (int64) { function toInt64(int256 a) public pure returns (int64) {
return a.toInt64(); return a.toInt64();
} }
function toInt32(int a) public pure returns (int32) { function toInt32(int256 a) public pure returns (int32) {
return a.toInt32(); return a.toInt32();
} }
function toInt16(int a) public pure returns (int16) { function toInt16(int256 a) public pure returns (int16) {
return a.toInt16(); return a.toInt16();
} }
function toInt8(int a) public pure returns (int8) { function toInt8(int256 a) public pure returns (int8) {
return a.toInt8(); return a.toInt8();
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -26,7 +26,11 @@ contract ERC20ReturnFalseMockUpgradeable is Initializable, ContextUpgradeable { ...@@ -26,7 +26,11 @@ contract ERC20ReturnFalseMockUpgradeable is Initializable, ContextUpgradeable {
return false; return false;
} }
function transferFrom(address, address, uint256) public returns (bool) { function transferFrom(
address,
address,
uint256
) public returns (bool) {
_dummy = 0; _dummy = 0;
return false; return false;
} }
...@@ -51,7 +55,7 @@ contract ERC20ReturnTrueMockUpgradeable is Initializable, ContextUpgradeable { ...@@ -51,7 +55,7 @@ contract ERC20ReturnTrueMockUpgradeable is Initializable, ContextUpgradeable {
function __ERC20ReturnTrueMock_init_unchained() internal initializer { function __ERC20ReturnTrueMock_init_unchained() internal initializer {
} }
mapping (address => uint256) private _allowances; mapping(address => uint256) private _allowances;
// IERC20's functions are not pure, but these mock implementations are: to prevent Solidity from issuing warnings, // IERC20's functions are not pure, but these mock implementations are: to prevent Solidity from issuing warnings,
// we write to a dummy state variable. // we write to a dummy state variable.
...@@ -62,7 +66,11 @@ contract ERC20ReturnTrueMockUpgradeable is Initializable, ContextUpgradeable { ...@@ -62,7 +66,11 @@ contract ERC20ReturnTrueMockUpgradeable is Initializable, ContextUpgradeable {
return true; return true;
} }
function transferFrom(address, address, uint256) public returns (bool) { function transferFrom(
address,
address,
uint256
) public returns (bool) {
_dummy = 0; _dummy = 0;
return true; return true;
} }
...@@ -90,7 +98,7 @@ contract ERC20NoReturnMockUpgradeable is Initializable, ContextUpgradeable { ...@@ -90,7 +98,7 @@ contract ERC20NoReturnMockUpgradeable is Initializable, ContextUpgradeable {
function __ERC20NoReturnMock_init_unchained() internal initializer { function __ERC20NoReturnMock_init_unchained() internal initializer {
} }
mapping (address => uint256) private _allowances; mapping(address => uint256) private _allowances;
// IERC20's functions are not pure, but these mock implementations are: to prevent Solidity from issuing warnings, // IERC20's functions are not pure, but these mock implementations are: to prevent Solidity from issuing warnings,
// we write to a dummy state variable. // we write to a dummy state variable.
...@@ -100,7 +108,11 @@ contract ERC20NoReturnMockUpgradeable is Initializable, ContextUpgradeable { ...@@ -100,7 +108,11 @@ contract ERC20NoReturnMockUpgradeable is Initializable, ContextUpgradeable {
_dummy = 0; _dummy = 0;
} }
function transferFrom(address, address, uint256) public { function transferFrom(
address,
address,
uint256
) public {
_dummy = 0; _dummy = 0;
} }
......
...@@ -54,62 +54,93 @@ contract SafeMathMockUpgradeable is Initializable { ...@@ -54,62 +54,93 @@ contract SafeMathMockUpgradeable is Initializable {
return SafeMathUpgradeable.mod(a, b); return SafeMathUpgradeable.mod(a, b);
} }
function subWithMessage(uint256 a, uint256 b, string memory errorMessage) public pure returns (uint256) { function subWithMessage(
uint256 a,
uint256 b,
string memory errorMessage
) public pure returns (uint256) {
return SafeMathUpgradeable.sub(a, b, errorMessage); return SafeMathUpgradeable.sub(a, b, errorMessage);
} }
function divWithMessage(uint256 a, uint256 b, string memory errorMessage) public pure returns (uint256) { function divWithMessage(
uint256 a,
uint256 b,
string memory errorMessage
) public pure returns (uint256) {
return SafeMathUpgradeable.div(a, b, errorMessage); return SafeMathUpgradeable.div(a, b, errorMessage);
} }
function modWithMessage(uint256 a, uint256 b, string memory errorMessage) public pure returns (uint256) { function modWithMessage(
uint256 a,
uint256 b,
string memory errorMessage
) public pure returns (uint256) {
return SafeMathUpgradeable.mod(a, b, errorMessage); return SafeMathUpgradeable.mod(a, b, errorMessage);
} }
function addMemoryCheck() public pure returns (uint256 mem) { function addMemoryCheck() public pure returns (uint256 mem) {
uint256 length = 32; uint256 length = 32;
// solhint-disable-next-line no-inline-assembly assembly {
assembly { mem := mload(0x40) } mem := mload(0x40)
for (uint256 i = 0; i < length; ++i) { SafeMathUpgradeable.add(1, 1); } }
// solhint-disable-next-line no-inline-assembly for (uint256 i = 0; i < length; ++i) {
assembly { mem := sub(mload(0x40), mem) } SafeMathUpgradeable.add(1, 1);
}
assembly {
mem := sub(mload(0x40), mem)
}
} }
function subMemoryCheck() public pure returns (uint256 mem) { function subMemoryCheck() public pure returns (uint256 mem) {
uint256 length = 32; uint256 length = 32;
// solhint-disable-next-line no-inline-assembly assembly {
assembly { mem := mload(0x40) } mem := mload(0x40)
for (uint256 i = 0; i < length; ++i) { SafeMathUpgradeable.sub(1, 1); } }
// solhint-disable-next-line no-inline-assembly for (uint256 i = 0; i < length; ++i) {
assembly { mem := sub(mload(0x40), mem) } SafeMathUpgradeable.sub(1, 1);
}
assembly {
mem := sub(mload(0x40), mem)
}
} }
function mulMemoryCheck() public pure returns (uint256 mem) { function mulMemoryCheck() public pure returns (uint256 mem) {
uint256 length = 32; uint256 length = 32;
// solhint-disable-next-line no-inline-assembly assembly {
assembly { mem := mload(0x40) } mem := mload(0x40)
for (uint256 i = 0; i < length; ++i) { SafeMathUpgradeable.mul(1, 1); } }
// solhint-disable-next-line no-inline-assembly for (uint256 i = 0; i < length; ++i) {
assembly { mem := sub(mload(0x40), mem) } SafeMathUpgradeable.mul(1, 1);
}
assembly {
mem := sub(mload(0x40), mem)
}
} }
function divMemoryCheck() public pure returns (uint256 mem) { function divMemoryCheck() public pure returns (uint256 mem) {
uint256 length = 32; uint256 length = 32;
// solhint-disable-next-line no-inline-assembly assembly {
assembly { mem := mload(0x40) } mem := mload(0x40)
for (uint256 i = 0; i < length; ++i) { SafeMathUpgradeable.div(1, 1); } }
// solhint-disable-next-line no-inline-assembly for (uint256 i = 0; i < length; ++i) {
assembly { mem := sub(mload(0x40), mem) } SafeMathUpgradeable.div(1, 1);
}
assembly {
mem := sub(mload(0x40), mem)
}
} }
function modMemoryCheck() public pure returns (uint256 mem) { function modMemoryCheck() public pure returns (uint256 mem) {
uint256 length = 32; uint256 length = 32;
// solhint-disable-next-line no-inline-assembly assembly {
assembly { mem := mload(0x40) } mem := mload(0x40)
for (uint256 i = 0; i < length; ++i) { SafeMathUpgradeable.mod(1, 1); } }
// solhint-disable-next-line no-inline-assembly for (uint256 i = 0; i < length; ++i) {
assembly { mem := sub(mload(0x40), mem) } SafeMathUpgradeable.mod(1, 1);
}
assembly {
mem := sub(mload(0x40), mem)
}
} }
uint256[50] private __gap; uint256[50] private __gap;
} }
...@@ -14,7 +14,11 @@ contract SignatureCheckerMockUpgradeable is Initializable { ...@@ -14,7 +14,11 @@ contract SignatureCheckerMockUpgradeable is Initializable {
} }
using SignatureCheckerUpgradeable for address; using SignatureCheckerUpgradeable for address;
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) public view returns (bool) { function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) public view returns (bool) {
return signer.isValidSignatureNow(hash, signature); return signer.isValidSignatureNow(hash, signature);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -13,13 +13,37 @@ contract StorageSlotMockUpgradeable is Initializable { ...@@ -13,13 +13,37 @@ contract StorageSlotMockUpgradeable is Initializable {
function __StorageSlotMock_init_unchained() internal initializer { function __StorageSlotMock_init_unchained() internal initializer {
} }
using StorageSlotUpgradeable for bytes32; using StorageSlotUpgradeable for bytes32;
function setBoolean(bytes32 slot, bool value) public { slot.getBooleanSlot().value = value; }
function setAddress(bytes32 slot, address value) public { slot.getAddressSlot().value = value; } function setBoolean(bytes32 slot, bool value) public {
function setBytes32(bytes32 slot, bytes32 value) public { slot.getBytes32Slot().value = value; } slot.getBooleanSlot().value = value;
function setUint256(bytes32 slot, uint256 value) public { slot.getUint256Slot().value = value; } }
function getBoolean(bytes32 slot) public view returns (bool) { return slot.getBooleanSlot().value; }
function getAddress(bytes32 slot) public view returns (address) { return slot.getAddressSlot().value; } function setAddress(bytes32 slot, address value) public {
function getBytes32(bytes32 slot) public view returns (bytes32) { return slot.getBytes32Slot().value; } slot.getAddressSlot().value = value;
function getUint256(bytes32 slot) public view returns (uint256) { return slot.getUint256Slot().value; } }
function setBytes32(bytes32 slot, bytes32 value) public {
slot.getBytes32Slot().value = value;
}
function setUint256(bytes32 slot, uint256 value) public {
slot.getUint256Slot().value = value;
}
function getBoolean(bytes32 slot) public view returns (bool) {
return slot.getBooleanSlot().value;
}
function getAddress(bytes32 slot) public view returns (address) {
return slot.getAddressSlot().value;
}
function getBytes32(bytes32 slot) public view returns (bytes32) {
return slot.getBytes32Slot().value;
}
function getUint256(bytes32 slot) public view returns (uint256) {
return slot.getUint256Slot().value;
}
uint256[50] private __gap; uint256[50] private __gap;
} }
...@@ -15,9 +15,11 @@ contract StringsMockUpgradeable is Initializable { ...@@ -15,9 +15,11 @@ contract StringsMockUpgradeable is Initializable {
function fromUint256(uint256 value) public pure returns (string memory) { function fromUint256(uint256 value) public pure returns (string memory) {
return StringsUpgradeable.toString(value); return StringsUpgradeable.toString(value);
} }
function fromUint256Hex(uint256 value) public pure returns (string memory) { function fromUint256Hex(uint256 value) public pure returns (string memory) {
return StringsUpgradeable.toHexString(value); return StringsUpgradeable.toHexString(value);
} }
function fromUint256HexFixed(uint256 value, uint256 length) public pure returns (string memory) { function fromUint256HexFixed(uint256 value, uint256 length) public pure returns (string memory) {
return StringsUpgradeable.toHexString(value, length); return StringsUpgradeable.toHexString(value, length);
} }
......
...@@ -60,6 +60,5 @@ contract UUPSUpgradeableBrokenMockUpgradeable is Initializable, UUPSUpgradeableM ...@@ -60,6 +60,5 @@ contract UUPSUpgradeableBrokenMockUpgradeable is Initializable, UUPSUpgradeableM
function upgradeToAndCall(address, bytes memory) external payable virtual override { function upgradeToAndCall(address, bytes memory) external payable virtual override {
// pass // pass
} }
uint256[50] private __gap; uint256[50] private __gap;
} }
...@@ -11,14 +11,22 @@ contract AccessControlMockUpgradeableWithInit is AccessControlMockUpgradeable { ...@@ -11,14 +11,22 @@ contract AccessControlMockUpgradeableWithInit is AccessControlMockUpgradeable {
import "../governance/TimelockControllerUpgradeable.sol"; import "../governance/TimelockControllerUpgradeable.sol";
contract TimelockControllerUpgradeableWithInit is TimelockControllerUpgradeable { contract TimelockControllerUpgradeableWithInit is TimelockControllerUpgradeable {
constructor(uint256 minDelay, address[] memory proposers, address[] memory executors) public payable { constructor(
uint256 minDelay,
address[] memory proposers,
address[] memory executors
) public payable {
__TimelockController_init(minDelay, proposers, executors); __TimelockController_init(minDelay, proposers, executors);
} }
} }
import "../token/ERC721/presets/ERC721PresetMinterPauserAutoIdUpgradeable.sol"; import "../token/ERC721/presets/ERC721PresetMinterPauserAutoIdUpgradeable.sol";
contract ERC721PresetMinterPauserAutoIdUpgradeableWithInit is ERC721PresetMinterPauserAutoIdUpgradeable { contract ERC721PresetMinterPauserAutoIdUpgradeableWithInit is ERC721PresetMinterPauserAutoIdUpgradeable {
constructor(string memory name, string memory symbol, string memory baseTokenURI) public payable { constructor(
string memory name,
string memory symbol,
string memory baseTokenURI
) public payable {
__ERC721PresetMinterPauserAutoId_init(name, symbol, baseTokenURI); __ERC721PresetMinterPauserAutoId_init(name, symbol, baseTokenURI);
} }
} }
...@@ -43,6 +51,13 @@ contract MathMockUpgradeableWithInit is MathMockUpgradeable { ...@@ -43,6 +51,13 @@ contract MathMockUpgradeableWithInit is MathMockUpgradeable {
__MathMock_init(); __MathMock_init();
} }
} }
import "./ERC20VotesMockUpgradeable.sol";
contract ERC20VotesMockUpgradeableWithInit is ERC20VotesMockUpgradeable {
constructor(string memory name, string memory symbol) public payable {
__ERC20VotesMock_init(name, symbol);
}
}
import "./ERC1271WalletMockUpgradeable.sol"; import "./ERC1271WalletMockUpgradeable.sol";
contract ERC1271WalletMockUpgradeableWithInit is ERC1271WalletMockUpgradeable { contract ERC1271WalletMockUpgradeableWithInit is ERC1271WalletMockUpgradeable {
...@@ -53,7 +68,11 @@ contract ERC1271WalletMockUpgradeableWithInit is ERC1271WalletMockUpgradeable { ...@@ -53,7 +68,11 @@ contract ERC1271WalletMockUpgradeableWithInit is ERC1271WalletMockUpgradeable {
import "../token/ERC20/utils/TokenTimelockUpgradeable.sol"; import "../token/ERC20/utils/TokenTimelockUpgradeable.sol";
contract TokenTimelockUpgradeableWithInit is TokenTimelockUpgradeable { contract TokenTimelockUpgradeableWithInit is TokenTimelockUpgradeable {
constructor(IERC20Upgradeable token_, address beneficiary_, uint256 releaseTime_) public payable { constructor(
IERC20Upgradeable token_,
address beneficiary_,
uint256 releaseTime_
) public payable {
__TokenTimelock_init(token_, beneficiary_, releaseTime_); __TokenTimelock_init(token_, beneficiary_, releaseTime_);
} }
} }
...@@ -325,14 +344,22 @@ contract ERC20FlashMintMockUpgradeableWithInit is ERC20FlashMintMockUpgradeable ...@@ -325,14 +344,22 @@ contract ERC20FlashMintMockUpgradeableWithInit is ERC20FlashMintMockUpgradeable
import "./ERC20DecimalsMockUpgradeable.sol"; import "./ERC20DecimalsMockUpgradeable.sol";
contract ERC20DecimalsMockUpgradeableWithInit is ERC20DecimalsMockUpgradeable { contract ERC20DecimalsMockUpgradeableWithInit is ERC20DecimalsMockUpgradeable {
constructor(string memory name_, string memory symbol_, uint8 decimals_) public payable { constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) public payable {
__ERC20DecimalsMock_init(name_, symbol_, decimals_); __ERC20DecimalsMock_init(name_, symbol_, decimals_);
} }
} }
import "./ERC20CappedMockUpgradeable.sol"; import "./ERC20CappedMockUpgradeable.sol";
contract ERC20CappedMockUpgradeableWithInit is ERC20CappedMockUpgradeable { contract ERC20CappedMockUpgradeableWithInit is ERC20CappedMockUpgradeable {
constructor(string memory name, string memory symbol, uint256 cap) public payable { constructor(
string memory name,
string memory symbol,
uint256 cap
) public payable {
__ERC20CappedMock_init(name, symbol, cap); __ERC20CappedMock_init(name, symbol, cap);
} }
} }
...@@ -591,11 +618,11 @@ contract SafeCastMockUpgradeableWithInit is SafeCastMockUpgradeable { ...@@ -591,11 +618,11 @@ contract SafeCastMockUpgradeableWithInit is SafeCastMockUpgradeable {
__SafeCastMock_init(); __SafeCastMock_init();
} }
} }
import "./ERC20VotesMockUpgradeable.sol"; import "./ERC20VotesCompMockUpgradeable.sol";
contract ERC20VotesMockUpgradeableWithInit is ERC20VotesMockUpgradeable { contract ERC20VotesCompMockUpgradeableWithInit is ERC20VotesCompMockUpgradeable {
constructor(string memory name, string memory symbol) public payable { constructor(string memory name, string memory symbol) public payable {
__ERC20VotesMock_init(name, symbol); __ERC20VotesCompMock_init(name, symbol);
} }
} }
import "./ArraysImplUpgradeable.sol"; import "./ArraysImplUpgradeable.sol";
......
...@@ -22,7 +22,6 @@ library ClonesUpgradeable { ...@@ -22,7 +22,6 @@ library ClonesUpgradeable {
* This function uses the create opcode, which should never revert. * This function uses the create opcode, which should never revert.
*/ */
function clone(address implementation) internal returns (address instance) { function clone(address implementation) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly { assembly {
let ptr := mload(0x40) let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
...@@ -41,7 +40,6 @@ library ClonesUpgradeable { ...@@ -41,7 +40,6 @@ library ClonesUpgradeable {
* the clones cannot be deployed twice at the same address. * the clones cannot be deployed twice at the same address.
*/ */
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly { assembly {
let ptr := mload(0x40) let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
...@@ -55,8 +53,11 @@ library ClonesUpgradeable { ...@@ -55,8 +53,11 @@ library ClonesUpgradeable {
/** /**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/ */
function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) { function predictDeterministicAddress(
// solhint-disable-next-line no-inline-assembly address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly { assembly {
let ptr := mload(0x40) let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
...@@ -72,7 +73,11 @@ library ClonesUpgradeable { ...@@ -72,7 +73,11 @@ library ClonesUpgradeable {
/** /**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/ */
function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this)); return predictDeterministicAddress(implementation, salt, address(this));
} }
} }
...@@ -67,7 +67,11 @@ abstract contract ERC1967UpgradeUpgradeable is Initializable { ...@@ -67,7 +67,11 @@ abstract contract ERC1967UpgradeUpgradeable is Initializable {
* *
* Emits an {Upgraded} event. * Emits an {Upgraded} event.
*/ */
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_setImplementation(newImplementation); _setImplementation(newImplementation);
emit Upgraded(newImplementation); emit Upgraded(newImplementation);
if (data.length > 0 || forceCall) { if (data.length > 0 || forceCall) {
...@@ -80,7 +84,11 @@ abstract contract ERC1967UpgradeUpgradeable is Initializable { ...@@ -80,7 +84,11 @@ abstract contract ERC1967UpgradeUpgradeable is Initializable {
* *
* Emits an {Upgraded} event. * Emits an {Upgraded} event.
*/ */
function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation(); address oldImplementation = _getImplementation();
// Initial upgrade and setup call // Initial upgrade and setup call
...@@ -96,10 +104,7 @@ abstract contract ERC1967UpgradeUpgradeable is Initializable { ...@@ -96,10 +104,7 @@ abstract contract ERC1967UpgradeUpgradeable is Initializable {
rollbackTesting.value = true; rollbackTesting.value = true;
_functionDelegateCall( _functionDelegateCall(
newImplementation, newImplementation,
abi.encodeWithSignature( abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
"upgradeTo(address)",
oldImplementation
)
); );
rollbackTesting.value = false; rollbackTesting.value = false;
// Check rollback was effective // Check rollback was effective
...@@ -116,7 +121,11 @@ abstract contract ERC1967UpgradeUpgradeable is Initializable { ...@@ -116,7 +121,11 @@ abstract contract ERC1967UpgradeUpgradeable is Initializable {
* *
* Emits a {BeaconUpgraded} event. * Emits a {BeaconUpgraded} event.
*/ */
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon); _setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon); emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) { if (data.length > 0 || forceCall) {
...@@ -183,10 +192,7 @@ abstract contract ERC1967UpgradeUpgradeable is Initializable { ...@@ -183,10 +192,7 @@ abstract contract ERC1967UpgradeUpgradeable is Initializable {
* @dev Stores a new beacon in the EIP1967 beacon slot. * @dev Stores a new beacon in the EIP1967 beacon slot.
*/ */
function _setBeacon(address newBeacon) private { function _setBeacon(address newBeacon) private {
require( require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
AddressUpgradeable.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require( require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract" "ERC1967: beacon implementation is not a contract"
......
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0; pragma solidity ^0.8.0;
/** /**
...@@ -16,7 +15,6 @@ pragma solidity ^0.8.0; ...@@ -16,7 +15,6 @@ pragma solidity ^0.8.0;
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/ */
abstract contract Initializable { abstract contract Initializable {
/** /**
* @dev Indicates that the contract has been initialized. * @dev Indicates that the contract has been initialized.
*/ */
......
...@@ -70,7 +70,7 @@ abstract contract PullPaymentUpgradeable is Initializable { ...@@ -70,7 +70,7 @@ abstract contract PullPaymentUpgradeable is Initializable {
* @param amount The amount to transfer. * @param amount The amount to transfer.
*/ */
function _asyncTransfer(address dest, uint256 amount) internal virtual { function _asyncTransfer(address dest, uint256 amount) internal virtual {
_escrow.deposit{ value: amount }(dest); _escrow.deposit{value: amount}(dest);
} }
uint256[50] private __gap; uint256[50] private __gap;
} }
...@@ -21,10 +21,10 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -21,10 +21,10 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
using AddressUpgradeable for address; using AddressUpgradeable for address;
// Mapping from token ID to account balances // Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances; mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals // Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri; string private _uri;
...@@ -46,9 +46,10 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -46,9 +46,10 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
* @dev See {IERC165-supportsInterface}. * @dev See {IERC165-supportsInterface}.
*/ */
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC1155Upgradeable).interfaceId return
|| interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId interfaceId == type(IERC1155Upgradeable).interfaceId ||
|| super.supportsInterface(interfaceId); interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
} }
/** /**
...@@ -84,10 +85,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -84,10 +85,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
* *
* - `accounts` and `ids` must have the same length. * - `accounts` and `ids` must have the same length.
*/ */
function balanceOfBatch( function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
address[] memory accounts,
uint256[] memory ids
)
public public
view view
virtual virtual
...@@ -131,11 +129,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -131,11 +129,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
uint256 id, uint256 id,
uint256 amount, uint256 amount,
bytes memory data bytes memory data
) ) public virtual override {
public
virtual
override
{
require( require(
from == _msgSender() || isApprovedForAll(from, _msgSender()), from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved" "ERC1155: caller is not owner nor approved"
...@@ -152,11 +146,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -152,11 +146,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
uint256[] memory ids, uint256[] memory ids,
uint256[] memory amounts, uint256[] memory amounts,
bytes memory data bytes memory data
) ) public virtual override {
public
virtual
override
{
require( require(
from == _msgSender() || isApprovedForAll(from, _msgSender()), from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved" "ERC1155: transfer caller is not owner nor approved"
...@@ -182,10 +172,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -182,10 +172,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
uint256 id, uint256 id,
uint256 amount, uint256 amount,
bytes memory data bytes memory data
) ) internal virtual {
internal
virtual
{
require(to != address(0), "ERC1155: transfer to the zero address"); require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender(); address operator = _msgSender();
...@@ -220,10 +207,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -220,10 +207,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
uint256[] memory ids, uint256[] memory ids,
uint256[] memory amounts, uint256[] memory amounts,
bytes memory data bytes memory data
) ) internal virtual {
internal
virtual
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address"); require(to != address(0), "ERC1155: transfer to the zero address");
...@@ -282,7 +266,12 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -282,7 +266,12 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value. * acceptance magic value.
*/ */
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address"); require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender(); address operator = _msgSender();
...@@ -304,7 +293,12 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -304,7 +293,12 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value. * acceptance magic value.
*/ */
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address"); require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
...@@ -312,7 +306,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -312,7 +306,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) { for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i]; _balances[ids[i]][to] += amounts[i];
} }
...@@ -329,7 +323,11 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -329,7 +323,11 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
* - `account` cannot be the zero address. * - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`. * - `account` must have at least `amount` tokens of token type `id`.
*/ */
function _burn(address account, uint256 id, uint256 amount) internal virtual { function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address"); require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender(); address operator = _msgSender();
...@@ -352,7 +350,11 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -352,7 +350,11 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
* *
* - `ids` and `amounts` must have the same length. * - `ids` and `amounts` must have the same length.
*/ */
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address"); require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
...@@ -360,7 +362,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -360,7 +362,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
_beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); _beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) { for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i]; uint256 id = ids[i];
uint256 amount = amounts[i]; uint256 amount = amounts[i];
...@@ -401,10 +403,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -401,10 +403,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
uint256[] memory ids, uint256[] memory ids,
uint256[] memory amounts, uint256[] memory amounts,
bytes memory data bytes memory data
) ) internal virtual {}
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck( function _doSafeTransferAcceptanceCheck(
address operator, address operator,
...@@ -413,9 +412,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -413,9 +412,7 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
uint256 id, uint256 id,
uint256 amount, uint256 amount,
bytes memory data bytes memory data
) ) private {
private
{
if (to.isContract()) { if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) {
...@@ -436,11 +433,11 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea ...@@ -436,11 +433,11 @@ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradea
uint256[] memory ids, uint256[] memory ids,
uint256[] memory amounts, uint256[] memory amounts,
bytes memory data bytes memory data
) ) private {
private
{
if (to.isContract()) { if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens"); revert("ERC1155: ERC1155Receiver rejected tokens");
} }
......
...@@ -8,7 +8,6 @@ import "../../utils/introspection/IERC165Upgradeable.sol"; ...@@ -8,7 +8,6 @@ import "../../utils/introspection/IERC165Upgradeable.sol";
* @dev _Available since v3.1._ * @dev _Available since v3.1._
*/ */
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/** /**
@dev Handles the receipt of a single ERC1155 token type. This function is @dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated. called at the end of a `safeTransferFrom` after the balance has been updated.
...@@ -28,9 +27,7 @@ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { ...@@ -28,9 +27,7 @@ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
uint256 id, uint256 id,
uint256 value, uint256 value,
bytes calldata data bytes calldata data
) ) external returns (bytes4);
external
returns(bytes4);
/** /**
@dev Handles the receipt of a multiple ERC1155 token types. This function @dev Handles the receipt of a multiple ERC1155 token types. This function
...@@ -51,7 +48,5 @@ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { ...@@ -51,7 +48,5 @@ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
uint256[] calldata ids, uint256[] calldata ids,
uint256[] calldata values, uint256[] calldata values,
bytes calldata data bytes calldata data
) ) external returns (bytes4);
external
returns(bytes4);
} }
...@@ -20,7 +20,13 @@ interface IERC1155Upgradeable is IERC165Upgradeable { ...@@ -20,7 +20,13 @@ interface IERC1155Upgradeable is IERC165Upgradeable {
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers. * transfers.
*/ */
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/** /**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
...@@ -53,7 +59,10 @@ interface IERC1155Upgradeable is IERC165Upgradeable { ...@@ -53,7 +59,10 @@ interface IERC1155Upgradeable is IERC165Upgradeable {
* *
* - `accounts` and `ids` must have the same length. * - `accounts` and `ids` must have the same length.
*/ */
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/** /**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
...@@ -86,7 +95,13 @@ interface IERC1155Upgradeable is IERC165Upgradeable { ...@@ -86,7 +95,13 @@ interface IERC1155Upgradeable is IERC165Upgradeable {
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value. * acceptance magic value.
*/ */
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/** /**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
...@@ -99,5 +114,11 @@ interface IERC1155Upgradeable is IERC165Upgradeable { ...@@ -99,5 +114,11 @@ interface IERC1155Upgradeable is IERC165Upgradeable {
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value. * acceptance magic value.
*/ */
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
} }
...@@ -20,7 +20,11 @@ abstract contract ERC1155BurnableUpgradeable is Initializable, ERC1155Upgradeabl ...@@ -20,7 +20,11 @@ abstract contract ERC1155BurnableUpgradeable is Initializable, ERC1155Upgradeabl
function __ERC1155Burnable_init_unchained() internal initializer { function __ERC1155Burnable_init_unchained() internal initializer {
} }
function burn(address account, uint256 id, uint256 value) public virtual { function burn(
address account,
uint256 id,
uint256 value
) public virtual {
require( require(
account == _msgSender() || isApprovedForAll(account, _msgSender()), account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved" "ERC1155: caller is not owner nor approved"
...@@ -29,7 +33,11 @@ abstract contract ERC1155BurnableUpgradeable is Initializable, ERC1155Upgradeabl ...@@ -29,7 +33,11 @@ abstract contract ERC1155BurnableUpgradeable is Initializable, ERC1155Upgradeabl
_burn(account, id, value); _burn(account, id, value);
} }
function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual { function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
) public virtual {
require( require(
account == _msgSender() || isApprovedForAll(account, _msgSender()), account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved" "ERC1155: caller is not owner nor approved"
......
...@@ -39,11 +39,7 @@ abstract contract ERC1155PausableUpgradeable is Initializable, ERC1155Upgradeabl ...@@ -39,11 +39,7 @@ abstract contract ERC1155PausableUpgradeable is Initializable, ERC1155Upgradeabl
uint256[] memory ids, uint256[] memory ids,
uint256[] memory amounts, uint256[] memory amounts,
bytes memory data bytes memory data
) ) internal virtual override {
internal
virtual
override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data); super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "ERC1155Pausable: token transfer while paused"); require(!paused(), "ERC1155Pausable: token transfer while paused");
......
...@@ -22,7 +22,7 @@ abstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable ...@@ -22,7 +22,7 @@ abstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable
function __ERC1155Supply_init_unchained() internal initializer { function __ERC1155Supply_init_unchained() internal initializer {
} }
mapping (uint256 => uint256) private _totalSupply; mapping(uint256 => uint256) private _totalSupply;
/** /**
* @dev Total amount of tokens in with a given id. * @dev Total amount of tokens in with a given id.
...@@ -34,14 +34,19 @@ abstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable ...@@ -34,14 +34,19 @@ abstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable
/** /**
* @dev Indicates weither any token exist with a given id, or not. * @dev Indicates weither any token exist with a given id, or not.
*/ */
function exists(uint256 id) public view virtual returns(bool) { function exists(uint256 id) public view virtual returns (bool) {
return ERC1155SupplyUpgradeable.totalSupply(id) > 0; return ERC1155SupplyUpgradeable.totalSupply(id) > 0;
} }
/** /**
* @dev See {ERC1155-_mint}. * @dev See {ERC1155-_mint}.
*/ */
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual override { function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual override {
super._mint(account, id, amount, data); super._mint(account, id, amount, data);
_totalSupply[id] += amount; _totalSupply[id] += amount;
} }
...@@ -49,7 +54,12 @@ abstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable ...@@ -49,7 +54,12 @@ abstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable
/** /**
* @dev See {ERC1155-_mintBatch}. * @dev See {ERC1155-_mintBatch}.
*/ */
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual override { function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._mintBatch(to, ids, amounts, data); super._mintBatch(to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) { for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i]; _totalSupply[ids[i]] += amounts[i];
...@@ -59,7 +69,11 @@ abstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable ...@@ -59,7 +69,11 @@ abstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable
/** /**
* @dev See {ERC1155-_burn}. * @dev See {ERC1155-_burn}.
*/ */
function _burn(address account, uint256 id, uint256 amount) internal virtual override { function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual override {
super._burn(account, id, amount); super._burn(account, id, amount);
_totalSupply[id] -= amount; _totalSupply[id] -= amount;
} }
...@@ -67,7 +81,11 @@ abstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable ...@@ -67,7 +81,11 @@ abstract contract ERC1155SupplyUpgradeable is Initializable, ERC1155Upgradeable
/** /**
* @dev See {ERC1155-_burnBatch}. * @dev See {ERC1155-_burnBatch}.
*/ */
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual override { function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual override {
super._burnBatch(account, ids, amounts); super._burnBatch(account, ids, amounts);
for (uint256 i = 0; i < ids.length; ++i) { for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] -= amounts[i]; _totalSupply[ids[i]] -= amounts[i];
......
...@@ -62,7 +62,12 @@ contract ERC1155PresetMinterPauserUpgradeable is Initializable, ContextUpgradeab ...@@ -62,7 +62,12 @@ contract ERC1155PresetMinterPauserUpgradeable is Initializable, ContextUpgradeab
* *
* - the caller must have the `MINTER_ROLE`. * - the caller must have the `MINTER_ROLE`.
*/ */
function mint(address to, uint256 id, uint256 amount, bytes memory data) public virtual { function mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mint(to, id, amount, data); _mint(to, id, amount, data);
...@@ -71,7 +76,12 @@ contract ERC1155PresetMinterPauserUpgradeable is Initializable, ContextUpgradeab ...@@ -71,7 +76,12 @@ contract ERC1155PresetMinterPauserUpgradeable is Initializable, ContextUpgradeab
/** /**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}. * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/ */
function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public virtual { function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mintBatch(to, ids, amounts, data); _mintBatch(to, ids, amounts, data);
...@@ -108,7 +118,13 @@ contract ERC1155PresetMinterPauserUpgradeable is Initializable, ContextUpgradeab ...@@ -108,7 +118,13 @@ contract ERC1155PresetMinterPauserUpgradeable is Initializable, ContextUpgradeab
/** /**
* @dev See {IERC165-supportsInterface}. * @dev See {IERC165-supportsInterface}.
*/ */
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, ERC1155Upgradeable) returns (bool) { function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, ERC1155Upgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId); return super.supportsInterface(interfaceId);
} }
...@@ -119,9 +135,7 @@ contract ERC1155PresetMinterPauserUpgradeable is Initializable, ContextUpgradeab ...@@ -119,9 +135,7 @@ contract ERC1155PresetMinterPauserUpgradeable is Initializable, ContextUpgradeab
uint256[] memory ids, uint256[] memory ids,
uint256[] memory amounts, uint256[] memory amounts,
bytes memory data bytes memory data
) ) internal virtual override(ERC1155Upgradeable, ERC1155PausableUpgradeable) {
internal virtual override(ERC1155Upgradeable, ERC1155PausableUpgradeable)
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data); super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -17,11 +17,23 @@ contract ERC1155HolderUpgradeable is Initializable, ERC1155ReceiverUpgradeable { ...@@ -17,11 +17,23 @@ contract ERC1155HolderUpgradeable is Initializable, ERC1155ReceiverUpgradeable {
function __ERC1155Holder_init_unchained() internal initializer { function __ERC1155Holder_init_unchained() internal initializer {
} }
function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector; return this.onERC1155Received.selector;
} }
function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector; return this.onERC1155BatchReceived.selector;
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -21,8 +21,7 @@ abstract contract ERC1155ReceiverUpgradeable is Initializable, ERC165Upgradeable ...@@ -21,8 +21,7 @@ abstract contract ERC1155ReceiverUpgradeable is Initializable, ERC165Upgradeable
* @dev See {IERC165-supportsInterface}. * @dev See {IERC165-supportsInterface}.
*/ */
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId);
|| super.supportsInterface(interfaceId);
} }
uint256[50] private __gap; uint256[50] private __gap;
} }
...@@ -32,9 +32,9 @@ import "../../proxy/utils/Initializable.sol"; ...@@ -32,9 +32,9 @@ import "../../proxy/utils/Initializable.sol";
* allowances. See {IERC20-approve}. * allowances. See {IERC20-approve}.
*/ */
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping (address => uint256) private _balances; mapping(address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances; mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply; uint256 private _totalSupply;
...@@ -151,7 +151,11 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl ...@@ -151,7 +151,11 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl
* - the caller must have allowance for ``sender``'s tokens of at least * - the caller must have allowance for ``sender``'s tokens of at least
* `amount`. * `amount`.
*/ */
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount); _transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()]; uint256 currentAllowance = _allowances[sender][_msgSender()];
...@@ -218,7 +222,11 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl ...@@ -218,7 +222,11 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl
* - `recipient` cannot be the zero address. * - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`. * - `sender` must have a balance of at least `amount`.
*/ */
function _transfer(address sender, address recipient, uint256 amount) internal virtual { function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address"); require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address");
...@@ -292,7 +300,11 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl ...@@ -292,7 +300,11 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl
* - `owner` cannot be the zero address. * - `owner` cannot be the zero address.
* - `spender` cannot be the zero address. * - `spender` cannot be the zero address.
*/ */
function _approve(address owner, address spender, uint256 amount) internal virtual { function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address"); require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address"); require(spender != address(0), "ERC20: approve to the zero address");
...@@ -314,6 +326,10 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl ...@@ -314,6 +326,10 @@ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeabl
* *
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/ */
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap; uint256[45] private __gap;
} }
...@@ -59,7 +59,11 @@ interface IERC20Upgradeable { ...@@ -59,7 +59,11 @@ interface IERC20Upgradeable {
* *
* Emits a {Transfer} event. * Emits a {Transfer} event.
*/ */
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/** /**
* @dev Emitted when `value` tokens are moved from one account (`from`) to * @dev Emitted when `value` tokens are moved from one account (`from`) to
......
...@@ -21,7 +21,8 @@ Additionally there are multiple custom extensions, including: ...@@ -21,7 +21,8 @@ Additionally there are multiple custom extensions, including:
* {ERC20Snapshot}: efficient storage of past token balances to be later queried at any point in time. * {ERC20Snapshot}: efficient storage of past token balances to be later queried at any point in time.
* {ERC20Permit}: gasless approval of tokens (standardized as ERC2612). * {ERC20Permit}: gasless approval of tokens (standardized as ERC2612).
* {ERC20FlashMint}: token level support for flash loans through the minting and burning of ephemeral tokens (standardized as ERC3156). * {ERC20FlashMint}: token level support for flash loans through the minting and burning of ephemeral tokens (standardized as ERC3156).
* {ERC20Votes}: support for voting and vote delegation (compatible with Compound's token). * {ERC20Votes}: support for voting and vote delegation.
* {ERC20VotesComp}: support for voting and vote delegation (compatible with Compound's tokenn, with uint96 restrictions).
Finally, there are some utilities to interact with ERC20 contracts in various ways. Finally, there are some utilities to interact with ERC20 contracts in various ways.
...@@ -32,7 +33,6 @@ The following related EIPs are in draft status. ...@@ -32,7 +33,6 @@ The following related EIPs are in draft status.
- {ERC20Permit} - {ERC20Permit}
- {ERC20FlashMint} - {ERC20FlashMint}
- {ERC20Votes}
NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC20 (such as <<ERC20-_mint-address-uint256-,`_mint`>>) and expose them as external functions in the way they prefer. On the other hand, xref:ROOT:erc20.adoc#Presets[ERC20 Presets] (such as {ERC20PresetMinterPauser}) are designed using opinionated patterns to provide developers with ready to use, deployable contracts. NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC20 (such as <<ERC20-_mint-address-uint256-,`_mint`>>) and expose them as external functions in the way they prefer. On the other hand, xref:ROOT:erc20.adoc#Presets[ERC20 Presets] (such as {ERC20PresetMinterPauser}) are designed using opinionated patterns to provide developers with ready to use, deployable contracts.
...@@ -54,6 +54,10 @@ NOTE: This core set of contracts is designed to be unopinionated, allowing devel ...@@ -54,6 +54,10 @@ NOTE: This core set of contracts is designed to be unopinionated, allowing devel
{{ERC20Snapshot}} {{ERC20Snapshot}}
{{ERC20Votes}}
{{ERC20VotesComp}}
== Draft EIPs == Draft EIPs
The following EIPs are still in Draft status. Due to their nature as drafts, the details of these contracts may change and we cannot guarantee their xref:ROOT:releases-stability.adoc[stability]. Minor releases of OpenZeppelin Contracts may contain breaking changes for the contracts in this directory, which will be duly announced in the https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/CHANGELOG.md[changelog]. The EIPs included here are used by projects in production and this may make them less likely to change significantly. The following EIPs are still in Draft status. Due to their nature as drafts, the details of these contracts may change and we cannot guarantee their xref:ROOT:releases-stability.adoc[stability]. Minor releases of OpenZeppelin Contracts may contain breaking changes for the contracts in this directory, which will be duly announced in the https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/CHANGELOG.md[changelog]. The EIPs included here are used by projects in production and this may make them less likely to change significantly.
...@@ -62,8 +66,6 @@ The following EIPs are still in Draft status. Due to their nature as drafts, the ...@@ -62,8 +66,6 @@ The following EIPs are still in Draft status. Due to their nature as drafts, the
{{ERC20FlashMint}} {{ERC20FlashMint}}
{{ERC20Votes}}
== Presets == 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. 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.
......
...@@ -23,7 +23,7 @@ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, ...@@ -23,7 +23,7 @@ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable,
function __ERC20FlashMint_init_unchained() internal initializer { function __ERC20FlashMint_init_unchained() internal initializer {
} }
bytes32 constant private RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
/** /**
* @dev Returns the maximum amount of tokens available for loan. * @dev Returns the maximum amount of tokens available for loan.
...@@ -68,12 +68,13 @@ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, ...@@ -68,12 +68,13 @@ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable,
address token, address token,
uint256 amount, uint256 amount,
bytes calldata data bytes calldata data
) ) public virtual override returns (bool) {
public virtual override returns (bool)
{
uint256 fee = flashFee(token, amount); uint256 fee = flashFee(token, amount);
_mint(address(receiver), amount); _mint(address(receiver), amount);
require(receiver.onFlashLoan(msg.sender, token, amount, fee, data) == RETURN_VALUE, "ERC20FlashMint: invalid return value"); require(
receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE,
"ERC20FlashMint: invalid return value"
);
uint256 currentAllowance = allowance(address(receiver), address(this)); uint256 currentAllowance = allowance(address(receiver), address(this));
require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund"); require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund");
_approve(address(receiver), address(this), currentAllowance - amount - fee); _approve(address(receiver), address(this), currentAllowance - amount - fee);
......
...@@ -29,7 +29,11 @@ abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, P ...@@ -29,7 +29,11 @@ abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, P
* *
* - the contract must not be paused. * - the contract must not be paused.
*/ */
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount); super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused"); require(!paused(), "ERC20Pausable: token transfer while paused");
......
...@@ -60,7 +60,7 @@ abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable { ...@@ -60,7 +60,7 @@ abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable {
uint256[] values; uint256[] values;
} }
mapping (address => Snapshots) private _accountBalanceSnapshots; mapping(address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots; Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
...@@ -119,7 +119,7 @@ abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable { ...@@ -119,7 +119,7 @@ abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable {
/** /**
* @dev Retrieves the total supply at the time `snapshotId` was created. * @dev Retrieves the total supply at the time `snapshotId` was created.
*/ */
function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) { function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply(); return snapshotted ? value : totalSupply();
...@@ -127,7 +127,11 @@ abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable { ...@@ -127,7 +127,11 @@ abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable {
// Update balance and/or total supply snapshots before the values are modified. This is implemented // Update balance and/or total supply snapshots before the values are modified. This is implemented
// in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount); super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { if (from == address(0)) {
...@@ -145,9 +149,7 @@ abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable { ...@@ -145,9 +149,7 @@ abstract contract ERC20SnapshotUpgradeable is Initializable, ERC20Upgradeable {
} }
} }
function _valueAt(uint256 snapshotId, Snapshots storage snapshots) function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) {
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0"); require(snapshotId > 0, "ERC20Snapshot: id is 0");
require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id"); require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id");
......
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20VotesUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of ERC20 to support Compound's voting and delegation. This version exactly matches Compound's
* interface, with the drawback of only supporting supply up to (2^96^ - 1).
*
* NOTE: You should use this contract if you need exact compatibility with COMP (for example in order to use your token
* with Governor Alpha or Bravo) and if you are sure the supply cap of 2^96^ is enough for you. Otherwise, use the
* {ERC20Votes} variant of this module.
*
* This extensions keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getCurrentVotes} and {getPriorVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
* Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this
* will significantly increase the base gas cost of transfers.
*
* _Available since v4.2._
*/
abstract contract ERC20VotesCompUpgradeable is Initializable, ERC20VotesUpgradeable {
function __ERC20VotesComp_init_unchained() internal initializer {
}
/**
* @dev Comp version of the {getVotes} accessor, with `uint96` return type.
*/
function getCurrentVotes(address account) external view returns (uint96) {
return SafeCastUpgradeable.toUint96(getVotes(account));
}
/**
* @dev Comp version of the {getPastVotes} accessor, with `uint96` return type.
*/
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96) {
return SafeCastUpgradeable.toUint96(getPastVotes(account, blockNumber));
}
/**
* @dev Maximum token supply. Reduced to `type(uint96).max` (2^96^ - 1) to fit COMP interface.
*/
function _maxSupply() internal view virtual override returns (uint224) {
return type(uint96).max;
}
uint256[50] private __gap;
}
...@@ -3,18 +3,20 @@ ...@@ -3,18 +3,20 @@
pragma solidity ^0.8.0; pragma solidity ^0.8.0;
import "./draft-ERC20PermitUpgradeable.sol"; import "./draft-ERC20PermitUpgradeable.sol";
import "./IERC20VotesUpgradeable.sol";
import "../../../utils/math/MathUpgradeable.sol"; import "../../../utils/math/MathUpgradeable.sol";
import "../../../utils/math/SafeCastUpgradeable.sol"; import "../../../utils/math/SafeCastUpgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol"; import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol"; import "../../../proxy/utils/Initializable.sol";
/** /**
* @dev Extension of the ERC20 token contract to support Compound's voting and delegation. * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
* *
* This extensions keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getCurrentVotes} and {getPriorVotes}. * power can be queried through the public accessors {getVotes} and {getPastVotes}.
* *
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
...@@ -23,40 +25,56 @@ import "../../../proxy/utils/Initializable.sol"; ...@@ -23,40 +25,56 @@ import "../../../proxy/utils/Initializable.sol";
* *
* _Available since v4.2._ * _Available since v4.2._
*/ */
abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable, ERC20PermitUpgradeable { abstract contract ERC20VotesUpgradeable is Initializable, ERC20PermitUpgradeable {
function __ERC20Votes_init_unchained() internal initializer { function __ERC20Votes_init_unchained() internal initializer {
} }
bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
mapping (address => address) private _delegates; bytes32 private constant _DELEGATION_TYPEHASH =
mapping (address => Checkpoint[]) private _checkpoints; keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints; 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`. * @dev Get the `pos`-th checkpoint for `account`.
*/ */
function checkpoints(address account, uint32 pos) external view virtual override returns (Checkpoint memory) { function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos]; return _checkpoints[account][pos];
} }
/** /**
* @dev Get number of checkpoints for `account`. * @dev Get number of checkpoints for `account`.
*/ */
function numCheckpoints(address account) external view virtual override returns (uint32) { function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCastUpgradeable.toUint32(_checkpoints[account].length); return SafeCastUpgradeable.toUint32(_checkpoints[account].length);
} }
/** /**
* @dev Get the address `account` is currently delegating to. * @dev Get the address `account` is currently delegating to.
*/ */
function delegates(address account) public view virtual override returns (address) { function delegates(address account) public view virtual returns (address) {
return _delegates[account]; return _delegates[account];
} }
/** /**
* @dev Gets the current votes balance for `account` * @dev Gets the current votes balance for `account`
*/ */
function getCurrentVotes(address account) external view override returns (uint256) { function getVotes(address account) public view returns (uint256) {
uint256 pos = _checkpoints[account].length; uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
} }
...@@ -68,7 +86,7 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable ...@@ -68,7 +86,7 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable
* *
* - `blockNumber` must have been already mined * - `blockNumber` must have been already mined
*/ */
function getPriorVotes(address account, uint256 blockNumber) external view override returns (uint256) { function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined"); require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber); return _checkpointsLookup(_checkpoints[account], blockNumber);
} }
...@@ -81,7 +99,7 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable ...@@ -81,7 +99,7 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable
* *
* - `blockNumber` must have been already mined * - `blockNumber` must have been already mined
*/ */
function getPriorTotalSupply(uint256 blockNumber) external view override returns (uint256) { function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined"); require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
} }
...@@ -118,58 +136,75 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable ...@@ -118,58 +136,75 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable
/** /**
* @dev Delegate votes from the sender to `delegatee`. * @dev Delegate votes from the sender to `delegatee`.
*/ */
function delegate(address delegatee) public virtual override { function delegate(address delegatee) public virtual {
return _delegate(_msgSender(), delegatee); return _delegate(_msgSender(), delegatee);
} }
/** /**
* @dev Delegates votes from signer to `delegatee` * @dev Delegates votes from signer to `delegatee`
*/ */
function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) function delegateBySig(
public virtual override address delegatee,
{ uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(block.timestamp <= expiry, "ERC20Votes: signature expired"); require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSAUpgradeable.recover( address signer = ECDSAUpgradeable.recover(
_hashTypedDataV4(keccak256(abi.encode( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
_DELEGATION_TYPEHASH, v,
delegatee, r,
nonce, s
expiry
))),
v, r, s
); );
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
return _delegate(signer, delegatee); return _delegate(signer, delegatee);
} }
/** /**
* @dev snapshot the totalSupply after it has been increassed. * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/ */
function _mint(address account, uint256 amount) internal virtual override { function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount); super._mint(account, amount);
require(totalSupply() <= type(uint224).max, "ERC20Votes: total supply exceeds 2**224"); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, add, amount); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
} }
/** /**
* @dev snapshot the totalSupply after it has been decreased. * @dev Snapshots the totalSupply after it has been decreased.
*/ */
function _burn(address account, uint256 amount) internal virtual override { function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount); super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, subtract, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
} }
/** /**
* @dev move voting power when tokens are transferred. * @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/ */
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
_moveVotingPower(delegates(from), delegates(to), amount); _moveVotingPower(delegates(from), delegates(to), amount);
} }
/** /**
* @dev Change delegation for `delegator` to `delegatee`. * @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/ */
function _delegate(address delegator, address delegatee) internal virtual { function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator); address currentDelegate = delegates(delegator);
...@@ -181,15 +216,19 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable ...@@ -181,15 +216,19 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable
_moveVotingPower(currentDelegate, delegatee, delegatorBalance); _moveVotingPower(currentDelegate, delegatee, delegatorBalance);
} }
function _moveVotingPower(address src, address dst, uint256 amount) private { function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) { if (src != dst && amount > 0) {
if (src != address(0)) { if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], subtract, amount); (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight); emit DelegateVotesChanged(src, oldWeight, newWeight);
} }
if (dst != address(0)) { if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], add, amount); (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight); emit DelegateVotesChanged(dst, oldWeight, newWeight);
} }
} }
...@@ -197,11 +236,9 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable ...@@ -197,11 +236,9 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable
function _writeCheckpoint( function _writeCheckpoint(
Checkpoint[] storage ckpts, Checkpoint[] storage ckpts,
function (uint256, uint256) view returns (uint256) op, function(uint256, uint256) view returns (uint256) op,
uint256 delta uint256 delta
) ) private returns (uint256 oldWeight, uint256 newWeight) {
private returns (uint256 oldWeight, uint256 newWeight)
{
uint256 pos = ckpts.length; uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta); newWeight = op(oldWeight, delta);
...@@ -209,18 +246,15 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable ...@@ -209,18 +246,15 @@ abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCastUpgradeable.toUint224(newWeight); ckpts[pos - 1].votes = SafeCastUpgradeable.toUint224(newWeight);
} else { } else {
ckpts.push(Checkpoint({ ckpts.push(Checkpoint({fromBlock: SafeCastUpgradeable.toUint32(block.number), votes: SafeCastUpgradeable.toUint224(newWeight)}));
fromBlock: SafeCastUpgradeable.toUint32(block.number),
votes: SafeCastUpgradeable.toUint224(newWeight)
}));
} }
} }
function add(uint256 a, uint256 b) private pure returns (uint256) { function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b; return a + b;
} }
function subtract(uint256 a, uint256 b) private pure returns (uint256) { function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b; return a - b;
} }
uint256[47] private __gap; uint256[47] private __gap;
......
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
interface IERC20VotesUpgradeable is IERC20Upgradeable {
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
function delegates(address owner) external view returns (address);
function checkpoints(address account, uint32 pos) external view returns (Checkpoint memory);
function numCheckpoints(address account) external view returns (uint32);
function getCurrentVotes(address account) external view returns (uint256);
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256);
function getPriorTotalSupply(uint256 blockNumber) external view returns(uint256);
function delegate(address delegatee) external;
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
}
...@@ -22,7 +22,7 @@ import "../../../proxy/utils/Initializable.sol"; ...@@ -22,7 +22,7 @@ import "../../../proxy/utils/Initializable.sol";
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter; using CountersUpgradeable for CountersUpgradeable.Counter;
mapping (address => CountersUpgradeable.Counter) private _nonces; mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase // solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH; bytes32 private _PERMIT_TYPEHASH;
...@@ -39,26 +39,23 @@ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IER ...@@ -39,26 +39,23 @@ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IER
} }
function __ERC20Permit_init_unchained(string memory name) internal initializer { function __ERC20Permit_init_unchained(string memory name) internal initializer {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
}
/** /**
* @dev See {IERC20Permit-permit}. * @dev See {IERC20Permit-permit}.
*/ */
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { function permit(
// solhint-disable-next-line not-rely-on-time address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256( bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_useNonce(owner),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash); bytes32 hash = _hashTypedDataV4(structHash);
......
...@@ -32,7 +32,15 @@ interface IERC20PermitUpgradeable { ...@@ -32,7 +32,15 @@ interface IERC20PermitUpgradeable {
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section]. * section].
*/ */
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/** /**
* @dev Returns the current nonce for `owner`. This value must be * @dev Returns the current nonce for `owner`. This value must be
......
...@@ -97,7 +97,11 @@ contract ERC20PresetMinterPauserUpgradeable is Initializable, ContextUpgradeable ...@@ -97,7 +97,11 @@ contract ERC20PresetMinterPauserUpgradeable is Initializable, ContextUpgradeable
_unpause(); _unpause();
} }
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount); super._beforeTokenTransfer(from, to, amount);
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -17,11 +17,20 @@ import "../../../utils/AddressUpgradeable.sol"; ...@@ -17,11 +17,20 @@ import "../../../utils/AddressUpgradeable.sol";
library SafeERC20Upgradeable { library SafeERC20Upgradeable {
using AddressUpgradeable for address; using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
} }
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
} }
...@@ -32,23 +41,35 @@ library SafeERC20Upgradeable { ...@@ -32,23 +41,35 @@ library SafeERC20Upgradeable {
* Whenever possible, use {safeIncreaseAllowance} and * Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead. * {safeDecreaseAllowance} instead.
*/ */
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance, // safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use // or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length require(
require((value == 0) || (token.allowance(address(this), spender) == 0), (value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance" "SafeERC20: approve from non-zero to non-zero allowance"
); );
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
} }
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value; uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
} }
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked { unchecked {
uint256 oldAllowance = token.allowance(address(this), spender); uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
...@@ -69,8 +90,8 @@ library SafeERC20Upgradeable { ...@@ -69,8 +90,8 @@ library SafeERC20Upgradeable {
// the target address contains contract code and also asserts for success in the low-level call. // the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional if (returndata.length > 0) {
// solhint-disable-next-line max-line-length // Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
} }
} }
......
...@@ -24,12 +24,19 @@ contract TokenTimelockUpgradeable is Initializable { ...@@ -24,12 +24,19 @@ contract TokenTimelockUpgradeable is Initializable {
// timestamp when token release is enabled // timestamp when token release is enabled
uint256 private _releaseTime; uint256 private _releaseTime;
function __TokenTimelock_init(IERC20Upgradeable token_, address beneficiary_, uint256 releaseTime_) internal initializer { function __TokenTimelock_init(
IERC20Upgradeable token_,
address beneficiary_,
uint256 releaseTime_
) internal initializer {
__TokenTimelock_init_unchained(token_, beneficiary_, releaseTime_); __TokenTimelock_init_unchained(token_, beneficiary_, releaseTime_);
} }
function __TokenTimelock_init_unchained(IERC20Upgradeable token_, address beneficiary_, uint256 releaseTime_) internal initializer { function __TokenTimelock_init_unchained(
// solhint-disable-next-line not-rely-on-time IERC20Upgradeable token_,
address beneficiary_,
uint256 releaseTime_
) internal initializer {
require(releaseTime_ > block.timestamp, "TokenTimelock: release time is before current time"); require(releaseTime_ > block.timestamp, "TokenTimelock: release time is before current time");
_token = token_; _token = token_;
_beneficiary = beneficiary_; _beneficiary = beneficiary_;
...@@ -61,7 +68,6 @@ contract TokenTimelockUpgradeable is Initializable { ...@@ -61,7 +68,6 @@ contract TokenTimelockUpgradeable is Initializable {
* @notice Transfers tokens held by timelock to beneficiary. * @notice Transfers tokens held by timelock to beneficiary.
*/ */
function release() public virtual { function release() public virtual {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time"); require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time");
uint256 amount = token().balanceOf(address(this)); uint256 amount = token().balanceOf(address(this));
......
...@@ -27,16 +27,16 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -27,16 +27,16 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
string private _symbol; string private _symbol;
// Mapping from token ID to owner address // Mapping from token ID to owner address
mapping (uint256 => address) private _owners; mapping(uint256 => address) private _owners;
// Mapping owner address to token count // Mapping owner address to token count
mapping (address => uint256) private _balances; mapping(address => uint256) private _balances;
// Mapping from token ID to approved address // Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals; mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals // Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals;
/** /**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
...@@ -56,9 +56,10 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -56,9 +56,10 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
* @dev See {IERC165-supportsInterface}. * @dev See {IERC165-supportsInterface}.
*/ */
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC721Upgradeable).interfaceId return
|| interfaceId == type(IERC721MetadataUpgradeable).interfaceId interfaceId == type(IERC721Upgradeable).interfaceId ||
|| super.supportsInterface(interfaceId); interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
} }
/** /**
...@@ -99,9 +100,7 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -99,9 +100,7 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI(); string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
} }
/** /**
...@@ -120,7 +119,8 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -120,7 +119,8 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
address owner = ERC721Upgradeable.ownerOf(tokenId); address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner"); require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all" "ERC721: approve caller is not owner nor approved for all"
); );
...@@ -156,7 +156,11 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -156,7 +156,11 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
/** /**
* @dev See {IERC721-transferFrom}. * @dev See {IERC721-transferFrom}.
*/ */
function transferFrom(address from, address to, uint256 tokenId) public virtual override { function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length //solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
...@@ -166,14 +170,23 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -166,14 +170,23 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
/** /**
* @dev See {IERC721-safeTransferFrom}. * @dev See {IERC721-safeTransferFrom}.
*/ */
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, ""); safeTransferFrom(from, to, tokenId, "");
} }
/** /**
* @dev See {IERC721-safeTransferFrom}. * @dev See {IERC721-safeTransferFrom}.
*/ */
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data); _safeTransfer(from, to, tokenId, _data);
} }
...@@ -196,7 +209,12 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -196,7 +209,12 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
* *
* Emits a {Transfer} event. * Emits a {Transfer} event.
*/ */
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId); _transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
} }
...@@ -244,9 +262,16 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -244,9 +262,16 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients. * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/ */
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId); _mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
} }
/** /**
...@@ -308,7 +333,11 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -308,7 +333,11 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
* *
* Emits a {Transfer} event. * Emits a {Transfer} event.
*/ */
function _transfer(address from, address to, uint256 tokenId) internal virtual { function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address"); require(to != address(0), "ERC721: transfer to the zero address");
...@@ -344,9 +373,12 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -344,9 +373,12 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
* @param _data bytes optional data to send along with the call * @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value * @return bool whether the call correctly returned the expected magic value
*/ */
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) function _checkOnERC721Received(
private returns (bool) address from,
{ address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) { if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
...@@ -354,7 +386,6 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -354,7 +386,6 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
if (reason.length == 0) { if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer"); revert("ERC721: transfer to non ERC721Receiver implementer");
} else { } else {
// solhint-disable-next-line no-inline-assembly
assembly { assembly {
revert(add(32, reason), mload(reason)) revert(add(32, reason), mload(reason))
} }
...@@ -379,6 +410,10 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab ...@@ -379,6 +410,10 @@ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeab
* *
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/ */
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap; uint256[44] private __gap;
} }
...@@ -17,5 +17,10 @@ interface IERC721ReceiverUpgradeable { ...@@ -17,5 +17,10 @@ interface IERC721ReceiverUpgradeable {
* *
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/ */
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
} }
...@@ -51,7 +51,11 @@ interface IERC721Upgradeable is IERC165Upgradeable { ...@@ -51,7 +51,11 @@ interface IERC721Upgradeable is IERC165Upgradeable {
* *
* Emits a {Transfer} event. * Emits a {Transfer} event.
*/ */
function safeTransferFrom(address from, address to, uint256 tokenId) external; function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/** /**
* @dev Transfers `tokenId` token from `from` to `to`. * @dev Transfers `tokenId` token from `from` to `to`.
...@@ -67,7 +71,11 @@ interface IERC721Upgradeable is IERC165Upgradeable { ...@@ -67,7 +71,11 @@ interface IERC721Upgradeable is IERC165Upgradeable {
* *
* Emits a {Transfer} event. * Emits a {Transfer} event.
*/ */
function transferFrom(address from, address to, uint256 tokenId) external; function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/** /**
* @dev Gives permission to `to` to transfer `tokenId` token to another account. * @dev Gives permission to `to` to transfer `tokenId` token to another account.
...@@ -125,5 +133,10 @@ interface IERC721Upgradeable is IERC165Upgradeable { ...@@ -125,5 +133,10 @@ interface IERC721Upgradeable is IERC165Upgradeable {
* *
* Emits a {Transfer} event. * Emits a {Transfer} event.
*/ */
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} }
...@@ -36,8 +36,7 @@ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeabl ...@@ -36,8 +36,7 @@ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeabl
* @dev See {IERC165-supportsInterface}. * @dev See {IERC165-supportsInterface}.
*/ */
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
|| super.supportsInterface(interfaceId);
} }
/** /**
...@@ -78,7 +77,11 @@ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeabl ...@@ -78,7 +77,11 @@ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeabl
* *
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/ */
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId); super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) { if (from == address(0)) {
......
...@@ -30,7 +30,11 @@ abstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, ...@@ -30,7 +30,11 @@ abstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable,
* *
* - the contract must not be paused. * - the contract must not be paused.
*/ */
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId); super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused"); require(!paused(), "ERC721Pausable: token transfer while paused");
......
...@@ -20,7 +20,7 @@ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeabl ...@@ -20,7 +20,7 @@ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeabl
using StringsUpgradeable for uint256; using StringsUpgradeable for uint256;
// Optional mapping for token URIs // Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs; mapping(uint256 => string) private _tokenURIs;
/** /**
* @dev See {IERC721Metadata-tokenURI}. * @dev See {IERC721Metadata-tokenURI}.
......
...@@ -9,7 +9,6 @@ import "../IERC721Upgradeable.sol"; ...@@ -9,7 +9,6 @@ import "../IERC721Upgradeable.sol";
* @dev See https://eips.ethereum.org/EIPS/eip-721 * @dev See https://eips.ethereum.org/EIPS/eip-721
*/ */
interface IERC721EnumerableUpgradeable is IERC721Upgradeable { interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/** /**
* @dev Returns the total amount of tokens stored by the contract. * @dev Returns the total amount of tokens stored by the contract.
*/ */
......
...@@ -9,7 +9,6 @@ import "../IERC721Upgradeable.sol"; ...@@ -9,7 +9,6 @@ import "../IERC721Upgradeable.sol";
* @dev See https://eips.ethereum.org/EIPS/eip-721 * @dev See https://eips.ethereum.org/EIPS/eip-721
*/ */
interface IERC721MetadataUpgradeable is IERC721Upgradeable { interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/** /**
* @dev Returns the token collection name. * @dev Returns the token collection name.
*/ */
......
...@@ -26,8 +26,18 @@ import "../../../proxy/utils/Initializable.sol"; ...@@ -26,8 +26,18 @@ import "../../../proxy/utils/Initializable.sol";
* roles, as well as the default admin role, which will let it grant both minter * roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts. * and pauser roles to other accounts.
*/ */
contract ERC721PresetMinterPauserAutoIdUpgradeable is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC721EnumerableUpgradeable, ERC721BurnableUpgradeable, ERC721PausableUpgradeable { contract ERC721PresetMinterPauserAutoIdUpgradeable is
function initialize(string memory name, string memory symbol, string memory baseTokenURI) public virtual initializer { Initializable, ContextUpgradeable,
AccessControlEnumerableUpgradeable,
ERC721EnumerableUpgradeable,
ERC721BurnableUpgradeable,
ERC721PausableUpgradeable
{
function initialize(
string memory name,
string memory symbol,
string memory baseTokenURI
) public virtual initializer {
__ERC721PresetMinterPauserAutoId_init(name, symbol, baseTokenURI); __ERC721PresetMinterPauserAutoId_init(name, symbol, baseTokenURI);
} }
using CountersUpgradeable for CountersUpgradeable.Counter; using CountersUpgradeable for CountersUpgradeable.Counter;
...@@ -46,7 +56,11 @@ contract ERC721PresetMinterPauserAutoIdUpgradeable is Initializable, ContextUpgr ...@@ -46,7 +56,11 @@ contract ERC721PresetMinterPauserAutoIdUpgradeable is Initializable, ContextUpgr
* Token URIs will be autogenerated based on `baseURI` and their token IDs. * Token URIs will be autogenerated based on `baseURI` and their token IDs.
* See {ERC721-tokenURI}. * See {ERC721-tokenURI}.
*/ */
function __ERC721PresetMinterPauserAutoId_init(string memory name, string memory symbol, string memory baseTokenURI) internal initializer { function __ERC721PresetMinterPauserAutoId_init(
string memory name,
string memory symbol,
string memory baseTokenURI
) internal initializer {
__Context_init_unchained(); __Context_init_unchained();
__ERC165_init_unchained(); __ERC165_init_unchained();
__AccessControl_init_unchained(); __AccessControl_init_unchained();
...@@ -59,7 +73,11 @@ contract ERC721PresetMinterPauserAutoIdUpgradeable is Initializable, ContextUpgr ...@@ -59,7 +73,11 @@ contract ERC721PresetMinterPauserAutoIdUpgradeable is Initializable, ContextUpgr
__ERC721PresetMinterPauserAutoId_init_unchained(name, symbol, baseTokenURI); __ERC721PresetMinterPauserAutoId_init_unchained(name, symbol, baseTokenURI);
} }
function __ERC721PresetMinterPauserAutoId_init_unchained(string memory name, string memory symbol, string memory baseTokenURI) internal initializer { function __ERC721PresetMinterPauserAutoId_init_unchained(
string memory name,
string memory symbol,
string memory baseTokenURI
) internal initializer {
_baseTokenURI = baseTokenURI; _baseTokenURI = baseTokenURI;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
...@@ -120,14 +138,24 @@ contract ERC721PresetMinterPauserAutoIdUpgradeable is Initializable, ContextUpgr ...@@ -120,14 +138,24 @@ contract ERC721PresetMinterPauserAutoIdUpgradeable is Initializable, ContextUpgr
_unpause(); _unpause();
} }
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721PausableUpgradeable) { function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721PausableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId); super._beforeTokenTransfer(from, to, tokenId);
} }
/** /**
* @dev See {IERC165-supportsInterface}. * @dev See {IERC165-supportsInterface}.
*/ */
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId); return super.supportsInterface(interfaceId);
} }
uint256[48] private __gap; uint256[48] private __gap;
......
...@@ -5,7 +5,7 @@ pragma solidity ^0.8.0; ...@@ -5,7 +5,7 @@ pragma solidity ^0.8.0;
import "../IERC721ReceiverUpgradeable.sol"; import "../IERC721ReceiverUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol"; import "../../../proxy/utils/Initializable.sol";
/** /**
* @dev Implementation of the {IERC721Receiver} interface. * @dev Implementation of the {IERC721Receiver} interface.
* *
* Accepts all token transfers. * Accepts all token transfers.
...@@ -18,13 +18,17 @@ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { ...@@ -18,13 +18,17 @@ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable {
function __ERC721Holder_init_unchained() internal initializer { function __ERC721Holder_init_unchained() internal initializer {
} }
/** /**
* @dev See {IERC721Receiver-onERC721Received}. * @dev See {IERC721Receiver-onERC721Received}.
* *
* Always returns `IERC721Receiver.onERC721Received.selector`. * Always returns `IERC721Receiver.onERC721Received.selector`.
*/ */
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector; return this.onERC721Received.selector;
} }
uint256[50] private __gap; uint256[50] private __gap;
......
...@@ -29,7 +29,7 @@ import "../../proxy/utils/Initializable.sol"; ...@@ -29,7 +29,7 @@ import "../../proxy/utils/Initializable.sol";
contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradeable, IERC20Upgradeable { contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradeable, IERC20Upgradeable {
using AddressUpgradeable for address; using AddressUpgradeable for address;
IERC1820RegistryUpgradeable constant internal _ERC1820_REGISTRY = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); IERC1820RegistryUpgradeable internal constant _ERC1820_REGISTRY = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances; mapping(address => uint256) private _balances;
...@@ -136,7 +136,11 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -136,7 +136,11 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
* *
* Also emits a {IERC20-Transfer} event for ERC20 compatibility. * Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/ */
function send(address recipient, uint256 amount, bytes memory data) public virtual override { function send(
address recipient,
uint256 amount,
bytes memory data
) public virtual override {
_send(_msgSender(), recipient, amount, data, "", true); _send(_msgSender(), recipient, amount, data, "", true);
} }
...@@ -175,7 +179,8 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -175,7 +179,8 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
* @dev See {IERC777-isOperatorFor}. * @dev See {IERC777-isOperatorFor}.
*/ */
function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) { function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) {
return operator == tokenHolder || return
operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator]; _operators[tokenHolder][operator];
} }
...@@ -228,11 +233,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -228,11 +233,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
uint256 amount, uint256 amount,
bytes memory data, bytes memory data,
bytes memory operatorData bytes memory operatorData
) ) public virtual override {
public
virtual
override
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true); _send(sender, recipient, amount, data, operatorData, true);
} }
...@@ -242,7 +243,12 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -242,7 +243,12 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
* *
* Emits {Burned} and {IERC20-Transfer} events. * Emits {Burned} and {IERC20-Transfer} events.
*/ */
function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public virtual override { function operatorBurn(
address account,
uint256 amount,
bytes memory data,
bytes memory operatorData
) public virtual override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData); _burn(account, amount, data, operatorData);
} }
...@@ -278,7 +284,11 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -278,7 +284,11 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
* *
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/ */
function transferFrom(address holder, address recipient, uint256 amount) public virtual override returns (bool) { function transferFrom(
address holder,
address recipient,
uint256 amount
) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address"); require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address"); require(holder != address(0), "ERC777: transfer from the zero address");
...@@ -319,10 +329,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -319,10 +329,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
uint256 amount, uint256 amount,
bytes memory userData, bytes memory userData,
bytes memory operatorData bytes memory operatorData
) ) internal virtual {
internal
virtual
{
_mint(account, amount, userData, operatorData, true); _mint(account, amount, userData, operatorData, true);
} }
...@@ -350,10 +357,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -350,10 +357,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
bytes memory userData, bytes memory userData,
bytes memory operatorData, bytes memory operatorData,
bool requireReceptionAck bool requireReceptionAck
) ) internal virtual {
internal
virtual
{
require(account != address(0), "ERC777: mint to the zero address"); require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender(); address operator = _msgSender();
...@@ -386,10 +390,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -386,10 +390,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
bytes memory userData, bytes memory userData,
bytes memory operatorData, bytes memory operatorData,
bool requireReceptionAck bool requireReceptionAck
) ) internal virtual {
internal
virtual
{
require(from != address(0), "ERC777: send from the zero address"); require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address"); require(to != address(0), "ERC777: send to the zero address");
...@@ -414,10 +415,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -414,10 +415,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
uint256 amount, uint256 amount,
bytes memory data, bytes memory data,
bytes memory operatorData bytes memory operatorData
) ) internal virtual {
internal
virtual
{
require(from != address(0), "ERC777: burn from the zero address"); require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender(); address operator = _msgSender();
...@@ -445,9 +443,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -445,9 +443,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
uint256 amount, uint256 amount,
bytes memory userData, bytes memory userData,
bytes memory operatorData bytes memory operatorData
) ) private {
private
{
_beforeTokenTransfer(operator, from, to, amount); _beforeTokenTransfer(operator, from, to, amount);
uint256 fromBalance = _balances[from]; uint256 fromBalance = _balances[from];
...@@ -466,7 +462,11 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -466,7 +462,11 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
* *
* Note that accounts cannot have allowance issued by their operators. * Note that accounts cannot have allowance issued by their operators.
*/ */
function _approve(address holder, address spender, uint256 value) internal { function _approve(
address holder,
address spender,
uint256 value
) internal {
require(holder != address(0), "ERC777: approve from the zero address"); require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address"); require(spender != address(0), "ERC777: approve to the zero address");
...@@ -490,9 +490,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -490,9 +490,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
uint256 amount, uint256 amount,
bytes memory userData, bytes memory userData,
bytes memory operatorData bytes memory operatorData
) ) private {
private
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) { if (implementer != address(0)) {
IERC777SenderUpgradeable(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); IERC777SenderUpgradeable(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
...@@ -518,9 +516,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -518,9 +516,7 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
bytes memory userData, bytes memory userData,
bytes memory operatorData, bytes memory operatorData,
bool requireReceptionAck bool requireReceptionAck
) ) private {
private
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) { if (implementer != address(0)) {
IERC777RecipientUpgradeable(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); IERC777RecipientUpgradeable(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
...@@ -543,6 +539,11 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea ...@@ -543,6 +539,11 @@ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradea
* *
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/ */
function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual { } function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256 amount
) internal virtual {}
uint256[41] private __gap; uint256[41] private __gap;
} }
...@@ -58,7 +58,11 @@ interface IERC777Upgradeable { ...@@ -58,7 +58,11 @@ interface IERC777Upgradeable {
* - if `recipient` is a contract, it must implement the {IERC777Recipient} * - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface. * interface.
*/ */
function send(address recipient, uint256 amount, bytes calldata data) external; function send(
address recipient,
uint256 amount,
bytes calldata data
) external;
/** /**
* @dev Destroys `amount` tokens from the caller's account, reducing the * @dev Destroys `amount` tokens from the caller's account, reducing the
......
...@@ -29,8 +29,9 @@ library AddressUpgradeable { ...@@ -29,8 +29,9 @@ library AddressUpgradeable {
// constructor execution. // constructor execution.
uint256 size; uint256 size;
// solhint-disable-next-line no-inline-assembly assembly {
assembly { size := extcodesize(account) } size := extcodesize(account)
}
return size > 0; return size > 0;
} }
...@@ -53,8 +54,7 @@ library AddressUpgradeable { ...@@ -53,8 +54,7 @@ library AddressUpgradeable {
function sendValue(address payable recipient, uint256 amount) internal { function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance"); require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}("");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted"); require(success, "Address: unable to send value, recipient may have reverted");
} }
...@@ -86,7 +86,11 @@ library AddressUpgradeable { ...@@ -86,7 +86,11 @@ library AddressUpgradeable {
* *
* _Available since v3.1._ * _Available since v3.1._
*/ */
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage); return functionCallWithValue(target, data, 0, errorMessage);
} }
...@@ -101,7 +105,11 @@ library AddressUpgradeable { ...@@ -101,7 +105,11 @@ library AddressUpgradeable {
* *
* _Available since v3.1._ * _Available since v3.1._
*/ */
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
} }
...@@ -111,12 +119,16 @@ library AddressUpgradeable { ...@@ -111,12 +119,16 @@ library AddressUpgradeable {
* *
* _Available since v3.1._ * _Available since v3.1._
*/ */
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call"); require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract"); require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data);
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage); return _verifyCallResult(success, returndata, errorMessage);
} }
...@@ -136,15 +148,22 @@ library AddressUpgradeable { ...@@ -136,15 +148,22 @@ library AddressUpgradeable {
* *
* _Available since v3.3._ * _Available since v3.3._
*/ */
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract"); require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data); (bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage); return _verifyCallResult(success, returndata, errorMessage);
} }
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) { if (success) {
return returndata; return returndata;
} else { } else {
...@@ -152,7 +171,6 @@ library AddressUpgradeable { ...@@ -152,7 +171,6 @@ library AddressUpgradeable {
if (returndata.length > 0) { if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly // The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly { assembly {
let returndata_size := mload(returndata) let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size) revert(add(32, returndata), returndata_size)
......
...@@ -26,11 +26,14 @@ library Create2Upgradeable { ...@@ -26,11 +26,14 @@ library Create2Upgradeable {
* - the factory must have a balance of at least `amount`. * - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/ */
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address) { function deploy(
uint256 amount,
bytes32 salt,
bytes memory bytecode
) internal returns (address) {
address addr; address addr;
require(address(this).balance >= amount, "Create2: insufficient balance"); require(address(this).balance >= amount, "Create2: insufficient balance");
require(bytecode.length != 0, "Create2: bytecode length is zero"); require(bytecode.length != 0, "Create2: bytecode length is zero");
// solhint-disable-next-line no-inline-assembly
assembly { assembly {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
} }
...@@ -50,10 +53,12 @@ library Create2Upgradeable { ...@@ -50,10 +53,12 @@ library Create2Upgradeable {
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/ */
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) { function computeAddress(
bytes32 _data = keccak256( bytes32 salt,
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash) bytes32 bytecodeHash,
); address deployer
) internal pure returns (address) {
bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash));
return address(uint160(uint256(_data))); return address(uint160(uint256(_data)));
} }
} }
...@@ -22,7 +22,7 @@ abstract contract MulticallUpgradeable is Initializable { ...@@ -22,7 +22,7 @@ abstract contract MulticallUpgradeable is Initializable {
*/ */
function multicall(bytes[] calldata data) external returns (bytes[] memory results) { function multicall(bytes[] calldata data) external returns (bytes[] memory results) {
results = new bytes[](data.length); results = new bytes[](data.length);
for (uint i = 0; i < data.length; i++) { for (uint256 i = 0; i < data.length; i++) {
results[i] = _functionDelegateCall(address(this), data[i]); results[i] = _functionDelegateCall(address(this), data[i]);
} }
return results; return results;
......
...@@ -6,7 +6,7 @@ pragma solidity ^0.8.0; ...@@ -6,7 +6,7 @@ pragma solidity ^0.8.0;
* @dev String operations. * @dev String operations.
*/ */
library StringsUpgradeable { library StringsUpgradeable {
bytes16 private constant alphabet = "0123456789abcdef"; bytes16 private constant _ALPHABET = "0123456789abcdef";
/** /**
* @dev Converts a `uint256` to its ASCII `string` decimal representation. * @dev Converts a `uint256` to its ASCII `string` decimal representation.
...@@ -57,11 +57,10 @@ library StringsUpgradeable { ...@@ -57,11 +57,10 @@ library StringsUpgradeable {
buffer[0] = "0"; buffer[0] = "0";
buffer[1] = "x"; buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) { for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf]; buffer[i] = _ALPHABET[value & 0xf];
value >>= 4; value >>= 4;
} }
require(value == 0, "Strings: hex length insufficient"); require(value == 0, "Strings: hex length insufficient");
return string(buffer); return string(buffer);
} }
} }
...@@ -39,7 +39,6 @@ library ECDSAUpgradeable { ...@@ -39,7 +39,6 @@ library ECDSAUpgradeable {
if (signature.length == 65) { if (signature.length == 65) {
// ecrecover takes the signature parameters, and the only way to get them // ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly. // currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly { assembly {
r := mload(add(signature, 0x20)) r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40)) s := mload(add(signature, 0x40))
...@@ -48,7 +47,6 @@ library ECDSAUpgradeable { ...@@ -48,7 +47,6 @@ library ECDSAUpgradeable {
} else if (signature.length == 64) { } else if (signature.length == 64) {
// ecrecover takes the signature parameters, and the only way to get them // ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly. // currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly { assembly {
let vs := mload(add(signature, 0x40)) let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20)) r := mload(add(signature, 0x20))
...@@ -66,7 +64,12 @@ library ECDSAUpgradeable { ...@@ -66,7 +64,12 @@ library ECDSAUpgradeable {
* @dev Overload of {ECDSA-recover} that receives the `v`, * @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately. * `r` and `s` signature fields separately.
*/ */
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
...@@ -76,7 +79,10 @@ library ECDSAUpgradeable { ...@@ -76,7 +79,10 @@ library ECDSAUpgradeable {
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well. // these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address // If the signature is valid (and not malleable), return the signer address
......
...@@ -18,7 +18,11 @@ library MerkleProofUpgradeable { ...@@ -18,7 +18,11 @@ library MerkleProofUpgradeable {
* sibling hashes on the branch from the leaf to the root of the tree. Each * sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted. * pair of leaves and each pair of pre-images are assumed to be sorted.
*/ */
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf; bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) { for (uint256 i = 0; i < proof.length; i++) {
......
...@@ -17,7 +17,11 @@ import "../../interfaces/IERC1271Upgradeable.sol"; ...@@ -17,7 +17,11 @@ import "../../interfaces/IERC1271Upgradeable.sol";
* _Available since v4.1._ * _Available since v4.1._
*/ */
library SignatureCheckerUpgradeable { library SignatureCheckerUpgradeable {
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) { function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
if (AddressUpgradeable.isContract(signer)) { if (AddressUpgradeable.isContract(signer)) {
try IERC1271Upgradeable(signer).isValidSignature(hash, signature) returns (bytes4 magicValue) { try IERC1271Upgradeable(signer).isValidSignature(hash, signature) returns (bytes4 magicValue) {
return magicValue == IERC1271Upgradeable(signer).isValidSignature.selector; return magicValue == IERC1271Upgradeable(signer).isValidSignature.selector;
......
...@@ -29,6 +29,7 @@ abstract contract EIP712Upgradeable is Initializable { ...@@ -29,6 +29,7 @@ abstract contract EIP712Upgradeable is Initializable {
bytes32 private _HASHED_NAME; bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION; bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */ /* solhint-enable var-name-mixedcase */
/** /**
...@@ -61,16 +62,12 @@ abstract contract EIP712Upgradeable is Initializable { ...@@ -61,16 +62,12 @@ abstract contract EIP712Upgradeable is Initializable {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
} }
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { function _buildDomainSeparator(
return keccak256( bytes32 typeHash,
abi.encode( bytes32 name,
typeHash, bytes32 version
name, ) private view returns (bytes32) {
version, return keccak256(abi.encode(typeHash, name, version, block.chainid, address(this)));
block.chainid,
address(this)
)
);
} }
/** /**
......
...@@ -6,7 +6,7 @@ import "../../access/OwnableUpgradeable.sol"; ...@@ -6,7 +6,7 @@ import "../../access/OwnableUpgradeable.sol";
import "../AddressUpgradeable.sol"; import "../AddressUpgradeable.sol";
import "../../proxy/utils/Initializable.sol"; import "../../proxy/utils/Initializable.sol";
/** /**
* @title Escrow * @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they * @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them. * withdraw them.
......
...@@ -18,7 +18,11 @@ import "../../proxy/utils/Initializable.sol"; ...@@ -18,7 +18,11 @@ import "../../proxy/utils/Initializable.sol";
contract RefundEscrowUpgradeable is Initializable, ConditionalEscrowUpgradeable { contract RefundEscrowUpgradeable is Initializable, ConditionalEscrowUpgradeable {
using AddressUpgradeable for address payable; using AddressUpgradeable for address payable;
enum State { Active, Refunding, Closed } enum State {
Active,
Refunding,
Closed
}
event RefundsClosed(); event RefundsClosed();
event RefundsEnabled(); event RefundsEnabled();
...@@ -80,7 +84,7 @@ contract RefundEscrowUpgradeable is Initializable, ConditionalEscrowUpgradeable ...@@ -80,7 +84,7 @@ contract RefundEscrowUpgradeable is Initializable, ConditionalEscrowUpgradeable
/** /**
* @dev Allows for refunds to take place, rejecting further deposits. * @dev Allows for refunds to take place, rejecting further deposits.
*/ */
function enableRefunds() public onlyOwner virtual { function enableRefunds() public virtual onlyOwner {
require(state() == State.Active, "RefundEscrow: can only enable refunds while active"); require(state() == State.Active, "RefundEscrow: can only enable refunds while active");
_state = State.Refunding; _state = State.Refunding;
emit RefundsEnabled(); emit RefundsEnabled();
......
...@@ -21,7 +21,8 @@ library ERC165CheckerUpgradeable { ...@@ -21,7 +21,8 @@ library ERC165CheckerUpgradeable {
function supportsERC165(address account) internal view returns (bool) { function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of // Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, type(IERC165Upgradeable).interfaceId) && return
_supportsERC165Interface(account, type(IERC165Upgradeable).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID); !_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
} }
...@@ -33,8 +34,7 @@ library ERC165CheckerUpgradeable { ...@@ -33,8 +34,7 @@ library ERC165CheckerUpgradeable {
*/ */
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId // query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) && return supportsERC165(account) && _supportsERC165Interface(account, interfaceId);
_supportsERC165Interface(account, interfaceId);
} }
/** /**
...@@ -47,7 +47,11 @@ library ERC165CheckerUpgradeable { ...@@ -47,7 +47,11 @@ library ERC165CheckerUpgradeable {
* *
* _Available since v3.4._ * _Available since v3.4._
*/ */
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
internal
view
returns (bool[] memory)
{
// an array of booleans corresponding to interfaceIds and whether they're supported or not // an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
...@@ -101,7 +105,7 @@ library ERC165CheckerUpgradeable { ...@@ -101,7 +105,7 @@ library ERC165CheckerUpgradeable {
*/ */
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable(account).supportsInterface.selector, interfaceId); bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable(account).supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams);
if (result.length < 32) return false; if (result.length < 32) return false;
return success && abi.decode(result, (bool)); return success && abi.decode(result, (bool));
} }
......
...@@ -27,7 +27,13 @@ contract ERC1820ImplementerUpgradeable is Initializable, IERC1820ImplementerUpgr ...@@ -27,7 +27,13 @@ contract ERC1820ImplementerUpgradeable is Initializable, IERC1820ImplementerUpgr
/** /**
* @dev See {IERC1820Implementer-canImplementInterfaceForAddress}. * @dev See {IERC1820Implementer-canImplementInterfaceForAddress}.
*/ */
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) public view virtual override returns (bytes32) { function canImplementInterfaceForAddress(bytes32 interfaceHash, address account)
public
view
virtual
override
returns (bytes32)
{
return _supportedInterfaces[interfaceHash][account] ? _ERC1820_ACCEPT_MAGIC : bytes32(0x00); return _supportedInterfaces[interfaceHash][account] ? _ERC1820_ACCEPT_MAGIC : bytes32(0x00);
} }
......
...@@ -59,7 +59,11 @@ interface IERC1820RegistryUpgradeable { ...@@ -59,7 +59,11 @@ interface IERC1820RegistryUpgradeable {
* queried for support, unless `implementer` is the caller. See * queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}. * {IERC1820Implementer-canImplementInterfaceForAddress}.
*/ */
function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external; function setInterfaceImplementer(
address account,
bytes32 _interfaceHash,
address implementer
) external;
/** /**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such * @dev Returns the implementer of `interfaceHash` for `account`. If no such
......
...@@ -26,7 +26,7 @@ library MathUpgradeable { ...@@ -26,7 +26,7 @@ library MathUpgradeable {
*/ */
function average(uint256 a, uint256 b) internal pure returns (uint256) { function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute. // (a + b) / 2 can overflow, so we distribute.
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
} }
/** /**
......
...@@ -29,7 +29,7 @@ library SafeCastUpgradeable { ...@@ -29,7 +29,7 @@ library SafeCastUpgradeable {
* - input must fit into 224 bits * - input must fit into 224 bits
*/ */
function toUint224(uint256 value) internal pure returns (uint224) { function toUint224(uint256 value) internal pure returns (uint224) {
require(value < 2**224, "SafeCast: value doesn\'t fit in 224 bits"); require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value); return uint224(value);
} }
...@@ -44,11 +44,26 @@ library SafeCastUpgradeable { ...@@ -44,11 +44,26 @@ library SafeCastUpgradeable {
* - input must fit into 128 bits * - input must fit into 128 bits
*/ */
function toUint128(uint256 value) internal pure returns (uint128) { function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value); return uint128(value);
} }
/** /**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on * @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64). * overflow (when the input is greater than largest uint64).
* *
...@@ -59,7 +74,7 @@ library SafeCastUpgradeable { ...@@ -59,7 +74,7 @@ library SafeCastUpgradeable {
* - input must fit into 64 bits * - input must fit into 64 bits
*/ */
function toUint64(uint256 value) internal pure returns (uint64) { function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value); return uint64(value);
} }
...@@ -74,7 +89,7 @@ library SafeCastUpgradeable { ...@@ -74,7 +89,7 @@ library SafeCastUpgradeable {
* - input must fit into 32 bits * - input must fit into 32 bits
*/ */
function toUint32(uint256 value) internal pure returns (uint32) { function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value); return uint32(value);
} }
...@@ -89,7 +104,7 @@ library SafeCastUpgradeable { ...@@ -89,7 +104,7 @@ library SafeCastUpgradeable {
* - input must fit into 16 bits * - input must fit into 16 bits
*/ */
function toUint16(uint256 value) internal pure returns (uint16) { function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value); return uint16(value);
} }
...@@ -104,7 +119,7 @@ library SafeCastUpgradeable { ...@@ -104,7 +119,7 @@ library SafeCastUpgradeable {
* - input must fit into 8 bits. * - input must fit into 8 bits.
*/ */
function toUint8(uint256 value) internal pure returns (uint8) { function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value); return uint8(value);
} }
...@@ -134,7 +149,7 @@ library SafeCastUpgradeable { ...@@ -134,7 +149,7 @@ library SafeCastUpgradeable {
* _Available since v3.1._ * _Available since v3.1._
*/ */
function toInt128(int256 value) internal pure returns (int128) { function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value); return int128(value);
} }
...@@ -152,7 +167,7 @@ library SafeCastUpgradeable { ...@@ -152,7 +167,7 @@ library SafeCastUpgradeable {
* _Available since v3.1._ * _Available since v3.1._
*/ */
function toInt64(int256 value) internal pure returns (int64) { function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value); return int64(value);
} }
...@@ -170,7 +185,7 @@ library SafeCastUpgradeable { ...@@ -170,7 +185,7 @@ library SafeCastUpgradeable {
* _Available since v3.1._ * _Available since v3.1._
*/ */
function toInt32(int256 value) internal pure returns (int32) { function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value); return int32(value);
} }
...@@ -188,7 +203,7 @@ library SafeCastUpgradeable { ...@@ -188,7 +203,7 @@ library SafeCastUpgradeable {
* _Available since v3.1._ * _Available since v3.1._
*/ */
function toInt16(int256 value) internal pure returns (int16) { function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value); return int16(value);
} }
...@@ -206,7 +221,7 @@ library SafeCastUpgradeable { ...@@ -206,7 +221,7 @@ library SafeCastUpgradeable {
* _Available since v3.1._ * _Available since v3.1._
*/ */
function toInt8(int256 value) internal pure returns (int8) { function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value); return int8(value);
} }
...@@ -218,7 +233,8 @@ library SafeCastUpgradeable { ...@@ -218,7 +233,8 @@ library SafeCastUpgradeable {
* - input must be less than or equal to maxInt256. * - input must be less than or equal to maxInt256.
*/ */
function toInt256(uint256 value) internal pure returns (int256) { function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256"); // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value); return int256(value);
} }
} }
...@@ -164,7 +164,11 @@ library SafeMathUpgradeable { ...@@ -164,7 +164,11 @@ library SafeMathUpgradeable {
* *
* - Subtraction cannot overflow. * - Subtraction cannot overflow.
*/ */
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked { unchecked {
require(b <= a, errorMessage); require(b <= a, errorMessage);
return a - b; return a - b;
...@@ -183,7 +187,11 @@ library SafeMathUpgradeable { ...@@ -183,7 +187,11 @@ library SafeMathUpgradeable {
* *
* - The divisor cannot be zero. * - The divisor cannot be zero.
*/ */
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked { unchecked {
require(b > 0, errorMessage); require(b > 0, errorMessage);
return a / b; return a / b;
...@@ -205,7 +213,11 @@ library SafeMathUpgradeable { ...@@ -205,7 +213,11 @@ library SafeMathUpgradeable {
* *
* - The divisor cannot be zero. * - The divisor cannot be zero.
*/ */
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked { unchecked {
require(b > 0, errorMessage); require(b > 0, errorMessage);
return a % b; return a % b;
......
...@@ -43,8 +43,7 @@ library EnumerableMapUpgradeable { ...@@ -43,8 +43,7 @@ library EnumerableMapUpgradeable {
struct Map { struct Map {
// Storage of keys // Storage of keys
EnumerableSetUpgradeable.Bytes32Set _keys; EnumerableSetUpgradeable.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
mapping (bytes32 => bytes32) _values;
} }
/** /**
...@@ -54,7 +53,11 @@ library EnumerableMapUpgradeable { ...@@ -54,7 +53,11 @@ library EnumerableMapUpgradeable {
* Returns true if the key was added to the map, that is if it was not * Returns true if the key was added to the map, that is if it was not
* already present. * already present.
*/ */
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
map._values[key] = value; map._values[key] = value;
return map._keys.add(key); return map._keys.add(key);
} }
...@@ -130,7 +133,11 @@ library EnumerableMapUpgradeable { ...@@ -130,7 +133,11 @@ library EnumerableMapUpgradeable {
* CAUTION: This function is deprecated because it requires allocating memory for the error * CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}. * message unnecessarily. For custom revert reasons use {_tryGet}.
*/ */
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
bytes32 value = map._values[key]; bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage); require(value != 0 || _contains(map, key), errorMessage);
return value; return value;
...@@ -149,7 +156,11 @@ library EnumerableMapUpgradeable { ...@@ -149,7 +156,11 @@ library EnumerableMapUpgradeable {
* Returns true if the key was added to the map, that is if it was not * Returns true if the key was added to the map, that is if it was not
* already present. * already present.
*/ */
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
} }
...@@ -218,7 +229,11 @@ library EnumerableMapUpgradeable { ...@@ -218,7 +229,11 @@ library EnumerableMapUpgradeable {
* CAUTION: This function is deprecated because it requires allocating memory for the error * CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}. * message unnecessarily. For custom revert reasons use {tryGet}.
*/ */
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
} }
} }
...@@ -39,10 +39,9 @@ library EnumerableSetUpgradeable { ...@@ -39,10 +39,9 @@ library EnumerableSetUpgradeable {
struct Set { struct Set {
// Storage of set values // Storage of set values
bytes32[] _values; bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0 // Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set. // means a value is not in the set.
mapping (bytes32 => uint256) _indexes; mapping(bytes32 => uint256) _indexes;
} }
/** /**
...@@ -73,7 +72,8 @@ library EnumerableSetUpgradeable { ...@@ -73,7 +72,8 @@ library EnumerableSetUpgradeable {
// We read and store the value's index to prevent multiple reads from the same storage slot // We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value]; uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value) if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop'). // the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}. // This modifies the order of the array, as noted in {at}.
...@@ -238,7 +238,6 @@ library EnumerableSetUpgradeable { ...@@ -238,7 +238,6 @@ library EnumerableSetUpgradeable {
return address(uint160(uint256(_at(set._inner, index)))); return address(uint160(uint256(_at(set._inner, index))));
} }
// UintSet // UintSet
struct UintSet { struct UintSet {
......
...@@ -13,7 +13,6 @@ const argv = require('yargs/yargs')() ...@@ -13,7 +13,6 @@ const argv = require('yargs/yargs')()
.argv; .argv;
require('@nomiclabs/hardhat-truffle5'); require('@nomiclabs/hardhat-truffle5');
require('@nomiclabs/hardhat-solhint');
require('solidity-coverage'); require('solidity-coverage');
if (argv.enableGasReport) { if (argv.enableGasReport) {
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -18,10 +18,11 @@ ...@@ -18,10 +18,11 @@
"docs:watch": "npm run docs watch contracts 'docs/*.hbs'", "docs:watch": "npm run docs watch contracts 'docs/*.hbs'",
"prepare-docs": "scripts/prepare-docs.sh", "prepare-docs": "scripts/prepare-docs.sh",
"lint": "npm run lint:js && npm run lint:sol", "lint": "npm run lint:js && npm run lint:sol",
"lint:fix": "npm run lint:js:fix", "lint:fix": "npm run lint:js:fix && npm run lint:sol:fix",
"lint:js": "eslint --ignore-path .gitignore .", "lint:js": "eslint --ignore-path .gitignore .",
"lint:js:fix": "eslint --ignore-path .gitignore . --fix", "lint:js:fix": "eslint --ignore-path .gitignore . --fix",
"lint:sol": "echo 'solidity linter currently disabled' # solhint --max-warnings 0 \"contracts/**/*.sol\"", "lint:sol": "solhint 'contracts/**/*.sol' && prettier -c 'contracts/**/*.sol'",
"lint:sol:fix": "prettier --write \"contracts/**/*.sol\"",
"prepublish": "rimraf build contracts/build artifacts cache", "prepublish": "rimraf build contracts/build artifacts cache",
"prepare": "env COMPILE_MODE=production npm run compile", "prepare": "env COMPILE_MODE=production npm run compile",
"prepack": "scripts/prepack.sh", "prepack": "scripts/prepack.sh",
...@@ -49,7 +50,6 @@ ...@@ -49,7 +50,6 @@
}, },
"homepage": "https://openzeppelin.com/contracts/", "homepage": "https://openzeppelin.com/contracts/",
"devDependencies": { "devDependencies": {
"@nomiclabs/hardhat-solhint": "^2.0.0",
"@nomiclabs/hardhat-truffle5": "^2.0.0", "@nomiclabs/hardhat-truffle5": "^2.0.0",
"@nomiclabs/hardhat-web3": "^2.0.0", "@nomiclabs/hardhat-web3": "^2.0.0",
"@openzeppelin/docs-utils": "^0.1.0", "@openzeppelin/docs-utils": "^0.1.0",
...@@ -73,8 +73,10 @@ ...@@ -73,8 +73,10 @@
"merkletreejs": "^0.2.13", "merkletreejs": "^0.2.13",
"micromatch": "^4.0.2", "micromatch": "^4.0.2",
"mocha": "^8.0.1", "mocha": "^8.0.1",
"prettier": "^2.3.0",
"prettier-plugin-solidity": "^1.0.0-beta.13",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"solhint": "^3.2.0", "solhint": "^3.3.6",
"solidity-coverage": "^0.7.11", "solidity-coverage": "^0.7.11",
"solidity-docgen": "^0.5.3", "solidity-docgen": "^0.5.3",
"web3": "^1.3.0", "web3": "^1.3.0",
......
...@@ -5,7 +5,7 @@ index a7a9af54..0b7f838d 100644 ...@@ -5,7 +5,7 @@ index a7a9af54..0b7f838d 100644
@@ -24,12 +24,6 @@ import "../../../proxy/utils/Initializable.sol"; @@ -24,12 +24,6 @@ import "../../../proxy/utils/Initializable.sol";
* _Available since v4.2._ * _Available since v4.2._
*/ */
abstract contract ERC20VotesUpgradeable is Initializable, IERC20VotesUpgradeable, ERC20PermitUpgradeable { abstract contract ERC20VotesUpgradeable is Initializable, ERC20PermitUpgradeable {
- function __ERC20Votes_init() internal initializer { - function __ERC20Votes_init() internal initializer {
- __Context_init_unchained(); - __Context_init_unchained();
- __EIP712_init_unchained(name, "1"); - __EIP712_init_unchained(name, "1");
...@@ -14,4 +14,4 @@ index a7a9af54..0b7f838d 100644 ...@@ -14,4 +14,4 @@ index a7a9af54..0b7f838d 100644
- -
function __ERC20Votes_init_unchained() internal initializer { function __ERC20Votes_init_unchained() internal initializer {
} }
bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); struct Checkpoint {
diff --git a/contracts/token/ERC20/extensions/ERC20VotesCompUpgradeable.sol b/contracts/token/ERC20/extensions/ERC20VotesCompUpgradeable.sol
index 6f1f8182..0f09ea48 100644
--- a/contracts/token/ERC20/extensions/ERC20VotesCompUpgradeable.sol
+++ b/contracts/token/ERC20/extensions/ERC20VotesCompUpgradeable.sol
@@ -25,13 +25,6 @@ import "../../../proxy/utils/Initializable.sol";
* _Available since v4.2._
*/
abstract contract ERC20VotesCompUpgradeable is Initializable, ERC20VotesUpgradeable {
- function __ERC20VotesComp_init() internal initializer {
- __Context_init_unchained();
- __EIP712_init_unchained(name, "1");
- __ERC20Votes_init_unchained();
- __ERC20VotesComp_init_unchained();
- }
-
function __ERC20VotesComp_init_unchained() internal initializer {
}
/**
...@@ -85,7 +85,7 @@ contract('ERC20Votes', function (accounts) { ...@@ -85,7 +85,7 @@ contract('ERC20Votes', function (accounts) {
const amount = new BN('2').pow(new BN('224')); const amount = new BN('2').pow(new BN('224'));
await expectRevert( await expectRevert(
this.token.mint(holder, amount), this.token.mint(holder, amount),
'ERC20Votes: total supply exceeds 2**224', 'ERC20Votes: total supply risks overflowing votes',
); );
}); });
...@@ -109,10 +109,10 @@ contract('ERC20Votes', function (accounts) { ...@@ -109,10 +109,10 @@ contract('ERC20Votes', function (accounts) {
expect(await this.token.delegates(holder)).to.be.equal(holder); expect(await this.token.delegates(holder)).to.be.equal(holder);
expect(await this.token.getCurrentVotes(holder)).to.be.bignumber.equal(supply); expect(await this.token.getVotes(holder)).to.be.bignumber.equal(supply);
expect(await this.token.getPriorVotes(holder, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); expect(await this.token.getPastVotes(holder, receipt.blockNumber - 1)).to.be.bignumber.equal('0');
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorVotes(holder, receipt.blockNumber)).to.be.bignumber.equal(supply); expect(await this.token.getPastVotes(holder, receipt.blockNumber)).to.be.bignumber.equal(supply);
}); });
it('delegation without balance', async function () { it('delegation without balance', async function () {
...@@ -172,10 +172,10 @@ contract('ERC20Votes', function (accounts) { ...@@ -172,10 +172,10 @@ contract('ERC20Votes', function (accounts) {
expect(await this.token.delegates(delegatorAddress)).to.be.equal(delegatorAddress); expect(await this.token.delegates(delegatorAddress)).to.be.equal(delegatorAddress);
expect(await this.token.getCurrentVotes(delegatorAddress)).to.be.bignumber.equal(supply); expect(await this.token.getVotes(delegatorAddress)).to.be.bignumber.equal(supply);
expect(await this.token.getPriorVotes(delegatorAddress, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); expect(await this.token.getPastVotes(delegatorAddress, receipt.blockNumber - 1)).to.be.bignumber.equal('0');
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorVotes(delegatorAddress, receipt.blockNumber)).to.be.bignumber.equal(supply); expect(await this.token.getPastVotes(delegatorAddress, receipt.blockNumber)).to.be.bignumber.equal(supply);
}); });
it('rejects reused signature', async function () { it('rejects reused signature', async function () {
...@@ -275,13 +275,13 @@ contract('ERC20Votes', function (accounts) { ...@@ -275,13 +275,13 @@ contract('ERC20Votes', function (accounts) {
expect(await this.token.delegates(holder)).to.be.equal(holderDelegatee); expect(await this.token.delegates(holder)).to.be.equal(holderDelegatee);
expect(await this.token.getCurrentVotes(holder)).to.be.bignumber.equal('0'); expect(await this.token.getVotes(holder)).to.be.bignumber.equal('0');
expect(await this.token.getCurrentVotes(holderDelegatee)).to.be.bignumber.equal(supply); expect(await this.token.getVotes(holderDelegatee)).to.be.bignumber.equal(supply);
expect(await this.token.getPriorVotes(holder, receipt.blockNumber - 1)).to.be.bignumber.equal(supply); expect(await this.token.getPastVotes(holder, receipt.blockNumber - 1)).to.be.bignumber.equal(supply);
expect(await this.token.getPriorVotes(holderDelegatee, receipt.blockNumber - 1)).to.be.bignumber.equal('0'); expect(await this.token.getPastVotes(holderDelegatee, receipt.blockNumber - 1)).to.be.bignumber.equal('0');
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorVotes(holder, receipt.blockNumber)).to.be.bignumber.equal('0'); expect(await this.token.getPastVotes(holder, receipt.blockNumber)).to.be.bignumber.equal('0');
expect(await this.token.getPriorVotes(holderDelegatee, receipt.blockNumber)).to.be.bignumber.equal(supply); expect(await this.token.getPastVotes(holderDelegatee, receipt.blockNumber)).to.be.bignumber.equal(supply);
}); });
}); });
...@@ -335,14 +335,14 @@ contract('ERC20Votes', function (accounts) { ...@@ -335,14 +335,14 @@ contract('ERC20Votes', function (accounts) {
}); });
afterEach(async function () { afterEach(async function () {
expect(await this.token.getCurrentVotes(holder)).to.be.bignumber.equal(this.holderVotes); expect(await this.token.getVotes(holder)).to.be.bignumber.equal(this.holderVotes);
expect(await this.token.getCurrentVotes(recipient)).to.be.bignumber.equal(this.recipientVotes); expect(await this.token.getVotes(recipient)).to.be.bignumber.equal(this.recipientVotes);
// need to advance 2 blocks to see the effect of a transfer on "getPriorVotes" // need to advance 2 blocks to see the effect of a transfer on "getPastVotes"
const blockNumber = await time.latestBlock(); const blockNumber = await time.latestBlock();
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorVotes(holder, blockNumber)).to.be.bignumber.equal(this.holderVotes); expect(await this.token.getPastVotes(holder, blockNumber)).to.be.bignumber.equal(this.holderVotes);
expect(await this.token.getPriorVotes(recipient, blockNumber)).to.be.bignumber.equal(this.recipientVotes); expect(await this.token.getPastVotes(recipient, blockNumber)).to.be.bignumber.equal(this.recipientVotes);
}); });
}); });
...@@ -381,10 +381,10 @@ contract('ERC20Votes', function (accounts) { ...@@ -381,10 +381,10 @@ contract('ERC20Votes', function (accounts) {
expect(await this.token.checkpoints(other1, 3)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]); expect(await this.token.checkpoints(other1, 3)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]);
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('100'); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('100');
expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('90'); expect(await this.token.getPastVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('90');
expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('80'); expect(await this.token.getPastVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('80');
expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('100'); expect(await this.token.getPastVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('100');
}); });
it('does not add more than one checkpoint in a block', async function () { it('does not add more than one checkpoint in a block', async function () {
...@@ -407,16 +407,16 @@ contract('ERC20Votes', function (accounts) { ...@@ -407,16 +407,16 @@ contract('ERC20Votes', function (accounts) {
}); });
}); });
describe('getPriorVotes', function () { describe('getPastVotes', function () {
it('reverts if block number >= current block', async function () { it('reverts if block number >= current block', async function () {
await expectRevert( await expectRevert(
this.token.getPriorVotes(other1, 5e10), this.token.getPastVotes(other1, 5e10),
'ERC20Votes: block not yet mined', 'ERC20Votes: block not yet mined',
); );
}); });
it('returns 0 if there are no checkpoints', async function () { it('returns 0 if there are no checkpoints', async function () {
expect(await this.token.getPriorVotes(other1, 0)).to.be.bignumber.equal('0'); expect(await this.token.getPastVotes(other1, 0)).to.be.bignumber.equal('0');
}); });
it('returns the latest block if >= last checkpoint block', async function () { it('returns the latest block if >= last checkpoint block', async function () {
...@@ -424,8 +424,8 @@ contract('ERC20Votes', function (accounts) { ...@@ -424,8 +424,8 @@ contract('ERC20Votes', function (accounts) {
await time.advanceBlock(); await time.advanceBlock();
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
}); });
it('returns zero if < first checkpoint block', async function () { it('returns zero if < first checkpoint block', async function () {
...@@ -434,8 +434,8 @@ contract('ERC20Votes', function (accounts) { ...@@ -434,8 +434,8 @@ contract('ERC20Votes', function (accounts) {
await time.advanceBlock(); await time.advanceBlock();
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0');
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
}); });
it('generally returns the voting balance at the appropriate checkpoint', async function () { it('generally returns the voting balance at the appropriate checkpoint', async function () {
...@@ -452,33 +452,33 @@ contract('ERC20Votes', function (accounts) { ...@@ -452,33 +452,33 @@ contract('ERC20Votes', function (accounts) {
await time.advanceBlock(); await time.advanceBlock();
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0');
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990'); expect(await this.token.getPastVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990');
expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990'); expect(await this.token.getPastVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990');
expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980'); expect(await this.token.getPastVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980');
expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980'); expect(await this.token.getPastVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980');
expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
}); });
}); });
}); });
describe('getPriorTotalSupply', function () { describe('getPastTotalSupply', function () {
beforeEach(async function () { beforeEach(async function () {
await this.token.delegate(holder, { from: holder }); await this.token.delegate(holder, { from: holder });
}); });
it('reverts if block number >= current block', async function () { it('reverts if block number >= current block', async function () {
await expectRevert( await expectRevert(
this.token.getPriorTotalSupply(5e10), this.token.getPastTotalSupply(5e10),
'ERC20Votes: block not yet mined', 'ERC20Votes: block not yet mined',
); );
}); });
it('returns 0 if there are no checkpoints', async function () { it('returns 0 if there are no checkpoints', async function () {
expect(await this.token.getPriorTotalSupply(0)).to.be.bignumber.equal('0'); expect(await this.token.getPastTotalSupply(0)).to.be.bignumber.equal('0');
}); });
it('returns the latest block if >= last checkpoint block', async function () { it('returns the latest block if >= last checkpoint block', async function () {
...@@ -487,8 +487,8 @@ contract('ERC20Votes', function (accounts) { ...@@ -487,8 +487,8 @@ contract('ERC20Votes', function (accounts) {
await time.advanceBlock(); await time.advanceBlock();
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal(supply); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal(supply);
expect(await this.token.getPriorTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal(supply); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal(supply);
}); });
it('returns zero if < first checkpoint block', async function () { it('returns zero if < first checkpoint block', async function () {
...@@ -497,8 +497,8 @@ contract('ERC20Votes', function (accounts) { ...@@ -497,8 +497,8 @@ contract('ERC20Votes', function (accounts) {
await time.advanceBlock(); await time.advanceBlock();
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0');
expect(await this.token.getPriorTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
}); });
it('generally returns the voting balance at the appropriate checkpoint', async function () { it('generally returns the voting balance at the appropriate checkpoint', async function () {
...@@ -515,15 +515,15 @@ contract('ERC20Votes', function (accounts) { ...@@ -515,15 +515,15 @@ contract('ERC20Votes', function (accounts) {
await time.advanceBlock(); await time.advanceBlock();
await time.advanceBlock(); await time.advanceBlock();
expect(await this.token.getPriorTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0'); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0');
expect(await this.token.getPriorTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990'); expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990');
expect(await this.token.getPriorTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990'); expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990');
expect(await this.token.getPriorTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980'); expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980');
expect(await this.token.getPriorTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980'); expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980');
expect(await this.token.getPriorTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000'); expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
}); });
}); });
}); });
/* eslint-disable */
const { BN, constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const { MAX_UINT256, ZERO_ADDRESS, ZERO_BYTES32 } = constants;
const { fromRpcSig } = require('ethereumjs-util');
const ethSigUtil = require('eth-sig-util');
const Wallet = require('ethereumjs-wallet').default;
const { promisify } = require('util');
const queue = promisify(setImmediate);
const ERC20VotesCompMock = artifacts.require('ERC20VotesCompMock');
const { EIP712Domain, domainSeparator } = require('../../../helpers/eip712');
const Delegation = [
{ name: 'delegatee', type: 'address' },
{ name: 'nonce', type: 'uint256' },
{ name: 'expiry', type: 'uint256' },
];
async function countPendingTransactions() {
return parseInt(
await network.provider.send('eth_getBlockTransactionCountByNumber', ['pending'])
);
}
async function batchInBlock (txs) {
try {
// disable auto-mining
await network.provider.send('evm_setAutomine', [false]);
// send all transactions
const promises = txs.map(fn => fn());
// wait for node to have all pending transactions
while (txs.length > await countPendingTransactions()) {
await queue();
}
// mine one block
await network.provider.send('evm_mine');
// fetch receipts
const receipts = await Promise.all(promises);
// Sanity check, all tx should be in the same block
const minedBlocks = new Set(receipts.map(({ receipt }) => receipt.blockNumber));
expect(minedBlocks.size).to.equal(1);
return receipts;
} finally {
// enable auto-mining
await network.provider.send('evm_setAutomine', [true]);
}
}
contract('ERC20Votes', function (accounts) {
const [ holder, recipient, holderDelegatee, recipientDelegatee, other1, other2 ] = accounts;
const name = 'My Token';
const symbol = 'MTKN';
const version = '1';
const supply = new BN('10000000000000000000000000');
beforeEach(async function () {
this.token = await ERC20VotesCompMock.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.token.getChainId();
});
it('initial nonce is 0', async function () {
expect(await this.token.nonces(holder)).to.be.bignumber.equal('0');
});
it('domain separator', async function () {
expect(
await this.token.DOMAIN_SEPARATOR(),
).to.equal(
await domainSeparator(name, version, this.chainId, this.token.address),
);
});
it('minting restriction', async function () {
const amount = new BN('2').pow(new BN('96'));
await expectRevert(
this.token.mint(holder, amount),
'ERC20Votes: total supply risks overflowing votes',
);
});
describe('set delegation', function () {
describe('call', function () {
it('delegation with balance', async function () {
await this.token.mint(holder, supply);
expect(await this.token.delegates(holder)).to.be.equal(ZERO_ADDRESS);
const { receipt } = await this.token.delegate(holder, { from: holder });
expectEvent(receipt, 'DelegateChanged', {
delegator: holder,
fromDelegate: ZERO_ADDRESS,
toDelegate: holder,
});
expectEvent(receipt, 'DelegateVotesChanged', {
delegate: holder,
previousBalance: '0',
newBalance: supply,
});
expect(await this.token.delegates(holder)).to.be.equal(holder);
expect(await this.token.getCurrentVotes(holder)).to.be.bignumber.equal(supply);
expect(await this.token.getPriorVotes(holder, receipt.blockNumber - 1)).to.be.bignumber.equal('0');
await time.advanceBlock();
expect(await this.token.getPriorVotes(holder, receipt.blockNumber)).to.be.bignumber.equal(supply);
});
it('delegation without balance', async function () {
expect(await this.token.delegates(holder)).to.be.equal(ZERO_ADDRESS);
const { receipt } = await this.token.delegate(holder, { from: holder });
expectEvent(receipt, 'DelegateChanged', {
delegator: holder,
fromDelegate: ZERO_ADDRESS,
toDelegate: holder,
});
expectEvent.notEmitted(receipt, 'DelegateVotesChanged');
expect(await this.token.delegates(holder)).to.be.equal(holder);
});
});
describe('with signature', function () {
const delegator = Wallet.generate();
const delegatorAddress = web3.utils.toChecksumAddress(delegator.getAddressString());
const nonce = 0;
const buildData = (chainId, verifyingContract, message) => ({ data: {
primaryType: 'Delegation',
types: { EIP712Domain, Delegation },
domain: { name, version, chainId, verifyingContract },
message,
}});
beforeEach(async function () {
await this.token.mint(delegatorAddress, supply);
});
it('accept signed delegation', async function () {
const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage(
delegator.getPrivateKey(),
buildData(this.chainId, this.token.address, {
delegatee: delegatorAddress,
nonce,
expiry: MAX_UINT256,
}),
));
expect(await this.token.delegates(delegatorAddress)).to.be.equal(ZERO_ADDRESS);
const { receipt } = await this.token.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: supply,
});
expect(await this.token.delegates(delegatorAddress)).to.be.equal(delegatorAddress);
expect(await this.token.getCurrentVotes(delegatorAddress)).to.be.bignumber.equal(supply);
expect(await this.token.getPriorVotes(delegatorAddress, receipt.blockNumber - 1)).to.be.bignumber.equal('0');
await time.advanceBlock();
expect(await this.token.getPriorVotes(delegatorAddress, receipt.blockNumber)).to.be.bignumber.equal(supply);
});
it('rejects reused signature', async function () {
const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage(
delegator.getPrivateKey(),
buildData(this.chainId, this.token.address, {
delegatee: delegatorAddress,
nonce,
expiry: MAX_UINT256,
}),
));
await this.token.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s);
await expectRevert(
this.token.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s),
'ERC20Votes: invalid nonce',
);
});
it('rejects bad delegatee', async function () {
const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage(
delegator.getPrivateKey(),
buildData(this.chainId, this.token.address, {
delegatee: delegatorAddress,
nonce,
expiry: MAX_UINT256,
}),
));
const { logs } = await this.token.delegateBySig(holderDelegatee, 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(holderDelegatee);
});
it('rejects bad nonce', async function () {
const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage(
delegator.getPrivateKey(),
buildData(this.chainId, this.token.address, {
delegatee: delegatorAddress,
nonce,
expiry: MAX_UINT256,
}),
));
await expectRevert(
this.token.delegateBySig(delegatorAddress, nonce + 1, MAX_UINT256, v, r, s),
'ERC20Votes: 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.token.address, {
delegatee: delegatorAddress,
nonce,
expiry,
}),
));
await expectRevert(
this.token.delegateBySig(delegatorAddress, nonce, expiry, v, r, s),
'ERC20Votes: signature expired',
);
});
});
});
describe('change delegation', function () {
beforeEach(async function () {
await this.token.mint(holder, supply);
await this.token.delegate(holder, { from: holder });
});
it('call', async function () {
expect(await this.token.delegates(holder)).to.be.equal(holder);
const { receipt } = await this.token.delegate(holderDelegatee, { from: holder });
expectEvent(receipt, 'DelegateChanged', {
delegator: holder,
fromDelegate: holder,
toDelegate: holderDelegatee,
});
expectEvent(receipt, 'DelegateVotesChanged', {
delegate: holder,
previousBalance: supply,
newBalance: '0',
});
expectEvent(receipt, 'DelegateVotesChanged', {
delegate: holderDelegatee,
previousBalance: '0',
newBalance: supply,
});
expect(await this.token.delegates(holder)).to.be.equal(holderDelegatee);
expect(await this.token.getCurrentVotes(holder)).to.be.bignumber.equal('0');
expect(await this.token.getCurrentVotes(holderDelegatee)).to.be.bignumber.equal(supply);
expect(await this.token.getPriorVotes(holder, receipt.blockNumber - 1)).to.be.bignumber.equal(supply);
expect(await this.token.getPriorVotes(holderDelegatee, receipt.blockNumber - 1)).to.be.bignumber.equal('0');
await time.advanceBlock();
expect(await this.token.getPriorVotes(holder, receipt.blockNumber)).to.be.bignumber.equal('0');
expect(await this.token.getPriorVotes(holderDelegatee, receipt.blockNumber)).to.be.bignumber.equal(supply);
});
});
describe('transfers', function () {
beforeEach(async function () {
await this.token.mint(holder, supply);
});
it('no delegation', async function () {
const { receipt } = await this.token.transfer(recipient, 1, { from: holder });
expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' });
expectEvent.notEmitted(receipt, 'DelegateVotesChanged');
this.holderVotes = '0';
this.recipientVotes = '0';
});
it('sender delegation', async function () {
await this.token.delegate(holder, { from: holder });
const { receipt } = await this.token.transfer(recipient, 1, { from: holder });
expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' });
expectEvent(receipt, 'DelegateVotesChanged', { delegate: holder, previousBalance: supply, newBalance: supply.subn(1) });
this.holderVotes = supply.subn(1);
this.recipientVotes = '0';
});
it('receiver delegation', async function () {
await this.token.delegate(recipient, { from: recipient });
const { receipt } = await this.token.transfer(recipient, 1, { from: holder });
expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' });
expectEvent(receipt, 'DelegateVotesChanged', { delegate: recipient, previousBalance: '0', newBalance: '1' });
this.holderVotes = '0';
this.recipientVotes = '1';
});
it('full delegation', async function () {
await this.token.delegate(holder, { from: holder });
await this.token.delegate(recipient, { from: recipient });
const { receipt } = await this.token.transfer(recipient, 1, { from: holder });
expectEvent(receipt, 'Transfer', { from: holder, to: recipient, value: '1' });
expectEvent(receipt, 'DelegateVotesChanged', { delegate: holder, previousBalance: supply, newBalance: supply.subn(1) });
expectEvent(receipt, 'DelegateVotesChanged', { delegate: recipient, previousBalance: '0', newBalance: '1' });
this.holderVotes = supply.subn(1);
this.recipientVotes = '1';
});
afterEach(async function () {
expect(await this.token.getCurrentVotes(holder)).to.be.bignumber.equal(this.holderVotes);
expect(await this.token.getCurrentVotes(recipient)).to.be.bignumber.equal(this.recipientVotes);
// need to advance 2 blocks to see the effect of a transfer on "getPriorVotes"
const blockNumber = await time.latestBlock();
await time.advanceBlock();
expect(await this.token.getPriorVotes(holder, blockNumber)).to.be.bignumber.equal(this.holderVotes);
expect(await this.token.getPriorVotes(recipient, blockNumber)).to.be.bignumber.equal(this.recipientVotes);
});
});
// 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.token.mint(holder, supply);
});
describe('balanceOf', function () {
it('grants to initial account', async function () {
expect(await this.token.balanceOf(holder)).to.be.bignumber.equal('10000000000000000000000000');
});
});
describe('numCheckpoints', function () {
it('returns the number of checkpoints for a delegate', async function () {
await this.token.transfer(recipient, '100', { from: holder }); //give an account a few tokens for readability
expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('0');
const t1 = await this.token.delegate(other1, { from: recipient });
expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('1');
const t2 = await this.token.transfer(other2, 10, { from: recipient });
expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('2');
const t3 = await this.token.transfer(other2, 10, { from: recipient });
expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('3');
const t4 = await this.token.transfer(recipient, 20, { from: holder });
expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('4');
expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([ t1.receipt.blockNumber.toString(), '100' ]);
expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ t2.receipt.blockNumber.toString(), '90' ]);
expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([ t3.receipt.blockNumber.toString(), '80' ]);
expect(await this.token.checkpoints(other1, 3)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]);
await time.advanceBlock();
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('100');
expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('90');
expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('80');
expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('100');
});
it('does not add more than one checkpoint in a block', async function () {
await this.token.transfer(recipient, '100', { from: holder });
expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('0');
const [ t1, t2, t3 ] = await batchInBlock([
() => this.token.delegate(other1, { from: recipient, gas: 100000 }),
() => this.token.transfer(other2, 10, { from: recipient, gas: 100000 }),
() => this.token.transfer(other2, 10, { from: recipient, gas: 100000 }),
]);
expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('1');
expect(await this.token.checkpoints(other1, 0)).to.be.deep.equal([ t1.receipt.blockNumber.toString(), '80' ]);
// expectReve(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ '0', '0' ]); // Reverts due to array overflow check
// expect(await this.token.checkpoints(other1, 2)).to.be.deep.equal([ '0', '0' ]); // Reverts due to array overflow check
const t4 = await this.token.transfer(recipient, 20, { from: holder });
expect(await this.token.numCheckpoints(other1)).to.be.bignumber.equal('2');
expect(await this.token.checkpoints(other1, 1)).to.be.deep.equal([ t4.receipt.blockNumber.toString(), '100' ]);
});
});
describe('getPriorVotes', function () {
it('reverts if block number >= current block', async function () {
await expectRevert(
this.token.getPriorVotes(other1, 5e10),
'ERC20Votes: block not yet mined',
);
});
it('returns 0 if there are no checkpoints', async function () {
expect(await this.token.getPriorVotes(other1, 0)).to.be.bignumber.equal('0');
});
it('returns the latest block if >= last checkpoint block', async function () {
const t1 = await this.token.delegate(other1, { from: holder });
await time.advanceBlock();
await time.advanceBlock();
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
});
it('returns zero if < first checkpoint block', async function () {
await time.advanceBlock();
const t1 = await this.token.delegate(other1, { from: holder });
await time.advanceBlock();
await time.advanceBlock();
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0');
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
});
it('generally returns the voting balance at the appropriate checkpoint', async function () {
const t1 = await this.token.delegate(other1, { from: holder });
await time.advanceBlock();
await time.advanceBlock();
const t2 = await this.token.transfer(other2, 10, { from: holder });
await time.advanceBlock();
await time.advanceBlock();
const t3 = await this.token.transfer(other2, 10, { from: holder });
await time.advanceBlock();
await time.advanceBlock();
const t4 = await this.token.transfer(holder, 20, { from: other2 });
await time.advanceBlock();
await time.advanceBlock();
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0');
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorVotes(other1, t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990');
expect(await this.token.getPriorVotes(other1, t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990');
expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980');
expect(await this.token.getPriorVotes(other1, t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980');
expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPriorVotes(other1, t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
});
});
});
describe('getPastTotalSupply', function () {
beforeEach(async function () {
await this.token.delegate(holder, { from: holder });
});
it('reverts if block number >= current block', async function () {
await expectRevert(
this.token.getPastTotalSupply(5e10),
'ERC20Votes: block not yet mined',
);
});
it('returns 0 if there are no checkpoints', async function () {
expect(await this.token.getPastTotalSupply(0)).to.be.bignumber.equal('0');
});
it('returns the latest block if >= last checkpoint block', async function () {
t1 = await this.token.mint(holder, supply);
await time.advanceBlock();
await time.advanceBlock();
expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal(supply);
expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal(supply);
});
it('returns zero if < first checkpoint block', async function () {
await time.advanceBlock();
const t1 = await this.token.mint(holder, supply);
await time.advanceBlock();
await time.advanceBlock();
expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0');
expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
});
it('generally returns the voting balance at the appropriate checkpoint', async function () {
const t1 = await this.token.mint(holder, supply);
await time.advanceBlock();
await time.advanceBlock();
const t2 = await this.token.burn(holder, 10);
await time.advanceBlock();
await time.advanceBlock();
const t3 = await this.token.burn(holder, 10);
await time.advanceBlock();
await time.advanceBlock();
const t4 = await this.token.mint(holder, 20);
await time.advanceBlock();
await time.advanceBlock();
expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber - 1)).to.be.bignumber.equal('0');
expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPastTotalSupply(t1.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999990');
expect(await this.token.getPastTotalSupply(t2.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999990');
expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber)).to.be.bignumber.equal('9999999999999999999999980');
expect(await this.token.getPastTotalSupply(t3.receipt.blockNumber + 1)).to.be.bignumber.equal('9999999999999999999999980');
expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber)).to.be.bignumber.equal('10000000000000000000000000');
expect(await this.token.getPastTotalSupply(t4.receipt.blockNumber + 1)).to.be.bignumber.equal('10000000000000000000000000');
});
});
});
...@@ -41,7 +41,7 @@ contract('SafeCast', async (accounts) => { ...@@ -41,7 +41,7 @@ contract('SafeCast', async (accounts) => {
}); });
} }
[8, 16, 32, 64, 128].forEach(bits => testToUint(bits)); [8, 16, 32, 64, 96, 128, 224].forEach(bits => testToUint(bits));
describe('toUint256', () => { describe('toUint256', () => {
const maxInt256 = new BN('2').pow(new BN(255)).subn(1); const maxInt256 = new BN('2').pow(new BN(255)).subn(1);
......
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