dexorder
This commit is contained in:
209
lib_openzeppelin_contracts/contracts/access/AccessControl.sol
Normal file
209
lib_openzeppelin_contracts/contracts/access/AccessControl.sol
Normal file
@@ -0,0 +1,209 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAccessControl} from "./IAccessControl.sol";
|
||||
import {Context} from "../utils/Context.sol";
|
||||
import {ERC165} from "../utils/introspection/ERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev Contract module that allows children to implement role-based access
|
||||
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
|
||||
* members except through off-chain means by accessing the contract event logs. Some
|
||||
* applications may benefit from on-chain enumerability, for those cases see
|
||||
* {AccessControlEnumerable}.
|
||||
*
|
||||
* Roles are referred to by their `bytes32` identifier. These should be exposed
|
||||
* in the external API and be unique. The best way to achieve this is by
|
||||
* using `public constant` hash digests:
|
||||
*
|
||||
* ```solidity
|
||||
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
|
||||
* ```
|
||||
*
|
||||
* Roles can be used to represent a set of permissions. To restrict access to a
|
||||
* function call, use {hasRole}:
|
||||
*
|
||||
* ```solidity
|
||||
* function foo() public {
|
||||
* require(hasRole(MY_ROLE, msg.sender));
|
||||
* ...
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Roles can be granted and revoked dynamically via the {grantRole} and
|
||||
* {revokeRole} functions. Each role has an associated admin role, and only
|
||||
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
|
||||
*
|
||||
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
|
||||
* that only accounts with this role will be able to grant or revoke other
|
||||
* roles. More complex role relationships can be created by using
|
||||
* {_setRoleAdmin}.
|
||||
*
|
||||
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
|
||||
* grant and revoke this role. Extra precautions should be taken to secure
|
||||
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
|
||||
* to enforce additional security measures for this role.
|
||||
*/
|
||||
abstract contract AccessControl is Context, IAccessControl, ERC165 {
|
||||
struct RoleData {
|
||||
mapping(address account => bool) hasRole;
|
||||
bytes32 adminRole;
|
||||
}
|
||||
|
||||
mapping(bytes32 role => RoleData) private _roles;
|
||||
|
||||
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
|
||||
|
||||
/**
|
||||
* @dev Modifier that checks that an account has a specific role. Reverts
|
||||
* with an {AccessControlUnauthorizedAccount} error including the required role.
|
||||
*/
|
||||
modifier onlyRole(bytes32 role) {
|
||||
_checkRole(role);
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
|
||||
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns `true` if `account` has been granted `role`.
|
||||
*/
|
||||
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
|
||||
return _roles[role].hasRole[account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
|
||||
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
|
||||
*/
|
||||
function _checkRole(bytes32 role) internal view virtual {
|
||||
_checkRole(role, _msgSender());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
|
||||
* is missing `role`.
|
||||
*/
|
||||
function _checkRole(bytes32 role, address account) internal view virtual {
|
||||
if (!hasRole(role, account)) {
|
||||
revert AccessControlUnauthorizedAccount(account, role);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the admin role that controls `role`. See {grantRole} and
|
||||
* {revokeRole}.
|
||||
*
|
||||
* To change a role's admin, use {_setRoleAdmin}.
|
||||
*/
|
||||
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
|
||||
return _roles[role].adminRole;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Grants `role` to `account`.
|
||||
*
|
||||
* If `account` had not been already granted `role`, emits a {RoleGranted}
|
||||
* event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have ``role``'s admin role.
|
||||
*
|
||||
* May emit a {RoleGranted} event.
|
||||
*/
|
||||
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
|
||||
_grantRole(role, account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Revokes `role` from `account`.
|
||||
*
|
||||
* If `account` had been granted `role`, emits a {RoleRevoked} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have ``role``'s admin role.
|
||||
*
|
||||
* May emit a {RoleRevoked} event.
|
||||
*/
|
||||
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
|
||||
_revokeRole(role, account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Revokes `role` from the calling account.
|
||||
*
|
||||
* Roles are often managed via {grantRole} and {revokeRole}: this function's
|
||||
* purpose is to provide a mechanism for accounts to lose their privileges
|
||||
* if they are compromised (such as when a trusted device is misplaced).
|
||||
*
|
||||
* If the calling account had been revoked `role`, emits a {RoleRevoked}
|
||||
* event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be `callerConfirmation`.
|
||||
*
|
||||
* May emit a {RoleRevoked} event.
|
||||
*/
|
||||
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
|
||||
if (callerConfirmation != _msgSender()) {
|
||||
revert AccessControlBadConfirmation();
|
||||
}
|
||||
|
||||
_revokeRole(role, callerConfirmation);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets `adminRole` as ``role``'s admin role.
|
||||
*
|
||||
* Emits a {RoleAdminChanged} event.
|
||||
*/
|
||||
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
|
||||
bytes32 previousAdminRole = getRoleAdmin(role);
|
||||
_roles[role].adminRole = adminRole;
|
||||
emit RoleAdminChanged(role, previousAdminRole, adminRole);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
|
||||
*
|
||||
* Internal function without access restriction.
|
||||
*
|
||||
* May emit a {RoleGranted} event.
|
||||
*/
|
||||
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
|
||||
if (!hasRole(role, account)) {
|
||||
_roles[role].hasRole[account] = true;
|
||||
emit RoleGranted(role, account, _msgSender());
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
|
||||
*
|
||||
* Internal function without access restriction.
|
||||
*
|
||||
* May emit a {RoleRevoked} event.
|
||||
*/
|
||||
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
|
||||
if (hasRole(role, account)) {
|
||||
_roles[role].hasRole[account] = false;
|
||||
emit RoleRevoked(role, account, _msgSender());
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev External interface of AccessControl declared to support ERC-165 detection.
|
||||
*/
|
||||
interface IAccessControl {
|
||||
/**
|
||||
* @dev The `account` is missing a role.
|
||||
*/
|
||||
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
|
||||
|
||||
/**
|
||||
* @dev The caller of a function is not the expected one.
|
||||
*
|
||||
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
|
||||
*/
|
||||
error AccessControlBadConfirmation();
|
||||
|
||||
/**
|
||||
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
|
||||
*
|
||||
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
|
||||
* {RoleAdminChanged} not being emitted signaling this.
|
||||
*/
|
||||
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `account` is granted `role`.
|
||||
*
|
||||
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
|
||||
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
|
||||
*/
|
||||
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `account` is revoked `role`.
|
||||
*
|
||||
* `sender` is the account that originated the contract call:
|
||||
* - if using `revokeRole`, it is the admin role bearer
|
||||
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
|
||||
*/
|
||||
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
|
||||
|
||||
/**
|
||||
* @dev Returns `true` if `account` has been granted `role`.
|
||||
*/
|
||||
function hasRole(bytes32 role, address account) external view returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Returns the admin role that controls `role`. See {grantRole} and
|
||||
* {revokeRole}.
|
||||
*
|
||||
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
|
||||
*/
|
||||
function getRoleAdmin(bytes32 role) external view returns (bytes32);
|
||||
|
||||
/**
|
||||
* @dev Grants `role` to `account`.
|
||||
*
|
||||
* If `account` had not been already granted `role`, emits a {RoleGranted}
|
||||
* event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have ``role``'s admin role.
|
||||
*/
|
||||
function grantRole(bytes32 role, address account) external;
|
||||
|
||||
/**
|
||||
* @dev Revokes `role` from `account`.
|
||||
*
|
||||
* If `account` had been granted `role`, emits a {RoleRevoked} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have ``role``'s admin role.
|
||||
*/
|
||||
function revokeRole(bytes32 role, address account) external;
|
||||
|
||||
/**
|
||||
* @dev Revokes `role` from the calling account.
|
||||
*
|
||||
* Roles are often managed via {grantRole} and {revokeRole}: this function's
|
||||
* purpose is to provide a mechanism for accounts to lose their privileges
|
||||
* if they are compromised (such as when a trusted device is misplaced).
|
||||
*
|
||||
* If the calling account had been granted `role`, emits a {RoleRevoked}
|
||||
* event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be `callerConfirmation`.
|
||||
*/
|
||||
function renounceRole(bytes32 role, address callerConfirmation) external;
|
||||
}
|
||||
100
lib_openzeppelin_contracts/contracts/access/Ownable.sol
Normal file
100
lib_openzeppelin_contracts/contracts/access/Ownable.sol
Normal file
@@ -0,0 +1,100 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Context} from "../utils/Context.sol";
|
||||
|
||||
/**
|
||||
* @dev Contract module which provides a basic access control mechanism, where
|
||||
* there is an account (an owner) that can be granted exclusive access to
|
||||
* specific functions.
|
||||
*
|
||||
* The initial owner is set to the address provided by the deployer. This can
|
||||
* later be changed with {transferOwnership}.
|
||||
*
|
||||
* This module is used through inheritance. It will make available the modifier
|
||||
* `onlyOwner`, which can be applied to your functions to restrict their use to
|
||||
* the owner.
|
||||
*/
|
||||
abstract contract Ownable is Context {
|
||||
address private _owner;
|
||||
|
||||
/**
|
||||
* @dev The caller account is not authorized to perform an operation.
|
||||
*/
|
||||
error OwnableUnauthorizedAccount(address account);
|
||||
|
||||
/**
|
||||
* @dev The owner is not a valid owner account. (eg. `address(0)`)
|
||||
*/
|
||||
error OwnableInvalidOwner(address owner);
|
||||
|
||||
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
|
||||
|
||||
/**
|
||||
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
|
||||
*/
|
||||
constructor(address initialOwner) {
|
||||
if (initialOwner == address(0)) {
|
||||
revert OwnableInvalidOwner(address(0));
|
||||
}
|
||||
_transferOwnership(initialOwner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Throws if called by any account other than the owner.
|
||||
*/
|
||||
modifier onlyOwner() {
|
||||
_checkOwner();
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the current owner.
|
||||
*/
|
||||
function owner() public view virtual returns (address) {
|
||||
return _owner;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Throws if the sender is not the owner.
|
||||
*/
|
||||
function _checkOwner() internal view virtual {
|
||||
if (owner() != _msgSender()) {
|
||||
revert OwnableUnauthorizedAccount(_msgSender());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Leaves the contract without owner. It will not be possible to call
|
||||
* `onlyOwner` functions. Can only be called by the current owner.
|
||||
*
|
||||
* NOTE: Renouncing ownership will leave the contract without an owner,
|
||||
* thereby disabling any functionality that is only available to the owner.
|
||||
*/
|
||||
function renounceOwnership() public virtual onlyOwner {
|
||||
_transferOwnership(address(0));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers ownership of the contract to a new account (`newOwner`).
|
||||
* Can only be called by the current owner.
|
||||
*/
|
||||
function transferOwnership(address newOwner) public virtual onlyOwner {
|
||||
if (newOwner == address(0)) {
|
||||
revert OwnableInvalidOwner(address(0));
|
||||
}
|
||||
_transferOwnership(newOwner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers ownership of the contract to a new account (`newOwner`).
|
||||
* Internal function without access restriction.
|
||||
*/
|
||||
function _transferOwnership(address newOwner) internal virtual {
|
||||
address oldOwner = _owner;
|
||||
_owner = newOwner;
|
||||
emit OwnershipTransferred(oldOwner, newOwner);
|
||||
}
|
||||
}
|
||||
65
lib_openzeppelin_contracts/contracts/access/Ownable2Step.sol
Normal file
65
lib_openzeppelin_contracts/contracts/access/Ownable2Step.sol
Normal file
@@ -0,0 +1,65 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Ownable} from "./Ownable.sol";
|
||||
|
||||
/**
|
||||
* @dev Contract module which provides access control mechanism, where
|
||||
* there is an account (an owner) that can be granted exclusive access to
|
||||
* specific functions.
|
||||
*
|
||||
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
|
||||
* ownership, where the new owner must call {acceptOwnership} in order to replace the
|
||||
* old one. This can help prevent common mistakes, such as transfers of ownership to
|
||||
* incorrect accounts, or to contracts that are unable to interact with the
|
||||
* permission system.
|
||||
*
|
||||
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
|
||||
* can later be changed with {transferOwnership} and {acceptOwnership}.
|
||||
*
|
||||
* This module is used through inheritance. It will make available all functions
|
||||
* from parent (Ownable).
|
||||
*/
|
||||
abstract contract Ownable2Step is Ownable {
|
||||
address private _pendingOwner;
|
||||
|
||||
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the pending owner.
|
||||
*/
|
||||
function pendingOwner() public view virtual returns (address) {
|
||||
return _pendingOwner;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
|
||||
* Can only be called by the current owner.
|
||||
*/
|
||||
function transferOwnership(address newOwner) public virtual override onlyOwner {
|
||||
_pendingOwner = newOwner;
|
||||
emit OwnershipTransferStarted(owner(), newOwner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
|
||||
* Internal function without access restriction.
|
||||
*/
|
||||
function _transferOwnership(address newOwner) internal virtual override {
|
||||
delete _pendingOwner;
|
||||
super._transferOwnership(newOwner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev The new owner accepts the ownership transfer.
|
||||
*/
|
||||
function acceptOwnership() public virtual {
|
||||
address sender = _msgSender();
|
||||
if (pendingOwner() != sender) {
|
||||
revert OwnableUnauthorizedAccount(sender);
|
||||
}
|
||||
_transferOwnership(sender);
|
||||
}
|
||||
}
|
||||
45
lib_openzeppelin_contracts/contracts/access/README.adoc
Normal file
45
lib_openzeppelin_contracts/contracts/access/README.adoc
Normal file
@@ -0,0 +1,45 @@
|
||||
= Access Control
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/access
|
||||
|
||||
This directory provides ways to restrict who can access the functions of a contract or when they can do it.
|
||||
|
||||
- {AccessManager} is a full-fledged access control solution for smart contract systems. Allows creating and assigning multiple hierarchical roles with execution delays for each account across various contracts.
|
||||
- {AccessManaged} delegates its access control to an authority that dictates the permissions of the managed contract. It's compatible with an AccessManager as an authority.
|
||||
- {AccessControl} provides a per-contract role based access control mechanism. Multiple hierarchical roles can be created and assigned each to multiple accounts within the same instance.
|
||||
- {Ownable} is a simpler mechanism with a single owner "role" that can be assigned to a single account. This simpler mechanism can be useful for quick tests but projects with production concerns are likely to outgrow it.
|
||||
|
||||
== Core
|
||||
|
||||
{{Ownable}}
|
||||
|
||||
{{Ownable2Step}}
|
||||
|
||||
{{IAccessControl}}
|
||||
|
||||
{{AccessControl}}
|
||||
|
||||
== Extensions
|
||||
|
||||
{{IAccessControlEnumerable}}
|
||||
|
||||
{{AccessControlEnumerable}}
|
||||
|
||||
{{IAccessControlDefaultAdminRules}}
|
||||
|
||||
{{AccessControlDefaultAdminRules}}
|
||||
|
||||
== AccessManager
|
||||
|
||||
{{IAuthority}}
|
||||
|
||||
{{IAccessManager}}
|
||||
|
||||
{{AccessManager}}
|
||||
|
||||
{{IAccessManaged}}
|
||||
|
||||
{{AccessManaged}}
|
||||
|
||||
{{AuthorityUtils}}
|
||||
@@ -0,0 +1,396 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/AccessControlDefaultAdminRules.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAccessControlDefaultAdminRules} from "./IAccessControlDefaultAdminRules.sol";
|
||||
import {AccessControl, IAccessControl} from "../AccessControl.sol";
|
||||
import {SafeCast} from "../../utils/math/SafeCast.sol";
|
||||
import {Math} from "../../utils/math/Math.sol";
|
||||
import {IERC5313} from "../../interfaces/IERC5313.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {AccessControl} that allows specifying special rules to manage
|
||||
* the `DEFAULT_ADMIN_ROLE` holder, which is a sensitive role with special permissions
|
||||
* over other roles that may potentially have privileged rights in the system.
|
||||
*
|
||||
* If a specific role doesn't have an admin role assigned, the holder of the
|
||||
* `DEFAULT_ADMIN_ROLE` will have the ability to grant it and revoke it.
|
||||
*
|
||||
* This contract implements the following risk mitigations on top of {AccessControl}:
|
||||
*
|
||||
* * Only one account holds the `DEFAULT_ADMIN_ROLE` since deployment until it's potentially renounced.
|
||||
* * Enforces a 2-step process to transfer the `DEFAULT_ADMIN_ROLE` to another account.
|
||||
* * Enforces a configurable delay between the two steps, with the ability to cancel before the transfer is accepted.
|
||||
* * The delay can be changed by scheduling, see {changeDefaultAdminDelay}.
|
||||
* * It is not possible to use another role to manage the `DEFAULT_ADMIN_ROLE`.
|
||||
*
|
||||
* Example usage:
|
||||
*
|
||||
* ```solidity
|
||||
* contract MyToken is AccessControlDefaultAdminRules {
|
||||
* constructor() AccessControlDefaultAdminRules(
|
||||
* 3 days,
|
||||
* msg.sender // Explicit initial `DEFAULT_ADMIN_ROLE` holder
|
||||
* ) {}
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
abstract contract AccessControlDefaultAdminRules is IAccessControlDefaultAdminRules, IERC5313, AccessControl {
|
||||
// pending admin pair read/written together frequently
|
||||
address private _pendingDefaultAdmin;
|
||||
uint48 private _pendingDefaultAdminSchedule; // 0 == unset
|
||||
|
||||
uint48 private _currentDelay;
|
||||
address private _currentDefaultAdmin;
|
||||
|
||||
// pending delay pair read/written together frequently
|
||||
uint48 private _pendingDelay;
|
||||
uint48 private _pendingDelaySchedule; // 0 == unset
|
||||
|
||||
/**
|
||||
* @dev Sets the initial values for {defaultAdminDelay} and {defaultAdmin} address.
|
||||
*/
|
||||
constructor(uint48 initialDelay, address initialDefaultAdmin) {
|
||||
if (initialDefaultAdmin == address(0)) {
|
||||
revert AccessControlInvalidDefaultAdmin(address(0));
|
||||
}
|
||||
_currentDelay = initialDelay;
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
|
||||
return interfaceId == type(IAccessControlDefaultAdminRules).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC5313-owner}.
|
||||
*/
|
||||
function owner() public view virtual returns (address) {
|
||||
return defaultAdmin();
|
||||
}
|
||||
|
||||
///
|
||||
/// Override AccessControl role management
|
||||
///
|
||||
|
||||
/**
|
||||
* @dev See {AccessControl-grantRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
|
||||
*/
|
||||
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
|
||||
if (role == DEFAULT_ADMIN_ROLE) {
|
||||
revert AccessControlEnforcedDefaultAdminRules();
|
||||
}
|
||||
super.grantRole(role, account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {AccessControl-revokeRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
|
||||
*/
|
||||
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
|
||||
if (role == DEFAULT_ADMIN_ROLE) {
|
||||
revert AccessControlEnforcedDefaultAdminRules();
|
||||
}
|
||||
super.revokeRole(role, account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {AccessControl-renounceRole}.
|
||||
*
|
||||
* For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling
|
||||
* {beginDefaultAdminTransfer} to the `address(0)`, so it's required that the {pendingDefaultAdmin} schedule
|
||||
* has also passed when calling this function.
|
||||
*
|
||||
* After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions.
|
||||
*
|
||||
* NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin},
|
||||
* thereby disabling any functionality that is only available for it, and the possibility of reassigning a
|
||||
* non-administrated role.
|
||||
*/
|
||||
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
|
||||
if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
|
||||
(address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin();
|
||||
if (newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
|
||||
revert AccessControlEnforcedDefaultAdminDelay(schedule);
|
||||
}
|
||||
delete _pendingDefaultAdminSchedule;
|
||||
}
|
||||
super.renounceRole(role, account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {AccessControl-_grantRole}.
|
||||
*
|
||||
* For `DEFAULT_ADMIN_ROLE`, it only allows granting if there isn't already a {defaultAdmin} or if the
|
||||
* role has been previously renounced.
|
||||
*
|
||||
* NOTE: Exposing this function through another mechanism may make the `DEFAULT_ADMIN_ROLE`
|
||||
* assignable again. Make sure to guarantee this is the expected behavior in your implementation.
|
||||
*/
|
||||
function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
|
||||
if (role == DEFAULT_ADMIN_ROLE) {
|
||||
if (defaultAdmin() != address(0)) {
|
||||
revert AccessControlEnforcedDefaultAdminRules();
|
||||
}
|
||||
_currentDefaultAdmin = account;
|
||||
}
|
||||
return super._grantRole(role, account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {AccessControl-_revokeRole}.
|
||||
*/
|
||||
function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
|
||||
if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
|
||||
delete _currentDefaultAdmin;
|
||||
}
|
||||
return super._revokeRole(role, account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {AccessControl-_setRoleAdmin}. Reverts for `DEFAULT_ADMIN_ROLE`.
|
||||
*/
|
||||
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual override {
|
||||
if (role == DEFAULT_ADMIN_ROLE) {
|
||||
revert AccessControlEnforcedDefaultAdminRules();
|
||||
}
|
||||
super._setRoleAdmin(role, adminRole);
|
||||
}
|
||||
|
||||
///
|
||||
/// AccessControlDefaultAdminRules accessors
|
||||
///
|
||||
|
||||
/**
|
||||
* @inheritdoc IAccessControlDefaultAdminRules
|
||||
*/
|
||||
function defaultAdmin() public view virtual returns (address) {
|
||||
return _currentDefaultAdmin;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IAccessControlDefaultAdminRules
|
||||
*/
|
||||
function pendingDefaultAdmin() public view virtual returns (address newAdmin, uint48 schedule) {
|
||||
return (_pendingDefaultAdmin, _pendingDefaultAdminSchedule);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IAccessControlDefaultAdminRules
|
||||
*/
|
||||
function defaultAdminDelay() public view virtual returns (uint48) {
|
||||
uint48 schedule = _pendingDelaySchedule;
|
||||
return (_isScheduleSet(schedule) && _hasSchedulePassed(schedule)) ? _pendingDelay : _currentDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IAccessControlDefaultAdminRules
|
||||
*/
|
||||
function pendingDefaultAdminDelay() public view virtual returns (uint48 newDelay, uint48 schedule) {
|
||||
schedule = _pendingDelaySchedule;
|
||||
return (_isScheduleSet(schedule) && !_hasSchedulePassed(schedule)) ? (_pendingDelay, schedule) : (0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IAccessControlDefaultAdminRules
|
||||
*/
|
||||
function defaultAdminDelayIncreaseWait() public view virtual returns (uint48) {
|
||||
return 5 days;
|
||||
}
|
||||
|
||||
///
|
||||
/// AccessControlDefaultAdminRules public and internal setters for defaultAdmin/pendingDefaultAdmin
|
||||
///
|
||||
|
||||
/**
|
||||
* @inheritdoc IAccessControlDefaultAdminRules
|
||||
*/
|
||||
function beginDefaultAdminTransfer(address newAdmin) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
_beginDefaultAdminTransfer(newAdmin);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {beginDefaultAdminTransfer}.
|
||||
*
|
||||
* Internal function without access restriction.
|
||||
*/
|
||||
function _beginDefaultAdminTransfer(address newAdmin) internal virtual {
|
||||
uint48 newSchedule = SafeCast.toUint48(block.timestamp) + defaultAdminDelay();
|
||||
_setPendingDefaultAdmin(newAdmin, newSchedule);
|
||||
emit DefaultAdminTransferScheduled(newAdmin, newSchedule);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IAccessControlDefaultAdminRules
|
||||
*/
|
||||
function cancelDefaultAdminTransfer() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
_cancelDefaultAdminTransfer();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {cancelDefaultAdminTransfer}.
|
||||
*
|
||||
* Internal function without access restriction.
|
||||
*/
|
||||
function _cancelDefaultAdminTransfer() internal virtual {
|
||||
_setPendingDefaultAdmin(address(0), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IAccessControlDefaultAdminRules
|
||||
*/
|
||||
function acceptDefaultAdminTransfer() public virtual {
|
||||
(address newDefaultAdmin, ) = pendingDefaultAdmin();
|
||||
if (_msgSender() != newDefaultAdmin) {
|
||||
// Enforce newDefaultAdmin explicit acceptance.
|
||||
revert AccessControlInvalidDefaultAdmin(_msgSender());
|
||||
}
|
||||
_acceptDefaultAdminTransfer();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {acceptDefaultAdminTransfer}.
|
||||
*
|
||||
* Internal function without access restriction.
|
||||
*/
|
||||
function _acceptDefaultAdminTransfer() internal virtual {
|
||||
(address newAdmin, uint48 schedule) = pendingDefaultAdmin();
|
||||
if (!_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
|
||||
revert AccessControlEnforcedDefaultAdminDelay(schedule);
|
||||
}
|
||||
_revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin());
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
|
||||
delete _pendingDefaultAdmin;
|
||||
delete _pendingDefaultAdminSchedule;
|
||||
}
|
||||
|
||||
///
|
||||
/// AccessControlDefaultAdminRules public and internal setters for defaultAdminDelay/pendingDefaultAdminDelay
|
||||
///
|
||||
|
||||
/**
|
||||
* @inheritdoc IAccessControlDefaultAdminRules
|
||||
*/
|
||||
function changeDefaultAdminDelay(uint48 newDelay) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
_changeDefaultAdminDelay(newDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {changeDefaultAdminDelay}.
|
||||
*
|
||||
* Internal function without access restriction.
|
||||
*/
|
||||
function _changeDefaultAdminDelay(uint48 newDelay) internal virtual {
|
||||
uint48 newSchedule = SafeCast.toUint48(block.timestamp) + _delayChangeWait(newDelay);
|
||||
_setPendingDelay(newDelay, newSchedule);
|
||||
emit DefaultAdminDelayChangeScheduled(newDelay, newSchedule);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IAccessControlDefaultAdminRules
|
||||
*/
|
||||
function rollbackDefaultAdminDelay() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||
_rollbackDefaultAdminDelay();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {rollbackDefaultAdminDelay}.
|
||||
*
|
||||
* Internal function without access restriction.
|
||||
*/
|
||||
function _rollbackDefaultAdminDelay() internal virtual {
|
||||
_setPendingDelay(0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the amount of seconds to wait after the `newDelay` will
|
||||
* become the new {defaultAdminDelay}.
|
||||
*
|
||||
* The value returned guarantees that if the delay is reduced, it will go into effect
|
||||
* after a wait that honors the previously set delay.
|
||||
*
|
||||
* See {defaultAdminDelayIncreaseWait}.
|
||||
*/
|
||||
function _delayChangeWait(uint48 newDelay) internal view virtual returns (uint48) {
|
||||
uint48 currentDelay = defaultAdminDelay();
|
||||
|
||||
// When increasing the delay, we schedule the delay change to occur after a period of "new delay" has passed, up
|
||||
// to a maximum given by defaultAdminDelayIncreaseWait, by default 5 days. For example, if increasing from 1 day
|
||||
// to 3 days, the new delay will come into effect after 3 days. If increasing from 1 day to 10 days, the new
|
||||
// delay will come into effect after 5 days. The 5 day wait period is intended to be able to fix an error like
|
||||
// using milliseconds instead of seconds.
|
||||
//
|
||||
// When decreasing the delay, we wait the difference between "current delay" and "new delay". This guarantees
|
||||
// that an admin transfer cannot be made faster than "current delay" at the time the delay change is scheduled.
|
||||
// For example, if decreasing from 10 days to 3 days, the new delay will come into effect after 7 days.
|
||||
return
|
||||
newDelay > currentDelay
|
||||
? uint48(Math.min(newDelay, defaultAdminDelayIncreaseWait())) // no need to safecast, both inputs are uint48
|
||||
: currentDelay - newDelay;
|
||||
}
|
||||
|
||||
///
|
||||
/// Private setters
|
||||
///
|
||||
|
||||
/**
|
||||
* @dev Setter of the tuple for pending admin and its schedule.
|
||||
*
|
||||
* May emit a DefaultAdminTransferCanceled event.
|
||||
*/
|
||||
function _setPendingDefaultAdmin(address newAdmin, uint48 newSchedule) private {
|
||||
(, uint48 oldSchedule) = pendingDefaultAdmin();
|
||||
|
||||
_pendingDefaultAdmin = newAdmin;
|
||||
_pendingDefaultAdminSchedule = newSchedule;
|
||||
|
||||
// An `oldSchedule` from `pendingDefaultAdmin()` is only set if it hasn't been accepted.
|
||||
if (_isScheduleSet(oldSchedule)) {
|
||||
// Emit for implicit cancellations when another default admin was scheduled.
|
||||
emit DefaultAdminTransferCanceled();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Setter of the tuple for pending delay and its schedule.
|
||||
*
|
||||
* May emit a DefaultAdminDelayChangeCanceled event.
|
||||
*/
|
||||
function _setPendingDelay(uint48 newDelay, uint48 newSchedule) private {
|
||||
uint48 oldSchedule = _pendingDelaySchedule;
|
||||
|
||||
if (_isScheduleSet(oldSchedule)) {
|
||||
if (_hasSchedulePassed(oldSchedule)) {
|
||||
// Materialize a virtual delay
|
||||
_currentDelay = _pendingDelay;
|
||||
} else {
|
||||
// Emit for implicit cancellations when another delay was scheduled.
|
||||
emit DefaultAdminDelayChangeCanceled();
|
||||
}
|
||||
}
|
||||
|
||||
_pendingDelay = newDelay;
|
||||
_pendingDelaySchedule = newSchedule;
|
||||
}
|
||||
|
||||
///
|
||||
/// Private helpers
|
||||
///
|
||||
|
||||
/**
|
||||
* @dev Defines if an `schedule` is considered set. For consistency purposes.
|
||||
*/
|
||||
function _isScheduleSet(uint48 schedule) private pure returns (bool) {
|
||||
return schedule != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Defines if an `schedule` is considered passed. For consistency purposes.
|
||||
*/
|
||||
function _hasSchedulePassed(uint48 schedule) private view returns (bool) {
|
||||
return schedule < block.timestamp;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/AccessControlEnumerable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAccessControlEnumerable} from "./IAccessControlEnumerable.sol";
|
||||
import {AccessControl} from "../AccessControl.sol";
|
||||
import {EnumerableSet} from "../../utils/structs/EnumerableSet.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
|
||||
*/
|
||||
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
|
||||
using EnumerableSet for EnumerableSet.AddressSet;
|
||||
|
||||
mapping(bytes32 role => EnumerableSet.AddressSet) private _roleMembers;
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
|
||||
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns one of the accounts that have `role`. `index` must be a
|
||||
* value between 0 and {getRoleMemberCount}, non-inclusive.
|
||||
*
|
||||
* Role bearers are not sorted in any particular way, and their ordering may
|
||||
* change at any point.
|
||||
*
|
||||
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
|
||||
* you perform all queries on the same block. See the following
|
||||
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
|
||||
* for more information.
|
||||
*/
|
||||
function getRoleMember(bytes32 role, uint256 index) public view virtual returns (address) {
|
||||
return _roleMembers[role].at(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the number of accounts that have `role`. Can be used
|
||||
* together with {getRoleMember} to enumerate all bearers of a role.
|
||||
*/
|
||||
function getRoleMemberCount(bytes32 role) public view virtual returns (uint256) {
|
||||
return _roleMembers[role].length();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Return all accounts that have `role`
|
||||
*
|
||||
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
|
||||
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
|
||||
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
|
||||
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
|
||||
*/
|
||||
function getRoleMembers(bytes32 role) public view virtual returns (address[] memory) {
|
||||
return _roleMembers[role].values();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overload {AccessControl-_grantRole} to track enumerable memberships
|
||||
*/
|
||||
function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
|
||||
bool granted = super._grantRole(role, account);
|
||||
if (granted) {
|
||||
_roleMembers[role].add(account);
|
||||
}
|
||||
return granted;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overload {AccessControl-_revokeRole} to track enumerable memberships
|
||||
*/
|
||||
function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
|
||||
bool revoked = super._revokeRole(role, account);
|
||||
if (revoked) {
|
||||
_roleMembers[role].remove(account);
|
||||
}
|
||||
return revoked;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/IAccessControlDefaultAdminRules.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAccessControl} from "../IAccessControl.sol";
|
||||
|
||||
/**
|
||||
* @dev External interface of AccessControlDefaultAdminRules declared to support ERC-165 detection.
|
||||
*/
|
||||
interface IAccessControlDefaultAdminRules is IAccessControl {
|
||||
/**
|
||||
* @dev The new default admin is not a valid default admin.
|
||||
*/
|
||||
error AccessControlInvalidDefaultAdmin(address defaultAdmin);
|
||||
|
||||
/**
|
||||
* @dev At least one of the following rules was violated:
|
||||
*
|
||||
* - The `DEFAULT_ADMIN_ROLE` must only be managed by itself.
|
||||
* - The `DEFAULT_ADMIN_ROLE` must only be held by one account at the time.
|
||||
* - Any `DEFAULT_ADMIN_ROLE` transfer must be in two delayed steps.
|
||||
*/
|
||||
error AccessControlEnforcedDefaultAdminRules();
|
||||
|
||||
/**
|
||||
* @dev The delay for transferring the default admin delay is enforced and
|
||||
* the operation must wait until `schedule`.
|
||||
*
|
||||
* NOTE: `schedule` can be 0 indicating there's no transfer scheduled.
|
||||
*/
|
||||
error AccessControlEnforcedDefaultAdminDelay(uint48 schedule);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next
|
||||
* address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after `acceptSchedule`
|
||||
* passes.
|
||||
*/
|
||||
event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its schedule.
|
||||
*/
|
||||
event DefaultAdminTransferCanceled();
|
||||
|
||||
/**
|
||||
* @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next
|
||||
* delay to be applied between default admin transfer after `effectSchedule` has passed.
|
||||
*/
|
||||
event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass.
|
||||
*/
|
||||
event DefaultAdminDelayChangeCanceled();
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder.
|
||||
*/
|
||||
function defaultAdmin() external view returns (address);
|
||||
|
||||
/**
|
||||
* @dev Returns a tuple of a `newAdmin` and an accept schedule.
|
||||
*
|
||||
* After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role
|
||||
* by calling {acceptDefaultAdminTransfer}, completing the role transfer.
|
||||
*
|
||||
* A zero value only in `acceptSchedule` indicates no pending admin transfer.
|
||||
*
|
||||
* NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced.
|
||||
*/
|
||||
function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule);
|
||||
|
||||
/**
|
||||
* @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer started.
|
||||
*
|
||||
* This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to set
|
||||
* the acceptance schedule.
|
||||
*
|
||||
* NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes, making this
|
||||
* function returns the new delay. See {changeDefaultAdminDelay}.
|
||||
*/
|
||||
function defaultAdminDelay() external view returns (uint48);
|
||||
|
||||
/**
|
||||
* @dev Returns a tuple of `newDelay` and an effect schedule.
|
||||
*
|
||||
* After the `schedule` passes, the `newDelay` will get into effect immediately for every
|
||||
* new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}.
|
||||
*
|
||||
* A zero value only in `effectSchedule` indicates no pending delay change.
|
||||
*
|
||||
* NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay}
|
||||
* will be zero after the effect schedule.
|
||||
*/
|
||||
function pendingDefaultAdminDelay() external view returns (uint48 newDelay, uint48 effectSchedule);
|
||||
|
||||
/**
|
||||
* @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for acceptance
|
||||
* after the current timestamp plus a {defaultAdminDelay}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - Only can be called by the current {defaultAdmin}.
|
||||
*
|
||||
* Emits a DefaultAdminRoleChangeStarted event.
|
||||
*/
|
||||
function beginDefaultAdminTransfer(address newAdmin) external;
|
||||
|
||||
/**
|
||||
* @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
|
||||
*
|
||||
* A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - Only can be called by the current {defaultAdmin}.
|
||||
*
|
||||
* May emit a DefaultAdminTransferCanceled event.
|
||||
*/
|
||||
function cancelDefaultAdminTransfer() external;
|
||||
|
||||
/**
|
||||
* @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
|
||||
*
|
||||
* After calling the function:
|
||||
*
|
||||
* - `DEFAULT_ADMIN_ROLE` should be granted to the caller.
|
||||
* - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder.
|
||||
* - {pendingDefaultAdmin} should be reset to zero values.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`.
|
||||
* - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed.
|
||||
*/
|
||||
function acceptDefaultAdminTransfer() external;
|
||||
|
||||
/**
|
||||
* @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled for getting
|
||||
* into effect after the current timestamp plus a {defaultAdminDelay}.
|
||||
*
|
||||
* This function guarantees that any call to {beginDefaultAdminTransfer} done between the timestamp this
|
||||
* method is called and the {pendingDefaultAdminDelay} effect schedule will use the current {defaultAdminDelay}
|
||||
* set before calling.
|
||||
*
|
||||
* The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the schedule and then
|
||||
* calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another {defaultAdmin}
|
||||
* complete transfer (including acceptance).
|
||||
*
|
||||
* The schedule is designed for two scenarios:
|
||||
*
|
||||
* - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay` capped by
|
||||
* {defaultAdminDelayIncreaseWait}.
|
||||
* - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current delay - new delay)`.
|
||||
*
|
||||
* A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new scheduled change.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - Only can be called by the current {defaultAdmin}.
|
||||
*
|
||||
* Emits a DefaultAdminDelayChangeScheduled event and may emit a DefaultAdminDelayChangeCanceled event.
|
||||
*/
|
||||
function changeDefaultAdminDelay(uint48 newDelay) external;
|
||||
|
||||
/**
|
||||
* @dev Cancels a scheduled {defaultAdminDelay} change.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - Only can be called by the current {defaultAdmin}.
|
||||
*
|
||||
* May emit a DefaultAdminDelayChangeCanceled event.
|
||||
*/
|
||||
function rollbackDefaultAdminDelay() external;
|
||||
|
||||
/**
|
||||
* @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using {changeDefaultAdminDelay})
|
||||
* to take effect. Default to 5 days.
|
||||
*
|
||||
* When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new delay has passed with
|
||||
* the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds instead of seconds)
|
||||
* that may lock the contract. However, to avoid excessive schedules, the wait is capped by this function and it can
|
||||
* be overrode for a custom {defaultAdminDelay} increase scheduling.
|
||||
*
|
||||
* IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise,
|
||||
* there's a risk of setting a high new delay that goes into effect almost immediately without the
|
||||
* possibility of human intervention in the case of an input error (eg. set milliseconds instead of seconds).
|
||||
*/
|
||||
function defaultAdminDelayIncreaseWait() external view returns (uint48);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/IAccessControlEnumerable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAccessControl} from "../IAccessControl.sol";
|
||||
|
||||
/**
|
||||
* @dev External interface of AccessControlEnumerable declared to support ERC-165 detection.
|
||||
*/
|
||||
interface IAccessControlEnumerable is IAccessControl {
|
||||
/**
|
||||
* @dev Returns one of the accounts that have `role`. `index` must be a
|
||||
* value between 0 and {getRoleMemberCount}, non-inclusive.
|
||||
*
|
||||
* Role bearers are not sorted in any particular way, and their ordering may
|
||||
* change at any point.
|
||||
*
|
||||
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
|
||||
* you perform all queries on the same block. See the following
|
||||
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
|
||||
* for more information.
|
||||
*/
|
||||
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
|
||||
|
||||
/**
|
||||
* @dev Returns the number of accounts that have `role`. Can be used
|
||||
* together with {getRoleMember} to enumerate all bearers of a role.
|
||||
*/
|
||||
function getRoleMemberCount(bytes32 role) external view returns (uint256);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AccessManaged.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAuthority} from "./IAuthority.sol";
|
||||
import {AuthorityUtils} from "./AuthorityUtils.sol";
|
||||
import {IAccessManager} from "./IAccessManager.sol";
|
||||
import {IAccessManaged} from "./IAccessManaged.sol";
|
||||
import {Context} from "../../utils/Context.sol";
|
||||
|
||||
/**
|
||||
* @dev This contract module makes available a {restricted} modifier. Functions decorated with this modifier will be
|
||||
* permissioned according to an "authority": a contract like {AccessManager} that follows the {IAuthority} interface,
|
||||
* implementing a policy that allows certain callers to access certain functions.
|
||||
*
|
||||
* IMPORTANT: The `restricted` modifier should never be used on `internal` functions, judiciously used in `public`
|
||||
* functions, and ideally only used in `external` functions. See {restricted}.
|
||||
*/
|
||||
abstract contract AccessManaged is Context, IAccessManaged {
|
||||
address private _authority;
|
||||
|
||||
bool private _consumingSchedule;
|
||||
|
||||
/**
|
||||
* @dev Initializes the contract connected to an initial authority.
|
||||
*/
|
||||
constructor(address initialAuthority) {
|
||||
_setAuthority(initialAuthority);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Restricts access to a function as defined by the connected Authority for this contract and the
|
||||
* caller and selector of the function that entered the contract.
|
||||
*
|
||||
* [IMPORTANT]
|
||||
* ====
|
||||
* In general, this modifier should only be used on `external` functions. It is okay to use it on `public`
|
||||
* functions that are used as external entry points and are not called internally. Unless you know what you're
|
||||
* doing, it should never be used on `internal` functions. Failure to follow these rules can have critical security
|
||||
* implications! This is because the permissions are determined by the function that entered the contract, i.e. the
|
||||
* function at the bottom of the call stack, and not the function where the modifier is visible in the source code.
|
||||
* ====
|
||||
*
|
||||
* [WARNING]
|
||||
* ====
|
||||
* Avoid adding this modifier to the https://docs.soliditylang.org/en/v0.8.20/contracts.html#receive-ether-function[`receive()`]
|
||||
* function or the https://docs.soliditylang.org/en/v0.8.20/contracts.html#fallback-function[`fallback()`]. These
|
||||
* functions are the only execution paths where a function selector cannot be unambiguously determined from the calldata
|
||||
* since the selector defaults to `0x00000000` in the `receive()` function and similarly in the `fallback()` function
|
||||
* if no calldata is provided. (See {_checkCanCall}).
|
||||
*
|
||||
* The `receive()` function will always panic whereas the `fallback()` may panic depending on the calldata length.
|
||||
* ====
|
||||
*/
|
||||
modifier restricted() {
|
||||
_checkCanCall(_msgSender(), _msgData());
|
||||
_;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManaged
|
||||
function authority() public view virtual returns (address) {
|
||||
return _authority;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManaged
|
||||
function setAuthority(address newAuthority) public virtual {
|
||||
address caller = _msgSender();
|
||||
if (caller != authority()) {
|
||||
revert AccessManagedUnauthorized(caller);
|
||||
}
|
||||
if (newAuthority.code.length == 0) {
|
||||
revert AccessManagedInvalidAuthority(newAuthority);
|
||||
}
|
||||
_setAuthority(newAuthority);
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManaged
|
||||
function isConsumingScheduledOp() public view returns (bytes4) {
|
||||
return _consumingSchedule ? this.isConsumingScheduledOp.selector : bytes4(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers control to a new authority. Internal function with no access restriction. Allows bypassing the
|
||||
* permissions set by the current authority.
|
||||
*/
|
||||
function _setAuthority(address newAuthority) internal virtual {
|
||||
_authority = newAuthority;
|
||||
emit AuthorityUpdated(newAuthority);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
|
||||
* is less than 4 bytes long.
|
||||
*/
|
||||
function _checkCanCall(address caller, bytes calldata data) internal virtual {
|
||||
(bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
|
||||
authority(),
|
||||
caller,
|
||||
address(this),
|
||||
bytes4(data[0:4])
|
||||
);
|
||||
if (!immediate) {
|
||||
if (delay > 0) {
|
||||
_consumingSchedule = true;
|
||||
IAccessManager(authority()).consumeScheduledOp(caller, data);
|
||||
_consumingSchedule = false;
|
||||
} else {
|
||||
revert AccessManagedUnauthorized(caller);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,731 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AccessManager.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAccessManager} from "./IAccessManager.sol";
|
||||
import {IAccessManaged} from "./IAccessManaged.sol";
|
||||
import {Address} from "../../utils/Address.sol";
|
||||
import {Context} from "../../utils/Context.sol";
|
||||
import {Multicall} from "../../utils/Multicall.sol";
|
||||
import {Math} from "../../utils/math/Math.sol";
|
||||
import {Time} from "../../utils/types/Time.sol";
|
||||
|
||||
/**
|
||||
* @dev AccessManager is a central contract to store the permissions of a system.
|
||||
*
|
||||
* A smart contract under the control of an AccessManager instance is known as a target, and will inherit from the
|
||||
* {AccessManaged} contract, be connected to this contract as its manager and implement the {AccessManaged-restricted}
|
||||
* modifier on a set of functions selected to be permissioned. Note that any function without this setup won't be
|
||||
* effectively restricted.
|
||||
*
|
||||
* The restriction rules for such functions are defined in terms of "roles" identified by an `uint64` and scoped
|
||||
* by target (`address`) and function selectors (`bytes4`). These roles are stored in this contract and can be
|
||||
* configured by admins (`ADMIN_ROLE` members) after a delay (see {getTargetAdminDelay}).
|
||||
*
|
||||
* For each target contract, admins can configure the following without any delay:
|
||||
*
|
||||
* * The target's {AccessManaged-authority} via {updateAuthority}.
|
||||
* * Close or open a target via {setTargetClosed} keeping the permissions intact.
|
||||
* * The roles that are allowed (or disallowed) to call a given function (identified by its selector) through {setTargetFunctionRole}.
|
||||
*
|
||||
* By default every address is member of the `PUBLIC_ROLE` and every target function is restricted to the `ADMIN_ROLE` until configured otherwise.
|
||||
* Additionally, each role has the following configuration options restricted to this manager's admins:
|
||||
*
|
||||
* * A role's admin role via {setRoleAdmin} who can grant or revoke roles.
|
||||
* * A role's guardian role via {setRoleGuardian} who's allowed to cancel operations.
|
||||
* * A delay in which a role takes effect after being granted through {setGrantDelay}.
|
||||
* * A delay of any target's admin action via {setTargetAdminDelay}.
|
||||
* * A role label for discoverability purposes with {labelRole}.
|
||||
*
|
||||
* Any account can be added and removed into any number of these roles by using the {grantRole} and {revokeRole} functions
|
||||
* restricted to each role's admin (see {getRoleAdmin}).
|
||||
*
|
||||
* Since all the permissions of the managed system can be modified by the admins of this instance, it is expected that
|
||||
* they will be highly secured (e.g., a multisig or a well-configured DAO).
|
||||
*
|
||||
* NOTE: This contract implements a form of the {IAuthority} interface, but {canCall} has additional return data so it
|
||||
* doesn't inherit `IAuthority`. It is however compatible with the `IAuthority` interface since the first 32 bytes of
|
||||
* the return data are a boolean as expected by that interface.
|
||||
*
|
||||
* NOTE: Systems that implement other access control mechanisms (for example using {Ownable}) can be paired with an
|
||||
* {AccessManager} by transferring permissions (ownership in the case of {Ownable}) directly to the {AccessManager}.
|
||||
* Users will be able to interact with these contracts through the {execute} function, following the access rules
|
||||
* registered in the {AccessManager}. Keep in mind that in that context, the msg.sender seen by restricted functions
|
||||
* will be {AccessManager} itself.
|
||||
*
|
||||
* WARNING: When granting permissions over an {Ownable} or {AccessControl} contract to an {AccessManager}, be very
|
||||
* mindful of the danger associated with functions such as {Ownable-renounceOwnership} or
|
||||
* {AccessControl-renounceRole}.
|
||||
*/
|
||||
contract AccessManager is Context, Multicall, IAccessManager {
|
||||
using Time for *;
|
||||
|
||||
// Structure that stores the details for a target contract.
|
||||
struct TargetConfig {
|
||||
mapping(bytes4 selector => uint64 roleId) allowedRoles;
|
||||
Time.Delay adminDelay;
|
||||
bool closed;
|
||||
}
|
||||
|
||||
// Structure that stores the details for a role/account pair. This structures fit into a single slot.
|
||||
struct Access {
|
||||
// Timepoint at which the user gets the permission.
|
||||
// If this is either 0 or in the future, then the role permission is not available.
|
||||
uint48 since;
|
||||
// Delay for execution. Only applies to restricted() / execute() calls.
|
||||
Time.Delay delay;
|
||||
}
|
||||
|
||||
// Structure that stores the details of a role.
|
||||
struct Role {
|
||||
// Members of the role.
|
||||
mapping(address user => Access access) members;
|
||||
// Admin who can grant or revoke permissions.
|
||||
uint64 admin;
|
||||
// Guardian who can cancel operations targeting functions that need this role.
|
||||
uint64 guardian;
|
||||
// Delay in which the role takes effect after being granted.
|
||||
Time.Delay grantDelay;
|
||||
}
|
||||
|
||||
// Structure that stores the details for a scheduled operation. This structure fits into a single slot.
|
||||
struct Schedule {
|
||||
// Moment at which the operation can be executed.
|
||||
uint48 timepoint;
|
||||
// Operation nonce to allow third-party contracts to identify the operation.
|
||||
uint32 nonce;
|
||||
}
|
||||
|
||||
uint64 public constant ADMIN_ROLE = type(uint64).min; // 0
|
||||
uint64 public constant PUBLIC_ROLE = type(uint64).max; // 2**64-1
|
||||
|
||||
mapping(address target => TargetConfig mode) private _targets;
|
||||
mapping(uint64 roleId => Role) private _roles;
|
||||
mapping(bytes32 operationId => Schedule) private _schedules;
|
||||
|
||||
// Used to identify operations that are currently being executed via {execute}.
|
||||
// This should be transient storage when supported by the EVM.
|
||||
bytes32 private _executionId;
|
||||
|
||||
/**
|
||||
* @dev Check that the caller is authorized to perform the operation.
|
||||
* See {AccessManager} description for a detailed breakdown of the authorization logic.
|
||||
*/
|
||||
modifier onlyAuthorized() {
|
||||
_checkAuthorized();
|
||||
_;
|
||||
}
|
||||
|
||||
constructor(address initialAdmin) {
|
||||
if (initialAdmin == address(0)) {
|
||||
revert AccessManagerInvalidInitialAdmin(address(0));
|
||||
}
|
||||
|
||||
// admin is active immediately and without any execution delay.
|
||||
_grantRole(ADMIN_ROLE, initialAdmin, 0, 0);
|
||||
}
|
||||
|
||||
// =================================================== GETTERS ====================================================
|
||||
/// @inheritdoc IAccessManager
|
||||
function canCall(
|
||||
address caller,
|
||||
address target,
|
||||
bytes4 selector
|
||||
) public view virtual returns (bool immediate, uint32 delay) {
|
||||
if (isTargetClosed(target)) {
|
||||
return (false, 0);
|
||||
} else if (caller == address(this)) {
|
||||
// Caller is AccessManager, this means the call was sent through {execute} and it already checked
|
||||
// permissions. We verify that the call "identifier", which is set during {execute}, is correct.
|
||||
return (_isExecuting(target, selector), 0);
|
||||
} else {
|
||||
uint64 roleId = getTargetFunctionRole(target, selector);
|
||||
(bool isMember, uint32 currentDelay) = hasRole(roleId, caller);
|
||||
return isMember ? (currentDelay == 0, currentDelay) : (false, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function expiration() public view virtual returns (uint32) {
|
||||
return 1 weeks;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function minSetback() public view virtual returns (uint32) {
|
||||
return 5 days;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function isTargetClosed(address target) public view virtual returns (bool) {
|
||||
return _targets[target].closed;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function getTargetFunctionRole(address target, bytes4 selector) public view virtual returns (uint64) {
|
||||
return _targets[target].allowedRoles[selector];
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function getTargetAdminDelay(address target) public view virtual returns (uint32) {
|
||||
return _targets[target].adminDelay.get();
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function getRoleAdmin(uint64 roleId) public view virtual returns (uint64) {
|
||||
return _roles[roleId].admin;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function getRoleGuardian(uint64 roleId) public view virtual returns (uint64) {
|
||||
return _roles[roleId].guardian;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function getRoleGrantDelay(uint64 roleId) public view virtual returns (uint32) {
|
||||
return _roles[roleId].grantDelay.get();
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function getAccess(
|
||||
uint64 roleId,
|
||||
address account
|
||||
) public view virtual returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect) {
|
||||
Access storage access = _roles[roleId].members[account];
|
||||
|
||||
since = access.since;
|
||||
(currentDelay, pendingDelay, effect) = access.delay.getFull();
|
||||
|
||||
return (since, currentDelay, pendingDelay, effect);
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function hasRole(
|
||||
uint64 roleId,
|
||||
address account
|
||||
) public view virtual returns (bool isMember, uint32 executionDelay) {
|
||||
if (roleId == PUBLIC_ROLE) {
|
||||
return (true, 0);
|
||||
} else {
|
||||
(uint48 hasRoleSince, uint32 currentDelay, , ) = getAccess(roleId, account);
|
||||
return (hasRoleSince != 0 && hasRoleSince <= Time.timestamp(), currentDelay);
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================== ROLE MANAGEMENT ===============================================
|
||||
/// @inheritdoc IAccessManager
|
||||
function labelRole(uint64 roleId, string calldata label) public virtual onlyAuthorized {
|
||||
if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
|
||||
revert AccessManagerLockedRole(roleId);
|
||||
}
|
||||
emit RoleLabel(roleId, label);
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function grantRole(uint64 roleId, address account, uint32 executionDelay) public virtual onlyAuthorized {
|
||||
_grantRole(roleId, account, getRoleGrantDelay(roleId), executionDelay);
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function revokeRole(uint64 roleId, address account) public virtual onlyAuthorized {
|
||||
_revokeRole(roleId, account);
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function renounceRole(uint64 roleId, address callerConfirmation) public virtual {
|
||||
if (callerConfirmation != _msgSender()) {
|
||||
revert AccessManagerBadConfirmation();
|
||||
}
|
||||
_revokeRole(roleId, callerConfirmation);
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function setRoleAdmin(uint64 roleId, uint64 admin) public virtual onlyAuthorized {
|
||||
_setRoleAdmin(roleId, admin);
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function setRoleGuardian(uint64 roleId, uint64 guardian) public virtual onlyAuthorized {
|
||||
_setRoleGuardian(roleId, guardian);
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function setGrantDelay(uint64 roleId, uint32 newDelay) public virtual onlyAuthorized {
|
||||
_setGrantDelay(roleId, newDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal version of {grantRole} without access control. Returns true if the role was newly granted.
|
||||
*
|
||||
* Emits a {RoleGranted} event.
|
||||
*/
|
||||
function _grantRole(
|
||||
uint64 roleId,
|
||||
address account,
|
||||
uint32 grantDelay,
|
||||
uint32 executionDelay
|
||||
) internal virtual returns (bool) {
|
||||
if (roleId == PUBLIC_ROLE) {
|
||||
revert AccessManagerLockedRole(roleId);
|
||||
}
|
||||
|
||||
bool newMember = _roles[roleId].members[account].since == 0;
|
||||
uint48 since;
|
||||
|
||||
if (newMember) {
|
||||
since = Time.timestamp() + grantDelay;
|
||||
_roles[roleId].members[account] = Access({since: since, delay: executionDelay.toDelay()});
|
||||
} else {
|
||||
// No setback here. Value can be reset by doing revoke + grant, effectively allowing the admin to perform
|
||||
// any change to the execution delay within the duration of the role admin delay.
|
||||
(_roles[roleId].members[account].delay, since) = _roles[roleId].members[account].delay.withUpdate(
|
||||
executionDelay,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
emit RoleGranted(roleId, account, executionDelay, since, newMember);
|
||||
return newMember;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal version of {revokeRole} without access control. This logic is also used by {renounceRole}.
|
||||
* Returns true if the role was previously granted.
|
||||
*
|
||||
* Emits a {RoleRevoked} event if the account had the role.
|
||||
*/
|
||||
function _revokeRole(uint64 roleId, address account) internal virtual returns (bool) {
|
||||
if (roleId == PUBLIC_ROLE) {
|
||||
revert AccessManagerLockedRole(roleId);
|
||||
}
|
||||
|
||||
if (_roles[roleId].members[account].since == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
delete _roles[roleId].members[account];
|
||||
|
||||
emit RoleRevoked(roleId, account);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal version of {setRoleAdmin} without access control.
|
||||
*
|
||||
* Emits a {RoleAdminChanged} event.
|
||||
*
|
||||
* NOTE: Setting the admin role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
|
||||
* anyone to set grant or revoke such role.
|
||||
*/
|
||||
function _setRoleAdmin(uint64 roleId, uint64 admin) internal virtual {
|
||||
if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
|
||||
revert AccessManagerLockedRole(roleId);
|
||||
}
|
||||
|
||||
_roles[roleId].admin = admin;
|
||||
|
||||
emit RoleAdminChanged(roleId, admin);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal version of {setRoleGuardian} without access control.
|
||||
*
|
||||
* Emits a {RoleGuardianChanged} event.
|
||||
*
|
||||
* NOTE: Setting the guardian role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
|
||||
* anyone to cancel any scheduled operation for such role.
|
||||
*/
|
||||
function _setRoleGuardian(uint64 roleId, uint64 guardian) internal virtual {
|
||||
if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
|
||||
revert AccessManagerLockedRole(roleId);
|
||||
}
|
||||
|
||||
_roles[roleId].guardian = guardian;
|
||||
|
||||
emit RoleGuardianChanged(roleId, guardian);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal version of {setGrantDelay} without access control.
|
||||
*
|
||||
* Emits a {RoleGrantDelayChanged} event.
|
||||
*/
|
||||
function _setGrantDelay(uint64 roleId, uint32 newDelay) internal virtual {
|
||||
if (roleId == PUBLIC_ROLE) {
|
||||
revert AccessManagerLockedRole(roleId);
|
||||
}
|
||||
|
||||
uint48 effect;
|
||||
(_roles[roleId].grantDelay, effect) = _roles[roleId].grantDelay.withUpdate(newDelay, minSetback());
|
||||
|
||||
emit RoleGrantDelayChanged(roleId, newDelay, effect);
|
||||
}
|
||||
|
||||
// ============================================= FUNCTION MANAGEMENT ==============================================
|
||||
/// @inheritdoc IAccessManager
|
||||
function setTargetFunctionRole(
|
||||
address target,
|
||||
bytes4[] calldata selectors,
|
||||
uint64 roleId
|
||||
) public virtual onlyAuthorized {
|
||||
for (uint256 i = 0; i < selectors.length; ++i) {
|
||||
_setTargetFunctionRole(target, selectors[i], roleId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal version of {setTargetFunctionRole} without access control.
|
||||
*
|
||||
* Emits a {TargetFunctionRoleUpdated} event.
|
||||
*/
|
||||
function _setTargetFunctionRole(address target, bytes4 selector, uint64 roleId) internal virtual {
|
||||
_targets[target].allowedRoles[selector] = roleId;
|
||||
emit TargetFunctionRoleUpdated(target, selector, roleId);
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function setTargetAdminDelay(address target, uint32 newDelay) public virtual onlyAuthorized {
|
||||
_setTargetAdminDelay(target, newDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal version of {setTargetAdminDelay} without access control.
|
||||
*
|
||||
* Emits a {TargetAdminDelayUpdated} event.
|
||||
*/
|
||||
function _setTargetAdminDelay(address target, uint32 newDelay) internal virtual {
|
||||
uint48 effect;
|
||||
(_targets[target].adminDelay, effect) = _targets[target].adminDelay.withUpdate(newDelay, minSetback());
|
||||
|
||||
emit TargetAdminDelayUpdated(target, newDelay, effect);
|
||||
}
|
||||
|
||||
// =============================================== MODE MANAGEMENT ================================================
|
||||
/// @inheritdoc IAccessManager
|
||||
function setTargetClosed(address target, bool closed) public virtual onlyAuthorized {
|
||||
_setTargetClosed(target, closed);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Set the closed flag for a contract. This is an internal setter with no access restrictions.
|
||||
*
|
||||
* Emits a {TargetClosed} event.
|
||||
*/
|
||||
function _setTargetClosed(address target, bool closed) internal virtual {
|
||||
if (target == address(this)) {
|
||||
revert AccessManagerLockedAccount(target);
|
||||
}
|
||||
_targets[target].closed = closed;
|
||||
emit TargetClosed(target, closed);
|
||||
}
|
||||
|
||||
// ============================================== DELAYED OPERATIONS ==============================================
|
||||
/// @inheritdoc IAccessManager
|
||||
function getSchedule(bytes32 id) public view virtual returns (uint48) {
|
||||
uint48 timepoint = _schedules[id].timepoint;
|
||||
return _isExpired(timepoint) ? 0 : timepoint;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function getNonce(bytes32 id) public view virtual returns (uint32) {
|
||||
return _schedules[id].nonce;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function schedule(
|
||||
address target,
|
||||
bytes calldata data,
|
||||
uint48 when
|
||||
) public virtual returns (bytes32 operationId, uint32 nonce) {
|
||||
address caller = _msgSender();
|
||||
|
||||
// Fetch restrictions that apply to the caller on the targeted function
|
||||
(, uint32 setback) = _canCallExtended(caller, target, data);
|
||||
|
||||
uint48 minWhen = Time.timestamp() + setback;
|
||||
|
||||
// If call with delay is not authorized, or if requested timing is too soon, revert
|
||||
if (setback == 0 || (when > 0 && when < minWhen)) {
|
||||
revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
|
||||
}
|
||||
|
||||
// Reuse variable due to stack too deep
|
||||
when = uint48(Math.max(when, minWhen)); // cast is safe: both inputs are uint48
|
||||
|
||||
// If caller is authorised, schedule operation
|
||||
operationId = hashOperation(caller, target, data);
|
||||
|
||||
_checkNotScheduled(operationId);
|
||||
|
||||
unchecked {
|
||||
// It's not feasible to overflow the nonce in less than 1000 years
|
||||
nonce = _schedules[operationId].nonce + 1;
|
||||
}
|
||||
_schedules[operationId].timepoint = when;
|
||||
_schedules[operationId].nonce = nonce;
|
||||
emit OperationScheduled(operationId, nonce, when, caller, target, data);
|
||||
|
||||
// Using named return values because otherwise we get stack too deep
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts if the operation is currently scheduled and has not expired.
|
||||
*
|
||||
* NOTE: This function was introduced due to stack too deep errors in schedule.
|
||||
*/
|
||||
function _checkNotScheduled(bytes32 operationId) private view {
|
||||
uint48 prevTimepoint = _schedules[operationId].timepoint;
|
||||
if (prevTimepoint != 0 && !_isExpired(prevTimepoint)) {
|
||||
revert AccessManagerAlreadyScheduled(operationId);
|
||||
}
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
// Reentrancy is not an issue because permissions are checked on msg.sender. Additionally,
|
||||
// _consumeScheduledOp guarantees a scheduled operation is only executed once.
|
||||
// slither-disable-next-line reentrancy-no-eth
|
||||
function execute(address target, bytes calldata data) public payable virtual returns (uint32) {
|
||||
address caller = _msgSender();
|
||||
|
||||
// Fetch restrictions that apply to the caller on the targeted function
|
||||
(bool immediate, uint32 setback) = _canCallExtended(caller, target, data);
|
||||
|
||||
// If call is not authorized, revert
|
||||
if (!immediate && setback == 0) {
|
||||
revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
|
||||
}
|
||||
|
||||
bytes32 operationId = hashOperation(caller, target, data);
|
||||
uint32 nonce;
|
||||
|
||||
// If caller is authorised, check operation was scheduled early enough
|
||||
// Consume an available schedule even if there is no currently enforced delay
|
||||
if (setback != 0 || getSchedule(operationId) != 0) {
|
||||
nonce = _consumeScheduledOp(operationId);
|
||||
}
|
||||
|
||||
// Mark the target and selector as authorised
|
||||
bytes32 executionIdBefore = _executionId;
|
||||
_executionId = _hashExecutionId(target, _checkSelector(data));
|
||||
|
||||
// Perform call
|
||||
Address.functionCallWithValue(target, data, msg.value);
|
||||
|
||||
// Reset execute identifier
|
||||
_executionId = executionIdBefore;
|
||||
|
||||
return nonce;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function cancel(address caller, address target, bytes calldata data) public virtual returns (uint32) {
|
||||
address msgsender = _msgSender();
|
||||
bytes4 selector = _checkSelector(data);
|
||||
|
||||
bytes32 operationId = hashOperation(caller, target, data);
|
||||
if (_schedules[operationId].timepoint == 0) {
|
||||
revert AccessManagerNotScheduled(operationId);
|
||||
} else if (caller != msgsender) {
|
||||
// calls can only be canceled by the account that scheduled them, a global admin, or by a guardian of the required role.
|
||||
(bool isAdmin, ) = hasRole(ADMIN_ROLE, msgsender);
|
||||
(bool isGuardian, ) = hasRole(getRoleGuardian(getTargetFunctionRole(target, selector)), msgsender);
|
||||
if (!isAdmin && !isGuardian) {
|
||||
revert AccessManagerUnauthorizedCancel(msgsender, caller, target, selector);
|
||||
}
|
||||
}
|
||||
|
||||
delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
|
||||
uint32 nonce = _schedules[operationId].nonce;
|
||||
emit OperationCanceled(operationId, nonce);
|
||||
|
||||
return nonce;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function consumeScheduledOp(address caller, bytes calldata data) public virtual {
|
||||
address target = _msgSender();
|
||||
if (IAccessManaged(target).isConsumingScheduledOp() != IAccessManaged.isConsumingScheduledOp.selector) {
|
||||
revert AccessManagerUnauthorizedConsume(target);
|
||||
}
|
||||
_consumeScheduledOp(hashOperation(caller, target, data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal variant of {consumeScheduledOp} that operates on bytes32 operationId.
|
||||
*
|
||||
* Returns the nonce of the scheduled operation that is consumed.
|
||||
*/
|
||||
function _consumeScheduledOp(bytes32 operationId) internal virtual returns (uint32) {
|
||||
uint48 timepoint = _schedules[operationId].timepoint;
|
||||
uint32 nonce = _schedules[operationId].nonce;
|
||||
|
||||
if (timepoint == 0) {
|
||||
revert AccessManagerNotScheduled(operationId);
|
||||
} else if (timepoint > Time.timestamp()) {
|
||||
revert AccessManagerNotReady(operationId);
|
||||
} else if (_isExpired(timepoint)) {
|
||||
revert AccessManagerExpired(operationId);
|
||||
}
|
||||
|
||||
delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
|
||||
emit OperationExecuted(operationId, nonce);
|
||||
|
||||
return nonce;
|
||||
}
|
||||
|
||||
/// @inheritdoc IAccessManager
|
||||
function hashOperation(address caller, address target, bytes calldata data) public view virtual returns (bytes32) {
|
||||
return keccak256(abi.encode(caller, target, data));
|
||||
}
|
||||
|
||||
// ==================================================== OTHERS ====================================================
|
||||
/// @inheritdoc IAccessManager
|
||||
function updateAuthority(address target, address newAuthority) public virtual onlyAuthorized {
|
||||
IAccessManaged(target).setAuthority(newAuthority);
|
||||
}
|
||||
|
||||
// ================================================= ADMIN LOGIC ==================================================
|
||||
/**
|
||||
* @dev Check if the current call is authorized according to admin logic.
|
||||
*/
|
||||
function _checkAuthorized() private {
|
||||
address caller = _msgSender();
|
||||
(bool immediate, uint32 delay) = _canCallSelf(caller, _msgData());
|
||||
if (!immediate) {
|
||||
if (delay == 0) {
|
||||
(, uint64 requiredRole, ) = _getAdminRestrictions(_msgData());
|
||||
revert AccessManagerUnauthorizedAccount(caller, requiredRole);
|
||||
} else {
|
||||
_consumeScheduledOp(hashOperation(caller, address(this), _msgData()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Get the admin restrictions of a given function call based on the function and arguments involved.
|
||||
*
|
||||
* Returns:
|
||||
* - bool restricted: does this data match a restricted operation
|
||||
* - uint64: which role is this operation restricted to
|
||||
* - uint32: minimum delay to enforce for that operation (max between operation's delay and admin's execution delay)
|
||||
*/
|
||||
function _getAdminRestrictions(
|
||||
bytes calldata data
|
||||
) private view returns (bool restricted, uint64 roleAdminId, uint32 executionDelay) {
|
||||
if (data.length < 4) {
|
||||
return (false, 0, 0);
|
||||
}
|
||||
|
||||
bytes4 selector = _checkSelector(data);
|
||||
|
||||
// Restricted to ADMIN with no delay beside any execution delay the caller may have
|
||||
if (
|
||||
selector == this.labelRole.selector ||
|
||||
selector == this.setRoleAdmin.selector ||
|
||||
selector == this.setRoleGuardian.selector ||
|
||||
selector == this.setGrantDelay.selector ||
|
||||
selector == this.setTargetAdminDelay.selector
|
||||
) {
|
||||
return (true, ADMIN_ROLE, 0);
|
||||
}
|
||||
|
||||
// Restricted to ADMIN with the admin delay corresponding to the target
|
||||
if (
|
||||
selector == this.updateAuthority.selector ||
|
||||
selector == this.setTargetClosed.selector ||
|
||||
selector == this.setTargetFunctionRole.selector
|
||||
) {
|
||||
// First argument is a target.
|
||||
address target = abi.decode(data[0x04:0x24], (address));
|
||||
uint32 delay = getTargetAdminDelay(target);
|
||||
return (true, ADMIN_ROLE, delay);
|
||||
}
|
||||
|
||||
// Restricted to that role's admin with no delay beside any execution delay the caller may have.
|
||||
if (selector == this.grantRole.selector || selector == this.revokeRole.selector) {
|
||||
// First argument is a roleId.
|
||||
uint64 roleId = abi.decode(data[0x04:0x24], (uint64));
|
||||
return (true, getRoleAdmin(roleId), 0);
|
||||
}
|
||||
|
||||
return (false, 0, 0);
|
||||
}
|
||||
|
||||
// =================================================== HELPERS ====================================================
|
||||
/**
|
||||
* @dev An extended version of {canCall} for internal usage that checks {_canCallSelf}
|
||||
* when the target is this contract.
|
||||
*
|
||||
* Returns:
|
||||
* - bool immediate: whether the operation can be executed immediately (with no delay)
|
||||
* - uint32 delay: the execution delay
|
||||
*/
|
||||
function _canCallExtended(
|
||||
address caller,
|
||||
address target,
|
||||
bytes calldata data
|
||||
) private view returns (bool immediate, uint32 delay) {
|
||||
if (target == address(this)) {
|
||||
return _canCallSelf(caller, data);
|
||||
} else {
|
||||
return data.length < 4 ? (false, 0) : canCall(caller, target, _checkSelector(data));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev A version of {canCall} that checks for admin restrictions in this contract.
|
||||
*/
|
||||
function _canCallSelf(address caller, bytes calldata data) private view returns (bool immediate, uint32 delay) {
|
||||
if (data.length < 4) {
|
||||
return (false, 0);
|
||||
}
|
||||
|
||||
if (caller == address(this)) {
|
||||
// Caller is AccessManager, this means the call was sent through {execute} and it already checked
|
||||
// permissions. We verify that the call "identifier", which is set during {execute}, is correct.
|
||||
return (_isExecuting(address(this), _checkSelector(data)), 0);
|
||||
}
|
||||
|
||||
(bool enabled, uint64 roleId, uint32 operationDelay) = _getAdminRestrictions(data);
|
||||
if (!enabled) {
|
||||
return (false, 0);
|
||||
}
|
||||
|
||||
(bool inRole, uint32 executionDelay) = hasRole(roleId, caller);
|
||||
if (!inRole) {
|
||||
return (false, 0);
|
||||
}
|
||||
|
||||
// downcast is safe because both options are uint32
|
||||
delay = uint32(Math.max(operationDelay, executionDelay));
|
||||
return (delay == 0, delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns true if a call with `target` and `selector` is being executed via {executed}.
|
||||
*/
|
||||
function _isExecuting(address target, bytes4 selector) private view returns (bool) {
|
||||
return _executionId == _hashExecutionId(target, selector);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns true if a schedule timepoint is past its expiration deadline.
|
||||
*/
|
||||
function _isExpired(uint48 timepoint) private view returns (bool) {
|
||||
return timepoint + expiration() <= Time.timestamp();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Extracts the selector from calldata. Panics if data is not at least 4 bytes
|
||||
*/
|
||||
function _checkSelector(bytes calldata data) private pure returns (bytes4) {
|
||||
return bytes4(data[0:4]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Hashing function for execute protection
|
||||
*/
|
||||
function _hashExecutionId(address target, bytes4 selector) private pure returns (bytes32) {
|
||||
return keccak256(abi.encode(target, selector));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AuthorityUtils.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAuthority} from "./IAuthority.sol";
|
||||
|
||||
library AuthorityUtils {
|
||||
/**
|
||||
* @dev Since `AccessManager` implements an extended IAuthority interface, invoking `canCall` with backwards compatibility
|
||||
* for the preexisting `IAuthority` interface requires special care to avoid reverting on insufficient return data.
|
||||
* This helper function takes care of invoking `canCall` in a backwards compatible way without reverting.
|
||||
*/
|
||||
function canCallWithDelay(
|
||||
address authority,
|
||||
address caller,
|
||||
address target,
|
||||
bytes4 selector
|
||||
) internal view returns (bool immediate, uint32 delay) {
|
||||
(bool success, bytes memory data) = authority.staticcall(
|
||||
abi.encodeCall(IAuthority.canCall, (caller, target, selector))
|
||||
);
|
||||
if (success) {
|
||||
if (data.length >= 0x40) {
|
||||
(immediate, delay) = abi.decode(data, (bool, uint32));
|
||||
} else if (data.length >= 0x20) {
|
||||
immediate = abi.decode(data, (bool));
|
||||
}
|
||||
}
|
||||
return (immediate, delay);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAccessManaged.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
interface IAccessManaged {
|
||||
/**
|
||||
* @dev Authority that manages this contract was updated.
|
||||
*/
|
||||
event AuthorityUpdated(address authority);
|
||||
|
||||
error AccessManagedUnauthorized(address caller);
|
||||
error AccessManagedRequiredDelay(address caller, uint32 delay);
|
||||
error AccessManagedInvalidAuthority(address authority);
|
||||
|
||||
/**
|
||||
* @dev Returns the current authority.
|
||||
*/
|
||||
function authority() external view returns (address);
|
||||
|
||||
/**
|
||||
* @dev Transfers control to a new authority. The caller must be the current authority.
|
||||
*/
|
||||
function setAuthority(address) external;
|
||||
|
||||
/**
|
||||
* @dev Returns true only in the context of a delayed restricted call, at the moment that the scheduled operation is
|
||||
* being consumed. Prevents denial of service for delayed restricted calls in the case that the contract performs
|
||||
* attacker controlled calls.
|
||||
*/
|
||||
function isConsumingScheduledOp() external view returns (bytes4);
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAccessManager.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAccessManaged} from "./IAccessManaged.sol";
|
||||
import {Time} from "../../utils/types/Time.sol";
|
||||
|
||||
interface IAccessManager {
|
||||
/**
|
||||
* @dev A delayed operation was scheduled.
|
||||
*/
|
||||
event OperationScheduled(
|
||||
bytes32 indexed operationId,
|
||||
uint32 indexed nonce,
|
||||
uint48 schedule,
|
||||
address caller,
|
||||
address target,
|
||||
bytes data
|
||||
);
|
||||
|
||||
/**
|
||||
* @dev A scheduled operation was executed.
|
||||
*/
|
||||
event OperationExecuted(bytes32 indexed operationId, uint32 indexed nonce);
|
||||
|
||||
/**
|
||||
* @dev A scheduled operation was canceled.
|
||||
*/
|
||||
event OperationCanceled(bytes32 indexed operationId, uint32 indexed nonce);
|
||||
|
||||
/**
|
||||
* @dev Informational labelling for a roleId.
|
||||
*/
|
||||
event RoleLabel(uint64 indexed roleId, string label);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `account` is granted `roleId`.
|
||||
*
|
||||
* NOTE: The meaning of the `since` argument depends on the `newMember` argument.
|
||||
* If the role is granted to a new member, the `since` argument indicates when the account becomes a member of the role,
|
||||
* otherwise it indicates the execution delay for this account and roleId is updated.
|
||||
*/
|
||||
event RoleGranted(uint64 indexed roleId, address indexed account, uint32 delay, uint48 since, bool newMember);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `account` membership or `roleId` is revoked. Unlike granting, revoking is instantaneous.
|
||||
*/
|
||||
event RoleRevoked(uint64 indexed roleId, address indexed account);
|
||||
|
||||
/**
|
||||
* @dev Role acting as admin over a given `roleId` is updated.
|
||||
*/
|
||||
event RoleAdminChanged(uint64 indexed roleId, uint64 indexed admin);
|
||||
|
||||
/**
|
||||
* @dev Role acting as guardian over a given `roleId` is updated.
|
||||
*/
|
||||
event RoleGuardianChanged(uint64 indexed roleId, uint64 indexed guardian);
|
||||
|
||||
/**
|
||||
* @dev Grant delay for a given `roleId` will be updated to `delay` when `since` is reached.
|
||||
*/
|
||||
event RoleGrantDelayChanged(uint64 indexed roleId, uint32 delay, uint48 since);
|
||||
|
||||
/**
|
||||
* @dev Target mode is updated (true = closed, false = open).
|
||||
*/
|
||||
event TargetClosed(address indexed target, bool closed);
|
||||
|
||||
/**
|
||||
* @dev Role required to invoke `selector` on `target` is updated to `roleId`.
|
||||
*/
|
||||
event TargetFunctionRoleUpdated(address indexed target, bytes4 selector, uint64 indexed roleId);
|
||||
|
||||
/**
|
||||
* @dev Admin delay for a given `target` will be updated to `delay` when `since` is reached.
|
||||
*/
|
||||
event TargetAdminDelayUpdated(address indexed target, uint32 delay, uint48 since);
|
||||
|
||||
error AccessManagerAlreadyScheduled(bytes32 operationId);
|
||||
error AccessManagerNotScheduled(bytes32 operationId);
|
||||
error AccessManagerNotReady(bytes32 operationId);
|
||||
error AccessManagerExpired(bytes32 operationId);
|
||||
error AccessManagerLockedAccount(address account);
|
||||
error AccessManagerLockedRole(uint64 roleId);
|
||||
error AccessManagerBadConfirmation();
|
||||
error AccessManagerUnauthorizedAccount(address msgsender, uint64 roleId);
|
||||
error AccessManagerUnauthorizedCall(address caller, address target, bytes4 selector);
|
||||
error AccessManagerUnauthorizedConsume(address target);
|
||||
error AccessManagerUnauthorizedCancel(address msgsender, address caller, address target, bytes4 selector);
|
||||
error AccessManagerInvalidInitialAdmin(address initialAdmin);
|
||||
|
||||
/**
|
||||
* @dev Check if an address (`caller`) is authorised to call a given function on a given contract directly (with
|
||||
* no restriction). Additionally, it returns the delay needed to perform the call indirectly through the {schedule}
|
||||
* & {execute} workflow.
|
||||
*
|
||||
* This function is usually called by the targeted contract to control immediate execution of restricted functions.
|
||||
* Therefore we only return true if the call can be performed without any delay. If the call is subject to a
|
||||
* previously set delay (not zero), then the function should return false and the caller should schedule the operation
|
||||
* for future execution.
|
||||
*
|
||||
* If `immediate` is true, the delay can be disregarded and the operation can be immediately executed, otherwise
|
||||
* the operation can be executed if and only if delay is greater than 0.
|
||||
*
|
||||
* NOTE: The IAuthority interface does not include the `uint32` delay. This is an extension of that interface that
|
||||
* is backward compatible. Some contracts may thus ignore the second return argument. In that case they will fail
|
||||
* to identify the indirect workflow, and will consider calls that require a delay to be forbidden.
|
||||
*
|
||||
* NOTE: This function does not report the permissions of this manager itself. These are defined by the
|
||||
* {AccessManager} documentation.
|
||||
*/
|
||||
function canCall(
|
||||
address caller,
|
||||
address target,
|
||||
bytes4 selector
|
||||
) external view returns (bool allowed, uint32 delay);
|
||||
|
||||
/**
|
||||
* @dev Expiration delay for scheduled proposals. Defaults to 1 week.
|
||||
*
|
||||
* IMPORTANT: Avoid overriding the expiration with 0. Otherwise every contract proposal will be expired immediately,
|
||||
* disabling any scheduling usage.
|
||||
*/
|
||||
function expiration() external view returns (uint32);
|
||||
|
||||
/**
|
||||
* @dev Minimum setback for all delay updates, with the exception of execution delays. It
|
||||
* can be increased without setback (and reset via {revokeRole} in the case event of an
|
||||
* accidental increase). Defaults to 5 days.
|
||||
*/
|
||||
function minSetback() external view returns (uint32);
|
||||
|
||||
/**
|
||||
* @dev Get whether the contract is closed disabling any access. Otherwise role permissions are applied.
|
||||
*/
|
||||
function isTargetClosed(address target) external view returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Get the role required to call a function.
|
||||
*/
|
||||
function getTargetFunctionRole(address target, bytes4 selector) external view returns (uint64);
|
||||
|
||||
/**
|
||||
* @dev Get the admin delay for a target contract. Changes to contract configuration are subject to this delay.
|
||||
*/
|
||||
function getTargetAdminDelay(address target) external view returns (uint32);
|
||||
|
||||
/**
|
||||
* @dev Get the id of the role that acts as an admin for the given role.
|
||||
*
|
||||
* The admin permission is required to grant the role, revoke the role and update the execution delay to execute
|
||||
* an operation that is restricted to this role.
|
||||
*/
|
||||
function getRoleAdmin(uint64 roleId) external view returns (uint64);
|
||||
|
||||
/**
|
||||
* @dev Get the role that acts as a guardian for a given role.
|
||||
*
|
||||
* The guardian permission allows canceling operations that have been scheduled under the role.
|
||||
*/
|
||||
function getRoleGuardian(uint64 roleId) external view returns (uint64);
|
||||
|
||||
/**
|
||||
* @dev Get the role current grant delay.
|
||||
*
|
||||
* Its value may change at any point without an event emitted following a call to {setGrantDelay}.
|
||||
* Changes to this value, including effect timepoint are notified in advance by the {RoleGrantDelayChanged} event.
|
||||
*/
|
||||
function getRoleGrantDelay(uint64 roleId) external view returns (uint32);
|
||||
|
||||
/**
|
||||
* @dev Get the access details for a given account for a given role. These details include the timepoint at which
|
||||
* membership becomes active, and the delay applied to all operation by this user that requires this permission
|
||||
* level.
|
||||
*
|
||||
* Returns:
|
||||
* [0] Timestamp at which the account membership becomes valid. 0 means role is not granted.
|
||||
* [1] Current execution delay for the account.
|
||||
* [2] Pending execution delay for the account.
|
||||
* [3] Timestamp at which the pending execution delay will become active. 0 means no delay update is scheduled.
|
||||
*/
|
||||
function getAccess(
|
||||
uint64 roleId,
|
||||
address account
|
||||
) external view returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect);
|
||||
|
||||
/**
|
||||
* @dev Check if a given account currently has the permission level corresponding to a given role. Note that this
|
||||
* permission might be associated with an execution delay. {getAccess} can provide more details.
|
||||
*/
|
||||
function hasRole(uint64 roleId, address account) external view returns (bool isMember, uint32 executionDelay);
|
||||
|
||||
/**
|
||||
* @dev Give a label to a role, for improved role discoverability by UIs.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be a global admin
|
||||
*
|
||||
* Emits a {RoleLabel} event.
|
||||
*/
|
||||
function labelRole(uint64 roleId, string calldata label) external;
|
||||
|
||||
/**
|
||||
* @dev Add `account` to `roleId`, or change its execution delay.
|
||||
*
|
||||
* This gives the account the authorization to call any function that is restricted to this role. An optional
|
||||
* execution delay (in seconds) can be set. If that delay is non 0, the user is required to schedule any operation
|
||||
* that is restricted to members of this role. The user will only be able to execute the operation after the delay has
|
||||
* passed, before it has expired. During this period, admin and guardians can cancel the operation (see {cancel}).
|
||||
*
|
||||
* If the account has already been granted this role, the execution delay will be updated. This update is not
|
||||
* immediate and follows the delay rules. For example, if a user currently has a delay of 3 hours, and this is
|
||||
* called to reduce that delay to 1 hour, the new delay will take some time to take effect, enforcing that any
|
||||
* operation executed in the 3 hours that follows this update was indeed scheduled before this update.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be an admin for the role (see {getRoleAdmin})
|
||||
* - granted role must not be the `PUBLIC_ROLE`
|
||||
*
|
||||
* Emits a {RoleGranted} event.
|
||||
*/
|
||||
function grantRole(uint64 roleId, address account, uint32 executionDelay) external;
|
||||
|
||||
/**
|
||||
* @dev Remove an account from a role, with immediate effect. If the account does not have the role, this call has
|
||||
* no effect.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be an admin for the role (see {getRoleAdmin})
|
||||
* - revoked role must not be the `PUBLIC_ROLE`
|
||||
*
|
||||
* Emits a {RoleRevoked} event if the account had the role.
|
||||
*/
|
||||
function revokeRole(uint64 roleId, address account) external;
|
||||
|
||||
/**
|
||||
* @dev Renounce role permissions for the calling account with immediate effect. If the sender is not in
|
||||
* the role this call has no effect.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be `callerConfirmation`.
|
||||
*
|
||||
* Emits a {RoleRevoked} event if the account had the role.
|
||||
*/
|
||||
function renounceRole(uint64 roleId, address callerConfirmation) external;
|
||||
|
||||
/**
|
||||
* @dev Change admin role for a given role.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be a global admin
|
||||
*
|
||||
* Emits a {RoleAdminChanged} event
|
||||
*/
|
||||
function setRoleAdmin(uint64 roleId, uint64 admin) external;
|
||||
|
||||
/**
|
||||
* @dev Change guardian role for a given role.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be a global admin
|
||||
*
|
||||
* Emits a {RoleGuardianChanged} event
|
||||
*/
|
||||
function setRoleGuardian(uint64 roleId, uint64 guardian) external;
|
||||
|
||||
/**
|
||||
* @dev Update the delay for granting a `roleId`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be a global admin
|
||||
*
|
||||
* Emits a {RoleGrantDelayChanged} event.
|
||||
*/
|
||||
function setGrantDelay(uint64 roleId, uint32 newDelay) external;
|
||||
|
||||
/**
|
||||
* @dev Set the role required to call functions identified by the `selectors` in the `target` contract.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be a global admin
|
||||
*
|
||||
* Emits a {TargetFunctionRoleUpdated} event per selector.
|
||||
*/
|
||||
function setTargetFunctionRole(address target, bytes4[] calldata selectors, uint64 roleId) external;
|
||||
|
||||
/**
|
||||
* @dev Set the delay for changing the configuration of a given target contract.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be a global admin
|
||||
*
|
||||
* Emits a {TargetAdminDelayUpdated} event.
|
||||
*/
|
||||
function setTargetAdminDelay(address target, uint32 newDelay) external;
|
||||
|
||||
/**
|
||||
* @dev Set the closed flag for a contract.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be a global admin
|
||||
*
|
||||
* Emits a {TargetClosed} event.
|
||||
*/
|
||||
function setTargetClosed(address target, bool closed) external;
|
||||
|
||||
/**
|
||||
* @dev Return the timepoint at which a scheduled operation will be ready for execution. This returns 0 if the
|
||||
* operation is not yet scheduled, has expired, was executed, or was canceled.
|
||||
*/
|
||||
function getSchedule(bytes32 id) external view returns (uint48);
|
||||
|
||||
/**
|
||||
* @dev Return the nonce for the latest scheduled operation with a given id. Returns 0 if the operation has never
|
||||
* been scheduled.
|
||||
*/
|
||||
function getNonce(bytes32 id) external view returns (uint32);
|
||||
|
||||
/**
|
||||
* @dev Schedule a delayed operation for future execution, and return the operation identifier. It is possible to
|
||||
* choose the timestamp at which the operation becomes executable as long as it satisfies the execution delays
|
||||
* required for the caller. The special value zero will automatically set the earliest possible time.
|
||||
*
|
||||
* Returns the `operationId` that was scheduled. Since this value is a hash of the parameters, it can reoccur when
|
||||
* the same parameters are used; if this is relevant, the returned `nonce` can be used to uniquely identify this
|
||||
* scheduled operation from other occurrences of the same `operationId` in invocations of {execute} and {cancel}.
|
||||
*
|
||||
* Emits a {OperationScheduled} event.
|
||||
*
|
||||
* NOTE: It is not possible to concurrently schedule more than one operation with the same `target` and `data`. If
|
||||
* this is necessary, a random byte can be appended to `data` to act as a salt that will be ignored by the target
|
||||
* contract if it is using standard Solidity ABI encoding.
|
||||
*/
|
||||
function schedule(
|
||||
address target,
|
||||
bytes calldata data,
|
||||
uint48 when
|
||||
) external returns (bytes32 operationId, uint32 nonce);
|
||||
|
||||
/**
|
||||
* @dev Execute a function that is delay restricted, provided it was properly scheduled beforehand, or the
|
||||
* execution delay is 0.
|
||||
*
|
||||
* Returns the nonce that identifies the previously scheduled operation that is executed, or 0 if the
|
||||
* operation wasn't previously scheduled (if the caller doesn't have an execution delay).
|
||||
*
|
||||
* Emits an {OperationExecuted} event only if the call was scheduled and delayed.
|
||||
*/
|
||||
function execute(address target, bytes calldata data) external payable returns (uint32);
|
||||
|
||||
/**
|
||||
* @dev Cancel a scheduled (delayed) operation. Returns the nonce that identifies the previously scheduled
|
||||
* operation that is cancelled.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be the proposer, a guardian of the targeted function, or a global admin
|
||||
*
|
||||
* Emits a {OperationCanceled} event.
|
||||
*/
|
||||
function cancel(address caller, address target, bytes calldata data) external returns (uint32);
|
||||
|
||||
/**
|
||||
* @dev Consume a scheduled operation targeting the caller. If such an operation exists, mark it as consumed
|
||||
* (emit an {OperationExecuted} event and clean the state). Otherwise, throw an error.
|
||||
*
|
||||
* This is useful for contract that want to enforce that calls targeting them were scheduled on the manager,
|
||||
* with all the verifications that it implies.
|
||||
*
|
||||
* Emit a {OperationExecuted} event.
|
||||
*/
|
||||
function consumeScheduledOp(address caller, bytes calldata data) external;
|
||||
|
||||
/**
|
||||
* @dev Hashing function for delayed operations.
|
||||
*/
|
||||
function hashOperation(address caller, address target, bytes calldata data) external view returns (bytes32);
|
||||
|
||||
/**
|
||||
* @dev Changes the authority of a target managed by this manager instance.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be a global admin
|
||||
*/
|
||||
function updateAuthority(address target, address newAuthority) external;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAuthority.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Standard interface for permissioning originally defined in Dappsys.
|
||||
*/
|
||||
interface IAuthority {
|
||||
/**
|
||||
* @dev Returns true if the caller can invoke on a target the function identified by a function selector.
|
||||
*/
|
||||
function canCall(address caller, address target, bytes4 selector) external view returns (bool allowed);
|
||||
}
|
||||
14
lib_openzeppelin_contracts/contracts/finance/README.adoc
Normal file
14
lib_openzeppelin_contracts/contracts/finance/README.adoc
Normal file
@@ -0,0 +1,14 @@
|
||||
= Finance
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/finance
|
||||
|
||||
This directory includes primitives for financial systems:
|
||||
|
||||
- {VestingWallet} handles the vesting of Ether and ERC-20 tokens for a given beneficiary. Custody of multiple tokens can
|
||||
be given to this contract, which will release the token to the beneficiary following a given, customizable, vesting
|
||||
schedule.
|
||||
|
||||
== Contracts
|
||||
|
||||
{{VestingWallet}}
|
||||
154
lib_openzeppelin_contracts/contracts/finance/VestingWallet.sol
Normal file
154
lib_openzeppelin_contracts/contracts/finance/VestingWallet.sol
Normal file
@@ -0,0 +1,154 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (finance/VestingWallet.sol)
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "../token/ERC20/IERC20.sol";
|
||||
import {SafeERC20} from "../token/ERC20/utils/SafeERC20.sol";
|
||||
import {Address} from "../utils/Address.sol";
|
||||
import {Context} from "../utils/Context.sol";
|
||||
import {Ownable} from "../access/Ownable.sol";
|
||||
|
||||
/**
|
||||
* @dev A vesting wallet is an ownable contract that can receive native currency and ERC-20 tokens, and release these
|
||||
* assets to the wallet owner, also referred to as "beneficiary", according to a vesting schedule.
|
||||
*
|
||||
* Any assets transferred to this contract will follow the vesting schedule as if they were locked from the beginning.
|
||||
* Consequently, if the vesting has already started, any amount of tokens sent to this contract will (at least partly)
|
||||
* be immediately releasable.
|
||||
*
|
||||
* By setting the duration to 0, one can configure this contract to behave like an asset timelock that hold tokens for
|
||||
* a beneficiary until a specified time.
|
||||
*
|
||||
* NOTE: Since the wallet is {Ownable}, and ownership can be transferred, it is possible to sell unvested tokens.
|
||||
* Preventing this in a smart contract is difficult, considering that: 1) a beneficiary address could be a
|
||||
* counterfactually deployed contract, 2) there is likely to be a migration path for EOAs to become contracts in the
|
||||
* near future.
|
||||
*
|
||||
* NOTE: When using this contract with any token whose balance is adjusted automatically (i.e. a rebase token), make
|
||||
* sure to account the supply/balance adjustment in the vesting schedule to ensure the vested amount is as intended.
|
||||
*/
|
||||
contract VestingWallet is Context, Ownable {
|
||||
event EtherReleased(uint256 amount);
|
||||
event ERC20Released(address indexed token, uint256 amount);
|
||||
|
||||
uint256 private _released;
|
||||
mapping(address token => uint256) private _erc20Released;
|
||||
uint64 private immutable _start;
|
||||
uint64 private immutable _duration;
|
||||
|
||||
/**
|
||||
* @dev Sets the sender as the initial owner, the beneficiary as the pending owner, the start timestamp and the
|
||||
* vesting duration of the vesting wallet.
|
||||
*/
|
||||
constructor(address beneficiary, uint64 startTimestamp, uint64 durationSeconds) payable Ownable(beneficiary) {
|
||||
_start = startTimestamp;
|
||||
_duration = durationSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev The contract should be able to receive Eth.
|
||||
*/
|
||||
receive() external payable virtual {}
|
||||
|
||||
/**
|
||||
* @dev Getter for the start timestamp.
|
||||
*/
|
||||
function start() public view virtual returns (uint256) {
|
||||
return _start;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the vesting duration.
|
||||
*/
|
||||
function duration() public view virtual returns (uint256) {
|
||||
return _duration;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the end timestamp.
|
||||
*/
|
||||
function end() public view virtual returns (uint256) {
|
||||
return start() + duration();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Amount of eth already released
|
||||
*/
|
||||
function released() public view virtual returns (uint256) {
|
||||
return _released;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Amount of token already released
|
||||
*/
|
||||
function released(address token) public view virtual returns (uint256) {
|
||||
return _erc20Released[token];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the amount of releasable eth.
|
||||
*/
|
||||
function releasable() public view virtual returns (uint256) {
|
||||
return vestedAmount(uint64(block.timestamp)) - released();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the amount of releasable `token` tokens. `token` should be the address of an
|
||||
* {IERC20} contract.
|
||||
*/
|
||||
function releasable(address token) public view virtual returns (uint256) {
|
||||
return vestedAmount(token, uint64(block.timestamp)) - released(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Release the native token (ether) that have already vested.
|
||||
*
|
||||
* Emits a {EtherReleased} event.
|
||||
*/
|
||||
function release() public virtual {
|
||||
uint256 amount = releasable();
|
||||
_released += amount;
|
||||
emit EtherReleased(amount);
|
||||
Address.sendValue(payable(owner()), amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Release the tokens that have already vested.
|
||||
*
|
||||
* Emits a {ERC20Released} event.
|
||||
*/
|
||||
function release(address token) public virtual {
|
||||
uint256 amount = releasable(token);
|
||||
_erc20Released[token] += amount;
|
||||
emit ERC20Released(token, amount);
|
||||
SafeERC20.safeTransfer(IERC20(token), owner(), amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Calculates the amount of ether that has already vested. Default implementation is a linear vesting curve.
|
||||
*/
|
||||
function vestedAmount(uint64 timestamp) public view virtual returns (uint256) {
|
||||
return _vestingSchedule(address(this).balance + released(), timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Calculates the amount of tokens that has already vested. Default implementation is a linear vesting curve.
|
||||
*/
|
||||
function vestedAmount(address token, uint64 timestamp) public view virtual returns (uint256) {
|
||||
return _vestingSchedule(IERC20(token).balanceOf(address(this)) + released(token), timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Virtual implementation of the vesting formula. This returns the amount vested, as a function of time, for
|
||||
* an asset given its total historical allocation.
|
||||
*/
|
||||
function _vestingSchedule(uint256 totalAllocation, uint64 timestamp) internal view virtual returns (uint256) {
|
||||
if (timestamp < start()) {
|
||||
return 0;
|
||||
} else if (timestamp >= end()) {
|
||||
return totalAllocation;
|
||||
} else {
|
||||
return (totalAllocation * (timestamp - start())) / duration();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {SafeCast} from "../utils/math/SafeCast.sol";
|
||||
import {VestingWallet} from "./VestingWallet.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {VestingWallet} that adds a cliff to the vesting schedule.
|
||||
*/
|
||||
abstract contract VestingWalletCliff is VestingWallet {
|
||||
using SafeCast for *;
|
||||
|
||||
uint64 private immutable _cliff;
|
||||
|
||||
/// @dev The specified cliff duration is larger than the vesting duration.
|
||||
error InvalidCliffDuration(uint64 cliffSeconds, uint64 durationSeconds);
|
||||
|
||||
/**
|
||||
* @dev Sets the sender as the initial owner, the beneficiary as the pending owner, the start timestamp, the
|
||||
* vesting duration and the duration of the cliff of the vesting wallet.
|
||||
*/
|
||||
constructor(uint64 cliffSeconds) {
|
||||
if (cliffSeconds > duration()) {
|
||||
revert InvalidCliffDuration(cliffSeconds, duration().toUint64());
|
||||
}
|
||||
_cliff = start().toUint64() + cliffSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the cliff timestamp.
|
||||
*/
|
||||
function cliff() public view virtual returns (uint256) {
|
||||
return _cliff;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Virtual implementation of the vesting formula. This returns the amount vested, as a function of time, for
|
||||
* an asset given its total historical allocation. Returns 0 if the {cliff} timestamp is not met.
|
||||
*
|
||||
* IMPORTANT: The cliff not only makes the schedule return 0, but it also ignores every possible side
|
||||
* effect from calling the inherited implementation (i.e. `super._vestingSchedule`). Carefully consider
|
||||
* this caveat if the overridden implementation of this function has any (e.g. writing to memory or reverting).
|
||||
*/
|
||||
function _vestingSchedule(
|
||||
uint256 totalAllocation,
|
||||
uint64 timestamp
|
||||
) internal view virtual override returns (uint256) {
|
||||
return timestamp < cliff() ? 0 : super._vestingSchedule(totalAllocation, timestamp);
|
||||
}
|
||||
}
|
||||
852
lib_openzeppelin_contracts/contracts/governance/Governor.sol
Normal file
852
lib_openzeppelin_contracts/contracts/governance/Governor.sol
Normal file
@@ -0,0 +1,852 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/Governor.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721Receiver} from "../token/ERC721/IERC721Receiver.sol";
|
||||
import {IERC1155Receiver} from "../token/ERC1155/IERC1155Receiver.sol";
|
||||
import {EIP712} from "../utils/cryptography/EIP712.sol";
|
||||
import {SignatureChecker} from "../utils/cryptography/SignatureChecker.sol";
|
||||
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
|
||||
import {SafeCast} from "../utils/math/SafeCast.sol";
|
||||
import {DoubleEndedQueue} from "../utils/structs/DoubleEndedQueue.sol";
|
||||
import {Address} from "../utils/Address.sol";
|
||||
import {Context} from "../utils/Context.sol";
|
||||
import {Nonces} from "../utils/Nonces.sol";
|
||||
import {IGovernor, IERC6372} from "./IGovernor.sol";
|
||||
|
||||
/**
|
||||
* @dev Core of the governance system, designed to be extended through various modules.
|
||||
*
|
||||
* This contract is abstract and requires several functions to be implemented in various modules:
|
||||
*
|
||||
* - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
|
||||
* - A voting module must implement {_getVotes}
|
||||
* - Additionally, {votingPeriod} must also be implemented
|
||||
*/
|
||||
abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC721Receiver, IERC1155Receiver {
|
||||
using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
|
||||
|
||||
bytes32 public constant BALLOT_TYPEHASH =
|
||||
keccak256("Ballot(uint256 proposalId,uint8 support,address voter,uint256 nonce)");
|
||||
bytes32 public constant EXTENDED_BALLOT_TYPEHASH =
|
||||
keccak256(
|
||||
"ExtendedBallot(uint256 proposalId,uint8 support,address voter,uint256 nonce,string reason,bytes params)"
|
||||
);
|
||||
|
||||
struct ProposalCore {
|
||||
address proposer;
|
||||
uint48 voteStart;
|
||||
uint32 voteDuration;
|
||||
bool executed;
|
||||
bool canceled;
|
||||
uint48 etaSeconds;
|
||||
}
|
||||
|
||||
bytes32 private constant ALL_PROPOSAL_STATES_BITMAP = bytes32((2 ** (uint8(type(ProposalState).max) + 1)) - 1);
|
||||
string private _name;
|
||||
|
||||
mapping(uint256 proposalId => ProposalCore) private _proposals;
|
||||
|
||||
// This queue keeps track of the governor operating on itself. Calls to functions protected by the {onlyGovernance}
|
||||
// modifier needs to be whitelisted in this queue. Whitelisting is set in {execute}, consumed by the
|
||||
// {onlyGovernance} modifier and eventually reset after {_executeOperations} completes. This ensures that the
|
||||
// execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
|
||||
DoubleEndedQueue.Bytes32Deque private _governanceCall;
|
||||
|
||||
/**
|
||||
* @dev Restricts a function so it can only be executed through governance proposals. For example, governance
|
||||
* parameter setters in {GovernorSettings} are protected using this modifier.
|
||||
*
|
||||
* The governance executing address may be different from the Governor's own address, for example it could be a
|
||||
* timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these
|
||||
* functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,
|
||||
* for example, additional timelock proposers are not able to change governance parameters without going through the
|
||||
* governance protocol (since v4.6).
|
||||
*/
|
||||
modifier onlyGovernance() {
|
||||
_checkGovernance();
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets the value for {name} and {version}
|
||||
*/
|
||||
constructor(string memory name_) EIP712(name_, version()) {
|
||||
_name = name_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
|
||||
*/
|
||||
receive() external payable virtual {
|
||||
if (_executor() != address(this)) {
|
||||
revert GovernorDisabledDeposit();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
|
||||
return
|
||||
interfaceId == type(IGovernor).interfaceId ||
|
||||
interfaceId == type(IERC1155Receiver).interfaceId ||
|
||||
super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-name}.
|
||||
*/
|
||||
function name() public view virtual returns (string memory) {
|
||||
return _name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-version}.
|
||||
*/
|
||||
function version() public view virtual returns (string memory) {
|
||||
return "1";
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-hashProposal}.
|
||||
*
|
||||
* The proposal id is produced by hashing the ABI encoded `targets` array, the `values` array, the `calldatas` array
|
||||
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
|
||||
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
|
||||
* advance, before the proposal is submitted.
|
||||
*
|
||||
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
|
||||
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
|
||||
* across multiple networks. This also means that in order to execute the same operation twice (on the same
|
||||
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
|
||||
*/
|
||||
function hashProposal(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public pure virtual returns (uint256) {
|
||||
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-state}.
|
||||
*/
|
||||
function state(uint256 proposalId) public view virtual returns (ProposalState) {
|
||||
// We read the struct fields into the stack at once so Solidity emits a single SLOAD
|
||||
ProposalCore storage proposal = _proposals[proposalId];
|
||||
bool proposalExecuted = proposal.executed;
|
||||
bool proposalCanceled = proposal.canceled;
|
||||
|
||||
if (proposalExecuted) {
|
||||
return ProposalState.Executed;
|
||||
}
|
||||
|
||||
if (proposalCanceled) {
|
||||
return ProposalState.Canceled;
|
||||
}
|
||||
|
||||
uint256 snapshot = proposalSnapshot(proposalId);
|
||||
|
||||
if (snapshot == 0) {
|
||||
revert GovernorNonexistentProposal(proposalId);
|
||||
}
|
||||
|
||||
uint256 currentTimepoint = clock();
|
||||
|
||||
if (snapshot >= currentTimepoint) {
|
||||
return ProposalState.Pending;
|
||||
}
|
||||
|
||||
uint256 deadline = proposalDeadline(proposalId);
|
||||
|
||||
if (deadline >= currentTimepoint) {
|
||||
return ProposalState.Active;
|
||||
} else if (!_quorumReached(proposalId) || !_voteSucceeded(proposalId)) {
|
||||
return ProposalState.Defeated;
|
||||
} else if (proposalEta(proposalId) == 0) {
|
||||
return ProposalState.Succeeded;
|
||||
} else {
|
||||
return ProposalState.Queued;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalThreshold}.
|
||||
*/
|
||||
function proposalThreshold() public view virtual returns (uint256) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalSnapshot}.
|
||||
*/
|
||||
function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256) {
|
||||
return _proposals[proposalId].voteStart;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalDeadline}.
|
||||
*/
|
||||
function proposalDeadline(uint256 proposalId) public view virtual returns (uint256) {
|
||||
return _proposals[proposalId].voteStart + _proposals[proposalId].voteDuration;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalProposer}.
|
||||
*/
|
||||
function proposalProposer(uint256 proposalId) public view virtual returns (address) {
|
||||
return _proposals[proposalId].proposer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalEta}.
|
||||
*/
|
||||
function proposalEta(uint256 proposalId) public view virtual returns (uint256) {
|
||||
return _proposals[proposalId].etaSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalNeedsQueuing}.
|
||||
*/
|
||||
function proposalNeedsQueuing(uint256) public view virtual returns (bool) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts if the `msg.sender` is not the executor. In case the executor is not this contract
|
||||
* itself, the function reverts if `msg.data` is not whitelisted as a result of an {execute}
|
||||
* operation. See {onlyGovernance}.
|
||||
*/
|
||||
function _checkGovernance() internal virtual {
|
||||
if (_executor() != _msgSender()) {
|
||||
revert GovernorOnlyExecutor(_msgSender());
|
||||
}
|
||||
if (_executor() != address(this)) {
|
||||
bytes32 msgDataHash = keccak256(_msgData());
|
||||
// loop until popping the expected operation - throw if deque is empty (operation not authorized)
|
||||
while (_governanceCall.popFront() != msgDataHash) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Amount of votes already cast passes the threshold limit.
|
||||
*/
|
||||
function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Is the proposal successful or not.
|
||||
*/
|
||||
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Get the voting weight of `account` at a specific `timepoint`, for a vote as described by `params`.
|
||||
*/
|
||||
function _getVotes(address account, uint256 timepoint, bytes memory params) internal view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Register a vote for `proposalId` by `account` with a given `support`, voting `weight` and voting `params`.
|
||||
*
|
||||
* Note: Support is generic and can represent various things depending on the voting system used.
|
||||
*/
|
||||
function _countVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
uint256 weight,
|
||||
bytes memory params
|
||||
) internal virtual;
|
||||
|
||||
/**
|
||||
* @dev Default additional encoded parameters used by castVote methods that don't include them
|
||||
*
|
||||
* Note: Should be overridden by specific implementations to use an appropriate value, the
|
||||
* meaning of the additional params, in the context of that implementation
|
||||
*/
|
||||
function _defaultParams() internal view virtual returns (bytes memory) {
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-propose}. This function has opt-in frontrunning protection, described in {_isValidDescriptionForProposer}.
|
||||
*/
|
||||
function propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
string memory description
|
||||
) public virtual returns (uint256) {
|
||||
address proposer = _msgSender();
|
||||
|
||||
// check description restriction
|
||||
if (!_isValidDescriptionForProposer(proposer, description)) {
|
||||
revert GovernorRestrictedProposer(proposer);
|
||||
}
|
||||
|
||||
// check proposal threshold
|
||||
uint256 votesThreshold = proposalThreshold();
|
||||
if (votesThreshold > 0) {
|
||||
uint256 proposerVotes = getVotes(proposer, clock() - 1);
|
||||
if (proposerVotes < votesThreshold) {
|
||||
revert GovernorInsufficientProposerVotes(proposer, proposerVotes, votesThreshold);
|
||||
}
|
||||
}
|
||||
|
||||
return _propose(targets, values, calldatas, description, proposer);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal propose mechanism. Can be overridden to add more logic on proposal creation.
|
||||
*
|
||||
* Emits a {IGovernor-ProposalCreated} event.
|
||||
*/
|
||||
function _propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
string memory description,
|
||||
address proposer
|
||||
) internal virtual returns (uint256 proposalId) {
|
||||
proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
|
||||
|
||||
if (targets.length != values.length || targets.length != calldatas.length || targets.length == 0) {
|
||||
revert GovernorInvalidProposalLength(targets.length, calldatas.length, values.length);
|
||||
}
|
||||
if (_proposals[proposalId].voteStart != 0) {
|
||||
revert GovernorUnexpectedProposalState(proposalId, state(proposalId), bytes32(0));
|
||||
}
|
||||
|
||||
uint256 snapshot = clock() + votingDelay();
|
||||
uint256 duration = votingPeriod();
|
||||
|
||||
ProposalCore storage proposal = _proposals[proposalId];
|
||||
proposal.proposer = proposer;
|
||||
proposal.voteStart = SafeCast.toUint48(snapshot);
|
||||
proposal.voteDuration = SafeCast.toUint32(duration);
|
||||
|
||||
emit ProposalCreated(
|
||||
proposalId,
|
||||
proposer,
|
||||
targets,
|
||||
values,
|
||||
new string[](targets.length),
|
||||
calldatas,
|
||||
snapshot,
|
||||
snapshot + duration,
|
||||
description
|
||||
);
|
||||
|
||||
// Using a named return variable to avoid stack too deep errors
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-queue}.
|
||||
*/
|
||||
function queue(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public virtual returns (uint256) {
|
||||
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
|
||||
|
||||
_validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Succeeded));
|
||||
|
||||
uint48 etaSeconds = _queueOperations(proposalId, targets, values, calldatas, descriptionHash);
|
||||
|
||||
if (etaSeconds != 0) {
|
||||
_proposals[proposalId].etaSeconds = etaSeconds;
|
||||
emit ProposalQueued(proposalId, etaSeconds);
|
||||
} else {
|
||||
revert GovernorQueueNotImplemented();
|
||||
}
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal queuing mechanism. Can be overridden (without a super call) to modify the way queuing is
|
||||
* performed (for example adding a vault/timelock).
|
||||
*
|
||||
* This is empty by default, and must be overridden to implement queuing.
|
||||
*
|
||||
* This function returns a timestamp that describes the expected ETA for execution. If the returned value is 0
|
||||
* (which is the default value), the core will consider queueing did not succeed, and the public {queue} function
|
||||
* will revert.
|
||||
*
|
||||
* NOTE: Calling this function directly will NOT check the current state of the proposal, or emit the
|
||||
* `ProposalQueued` event. Queuing a proposal should be done using {queue}.
|
||||
*/
|
||||
function _queueOperations(
|
||||
uint256 /*proposalId*/,
|
||||
address[] memory /*targets*/,
|
||||
uint256[] memory /*values*/,
|
||||
bytes[] memory /*calldatas*/,
|
||||
bytes32 /*descriptionHash*/
|
||||
) internal virtual returns (uint48) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-execute}.
|
||||
*/
|
||||
function execute(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public payable virtual returns (uint256) {
|
||||
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
|
||||
|
||||
_validateStateBitmap(
|
||||
proposalId,
|
||||
_encodeStateBitmap(ProposalState.Succeeded) | _encodeStateBitmap(ProposalState.Queued)
|
||||
);
|
||||
|
||||
// mark as executed before calls to avoid reentrancy
|
||||
_proposals[proposalId].executed = true;
|
||||
|
||||
// before execute: register governance call in queue.
|
||||
if (_executor() != address(this)) {
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
if (targets[i] == address(this)) {
|
||||
_governanceCall.pushBack(keccak256(calldatas[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_executeOperations(proposalId, targets, values, calldatas, descriptionHash);
|
||||
|
||||
// after execute: cleanup governance call queue.
|
||||
if (_executor() != address(this) && !_governanceCall.empty()) {
|
||||
_governanceCall.clear();
|
||||
}
|
||||
|
||||
emit ProposalExecuted(proposalId);
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal execution mechanism. Can be overridden (without a super call) to modify the way execution is
|
||||
* performed (for example adding a vault/timelock).
|
||||
*
|
||||
* NOTE: Calling this function directly will NOT check the current state of the proposal, set the executed flag to
|
||||
* true or emit the `ProposalExecuted` event. Executing a proposal should be done using {execute} or {_execute}.
|
||||
*/
|
||||
function _executeOperations(
|
||||
uint256 /* proposalId */,
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 /*descriptionHash*/
|
||||
) internal virtual {
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
|
||||
Address.verifyCallResult(success, returndata);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-cancel}.
|
||||
*/
|
||||
function cancel(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public virtual returns (uint256) {
|
||||
// The proposalId will be recomputed in the `_cancel` call further down. However we need the value before we
|
||||
// do the internal call, because we need to check the proposal state BEFORE the internal `_cancel` call
|
||||
// changes it. The `hashProposal` duplication has a cost that is limited, and that we accept.
|
||||
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
|
||||
|
||||
// public cancel restrictions (on top of existing _cancel restrictions).
|
||||
_validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Pending));
|
||||
if (_msgSender() != proposalProposer(proposalId)) {
|
||||
revert GovernorOnlyProposer(_msgSender());
|
||||
}
|
||||
|
||||
return _cancel(targets, values, calldatas, descriptionHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal cancel mechanism with minimal restrictions. A proposal can be cancelled in any state other than
|
||||
* Canceled, Expired, or Executed. Once cancelled a proposal can't be re-submitted.
|
||||
*
|
||||
* Emits a {IGovernor-ProposalCanceled} event.
|
||||
*/
|
||||
function _cancel(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual returns (uint256) {
|
||||
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
|
||||
|
||||
_validateStateBitmap(
|
||||
proposalId,
|
||||
ALL_PROPOSAL_STATES_BITMAP ^
|
||||
_encodeStateBitmap(ProposalState.Canceled) ^
|
||||
_encodeStateBitmap(ProposalState.Expired) ^
|
||||
_encodeStateBitmap(ProposalState.Executed)
|
||||
);
|
||||
|
||||
_proposals[proposalId].canceled = true;
|
||||
emit ProposalCanceled(proposalId);
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-getVotes}.
|
||||
*/
|
||||
function getVotes(address account, uint256 timepoint) public view virtual returns (uint256) {
|
||||
return _getVotes(account, timepoint, _defaultParams());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-getVotesWithParams}.
|
||||
*/
|
||||
function getVotesWithParams(
|
||||
address account,
|
||||
uint256 timepoint,
|
||||
bytes memory params
|
||||
) public view virtual returns (uint256) {
|
||||
return _getVotes(account, timepoint, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-castVote}.
|
||||
*/
|
||||
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256) {
|
||||
address voter = _msgSender();
|
||||
return _castVote(proposalId, voter, support, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-castVoteWithReason}.
|
||||
*/
|
||||
function castVoteWithReason(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
string calldata reason
|
||||
) public virtual returns (uint256) {
|
||||
address voter = _msgSender();
|
||||
return _castVote(proposalId, voter, support, reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-castVoteWithReasonAndParams}.
|
||||
*/
|
||||
function castVoteWithReasonAndParams(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
string calldata reason,
|
||||
bytes memory params
|
||||
) public virtual returns (uint256) {
|
||||
address voter = _msgSender();
|
||||
return _castVote(proposalId, voter, support, reason, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-castVoteBySig}.
|
||||
*/
|
||||
function castVoteBySig(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
address voter,
|
||||
bytes memory signature
|
||||
) public virtual returns (uint256) {
|
||||
bool valid = SignatureChecker.isValidSignatureNow(
|
||||
voter,
|
||||
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support, voter, _useNonce(voter)))),
|
||||
signature
|
||||
);
|
||||
|
||||
if (!valid) {
|
||||
revert GovernorInvalidSignature(voter);
|
||||
}
|
||||
|
||||
return _castVote(proposalId, voter, support, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
|
||||
*/
|
||||
function castVoteWithReasonAndParamsBySig(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
address voter,
|
||||
string calldata reason,
|
||||
bytes memory params,
|
||||
bytes memory signature
|
||||
) public virtual returns (uint256) {
|
||||
bool valid = SignatureChecker.isValidSignatureNow(
|
||||
voter,
|
||||
_hashTypedDataV4(
|
||||
keccak256(
|
||||
abi.encode(
|
||||
EXTENDED_BALLOT_TYPEHASH,
|
||||
proposalId,
|
||||
support,
|
||||
voter,
|
||||
_useNonce(voter),
|
||||
keccak256(bytes(reason)),
|
||||
keccak256(params)
|
||||
)
|
||||
)
|
||||
),
|
||||
signature
|
||||
);
|
||||
|
||||
if (!valid) {
|
||||
revert GovernorInvalidSignature(voter);
|
||||
}
|
||||
|
||||
return _castVote(proposalId, voter, support, reason, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
|
||||
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams().
|
||||
*
|
||||
* Emits a {IGovernor-VoteCast} event.
|
||||
*/
|
||||
function _castVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
string memory reason
|
||||
) internal virtual returns (uint256) {
|
||||
return _castVote(proposalId, account, support, reason, _defaultParams());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
|
||||
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
|
||||
*
|
||||
* Emits a {IGovernor-VoteCast} event.
|
||||
*/
|
||||
function _castVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
string memory reason,
|
||||
bytes memory params
|
||||
) internal virtual returns (uint256) {
|
||||
_validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Active));
|
||||
|
||||
uint256 weight = _getVotes(account, proposalSnapshot(proposalId), params);
|
||||
_countVote(proposalId, account, support, weight, params);
|
||||
|
||||
if (params.length == 0) {
|
||||
emit VoteCast(account, proposalId, support, weight, reason);
|
||||
} else {
|
||||
emit VoteCastWithParams(account, proposalId, support, weight, reason, params);
|
||||
}
|
||||
|
||||
return weight;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
|
||||
* is some contract other than the governor itself, like when using a timelock, this function can be invoked
|
||||
* in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
|
||||
* Note that if the executor is simply the governor itself, use of `relay` is redundant.
|
||||
*/
|
||||
function relay(address target, uint256 value, bytes calldata data) external payable virtual onlyGovernance {
|
||||
(bool success, bytes memory returndata) = target.call{value: value}(data);
|
||||
Address.verifyCallResult(success, returndata);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
|
||||
* through another contract such as a timelock.
|
||||
*/
|
||||
function _executor() internal view virtual returns (address) {
|
||||
return address(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Receiver-onERC721Received}.
|
||||
* Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
|
||||
*/
|
||||
function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
|
||||
if (_executor() != address(this)) {
|
||||
revert GovernorDisabledDeposit();
|
||||
}
|
||||
return this.onERC721Received.selector;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155Receiver-onERC1155Received}.
|
||||
* Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
|
||||
*/
|
||||
function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual returns (bytes4) {
|
||||
if (_executor() != address(this)) {
|
||||
revert GovernorDisabledDeposit();
|
||||
}
|
||||
return this.onERC1155Received.selector;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155Receiver-onERC1155BatchReceived}.
|
||||
* Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
|
||||
*/
|
||||
function onERC1155BatchReceived(
|
||||
address,
|
||||
address,
|
||||
uint256[] memory,
|
||||
uint256[] memory,
|
||||
bytes memory
|
||||
) public virtual returns (bytes4) {
|
||||
if (_executor() != address(this)) {
|
||||
revert GovernorDisabledDeposit();
|
||||
}
|
||||
return this.onERC1155BatchReceived.selector;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Encodes a `ProposalState` into a `bytes32` representation where each bit enabled corresponds to
|
||||
* the underlying position in the `ProposalState` enum. For example:
|
||||
*
|
||||
* 0x000...10000
|
||||
* ^^^^^^------ ...
|
||||
* ^----- Succeeded
|
||||
* ^---- Defeated
|
||||
* ^--- Canceled
|
||||
* ^-- Active
|
||||
* ^- Pending
|
||||
*/
|
||||
function _encodeStateBitmap(ProposalState proposalState) internal pure returns (bytes32) {
|
||||
return bytes32(1 << uint8(proposalState));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Check that the current state of a proposal matches the requirements described by the `allowedStates` bitmap.
|
||||
* This bitmap should be built using `_encodeStateBitmap`.
|
||||
*
|
||||
* If requirements are not met, reverts with a {GovernorUnexpectedProposalState} error.
|
||||
*/
|
||||
function _validateStateBitmap(uint256 proposalId, bytes32 allowedStates) private view returns (ProposalState) {
|
||||
ProposalState currentState = state(proposalId);
|
||||
if (_encodeStateBitmap(currentState) & allowedStates == bytes32(0)) {
|
||||
revert GovernorUnexpectedProposalState(proposalId, currentState, allowedStates);
|
||||
}
|
||||
return currentState;
|
||||
}
|
||||
|
||||
/*
|
||||
* @dev Check if the proposer is authorized to submit a proposal with the given description.
|
||||
*
|
||||
* If the proposal description ends with `#proposer=0x???`, where `0x???` is an address written as a hex string
|
||||
* (case insensitive), then the submission of this proposal will only be authorized to said address.
|
||||
*
|
||||
* This is used for frontrunning protection. By adding this pattern at the end of their proposal, one can ensure
|
||||
* that no other address can submit the same proposal. An attacker would have to either remove or change that part,
|
||||
* which would result in a different proposal id.
|
||||
*
|
||||
* If the description does not match this pattern, it is unrestricted and anyone can submit it. This includes:
|
||||
* - If the `0x???` part is not a valid hex string.
|
||||
* - If the `0x???` part is a valid hex string, but does not contain exactly 40 hex digits.
|
||||
* - If it ends with the expected suffix followed by newlines or other whitespace.
|
||||
* - If it ends with some other similar suffix, e.g. `#other=abc`.
|
||||
* - If it does not end with any such suffix.
|
||||
*/
|
||||
function _isValidDescriptionForProposer(
|
||||
address proposer,
|
||||
string memory description
|
||||
) internal view virtual returns (bool) {
|
||||
uint256 len = bytes(description).length;
|
||||
|
||||
// Length is too short to contain a valid proposer suffix
|
||||
if (len < 52) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Extract what would be the `#proposer=0x` marker beginning the suffix
|
||||
bytes12 marker;
|
||||
assembly {
|
||||
// - Start of the string contents in memory = description + 32
|
||||
// - First character of the marker = len - 52
|
||||
// - Length of "#proposer=0x0000000000000000000000000000000000000000" = 52
|
||||
// - We read the memory word starting at the first character of the marker:
|
||||
// - (description + 32) + (len - 52) = description + (len - 20)
|
||||
// - Note: Solidity will ignore anything past the first 12 bytes
|
||||
marker := mload(add(description, sub(len, 20)))
|
||||
}
|
||||
|
||||
// If the marker is not found, there is no proposer suffix to check
|
||||
if (marker != bytes12("#proposer=0x")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Parse the 40 characters following the marker as uint160
|
||||
uint160 recovered = 0;
|
||||
for (uint256 i = len - 40; i < len; ++i) {
|
||||
(bool isHex, uint8 value) = _tryHexToUint(bytes(description)[i]);
|
||||
// If any of the characters is not a hex digit, ignore the suffix entirely
|
||||
if (!isHex) {
|
||||
return true;
|
||||
}
|
||||
recovered = (recovered << 4) | value;
|
||||
}
|
||||
|
||||
return recovered == uint160(proposer);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Try to parse a character from a string as a hex value. Returns `(true, value)` if the char is in
|
||||
* `[0-9a-fA-F]` and `(false, 0)` otherwise. Value is guaranteed to be in the range `0 <= value < 16`
|
||||
*/
|
||||
function _tryHexToUint(bytes1 char) private pure returns (bool, uint8) {
|
||||
uint8 c = uint8(char);
|
||||
unchecked {
|
||||
// Case 0-9
|
||||
if (47 < c && c < 58) {
|
||||
return (true, c - 48);
|
||||
}
|
||||
// Case A-F
|
||||
else if (64 < c && c < 71) {
|
||||
return (true, c - 55);
|
||||
}
|
||||
// Case a-f
|
||||
else if (96 < c && c < 103) {
|
||||
return (true, c - 87);
|
||||
}
|
||||
// Else: not a hex char
|
||||
else {
|
||||
return (false, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC6372
|
||||
*/
|
||||
function clock() public view virtual returns (uint48);
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC6372
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function CLOCK_MODE() public view virtual returns (string memory);
|
||||
|
||||
/**
|
||||
* @inheritdoc IGovernor
|
||||
*/
|
||||
function votingDelay() public view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @inheritdoc IGovernor
|
||||
*/
|
||||
function votingPeriod() public view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @inheritdoc IGovernor
|
||||
*/
|
||||
function quorum(uint256 timepoint) public view virtual returns (uint256);
|
||||
}
|
||||
433
lib_openzeppelin_contracts/contracts/governance/IGovernor.sol
Normal file
433
lib_openzeppelin_contracts/contracts/governance/IGovernor.sol
Normal file
@@ -0,0 +1,433 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/IGovernor.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "../interfaces/IERC165.sol";
|
||||
import {IERC6372} from "../interfaces/IERC6372.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface of the {Governor} core.
|
||||
*/
|
||||
interface IGovernor is IERC165, IERC6372 {
|
||||
enum ProposalState {
|
||||
Pending,
|
||||
Active,
|
||||
Canceled,
|
||||
Defeated,
|
||||
Succeeded,
|
||||
Queued,
|
||||
Expired,
|
||||
Executed
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Empty proposal or a mismatch between the parameters length for a proposal call.
|
||||
*/
|
||||
error GovernorInvalidProposalLength(uint256 targets, uint256 calldatas, uint256 values);
|
||||
|
||||
/**
|
||||
* @dev The vote was already cast.
|
||||
*/
|
||||
error GovernorAlreadyCastVote(address voter);
|
||||
|
||||
/**
|
||||
* @dev Token deposits are disabled in this contract.
|
||||
*/
|
||||
error GovernorDisabledDeposit();
|
||||
|
||||
/**
|
||||
* @dev The `account` is not a proposer.
|
||||
*/
|
||||
error GovernorOnlyProposer(address account);
|
||||
|
||||
/**
|
||||
* @dev The `account` is not the governance executor.
|
||||
*/
|
||||
error GovernorOnlyExecutor(address account);
|
||||
|
||||
/**
|
||||
* @dev The `proposalId` doesn't exist.
|
||||
*/
|
||||
error GovernorNonexistentProposal(uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev The current state of a proposal is not the required for performing an operation.
|
||||
* The `expectedStates` is a bitmap with the bits enabled for each ProposalState enum position
|
||||
* counting from right to left.
|
||||
*
|
||||
* NOTE: If `expectedState` is `bytes32(0)`, the proposal is expected to not be in any state (i.e. not exist).
|
||||
* This is the case when a proposal that is expected to be unset is already initiated (the proposal is duplicated).
|
||||
*
|
||||
* See {Governor-_encodeStateBitmap}.
|
||||
*/
|
||||
error GovernorUnexpectedProposalState(uint256 proposalId, ProposalState current, bytes32 expectedStates);
|
||||
|
||||
/**
|
||||
* @dev The voting period set is not a valid period.
|
||||
*/
|
||||
error GovernorInvalidVotingPeriod(uint256 votingPeriod);
|
||||
|
||||
/**
|
||||
* @dev The `proposer` does not have the required votes to create a proposal.
|
||||
*/
|
||||
error GovernorInsufficientProposerVotes(address proposer, uint256 votes, uint256 threshold);
|
||||
|
||||
/**
|
||||
* @dev The `proposer` is not allowed to create a proposal.
|
||||
*/
|
||||
error GovernorRestrictedProposer(address proposer);
|
||||
|
||||
/**
|
||||
* @dev The vote type used is not valid for the corresponding counting module.
|
||||
*/
|
||||
error GovernorInvalidVoteType();
|
||||
|
||||
/**
|
||||
* @dev Queue operation is not implemented for this governor. Execute should be called directly.
|
||||
*/
|
||||
error GovernorQueueNotImplemented();
|
||||
|
||||
/**
|
||||
* @dev The proposal hasn't been queued yet.
|
||||
*/
|
||||
error GovernorNotQueuedProposal(uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev The proposal has already been queued.
|
||||
*/
|
||||
error GovernorAlreadyQueuedProposal(uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev The provided signature is not valid for the expected `voter`.
|
||||
* If the `voter` is a contract, the signature is not valid using {IERC1271-isValidSignature}.
|
||||
*/
|
||||
error GovernorInvalidSignature(address voter);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a proposal is created.
|
||||
*/
|
||||
event ProposalCreated(
|
||||
uint256 proposalId,
|
||||
address proposer,
|
||||
address[] targets,
|
||||
uint256[] values,
|
||||
string[] signatures,
|
||||
bytes[] calldatas,
|
||||
uint256 voteStart,
|
||||
uint256 voteEnd,
|
||||
string description
|
||||
);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a proposal is queued.
|
||||
*/
|
||||
event ProposalQueued(uint256 proposalId, uint256 etaSeconds);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a proposal is executed.
|
||||
*/
|
||||
event ProposalExecuted(uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a proposal is canceled.
|
||||
*/
|
||||
event ProposalCanceled(uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a vote is cast without params.
|
||||
*
|
||||
* Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used.
|
||||
*/
|
||||
event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a vote is cast with params.
|
||||
*
|
||||
* Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used.
|
||||
* `params` are additional encoded parameters. Their interpepretation also depends on the voting module used.
|
||||
*/
|
||||
event VoteCastWithParams(
|
||||
address indexed voter,
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
uint256 weight,
|
||||
string reason,
|
||||
bytes params
|
||||
);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Name of the governor instance (used in building the EIP-712 domain separator).
|
||||
*/
|
||||
function name() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Version of the governor instance (used in building the EIP-712 domain separator). Default: "1"
|
||||
*/
|
||||
function version() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @notice module:voting
|
||||
* @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to
|
||||
* be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of
|
||||
* key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
|
||||
*
|
||||
* There are 2 standard keys: `support` and `quorum`.
|
||||
*
|
||||
* - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`.
|
||||
* - `quorum=bravo` means that only For votes are counted towards quorum.
|
||||
* - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
|
||||
*
|
||||
* If a counting module makes use of encoded `params`, it should include this under a `params` key with a unique
|
||||
* name that describes the behavior. For example:
|
||||
*
|
||||
* - `params=fractional` might refer to a scheme where votes are divided fractionally between for/against/abstain.
|
||||
* - `params=erc721` might refer to a scheme where specific NFTs are delegated to vote.
|
||||
*
|
||||
* NOTE: The string can be decoded by the standard
|
||||
* https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`]
|
||||
* JavaScript class.
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function COUNTING_MODE() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Hashing function used to (re)build the proposal id from the proposal details..
|
||||
*/
|
||||
function hashProposal(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) external pure returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Current state of a proposal, following Compound's convention
|
||||
*/
|
||||
function state(uint256 proposalId) external view returns (ProposalState);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev The number of votes required in order for a voter to become a proposer.
|
||||
*/
|
||||
function proposalThreshold() external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Timepoint used to retrieve user's votes and quorum. If using block number (as per Compound's Comp), the
|
||||
* snapshot is performed at the end of this block. Hence, voting for this proposal starts at the beginning of the
|
||||
* following block.
|
||||
*/
|
||||
function proposalSnapshot(uint256 proposalId) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Timepoint at which votes close. If using block number, votes close at the end of this block, so it is
|
||||
* possible to cast a vote during this block.
|
||||
*/
|
||||
function proposalDeadline(uint256 proposalId) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev The account that created a proposal.
|
||||
*/
|
||||
function proposalProposer(uint256 proposalId) external view returns (address);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev The time when a queued proposal becomes executable ("ETA"). Unlike {proposalSnapshot} and
|
||||
* {proposalDeadline}, this doesn't use the governor clock, and instead relies on the executor's clock which may be
|
||||
* different. In most cases this will be a timestamp.
|
||||
*/
|
||||
function proposalEta(uint256 proposalId) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Whether a proposal needs to be queued before execution.
|
||||
*/
|
||||
function proposalNeedsQueuing(uint256 proposalId) external view returns (bool);
|
||||
|
||||
/**
|
||||
* @notice module:user-config
|
||||
* @dev Delay, between the proposal is created and the vote starts. The unit this duration is expressed in depends
|
||||
* on the clock (see ERC-6372) this contract uses.
|
||||
*
|
||||
* This can be increased to leave time for users to buy voting power, or delegate it, before the voting of a
|
||||
* proposal starts.
|
||||
*
|
||||
* NOTE: While this interface returns a uint256, timepoints are stored as uint48 following the ERC-6372 clock type.
|
||||
* Consequently this value must fit in a uint48 (when added to the current clock). See {IERC6372-clock}.
|
||||
*/
|
||||
function votingDelay() external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:user-config
|
||||
* @dev Delay between the vote start and vote end. The unit this duration is expressed in depends on the clock
|
||||
* (see ERC-6372) this contract uses.
|
||||
*
|
||||
* NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting
|
||||
* duration compared to the voting delay.
|
||||
*
|
||||
* NOTE: This value is stored when the proposal is submitted so that possible changes to the value do not affect
|
||||
* proposals that have already been submitted. The type used to save it is a uint32. Consequently, while this
|
||||
* interface returns a uint256, the value it returns should fit in a uint32.
|
||||
*/
|
||||
function votingPeriod() external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:user-config
|
||||
* @dev Minimum number of cast voted required for a proposal to be successful.
|
||||
*
|
||||
* NOTE: The `timepoint` parameter corresponds to the snapshot used for counting vote. This allows to scale the
|
||||
* quorum depending on values such as the totalSupply of a token at this timepoint (see {ERC20Votes}).
|
||||
*/
|
||||
function quorum(uint256 timepoint) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:reputation
|
||||
* @dev Voting power of an `account` at a specific `timepoint`.
|
||||
*
|
||||
* Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or
|
||||
* multiple), {ERC20Votes} tokens.
|
||||
*/
|
||||
function getVotes(address account, uint256 timepoint) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:reputation
|
||||
* @dev Voting power of an `account` at a specific `timepoint` given additional encoded parameters.
|
||||
*/
|
||||
function getVotesWithParams(
|
||||
address account,
|
||||
uint256 timepoint,
|
||||
bytes memory params
|
||||
) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:voting
|
||||
* @dev Returns whether `account` has cast a vote on `proposalId`.
|
||||
*/
|
||||
function hasVoted(uint256 proposalId, address account) external view returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Create a new proposal. Vote start after a delay specified by {IGovernor-votingDelay} and lasts for a
|
||||
* duration specified by {IGovernor-votingPeriod}.
|
||||
*
|
||||
* Emits a {ProposalCreated} event.
|
||||
*
|
||||
* NOTE: The state of the Governor and `targets` may change between the proposal creation and its execution.
|
||||
* This may be the result of third party actions on the targeted contracts, or other governor proposals.
|
||||
* For example, the balance of this contract could be updated or its access control permissions may be modified,
|
||||
* possibly compromising the proposal's ability to execute successfully (e.g. the governor doesn't have enough
|
||||
* value to cover a proposal with multiple transfers).
|
||||
*/
|
||||
function propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
string memory description
|
||||
) external returns (uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev Queue a proposal. Some governors require this step to be performed before execution can happen. If queuing
|
||||
* is not necessary, this function may revert.
|
||||
* Queuing a proposal requires the quorum to be reached, the vote to be successful, and the deadline to be reached.
|
||||
*
|
||||
* Emits a {ProposalQueued} event.
|
||||
*/
|
||||
function queue(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) external returns (uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the
|
||||
* deadline to be reached. Depending on the governor it might also be required that the proposal was queued and
|
||||
* that some delay passed.
|
||||
*
|
||||
* Emits a {ProposalExecuted} event.
|
||||
*
|
||||
* NOTE: Some modules can modify the requirements for execution, for example by adding an additional timelock.
|
||||
*/
|
||||
function execute(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) external payable returns (uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev Cancel a proposal. A proposal is cancellable by the proposer, but only while it is Pending state, i.e.
|
||||
* before the vote starts.
|
||||
*
|
||||
* Emits a {ProposalCanceled} event.
|
||||
*/
|
||||
function cancel(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) external returns (uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev Cast a vote
|
||||
*
|
||||
* Emits a {VoteCast} event.
|
||||
*/
|
||||
function castVote(uint256 proposalId, uint8 support) external returns (uint256 balance);
|
||||
|
||||
/**
|
||||
* @dev Cast a vote with a reason
|
||||
*
|
||||
* Emits a {VoteCast} event.
|
||||
*/
|
||||
function castVoteWithReason(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
string calldata reason
|
||||
) external returns (uint256 balance);
|
||||
|
||||
/**
|
||||
* @dev Cast a vote with a reason and additional encoded parameters
|
||||
*
|
||||
* Emits a {VoteCast} or {VoteCastWithParams} event depending on the length of params.
|
||||
*/
|
||||
function castVoteWithReasonAndParams(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
string calldata reason,
|
||||
bytes memory params
|
||||
) external returns (uint256 balance);
|
||||
|
||||
/**
|
||||
* @dev Cast a vote using the voter's signature, including ERC-1271 signature support.
|
||||
*
|
||||
* Emits a {VoteCast} event.
|
||||
*/
|
||||
function castVoteBySig(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
address voter,
|
||||
bytes memory signature
|
||||
) external returns (uint256 balance);
|
||||
|
||||
/**
|
||||
* @dev Cast a vote with a reason and additional encoded parameters using the voter's signature,
|
||||
* including ERC-1271 signature support.
|
||||
*
|
||||
* Emits a {VoteCast} or {VoteCastWithParams} event depending on the length of params.
|
||||
*/
|
||||
function castVoteWithReasonAndParamsBySig(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
address voter,
|
||||
string calldata reason,
|
||||
bytes memory params,
|
||||
bytes memory signature
|
||||
) external returns (uint256 balance);
|
||||
}
|
||||
171
lib_openzeppelin_contracts/contracts/governance/README.adoc
Normal file
171
lib_openzeppelin_contracts/contracts/governance/README.adoc
Normal file
@@ -0,0 +1,171 @@
|
||||
= Governance
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/governance
|
||||
|
||||
This directory includes primitives for on-chain governance.
|
||||
|
||||
== Governor
|
||||
|
||||
This modular system of Governor contracts allows the deployment on-chain voting protocols similar to https://compound.finance/docs/governance[Compound's Governor Alpha & Bravo] and beyond, through the ability to easily customize multiple aspects of the protocol.
|
||||
|
||||
[TIP]
|
||||
====
|
||||
For a guided experience, set up your Governor contract using https://wizard.openzeppelin.com/#governor[Contracts Wizard].
|
||||
|
||||
For a written walkthrough, check out our guide on xref:ROOT:governance.adoc[How to set up on-chain governance].
|
||||
====
|
||||
|
||||
* {Governor}: The core contract that contains all the logic and primitives. It is abstract and requires choosing one of each of the modules below, or custom ones.
|
||||
|
||||
Votes modules determine the source of voting power, and sometimes quorum number.
|
||||
|
||||
* {GovernorVotes}: Extracts voting weight from an {ERC20Votes}, or since v4.5 an {ERC721Votes} token.
|
||||
|
||||
* {GovernorVotesQuorumFraction}: Combines with `GovernorVotes` to set the quorum as a fraction of the total token supply.
|
||||
|
||||
Counting modules determine valid voting options.
|
||||
|
||||
* {GovernorCountingSimple}: Simple voting mechanism with 3 voting options: Against, For and Abstain.
|
||||
|
||||
Timelock extensions add a delay for governance decisions to be executed. The workflow is extended to require a `queue` step before execution. With these modules, proposals are executed by the external timelock contract, thus it is the timelock that has to hold the assets that are being governed.
|
||||
|
||||
* {GovernorTimelockAccess}: Connects with an instance of an {AccessManager}. This allows restrictions (and delays) enforced by the manager to be considered by the Governor and integrated into the AccessManager's "schedule + execute" workflow.
|
||||
|
||||
* {GovernorTimelockControl}: Connects with an instance of {TimelockController}. Allows multiple proposers and executors, in addition to the Governor itself.
|
||||
|
||||
* {GovernorTimelockCompound}: Connects with an instance of Compound's https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol[`Timelock`] contract.
|
||||
|
||||
Other extensions can customize the behavior or interface in multiple ways.
|
||||
|
||||
* {GovernorStorage}: Stores the proposal details onchain and provides enumerability of the proposals. This can be useful for some L2 chains where storage is cheap compared to calldata.
|
||||
|
||||
* {GovernorSettings}: Manages some of the settings (voting delay, voting period duration, and proposal threshold) in a way that can be updated through a governance proposal, without requiring an upgrade.
|
||||
|
||||
* {GovernorPreventLateQuorum}: Ensures there is a minimum voting period after quorum is reached as a security protection against large voters.
|
||||
|
||||
In addition to modules and extensions, the core contract requires a few virtual functions to be implemented to your particular specifications:
|
||||
|
||||
* <<Governor-votingDelay-,`votingDelay()`>>: Delay (in ERC-6372 clock) since the proposal is submitted until voting power is fixed and voting starts. This can be used to enforce a delay after a proposal is published for users to buy tokens, or delegate their votes.
|
||||
* <<Governor-votingPeriod-,`votingPeriod()`>>: Delay (in ERC-6372 clock) since the proposal starts until voting ends.
|
||||
* <<Governor-quorum-uint256-,`quorum(uint256 timepoint)`>>: Quorum required for a proposal to be successful. This function includes a `timepoint` argument (see ERC-6372) so the quorum can adapt through time, for example, to follow a token's `totalSupply`.
|
||||
|
||||
NOTE: Functions of the `Governor` contract do not include access control. If you want to restrict access, you should add these checks by overloading the particular functions. Among these, {Governor-_cancel} is internal by default, and you will have to expose it (with the right access control mechanism) yourself if this function is needed.
|
||||
|
||||
=== Core
|
||||
|
||||
{{IGovernor}}
|
||||
|
||||
{{Governor}}
|
||||
|
||||
=== Modules
|
||||
|
||||
{{GovernorCountingSimple}}
|
||||
|
||||
{{GovernorVotes}}
|
||||
|
||||
{{GovernorVotesQuorumFraction}}
|
||||
|
||||
=== Extensions
|
||||
|
||||
{{GovernorTimelockAccess}}
|
||||
|
||||
{{GovernorTimelockControl}}
|
||||
|
||||
{{GovernorTimelockCompound}}
|
||||
|
||||
{{GovernorSettings}}
|
||||
|
||||
{{GovernorPreventLateQuorum}}
|
||||
|
||||
{{GovernorStorage}}
|
||||
|
||||
== Utils
|
||||
|
||||
{{Votes}}
|
||||
|
||||
== Timelock
|
||||
|
||||
In a governance system, the {TimelockController} contract is in charge of introducing a delay between a proposal and its execution. It can be used with or without a {Governor}.
|
||||
|
||||
{{TimelockController}}
|
||||
|
||||
[[timelock-terminology]]
|
||||
==== Terminology
|
||||
|
||||
* *Operation:* A transaction (or a set of transactions) that is the subject of the timelock. It has to be scheduled by a proposer and executed by an executor. The timelock enforces a minimum delay between the proposition and the execution (see xref:access-control.adoc#operation_lifecycle[operation lifecycle]). If the operation contains multiple transactions (batch mode), they are executed atomically. Operations are identified by the hash of their content.
|
||||
* *Operation status:*
|
||||
** *Unset:* An operation that is not part of the timelock mechanism.
|
||||
** *Waiting:* An operation that has been scheduled, before the timer expires.
|
||||
** *Ready:* An operation that has been scheduled, after the timer expires.
|
||||
** *Pending:* An operation that is either waiting or ready.
|
||||
** *Done:* An operation that has been executed.
|
||||
* *Predecessor*: An (optional) dependency between operations. An operation can depend on another operation (its predecessor), forcing the execution order of these two operations.
|
||||
* *Role*:
|
||||
** *Admin:* An address (smart contract or EOA) that is in charge of granting the roles of Proposer and Executor.
|
||||
** *Proposer:* An address (smart contract or EOA) that is in charge of scheduling (and cancelling) operations.
|
||||
** *Executor:* An address (smart contract or EOA) that is in charge of executing operations once the timelock has expired. This role can be given to the zero address to allow anyone to execute operations.
|
||||
|
||||
[[timelock-operation]]
|
||||
==== Operation structure
|
||||
|
||||
Operation executed by the xref:api:governance.adoc#TimelockController[`TimelockController`] can contain one or multiple subsequent calls. Depending on whether you need to multiple calls to be executed atomically, you can either use simple or batched operations.
|
||||
|
||||
Both operations contain:
|
||||
|
||||
* *Target*, the address of the smart contract that the timelock should operate on.
|
||||
* *Value*, in wei, that should be sent with the transaction. Most of the time this will be 0. Ether can be deposited before-end or passed along when executing the transaction.
|
||||
* *Data*, containing the encoded function selector and parameters of the call. This can be produced using a number of tools. For example, a maintenance operation granting role `ROLE` to `ACCOUNT` can be encoded using web3js as follows:
|
||||
|
||||
```javascript
|
||||
const data = timelock.contract.methods.grantRole(ROLE, ACCOUNT).encodeABI()
|
||||
```
|
||||
|
||||
* *Predecessor*, that specifies a dependency between operations. This dependency is optional. Use `bytes32(0)` if the operation does not have any dependency.
|
||||
* *Salt*, used to disambiguate two otherwise identical operations. This can be any random value.
|
||||
|
||||
In the case of batched operations, `target`, `value` and `data` are specified as arrays, which must be of the same length.
|
||||
|
||||
[[timelock-operation-lifecycle]]
|
||||
==== Operation lifecycle
|
||||
|
||||
Timelocked operations are identified by a unique id (their hash) and follow a specific lifecycle:
|
||||
|
||||
`Unset` -> `Pending` -> `Pending` + `Ready` -> `Done`
|
||||
|
||||
* By calling xref:api:governance.adoc#TimelockController-schedule-address-uint256-bytes-bytes32-bytes32-uint256-[`schedule`] (or xref:api:governance.adoc#TimelockController-scheduleBatch-address---uint256---bytes---bytes32-bytes32-uint256-[`scheduleBatch`]), a proposer moves the operation from the `Unset` to the `Pending` state. This starts a timer that must be longer than the minimum delay. The timer expires at a timestamp accessible through the xref:api:governance.adoc#TimelockController-getTimestamp-bytes32-[`getTimestamp`] method.
|
||||
* Once the timer expires, the operation automatically gets the `Ready` state. At this point, it can be executed.
|
||||
* By calling xref:api:governance.adoc#TimelockController-TimelockController-execute-address-uint256-bytes-bytes32-bytes32-[`execute`] (or xref:api:governance.adoc#TimelockController-executeBatch-address---uint256---bytes---bytes32-bytes32-[`executeBatch`]), an executor triggers the operation's underlying transactions and moves it to the `Done` state. If the operation has a predecessor, it has to be in the `Done` state for this transition to succeed.
|
||||
* xref:api:governance.adoc#TimelockController-TimelockController-cancel-bytes32-[`cancel`] allows proposers to cancel any `Pending` operation. This resets the operation to the `Unset` state. It is thus possible for a proposer to re-schedule an operation that has been cancelled. In this case, the timer restarts when the operation is re-scheduled.
|
||||
|
||||
Operations status can be queried using the functions:
|
||||
|
||||
* xref:api:governance.adoc#TimelockController-isOperationPending-bytes32-[`isOperationPending(bytes32)`]
|
||||
* xref:api:governance.adoc#TimelockController-isOperationReady-bytes32-[`isOperationReady(bytes32)`]
|
||||
* xref:api:governance.adoc#TimelockController-isOperationDone-bytes32-[`isOperationDone(bytes32)`]
|
||||
|
||||
[[timelock-roles]]
|
||||
==== Roles
|
||||
|
||||
[[timelock-admin]]
|
||||
===== Admin
|
||||
|
||||
The admins are in charge of managing proposers and executors. For the timelock to be self-governed, this role should only be given to the timelock itself. Upon deployment, the admin role can be granted to any address (in addition to the timelock itself). After further configuration and testing, this optional admin should renounce its role such that all further maintenance operations have to go through the timelock process.
|
||||
|
||||
[[timelock-proposer]]
|
||||
===== Proposer
|
||||
|
||||
The proposers are in charge of scheduling (and cancelling) operations. This is a critical role, that should be given to governing entities. This could be an EOA, a multisig, or a DAO.
|
||||
|
||||
WARNING: *Proposer fight:* Having multiple proposers, while providing redundancy in case one becomes unavailable, can be dangerous. As proposer have their say on all operations, they could cancel operations they disagree with, including operations to remove them for the proposers.
|
||||
|
||||
This role is identified by the *PROPOSER_ROLE* value: `0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1`
|
||||
|
||||
[[timelock-executor]]
|
||||
===== Executor
|
||||
|
||||
The executors are in charge of executing the operations scheduled by the proposers once the timelock expires. Logic dictates that multisig or DAO that are proposers should also be executors in order to guarantee operations that have been scheduled will eventually be executed. However, having additional executors can reduce the cost (the executing transaction does not require validation by the multisig or DAO that proposed it), while ensuring whoever is in charge of execution cannot trigger actions that have not been scheduled by the proposers. Alternatively, it is possible to allow _any_ address to execute a proposal once the timelock has expired by granting the executor role to the zero address.
|
||||
|
||||
This role is identified by the *EXECUTOR_ROLE* value: `0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63`
|
||||
|
||||
WARNING: A live contract without at least one proposer and one executor is locked. Make sure these roles are filled by reliable entities before the deployer renounces its administrative rights in favour of the timelock contract itself. See the {AccessControl} documentation to learn more about role management.
|
||||
@@ -0,0 +1,472 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/TimelockController.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {AccessControl} from "../access/AccessControl.sol";
|
||||
import {ERC721Holder} from "../token/ERC721/utils/ERC721Holder.sol";
|
||||
import {ERC1155Holder} from "../token/ERC1155/utils/ERC1155Holder.sol";
|
||||
import {Address} from "../utils/Address.sol";
|
||||
|
||||
/**
|
||||
* @dev Contract module which acts as a timelocked controller. When set as the
|
||||
* owner of an `Ownable` smart contract, it enforces a timelock on all
|
||||
* `onlyOwner` maintenance operations. This gives time for users of the
|
||||
* controlled contract to exit before a potentially dangerous maintenance
|
||||
* operation is applied.
|
||||
*
|
||||
* By default, this contract is self administered, meaning administration tasks
|
||||
* have to go through the timelock process. The proposer (resp executor) role
|
||||
* is in charge of proposing (resp executing) operations. A common use case is
|
||||
* to position this {TimelockController} as the owner of a smart contract, with
|
||||
* a multisig or a DAO as the sole proposer.
|
||||
*/
|
||||
contract TimelockController is AccessControl, ERC721Holder, ERC1155Holder {
|
||||
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
|
||||
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
|
||||
bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE");
|
||||
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
|
||||
|
||||
mapping(bytes32 id => uint256) private _timestamps;
|
||||
uint256 private _minDelay;
|
||||
|
||||
enum OperationState {
|
||||
Unset,
|
||||
Waiting,
|
||||
Ready,
|
||||
Done
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Mismatch between the parameters length for an operation call.
|
||||
*/
|
||||
error TimelockInvalidOperationLength(uint256 targets, uint256 payloads, uint256 values);
|
||||
|
||||
/**
|
||||
* @dev The schedule operation doesn't meet the minimum delay.
|
||||
*/
|
||||
error TimelockInsufficientDelay(uint256 delay, uint256 minDelay);
|
||||
|
||||
/**
|
||||
* @dev The current state of an operation is not as required.
|
||||
* The `expectedStates` is a bitmap with the bits enabled for each OperationState enum position
|
||||
* counting from right to left.
|
||||
*
|
||||
* See {_encodeStateBitmap}.
|
||||
*/
|
||||
error TimelockUnexpectedOperationState(bytes32 operationId, bytes32 expectedStates);
|
||||
|
||||
/**
|
||||
* @dev The predecessor to an operation not yet done.
|
||||
*/
|
||||
error TimelockUnexecutedPredecessor(bytes32 predecessorId);
|
||||
|
||||
/**
|
||||
* @dev The caller account is not authorized.
|
||||
*/
|
||||
error TimelockUnauthorizedCaller(address caller);
|
||||
|
||||
/**
|
||||
* @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
|
||||
);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a call is performed as part of operation `id`.
|
||||
*/
|
||||
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
|
||||
|
||||
/**
|
||||
* @dev Emitted when new proposal is scheduled with non-zero salt.
|
||||
*/
|
||||
event CallSalt(bytes32 indexed id, bytes32 salt);
|
||||
|
||||
/**
|
||||
* @dev Emitted when operation `id` is cancelled.
|
||||
*/
|
||||
event Cancelled(bytes32 indexed id);
|
||||
|
||||
/**
|
||||
* @dev Emitted when the minimum delay for future operations is modified.
|
||||
*/
|
||||
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
|
||||
|
||||
/**
|
||||
* @dev Initializes the contract with the following parameters:
|
||||
*
|
||||
* - `minDelay`: initial minimum delay in seconds for operations
|
||||
* - `proposers`: accounts to be granted proposer and canceller roles
|
||||
* - `executors`: accounts to be granted executor role
|
||||
* - `admin`: optional account to be granted admin role; disable with zero address
|
||||
*
|
||||
* IMPORTANT: The optional admin can aid with initial configuration of roles after deployment
|
||||
* without being subject to delay, but this role should be subsequently renounced in favor of
|
||||
* administration through timelocked proposals. Previous versions of this contract would assign
|
||||
* this admin to the deployer automatically and should be renounced as well.
|
||||
*/
|
||||
constructor(uint256 minDelay, address[] memory proposers, address[] memory executors, address admin) {
|
||||
// self administration
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, address(this));
|
||||
|
||||
// optional admin
|
||||
if (admin != address(0)) {
|
||||
_grantRole(DEFAULT_ADMIN_ROLE, admin);
|
||||
}
|
||||
|
||||
// register proposers and cancellers
|
||||
for (uint256 i = 0; i < proposers.length; ++i) {
|
||||
_grantRole(PROPOSER_ROLE, proposers[i]);
|
||||
_grantRole(CANCELLER_ROLE, proposers[i]);
|
||||
}
|
||||
|
||||
// register executors
|
||||
for (uint256 i = 0; i < executors.length; ++i) {
|
||||
_grantRole(EXECUTOR_ROLE, executors[i]);
|
||||
}
|
||||
|
||||
_minDelay = minDelay;
|
||||
emit MinDelayChange(0, minDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Modifier to make a function callable only by a certain role. In
|
||||
* addition to checking the sender's role, `address(0)` 's role is also
|
||||
* considered. Granting a role to `address(0)` is equivalent to enabling
|
||||
* this role for everyone.
|
||||
*/
|
||||
modifier onlyRoleOrOpenRole(bytes32 role) {
|
||||
if (!hasRole(role, address(0))) {
|
||||
_checkRole(role, _msgSender());
|
||||
}
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Contract might receive/hold ETH as part of the maintenance process.
|
||||
*/
|
||||
receive() external payable {}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(
|
||||
bytes4 interfaceId
|
||||
) public view virtual override(AccessControl, ERC1155Holder) returns (bool) {
|
||||
return super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns whether an id corresponds to a registered operation. This
|
||||
* includes both Waiting, Ready, and Done operations.
|
||||
*/
|
||||
function isOperation(bytes32 id) public view returns (bool) {
|
||||
return getOperationState(id) != OperationState.Unset;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready".
|
||||
*/
|
||||
function isOperationPending(bytes32 id) public view returns (bool) {
|
||||
OperationState state = getOperationState(id);
|
||||
return state == OperationState.Waiting || state == OperationState.Ready;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending".
|
||||
*/
|
||||
function isOperationReady(bytes32 id) public view returns (bool) {
|
||||
return getOperationState(id) == OperationState.Ready;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns whether an operation is done or not.
|
||||
*/
|
||||
function isOperationDone(bytes32 id) public view returns (bool) {
|
||||
return getOperationState(id) == OperationState.Done;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the timestamp at which an operation becomes ready (0 for
|
||||
* unset operations, 1 for done operations).
|
||||
*/
|
||||
function getTimestamp(bytes32 id) public view virtual returns (uint256) {
|
||||
return _timestamps[id];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns operation state.
|
||||
*/
|
||||
function getOperationState(bytes32 id) public view virtual returns (OperationState) {
|
||||
uint256 timestamp = getTimestamp(id);
|
||||
if (timestamp == 0) {
|
||||
return OperationState.Unset;
|
||||
} else if (timestamp == _DONE_TIMESTAMP) {
|
||||
return OperationState.Done;
|
||||
} else if (timestamp > block.timestamp) {
|
||||
return OperationState.Waiting;
|
||||
} else {
|
||||
return OperationState.Ready;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the minimum delay in seconds for an operation to become valid.
|
||||
*
|
||||
* This value can be changed by executing an operation that calls `updateDelay`.
|
||||
*/
|
||||
function getMinDelay() public view virtual returns (uint256) {
|
||||
return _minDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the identifier of an operation containing a single
|
||||
* transaction.
|
||||
*/
|
||||
function hashOperation(
|
||||
address target,
|
||||
uint256 value,
|
||||
bytes calldata data,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt
|
||||
) public pure virtual returns (bytes32) {
|
||||
return keccak256(abi.encode(target, value, data, predecessor, salt));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the identifier of an operation containing a batch of
|
||||
* transactions.
|
||||
*/
|
||||
function hashOperationBatch(
|
||||
address[] calldata targets,
|
||||
uint256[] calldata values,
|
||||
bytes[] calldata payloads,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt
|
||||
) public pure virtual returns (bytes32) {
|
||||
return keccak256(abi.encode(targets, values, payloads, predecessor, salt));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Schedule an operation containing a single transaction.
|
||||
*
|
||||
* Emits {CallSalt} if salt is nonzero, and {CallScheduled}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - 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) {
|
||||
bytes32 id = hashOperation(target, value, data, predecessor, salt);
|
||||
_schedule(id, delay);
|
||||
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
|
||||
if (salt != bytes32(0)) {
|
||||
emit CallSalt(id, salt);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Schedule an operation containing a batch of transactions.
|
||||
*
|
||||
* Emits {CallSalt} if salt is nonzero, and one {CallScheduled} event per transaction in the batch.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have the 'proposer' role.
|
||||
*/
|
||||
function scheduleBatch(
|
||||
address[] calldata targets,
|
||||
uint256[] calldata values,
|
||||
bytes[] calldata payloads,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt,
|
||||
uint256 delay
|
||||
) public virtual onlyRole(PROPOSER_ROLE) {
|
||||
if (targets.length != values.length || targets.length != payloads.length) {
|
||||
revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length);
|
||||
}
|
||||
|
||||
bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
|
||||
_schedule(id, delay);
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay);
|
||||
}
|
||||
if (salt != bytes32(0)) {
|
||||
emit CallSalt(id, salt);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Schedule an operation that is to become valid after a given delay.
|
||||
*/
|
||||
function _schedule(bytes32 id, uint256 delay) private {
|
||||
if (isOperation(id)) {
|
||||
revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Unset));
|
||||
}
|
||||
uint256 minDelay = getMinDelay();
|
||||
if (delay < minDelay) {
|
||||
revert TimelockInsufficientDelay(delay, minDelay);
|
||||
}
|
||||
_timestamps[id] = block.timestamp + delay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Cancel an operation.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have the 'canceller' role.
|
||||
*/
|
||||
function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
|
||||
if (!isOperationPending(id)) {
|
||||
revert TimelockUnexpectedOperationState(
|
||||
id,
|
||||
_encodeStateBitmap(OperationState.Waiting) | _encodeStateBitmap(OperationState.Ready)
|
||||
);
|
||||
}
|
||||
delete _timestamps[id];
|
||||
|
||||
emit Cancelled(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Execute an (ready) operation containing a single transaction.
|
||||
*
|
||||
* Emits a {CallExecuted} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have the 'executor' role.
|
||||
*/
|
||||
// This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
|
||||
// thus any modifications to the operation during reentrancy should be caught.
|
||||
// slither-disable-next-line reentrancy-eth
|
||||
function execute(
|
||||
address target,
|
||||
uint256 value,
|
||||
bytes calldata payload,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt
|
||||
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
|
||||
bytes32 id = hashOperation(target, value, payload, predecessor, salt);
|
||||
|
||||
_beforeCall(id, predecessor);
|
||||
_execute(target, value, payload);
|
||||
emit CallExecuted(id, 0, target, value, payload);
|
||||
_afterCall(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Execute an (ready) operation containing a batch of transactions.
|
||||
*
|
||||
* Emits one {CallExecuted} event per transaction in the batch.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have the 'executor' role.
|
||||
*/
|
||||
// This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
|
||||
// thus any modifications to the operation during reentrancy should be caught.
|
||||
// slither-disable-next-line reentrancy-eth
|
||||
function executeBatch(
|
||||
address[] calldata targets,
|
||||
uint256[] calldata values,
|
||||
bytes[] calldata payloads,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt
|
||||
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
|
||||
if (targets.length != values.length || targets.length != payloads.length) {
|
||||
revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length);
|
||||
}
|
||||
|
||||
bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
|
||||
|
||||
_beforeCall(id, predecessor);
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
address target = targets[i];
|
||||
uint256 value = values[i];
|
||||
bytes calldata payload = payloads[i];
|
||||
_execute(target, value, payload);
|
||||
emit CallExecuted(id, i, target, value, payload);
|
||||
}
|
||||
_afterCall(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Execute an operation's call.
|
||||
*/
|
||||
function _execute(address target, uint256 value, bytes calldata data) internal virtual {
|
||||
(bool success, bytes memory returndata) = target.call{value: value}(data);
|
||||
Address.verifyCallResult(success, returndata);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Checks before execution of an operation's calls.
|
||||
*/
|
||||
function _beforeCall(bytes32 id, bytes32 predecessor) private view {
|
||||
if (!isOperationReady(id)) {
|
||||
revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready));
|
||||
}
|
||||
if (predecessor != bytes32(0) && !isOperationDone(predecessor)) {
|
||||
revert TimelockUnexecutedPredecessor(predecessor);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Checks after execution of an operation's calls.
|
||||
*/
|
||||
function _afterCall(bytes32 id) private {
|
||||
if (!isOperationReady(id)) {
|
||||
revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready));
|
||||
}
|
||||
_timestamps[id] = _DONE_TIMESTAMP;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the minimum timelock duration for future operations.
|
||||
*
|
||||
* Emits a {MinDelayChange} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
|
||||
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
|
||||
*/
|
||||
function updateDelay(uint256 newDelay) external virtual {
|
||||
address sender = _msgSender();
|
||||
if (sender != address(this)) {
|
||||
revert TimelockUnauthorizedCaller(sender);
|
||||
}
|
||||
emit MinDelayChange(_minDelay, newDelay);
|
||||
_minDelay = newDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Encodes a `OperationState` into a `bytes32` representation where each bit enabled corresponds to
|
||||
* the underlying position in the `OperationState` enum. For example:
|
||||
*
|
||||
* 0x000...1000
|
||||
* ^^^^^^----- ...
|
||||
* ^---- Done
|
||||
* ^--- Ready
|
||||
* ^-- Waiting
|
||||
* ^- Unset
|
||||
*/
|
||||
function _encodeStateBitmap(OperationState operationState) internal pure returns (bytes32) {
|
||||
return bytes32(1 << uint8(operationState));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/extensions/GovernorCountingSimple.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Governor} from "../Governor.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} for simple, 3 options, vote counting.
|
||||
*/
|
||||
abstract contract GovernorCountingSimple is Governor {
|
||||
/**
|
||||
* @dev Supported vote types. Matches Governor Bravo ordering.
|
||||
*/
|
||||
enum VoteType {
|
||||
Against,
|
||||
For,
|
||||
Abstain
|
||||
}
|
||||
|
||||
struct ProposalVote {
|
||||
uint256 againstVotes;
|
||||
uint256 forVotes;
|
||||
uint256 abstainVotes;
|
||||
mapping(address voter => bool) hasVoted;
|
||||
}
|
||||
|
||||
mapping(uint256 proposalId => ProposalVote) private _proposalVotes;
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-COUNTING_MODE}.
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function COUNTING_MODE() public pure virtual override returns (string memory) {
|
||||
return "support=bravo&quorum=for,abstain";
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-hasVoted}.
|
||||
*/
|
||||
function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) {
|
||||
return _proposalVotes[proposalId].hasVoted[account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Accessor to the internal vote counts.
|
||||
*/
|
||||
function proposalVotes(
|
||||
uint256 proposalId
|
||||
) public view virtual returns (uint256 againstVotes, uint256 forVotes, uint256 abstainVotes) {
|
||||
ProposalVote storage proposalVote = _proposalVotes[proposalId];
|
||||
return (proposalVote.againstVotes, proposalVote.forVotes, proposalVote.abstainVotes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-_quorumReached}.
|
||||
*/
|
||||
function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
|
||||
ProposalVote storage proposalVote = _proposalVotes[proposalId];
|
||||
|
||||
return quorum(proposalSnapshot(proposalId)) <= proposalVote.forVotes + proposalVote.abstainVotes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be strictly over the againstVotes.
|
||||
*/
|
||||
function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
|
||||
ProposalVote storage proposalVote = _proposalVotes[proposalId];
|
||||
|
||||
return proposalVote.forVotes > proposalVote.againstVotes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-_countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo).
|
||||
*/
|
||||
function _countVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
uint256 weight,
|
||||
bytes memory // params
|
||||
) internal virtual override {
|
||||
ProposalVote storage proposalVote = _proposalVotes[proposalId];
|
||||
|
||||
if (proposalVote.hasVoted[account]) {
|
||||
revert GovernorAlreadyCastVote(account);
|
||||
}
|
||||
proposalVote.hasVoted[account] = true;
|
||||
|
||||
if (support == uint8(VoteType.Against)) {
|
||||
proposalVote.againstVotes += weight;
|
||||
} else if (support == uint8(VoteType.For)) {
|
||||
proposalVote.forVotes += weight;
|
||||
} else if (support == uint8(VoteType.Abstain)) {
|
||||
proposalVote.abstainVotes += weight;
|
||||
} else {
|
||||
revert GovernorInvalidVoteType();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/extensions/GovernorPreventLateQuorum.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Governor} from "../Governor.sol";
|
||||
import {Math} from "../../utils/math/Math.sol";
|
||||
|
||||
/**
|
||||
* @dev A module that ensures there is a minimum voting period after quorum is reached. This prevents a large voter from
|
||||
* swaying a vote and triggering quorum at the last minute, by ensuring there is always time for other voters to react
|
||||
* and try to oppose the decision.
|
||||
*
|
||||
* If a vote causes quorum to be reached, the proposal's voting period may be extended so that it does not end before at
|
||||
* least a specified time has passed (the "vote extension" parameter). This parameter can be set through a governance
|
||||
* proposal.
|
||||
*/
|
||||
abstract contract GovernorPreventLateQuorum is Governor {
|
||||
uint48 private _voteExtension;
|
||||
|
||||
mapping(uint256 proposalId => uint48) private _extendedDeadlines;
|
||||
|
||||
/// @dev Emitted when a proposal deadline is pushed back due to reaching quorum late in its voting period.
|
||||
event ProposalExtended(uint256 indexed proposalId, uint64 extendedDeadline);
|
||||
|
||||
/// @dev Emitted when the {lateQuorumVoteExtension} parameter is changed.
|
||||
event LateQuorumVoteExtensionSet(uint64 oldVoteExtension, uint64 newVoteExtension);
|
||||
|
||||
/**
|
||||
* @dev Initializes the vote extension parameter: the time in either number of blocks or seconds (depending on the
|
||||
* governor clock mode) that is required to pass since the moment a proposal reaches quorum until its voting period
|
||||
* ends. If necessary the voting period will be extended beyond the one set during proposal creation.
|
||||
*/
|
||||
constructor(uint48 initialVoteExtension) {
|
||||
_setLateQuorumVoteExtension(initialVoteExtension);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the proposal deadline, which may have been extended beyond that set at proposal creation, if the
|
||||
* proposal reached quorum late in the voting period. See {Governor-proposalDeadline}.
|
||||
*/
|
||||
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
|
||||
return Math.max(super.proposalDeadline(proposalId), _extendedDeadlines[proposalId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Casts a vote and detects if it caused quorum to be reached, potentially extending the voting period. See
|
||||
* {Governor-_castVote}.
|
||||
*
|
||||
* May emit a {ProposalExtended} event.
|
||||
*/
|
||||
function _castVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
string memory reason,
|
||||
bytes memory params
|
||||
) internal virtual override returns (uint256) {
|
||||
uint256 result = super._castVote(proposalId, account, support, reason, params);
|
||||
|
||||
if (_extendedDeadlines[proposalId] == 0 && _quorumReached(proposalId)) {
|
||||
uint48 extendedDeadline = clock() + lateQuorumVoteExtension();
|
||||
|
||||
if (extendedDeadline > proposalDeadline(proposalId)) {
|
||||
emit ProposalExtended(proposalId, extendedDeadline);
|
||||
}
|
||||
|
||||
_extendedDeadlines[proposalId] = extendedDeadline;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the current value of the vote extension parameter: the number of blocks that are required to pass
|
||||
* from the time a proposal reaches quorum until its voting period ends.
|
||||
*/
|
||||
function lateQuorumVoteExtension() public view virtual returns (uint48) {
|
||||
return _voteExtension;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the {lateQuorumVoteExtension}. This operation can only be performed by the governance executor,
|
||||
* generally through a governance proposal.
|
||||
*
|
||||
* Emits a {LateQuorumVoteExtensionSet} event.
|
||||
*/
|
||||
function setLateQuorumVoteExtension(uint48 newVoteExtension) public virtual onlyGovernance {
|
||||
_setLateQuorumVoteExtension(newVoteExtension);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the {lateQuorumVoteExtension}. This is an internal function that can be exposed in a public function
|
||||
* like {setLateQuorumVoteExtension} if another access control mechanism is needed.
|
||||
*
|
||||
* Emits a {LateQuorumVoteExtensionSet} event.
|
||||
*/
|
||||
function _setLateQuorumVoteExtension(uint48 newVoteExtension) internal virtual {
|
||||
emit LateQuorumVoteExtensionSet(_voteExtension, newVoteExtension);
|
||||
_voteExtension = newVoteExtension;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/extensions/GovernorSettings.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Governor} from "../Governor.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} for settings updatable through governance.
|
||||
*/
|
||||
abstract contract GovernorSettings is Governor {
|
||||
// amount of token
|
||||
uint256 private _proposalThreshold;
|
||||
// timepoint: limited to uint48 in core (same as clock() type)
|
||||
uint48 private _votingDelay;
|
||||
// duration: limited to uint32 in core
|
||||
uint32 private _votingPeriod;
|
||||
|
||||
event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay);
|
||||
event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod);
|
||||
event ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold);
|
||||
|
||||
/**
|
||||
* @dev Initialize the governance parameters.
|
||||
*/
|
||||
constructor(uint48 initialVotingDelay, uint32 initialVotingPeriod, uint256 initialProposalThreshold) {
|
||||
_setVotingDelay(initialVotingDelay);
|
||||
_setVotingPeriod(initialVotingPeriod);
|
||||
_setProposalThreshold(initialProposalThreshold);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-votingDelay}.
|
||||
*/
|
||||
function votingDelay() public view virtual override returns (uint256) {
|
||||
return _votingDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-votingPeriod}.
|
||||
*/
|
||||
function votingPeriod() public view virtual override returns (uint256) {
|
||||
return _votingPeriod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-proposalThreshold}.
|
||||
*/
|
||||
function proposalThreshold() public view virtual override returns (uint256) {
|
||||
return _proposalThreshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Update the voting delay. This operation can only be performed through a governance proposal.
|
||||
*
|
||||
* Emits a {VotingDelaySet} event.
|
||||
*/
|
||||
function setVotingDelay(uint48 newVotingDelay) public virtual onlyGovernance {
|
||||
_setVotingDelay(newVotingDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Update the voting period. This operation can only be performed through a governance proposal.
|
||||
*
|
||||
* Emits a {VotingPeriodSet} event.
|
||||
*/
|
||||
function setVotingPeriod(uint32 newVotingPeriod) public virtual onlyGovernance {
|
||||
_setVotingPeriod(newVotingPeriod);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Update the proposal threshold. This operation can only be performed through a governance proposal.
|
||||
*
|
||||
* Emits a {ProposalThresholdSet} event.
|
||||
*/
|
||||
function setProposalThreshold(uint256 newProposalThreshold) public virtual onlyGovernance {
|
||||
_setProposalThreshold(newProposalThreshold);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal setter for the voting delay.
|
||||
*
|
||||
* Emits a {VotingDelaySet} event.
|
||||
*/
|
||||
function _setVotingDelay(uint48 newVotingDelay) internal virtual {
|
||||
emit VotingDelaySet(_votingDelay, newVotingDelay);
|
||||
_votingDelay = newVotingDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal setter for the voting period.
|
||||
*
|
||||
* Emits a {VotingPeriodSet} event.
|
||||
*/
|
||||
function _setVotingPeriod(uint32 newVotingPeriod) internal virtual {
|
||||
if (newVotingPeriod == 0) {
|
||||
revert GovernorInvalidVotingPeriod(0);
|
||||
}
|
||||
emit VotingPeriodSet(_votingPeriod, newVotingPeriod);
|
||||
_votingPeriod = newVotingPeriod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal setter for the proposal threshold.
|
||||
*
|
||||
* Emits a {ProposalThresholdSet} event.
|
||||
*/
|
||||
function _setProposalThreshold(uint256 newProposalThreshold) internal virtual {
|
||||
emit ProposalThresholdSet(_proposalThreshold, newProposalThreshold);
|
||||
_proposalThreshold = newProposalThreshold;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/extensions/GovernorStorage.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Governor} from "../Governor.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} that implements storage of proposal details. This modules also provides primitives for
|
||||
* the enumerability of proposals.
|
||||
*
|
||||
* Use cases for this module include:
|
||||
* - UIs that explore the proposal state without relying on event indexing.
|
||||
* - Using only the proposalId as an argument in the {Governor-queue} and {Governor-execute} functions for L2 chains
|
||||
* where storage is cheap compared to calldata.
|
||||
*/
|
||||
abstract contract GovernorStorage is Governor {
|
||||
struct ProposalDetails {
|
||||
address[] targets;
|
||||
uint256[] values;
|
||||
bytes[] calldatas;
|
||||
bytes32 descriptionHash;
|
||||
}
|
||||
|
||||
uint256[] private _proposalIds;
|
||||
mapping(uint256 proposalId => ProposalDetails) private _proposalDetails;
|
||||
|
||||
/**
|
||||
* @dev Hook into the proposing mechanism
|
||||
*/
|
||||
function _propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
string memory description,
|
||||
address proposer
|
||||
) internal virtual override returns (uint256) {
|
||||
uint256 proposalId = super._propose(targets, values, calldatas, description, proposer);
|
||||
|
||||
// store
|
||||
_proposalIds.push(proposalId);
|
||||
_proposalDetails[proposalId] = ProposalDetails({
|
||||
targets: targets,
|
||||
values: values,
|
||||
calldatas: calldatas,
|
||||
descriptionHash: keccak256(bytes(description))
|
||||
});
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Version of {IGovernorTimelock-queue} with only `proposalId` as an argument.
|
||||
*/
|
||||
function queue(uint256 proposalId) public virtual {
|
||||
// here, using storage is more efficient than memory
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
queue(details.targets, details.values, details.calldatas, details.descriptionHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Version of {IGovernor-execute} with only `proposalId` as an argument.
|
||||
*/
|
||||
function execute(uint256 proposalId) public payable virtual {
|
||||
// here, using storage is more efficient than memory
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
execute(details.targets, details.values, details.calldatas, details.descriptionHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev ProposalId version of {IGovernor-cancel}.
|
||||
*/
|
||||
function cancel(uint256 proposalId) public virtual {
|
||||
// here, using storage is more efficient than memory
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
cancel(details.targets, details.values, details.calldatas, details.descriptionHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the number of stored proposals.
|
||||
*/
|
||||
function proposalCount() public view virtual returns (uint256) {
|
||||
return _proposalIds.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the details of a proposalId. Reverts if `proposalId` is not a known proposal.
|
||||
*/
|
||||
function proposalDetails(
|
||||
uint256 proposalId
|
||||
) public view virtual returns (address[] memory, uint256[] memory, bytes[] memory, bytes32) {
|
||||
// here, using memory is more efficient than storage
|
||||
ProposalDetails memory details = _proposalDetails[proposalId];
|
||||
if (details.descriptionHash == 0) {
|
||||
revert GovernorNonexistentProposal(proposalId);
|
||||
}
|
||||
return (details.targets, details.values, details.calldatas, details.descriptionHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the details (including the proposalId) of a proposal given its sequential index.
|
||||
*/
|
||||
function proposalDetailsAt(
|
||||
uint256 index
|
||||
) public view virtual returns (uint256, address[] memory, uint256[] memory, bytes[] memory, bytes32) {
|
||||
uint256 proposalId = _proposalIds[index];
|
||||
(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) = proposalDetails(proposalId);
|
||||
return (proposalId, targets, values, calldatas, descriptionHash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/extensions/GovernorTimelockAccess.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Governor} from "../Governor.sol";
|
||||
import {AuthorityUtils} from "../../access/manager/AuthorityUtils.sol";
|
||||
import {IAccessManager} from "../../access/manager/IAccessManager.sol";
|
||||
import {Address} from "../../utils/Address.sol";
|
||||
import {Math} from "../../utils/math/Math.sol";
|
||||
import {SafeCast} from "../../utils/math/SafeCast.sol";
|
||||
import {Time} from "../../utils/types/Time.sol";
|
||||
|
||||
/**
|
||||
* @dev This module connects a {Governor} instance to an {AccessManager} instance, allowing the governor to make calls
|
||||
* that are delay-restricted by the manager using the normal {queue} workflow. An optional base delay is applied to
|
||||
* operations that are not delayed externally by the manager. Execution of a proposal will be delayed as much as
|
||||
* necessary to meet the required delays of all of its operations.
|
||||
*
|
||||
* This extension allows the governor to hold and use its own assets and permissions, unlike {GovernorTimelockControl}
|
||||
* and {GovernorTimelockCompound}, where the timelock is a separate contract that must be the one to hold assets and
|
||||
* permissions. Operations that are delay-restricted by the manager, however, will be executed through the
|
||||
* {AccessManager-execute} function.
|
||||
*
|
||||
* ==== Security Considerations
|
||||
*
|
||||
* Some operations may be cancelable in the `AccessManager` by the admin or a set of guardians, depending on the
|
||||
* restricted function being invoked. Since proposals are atomic, the cancellation by a guardian of a single operation
|
||||
* in a proposal will cause all of the proposal to become unable to execute. Consider proposing cancellable operations
|
||||
* separately.
|
||||
*
|
||||
* By default, function calls will be routed through the associated `AccessManager` whenever it claims the target
|
||||
* function to be restricted by it. However, admins may configure the manager to make that claim for functions that a
|
||||
* governor would want to call directly (e.g., token transfers) in an attempt to deny it access to those functions. To
|
||||
* mitigate this attack vector, the governor is able to ignore the restrictions claimed by the `AccessManager` using
|
||||
* {setAccessManagerIgnored}. While permanent denial of service is mitigated, temporary DoS may still be technically
|
||||
* possible. All of the governor's own functions (e.g., {setBaseDelaySeconds}) ignore the `AccessManager` by default.
|
||||
*
|
||||
* NOTE: `AccessManager` does not support scheduling more than one operation with the same target and calldata at
|
||||
* the same time. See {AccessManager-schedule} for a workaround.
|
||||
*/
|
||||
abstract contract GovernorTimelockAccess is Governor {
|
||||
// An execution plan is produced at the moment a proposal is created, in order to fix at that point the exact
|
||||
// execution semantics of the proposal, namely whether a call will go through {AccessManager-execute}.
|
||||
struct ExecutionPlan {
|
||||
uint16 length;
|
||||
uint32 delay;
|
||||
// We use mappings instead of arrays because it allows us to pack values in storage more tightly without
|
||||
// storing the length redundantly.
|
||||
// We pack 8 operations' data in each bucket. Each uint32 value is set to 1 upon proposal creation if it has
|
||||
// to be scheduled and executed through the manager. Upon queuing, the value is set to nonce + 2, where the
|
||||
// nonce is received from the manager when scheduling the operation.
|
||||
mapping(uint256 operationBucket => uint32[8]) managerData;
|
||||
}
|
||||
|
||||
// The meaning of the "toggle" set to true depends on the target contract.
|
||||
// If target == address(this), the manager is ignored by default, and a true toggle means it won't be ignored.
|
||||
// For all other target contracts, the manager is used by default, and a true toggle means it will be ignored.
|
||||
mapping(address target => mapping(bytes4 selector => bool)) private _ignoreToggle;
|
||||
|
||||
mapping(uint256 proposalId => ExecutionPlan) private _executionPlan;
|
||||
|
||||
uint32 private _baseDelay;
|
||||
|
||||
IAccessManager private immutable _manager;
|
||||
|
||||
error GovernorUnmetDelay(uint256 proposalId, uint256 neededTimestamp);
|
||||
error GovernorMismatchedNonce(uint256 proposalId, uint256 expectedNonce, uint256 actualNonce);
|
||||
error GovernorLockedIgnore();
|
||||
|
||||
event BaseDelaySet(uint32 oldBaseDelaySeconds, uint32 newBaseDelaySeconds);
|
||||
event AccessManagerIgnoredSet(address target, bytes4 selector, bool ignored);
|
||||
|
||||
/**
|
||||
* @dev Initialize the governor with an {AccessManager} and initial base delay.
|
||||
*/
|
||||
constructor(address manager, uint32 initialBaseDelay) {
|
||||
_manager = IAccessManager(manager);
|
||||
_setBaseDelaySeconds(initialBaseDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the {AccessManager} instance associated to this governor.
|
||||
*/
|
||||
function accessManager() public view virtual returns (IAccessManager) {
|
||||
return _manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Base delay that will be applied to all function calls. Some may be further delayed by their associated
|
||||
* `AccessManager` authority; in this case the final delay will be the maximum of the base delay and the one
|
||||
* demanded by the authority.
|
||||
*
|
||||
* NOTE: Execution delays are processed by the `AccessManager` contracts, and according to that contract are
|
||||
* expressed in seconds. Therefore, the base delay is also in seconds, regardless of the governor's clock mode.
|
||||
*/
|
||||
function baseDelaySeconds() public view virtual returns (uint32) {
|
||||
return _baseDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Change the value of {baseDelaySeconds}. This operation can only be invoked through a governance proposal.
|
||||
*/
|
||||
function setBaseDelaySeconds(uint32 newBaseDelay) public virtual onlyGovernance {
|
||||
_setBaseDelaySeconds(newBaseDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Change the value of {baseDelaySeconds}. Internal function without access control.
|
||||
*/
|
||||
function _setBaseDelaySeconds(uint32 newBaseDelay) internal virtual {
|
||||
emit BaseDelaySet(_baseDelay, newBaseDelay);
|
||||
_baseDelay = newBaseDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Check if restrictions from the associated {AccessManager} are ignored for a target function. Returns true
|
||||
* when the target function will be invoked directly regardless of `AccessManager` settings for the function.
|
||||
* See {setAccessManagerIgnored} and Security Considerations above.
|
||||
*/
|
||||
function isAccessManagerIgnored(address target, bytes4 selector) public view virtual returns (bool) {
|
||||
bool isGovernor = target == address(this);
|
||||
return _ignoreToggle[target][selector] != isGovernor; // equivalent to: isGovernor ? !toggle : toggle
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Configure whether restrictions from the associated {AccessManager} are ignored for a target function.
|
||||
* See Security Considerations above.
|
||||
*/
|
||||
function setAccessManagerIgnored(
|
||||
address target,
|
||||
bytes4[] calldata selectors,
|
||||
bool ignored
|
||||
) public virtual onlyGovernance {
|
||||
for (uint256 i = 0; i < selectors.length; ++i) {
|
||||
_setAccessManagerIgnored(target, selectors[i], ignored);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal version of {setAccessManagerIgnored} without access restriction.
|
||||
*/
|
||||
function _setAccessManagerIgnored(address target, bytes4 selector, bool ignored) internal virtual {
|
||||
bool isGovernor = target == address(this);
|
||||
if (isGovernor && selector == this.setAccessManagerIgnored.selector) {
|
||||
revert GovernorLockedIgnore();
|
||||
}
|
||||
_ignoreToggle[target][selector] = ignored != isGovernor; // equivalent to: isGovernor ? !ignored : ignored
|
||||
emit AccessManagerIgnoredSet(target, selector, ignored);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public accessor to check the execution plan, including the number of seconds that the proposal will be
|
||||
* delayed since queuing, an array indicating which of the proposal actions will be executed indirectly through
|
||||
* the associated {AccessManager}, and another indicating which will be scheduled in {queue}. Note that
|
||||
* those that must be scheduled are cancellable by `AccessManager` guardians.
|
||||
*/
|
||||
function proposalExecutionPlan(
|
||||
uint256 proposalId
|
||||
) public view returns (uint32 delay, bool[] memory indirect, bool[] memory withDelay) {
|
||||
ExecutionPlan storage plan = _executionPlan[proposalId];
|
||||
|
||||
uint32 length = plan.length;
|
||||
delay = plan.delay;
|
||||
indirect = new bool[](length);
|
||||
withDelay = new bool[](length);
|
||||
for (uint256 i = 0; i < length; ++i) {
|
||||
(indirect[i], withDelay[i], ) = _getManagerData(plan, i);
|
||||
}
|
||||
|
||||
return (delay, indirect, withDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalNeedsQueuing}.
|
||||
*/
|
||||
function proposalNeedsQueuing(uint256 proposalId) public view virtual override returns (bool) {
|
||||
return _executionPlan[proposalId].delay > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-propose}
|
||||
*/
|
||||
function propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
string memory description
|
||||
) public virtual override returns (uint256) {
|
||||
uint256 proposalId = super.propose(targets, values, calldatas, description);
|
||||
|
||||
uint32 neededDelay = baseDelaySeconds();
|
||||
|
||||
ExecutionPlan storage plan = _executionPlan[proposalId];
|
||||
plan.length = SafeCast.toUint16(targets.length);
|
||||
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
if (calldatas[i].length < 4) {
|
||||
continue;
|
||||
}
|
||||
address target = targets[i];
|
||||
bytes4 selector = bytes4(calldatas[i]);
|
||||
(bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
|
||||
address(_manager),
|
||||
address(this),
|
||||
target,
|
||||
selector
|
||||
);
|
||||
if ((immediate || delay > 0) && !isAccessManagerIgnored(target, selector)) {
|
||||
_setManagerData(plan, i, !immediate, 0);
|
||||
// downcast is safe because both arguments are uint32
|
||||
neededDelay = uint32(Math.max(delay, neededDelay));
|
||||
}
|
||||
}
|
||||
|
||||
plan.delay = neededDelay;
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Mechanism to queue a proposal, potentially scheduling some of its operations in the AccessManager.
|
||||
*
|
||||
* NOTE: The execution delay is chosen based on the delay information retrieved in {propose}. This value may be
|
||||
* off if the delay was updated since proposal creation. In this case, the proposal needs to be recreated.
|
||||
*/
|
||||
function _queueOperations(
|
||||
uint256 proposalId,
|
||||
address[] memory targets,
|
||||
uint256[] memory /* values */,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 /* descriptionHash */
|
||||
) internal virtual override returns (uint48) {
|
||||
ExecutionPlan storage plan = _executionPlan[proposalId];
|
||||
uint48 etaSeconds = Time.timestamp() + plan.delay;
|
||||
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
(, bool withDelay, ) = _getManagerData(plan, i);
|
||||
if (withDelay) {
|
||||
(, uint32 nonce) = _manager.schedule(targets[i], calldatas[i], etaSeconds);
|
||||
_setManagerData(plan, i, true, nonce);
|
||||
}
|
||||
}
|
||||
|
||||
return etaSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Mechanism to execute a proposal, potentially going through {AccessManager-execute} for delayed operations.
|
||||
*/
|
||||
function _executeOperations(
|
||||
uint256 proposalId,
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 /* descriptionHash */
|
||||
) internal virtual override {
|
||||
uint48 etaSeconds = SafeCast.toUint48(proposalEta(proposalId));
|
||||
if (block.timestamp < etaSeconds) {
|
||||
revert GovernorUnmetDelay(proposalId, etaSeconds);
|
||||
}
|
||||
|
||||
ExecutionPlan storage plan = _executionPlan[proposalId];
|
||||
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
(bool controlled, bool withDelay, uint32 nonce) = _getManagerData(plan, i);
|
||||
if (controlled) {
|
||||
uint32 executedNonce = _manager.execute{value: values[i]}(targets[i], calldatas[i]);
|
||||
if (withDelay && executedNonce != nonce) {
|
||||
revert GovernorMismatchedNonce(proposalId, nonce, executedNonce);
|
||||
}
|
||||
} else {
|
||||
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
|
||||
Address.verifyCallResult(success, returndata);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-_cancel}
|
||||
*/
|
||||
function _cancel(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual override returns (uint256) {
|
||||
uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
|
||||
|
||||
uint48 etaSeconds = SafeCast.toUint48(proposalEta(proposalId));
|
||||
|
||||
ExecutionPlan storage plan = _executionPlan[proposalId];
|
||||
|
||||
// If the proposal has been scheduled it will have an ETA and we may have to externally cancel
|
||||
if (etaSeconds != 0) {
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
(, bool withDelay, uint32 nonce) = _getManagerData(plan, i);
|
||||
// Only attempt to cancel if the execution plan included a delay
|
||||
if (withDelay) {
|
||||
bytes32 operationId = _manager.hashOperation(address(this), targets[i], calldatas[i]);
|
||||
// Check first if the current operation nonce is the one that we observed previously. It could
|
||||
// already have been cancelled and rescheduled. We don't want to cancel unless it is exactly the
|
||||
// instance that we previously scheduled.
|
||||
if (nonce == _manager.getNonce(operationId)) {
|
||||
// It is important that all calls have an opportunity to be cancelled. We chose to ignore
|
||||
// potential failures of some of the cancel operations to give the other operations a chance to
|
||||
// be properly cancelled. In particular cancel might fail if the operation was already cancelled
|
||||
// by guardians previously. We don't match on the revert reason to avoid encoding assumptions
|
||||
// about specific errors.
|
||||
try _manager.cancel(address(this), targets[i], calldatas[i]) {} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns whether the operation at an index is delayed by the manager, and its scheduling nonce once queued.
|
||||
*/
|
||||
function _getManagerData(
|
||||
ExecutionPlan storage plan,
|
||||
uint256 index
|
||||
) private view returns (bool controlled, bool withDelay, uint32 nonce) {
|
||||
(uint256 bucket, uint256 subindex) = _getManagerDataIndices(index);
|
||||
uint32 value = plan.managerData[bucket][subindex];
|
||||
unchecked {
|
||||
return (value > 0, value > 1, value > 1 ? value - 2 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Marks an operation at an index as permissioned by the manager, potentially delayed, and
|
||||
* when delayed sets its scheduling nonce.
|
||||
*/
|
||||
function _setManagerData(ExecutionPlan storage plan, uint256 index, bool withDelay, uint32 nonce) private {
|
||||
(uint256 bucket, uint256 subindex) = _getManagerDataIndices(index);
|
||||
plan.managerData[bucket][subindex] = withDelay ? nonce + 2 : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns bucket and subindex for reading manager data from the packed array mapping.
|
||||
*/
|
||||
function _getManagerDataIndices(uint256 index) private pure returns (uint256 bucket, uint256 subindex) {
|
||||
bucket = index >> 3; // index / 8
|
||||
subindex = index & 7; // index % 8
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/extensions/GovernorTimelockCompound.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IGovernor, Governor} from "../Governor.sol";
|
||||
import {ICompoundTimelock} from "../../vendor/compound/ICompoundTimelock.sol";
|
||||
import {Address} from "../../utils/Address.sol";
|
||||
import {SafeCast} from "../../utils/math/SafeCast.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} that binds the execution process to a Compound Timelock. This adds a delay, enforced by
|
||||
* the external timelock to all successful proposal (in addition to the voting duration). The {Governor} needs to be
|
||||
* the admin of the timelock for any operation to be performed. A public, unrestricted,
|
||||
* {GovernorTimelockCompound-__acceptAdmin} is available to accept ownership of the timelock.
|
||||
*
|
||||
* Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,
|
||||
* the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be
|
||||
* inaccessible from a proposal, unless executed via {Governor-relay}.
|
||||
*/
|
||||
abstract contract GovernorTimelockCompound is Governor {
|
||||
ICompoundTimelock private _timelock;
|
||||
|
||||
/**
|
||||
* @dev Emitted when the timelock controller used for proposal execution is modified.
|
||||
*/
|
||||
event TimelockChange(address oldTimelock, address newTimelock);
|
||||
|
||||
/**
|
||||
* @dev Set the timelock.
|
||||
*/
|
||||
constructor(ICompoundTimelock timelockAddress) {
|
||||
_updateTimelock(timelockAddress);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden version of the {Governor-state} function with added support for the `Expired` state.
|
||||
*/
|
||||
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
|
||||
ProposalState currentState = super.state(proposalId);
|
||||
|
||||
return
|
||||
(currentState == ProposalState.Queued &&
|
||||
block.timestamp >= proposalEta(proposalId) + _timelock.GRACE_PERIOD())
|
||||
? ProposalState.Expired
|
||||
: currentState;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public accessor to check the address of the timelock
|
||||
*/
|
||||
function timelock() public view virtual returns (address) {
|
||||
return address(_timelock);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalNeedsQueuing}.
|
||||
*/
|
||||
function proposalNeedsQueuing(uint256) public view virtual override returns (bool) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Function to queue a proposal to the timelock.
|
||||
*/
|
||||
function _queueOperations(
|
||||
uint256 proposalId,
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 /*descriptionHash*/
|
||||
) internal virtual override returns (uint48) {
|
||||
uint48 etaSeconds = SafeCast.toUint48(block.timestamp + _timelock.delay());
|
||||
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
if (
|
||||
_timelock.queuedTransactions(keccak256(abi.encode(targets[i], values[i], "", calldatas[i], etaSeconds)))
|
||||
) {
|
||||
revert GovernorAlreadyQueuedProposal(proposalId);
|
||||
}
|
||||
_timelock.queueTransaction(targets[i], values[i], "", calldatas[i], etaSeconds);
|
||||
}
|
||||
|
||||
return etaSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden version of the {Governor-_executeOperations} function that run the already queued proposal
|
||||
* through the timelock.
|
||||
*/
|
||||
function _executeOperations(
|
||||
uint256 proposalId,
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 /*descriptionHash*/
|
||||
) internal virtual override {
|
||||
uint256 etaSeconds = proposalEta(proposalId);
|
||||
if (etaSeconds == 0) {
|
||||
revert GovernorNotQueuedProposal(proposalId);
|
||||
}
|
||||
Address.sendValue(payable(_timelock), msg.value);
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
_timelock.executeTransaction(targets[i], values[i], "", calldatas[i], etaSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden version of the {Governor-_cancel} function to cancel the timelocked proposal if it has already
|
||||
* been queued.
|
||||
*/
|
||||
function _cancel(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual override returns (uint256) {
|
||||
uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
|
||||
|
||||
uint256 etaSeconds = proposalEta(proposalId);
|
||||
if (etaSeconds > 0) {
|
||||
// do external call later
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
_timelock.cancelTransaction(targets[i], values[i], "", calldatas[i], etaSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Address through which the governor executes action. In this case, the timelock.
|
||||
*/
|
||||
function _executor() internal view virtual override returns (address) {
|
||||
return address(_timelock);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Accept admin right over the timelock.
|
||||
*/
|
||||
// solhint-disable-next-line private-vars-leading-underscore
|
||||
function __acceptAdmin() public {
|
||||
_timelock.acceptAdmin();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
|
||||
* must be proposed, scheduled, and executed through governance proposals.
|
||||
*
|
||||
* For security reasons, the timelock must be handed over to another admin before setting up a new one. The two
|
||||
* operations (hand over the timelock) and do the update can be batched in a single proposal.
|
||||
*
|
||||
* Note that if the timelock admin has been handed over in a previous operation, we refuse updates made through the
|
||||
* timelock if admin of the timelock has already been accepted and the operation is executed outside the scope of
|
||||
* governance.
|
||||
|
||||
* CAUTION: It is not recommended to change the timelock while there are other queued governance proposals.
|
||||
*/
|
||||
function updateTimelock(ICompoundTimelock newTimelock) external virtual onlyGovernance {
|
||||
_updateTimelock(newTimelock);
|
||||
}
|
||||
|
||||
function _updateTimelock(ICompoundTimelock newTimelock) private {
|
||||
emit TimelockChange(address(_timelock), address(newTimelock));
|
||||
_timelock = newTimelock;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/extensions/GovernorTimelockControl.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IGovernor, Governor} from "../Governor.sol";
|
||||
import {TimelockController} from "../TimelockController.sol";
|
||||
import {IERC165} from "../../interfaces/IERC165.sol";
|
||||
import {SafeCast} from "../../utils/math/SafeCast.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a
|
||||
* delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The
|
||||
* {Governor} needs the proposer (and ideally the executor and canceller) roles for the {Governor} to work properly.
|
||||
*
|
||||
* Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,
|
||||
* the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be
|
||||
* inaccessible from a proposal, unless executed via {Governor-relay}.
|
||||
*
|
||||
* WARNING: Setting up the TimelockController to have additional proposers or cancellers besides the governor is very
|
||||
* risky, as it grants them the ability to: 1) execute operations as the timelock, and thus possibly performing
|
||||
* operations or accessing funds that are expected to only be accessible through a vote, and 2) block governance
|
||||
* proposals that have been approved by the voters, effectively executing a Denial of Service attack.
|
||||
*/
|
||||
abstract contract GovernorTimelockControl is Governor {
|
||||
TimelockController private _timelock;
|
||||
mapping(uint256 proposalId => bytes32) private _timelockIds;
|
||||
|
||||
/**
|
||||
* @dev Emitted when the timelock controller used for proposal execution is modified.
|
||||
*/
|
||||
event TimelockChange(address oldTimelock, address newTimelock);
|
||||
|
||||
/**
|
||||
* @dev Set the timelock.
|
||||
*/
|
||||
constructor(TimelockController timelockAddress) {
|
||||
_updateTimelock(timelockAddress);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden version of the {Governor-state} function that considers the status reported by the timelock.
|
||||
*/
|
||||
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
|
||||
ProposalState currentState = super.state(proposalId);
|
||||
|
||||
if (currentState != ProposalState.Queued) {
|
||||
return currentState;
|
||||
}
|
||||
|
||||
bytes32 queueid = _timelockIds[proposalId];
|
||||
if (_timelock.isOperationPending(queueid)) {
|
||||
return ProposalState.Queued;
|
||||
} else if (_timelock.isOperationDone(queueid)) {
|
||||
// This can happen if the proposal is executed directly on the timelock.
|
||||
return ProposalState.Executed;
|
||||
} else {
|
||||
// This can happen if the proposal is canceled directly on the timelock.
|
||||
return ProposalState.Canceled;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public accessor to check the address of the timelock
|
||||
*/
|
||||
function timelock() public view virtual returns (address) {
|
||||
return address(_timelock);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalNeedsQueuing}.
|
||||
*/
|
||||
function proposalNeedsQueuing(uint256) public view virtual override returns (bool) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Function to queue a proposal to the timelock.
|
||||
*/
|
||||
function _queueOperations(
|
||||
uint256 proposalId,
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual override returns (uint48) {
|
||||
uint256 delay = _timelock.getMinDelay();
|
||||
|
||||
bytes32 salt = _timelockSalt(descriptionHash);
|
||||
_timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, salt);
|
||||
_timelock.scheduleBatch(targets, values, calldatas, 0, salt, delay);
|
||||
|
||||
return SafeCast.toUint48(block.timestamp + delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden version of the {Governor-_executeOperations} function that runs the already queued proposal
|
||||
* through the timelock.
|
||||
*/
|
||||
function _executeOperations(
|
||||
uint256 proposalId,
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual override {
|
||||
// execute
|
||||
_timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, _timelockSalt(descriptionHash));
|
||||
// cleanup for refund
|
||||
delete _timelockIds[proposalId];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden version of the {Governor-_cancel} function to cancel the timelocked proposal if it has already
|
||||
* been queued.
|
||||
*/
|
||||
// This function can reenter through the external call to the timelock, but we assume the timelock is trusted and
|
||||
// well behaved (according to TimelockController) and this will not happen.
|
||||
// slither-disable-next-line reentrancy-no-eth
|
||||
function _cancel(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual override returns (uint256) {
|
||||
uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
|
||||
|
||||
bytes32 timelockId = _timelockIds[proposalId];
|
||||
if (timelockId != 0) {
|
||||
// cancel
|
||||
_timelock.cancel(timelockId);
|
||||
// cleanup
|
||||
delete _timelockIds[proposalId];
|
||||
}
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Address through which the governor executes action. In this case, the timelock.
|
||||
*/
|
||||
function _executor() internal view virtual override returns (address) {
|
||||
return address(_timelock);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
|
||||
* must be proposed, scheduled, and executed through governance proposals.
|
||||
*
|
||||
* CAUTION: It is not recommended to change the timelock while there are other queued governance proposals.
|
||||
*/
|
||||
function updateTimelock(TimelockController newTimelock) external virtual onlyGovernance {
|
||||
_updateTimelock(newTimelock);
|
||||
}
|
||||
|
||||
function _updateTimelock(TimelockController newTimelock) private {
|
||||
emit TimelockChange(address(_timelock), address(newTimelock));
|
||||
_timelock = newTimelock;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Computes the {TimelockController} operation salt.
|
||||
*
|
||||
* It is computed with the governor address itself to avoid collisions across governor instances using the
|
||||
* same timelock.
|
||||
*/
|
||||
function _timelockSalt(bytes32 descriptionHash) private view returns (bytes32) {
|
||||
return bytes20(address(this)) ^ descriptionHash;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/extensions/GovernorVotes.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Governor} from "../Governor.sol";
|
||||
import {IVotes} from "../utils/IVotes.sol";
|
||||
import {IERC5805} from "../../interfaces/IERC5805.sol";
|
||||
import {SafeCast} from "../../utils/math/SafeCast.sol";
|
||||
import {Time} from "../../utils/types/Time.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token, or since v4.5 an {ERC721Votes}
|
||||
* token.
|
||||
*/
|
||||
abstract contract GovernorVotes is Governor {
|
||||
IERC5805 private immutable _token;
|
||||
|
||||
constructor(IVotes tokenAddress) {
|
||||
_token = IERC5805(address(tokenAddress));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev The token that voting power is sourced from.
|
||||
*/
|
||||
function token() public view virtual returns (IERC5805) {
|
||||
return _token;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Clock (as specified in ERC-6372) is set to match the token's clock. Fallback to block numbers if the token
|
||||
* does not implement ERC-6372.
|
||||
*/
|
||||
function clock() public view virtual override returns (uint48) {
|
||||
try token().clock() returns (uint48 timepoint) {
|
||||
return timepoint;
|
||||
} catch {
|
||||
return Time.blockNumber();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Machine-readable description of the clock as specified in ERC-6372.
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function CLOCK_MODE() public view virtual override returns (string memory) {
|
||||
try token().CLOCK_MODE() returns (string memory clockmode) {
|
||||
return clockmode;
|
||||
} catch {
|
||||
return "mode=blocknumber&from=default";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the voting weight from the token's built in snapshot mechanism (see {Governor-_getVotes}).
|
||||
*/
|
||||
function _getVotes(
|
||||
address account,
|
||||
uint256 timepoint,
|
||||
bytes memory /*params*/
|
||||
) internal view virtual override returns (uint256) {
|
||||
return token().getPastVotes(account, timepoint);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/extensions/GovernorVotesQuorumFraction.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {GovernorVotes} from "./GovernorVotes.sol";
|
||||
import {SafeCast} from "../../utils/math/SafeCast.sol";
|
||||
import {Checkpoints} from "../../utils/structs/Checkpoints.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token and a quorum expressed as a
|
||||
* fraction of the total supply.
|
||||
*/
|
||||
abstract contract GovernorVotesQuorumFraction is GovernorVotes {
|
||||
using Checkpoints for Checkpoints.Trace208;
|
||||
|
||||
Checkpoints.Trace208 private _quorumNumeratorHistory;
|
||||
|
||||
event QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator);
|
||||
|
||||
/**
|
||||
* @dev The quorum set is not a valid fraction.
|
||||
*/
|
||||
error GovernorInvalidQuorumFraction(uint256 quorumNumerator, uint256 quorumDenominator);
|
||||
|
||||
/**
|
||||
* @dev Initialize quorum as a fraction of the token's total supply.
|
||||
*
|
||||
* The fraction is specified as `numerator / denominator`. By default the denominator is 100, so quorum is
|
||||
* specified as a percent: a numerator of 10 corresponds to quorum being 10% of total supply. The denominator can be
|
||||
* customized by overriding {quorumDenominator}.
|
||||
*/
|
||||
constructor(uint256 quorumNumeratorValue) {
|
||||
_updateQuorumNumerator(quorumNumeratorValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the current quorum numerator. See {quorumDenominator}.
|
||||
*/
|
||||
function quorumNumerator() public view virtual returns (uint256) {
|
||||
return _quorumNumeratorHistory.latest();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the quorum numerator at a specific timepoint. See {quorumDenominator}.
|
||||
*/
|
||||
function quorumNumerator(uint256 timepoint) public view virtual returns (uint256) {
|
||||
uint256 length = _quorumNumeratorHistory._checkpoints.length;
|
||||
|
||||
// Optimistic search, check the latest checkpoint
|
||||
Checkpoints.Checkpoint208 storage latest = _quorumNumeratorHistory._checkpoints[length - 1];
|
||||
uint48 latestKey = latest._key;
|
||||
uint208 latestValue = latest._value;
|
||||
if (latestKey <= timepoint) {
|
||||
return latestValue;
|
||||
}
|
||||
|
||||
// Otherwise, do the binary search
|
||||
return _quorumNumeratorHistory.upperLookupRecent(SafeCast.toUint48(timepoint));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the quorum denominator. Defaults to 100, but may be overridden.
|
||||
*/
|
||||
function quorumDenominator() public view virtual returns (uint256) {
|
||||
return 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the quorum for a timepoint, in terms of number of votes: `supply * numerator / denominator`.
|
||||
*/
|
||||
function quorum(uint256 timepoint) public view virtual override returns (uint256) {
|
||||
return (token().getPastTotalSupply(timepoint) * quorumNumerator(timepoint)) / quorumDenominator();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the quorum numerator.
|
||||
*
|
||||
* Emits a {QuorumNumeratorUpdated} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - Must be called through a governance proposal.
|
||||
* - New numerator must be smaller or equal to the denominator.
|
||||
*/
|
||||
function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance {
|
||||
_updateQuorumNumerator(newQuorumNumerator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the quorum numerator.
|
||||
*
|
||||
* Emits a {QuorumNumeratorUpdated} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - New numerator must be smaller or equal to the denominator.
|
||||
*/
|
||||
function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual {
|
||||
uint256 denominator = quorumDenominator();
|
||||
if (newQuorumNumerator > denominator) {
|
||||
revert GovernorInvalidQuorumFraction(newQuorumNumerator, denominator);
|
||||
}
|
||||
|
||||
uint256 oldQuorumNumerator = quorumNumerator();
|
||||
_quorumNumeratorHistory.push(clock(), SafeCast.toUint208(newQuorumNumerator));
|
||||
|
||||
emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/utils/IVotes.sol)
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
|
||||
*/
|
||||
interface IVotes {
|
||||
/**
|
||||
* @dev The signature used has expired.
|
||||
*/
|
||||
error VotesExpiredSignature(uint256 expiry);
|
||||
|
||||
/**
|
||||
* @dev Emitted when an account changes their delegate.
|
||||
*/
|
||||
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of voting units.
|
||||
*/
|
||||
event DelegateVotesChanged(address indexed delegate, uint256 previousVotes, uint256 newVotes);
|
||||
|
||||
/**
|
||||
* @dev Returns the current amount of votes that `account` has.
|
||||
*/
|
||||
function getVotes(address account) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is
|
||||
* configured to use block numbers, this will return the value at the end of the corresponding block.
|
||||
*/
|
||||
function getPastVotes(address account, uint256 timepoint) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is
|
||||
* configured to use block numbers, this will return the value at the end of the corresponding block.
|
||||
*
|
||||
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
|
||||
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
|
||||
* vote.
|
||||
*/
|
||||
function getPastTotalSupply(uint256 timepoint) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the delegate that `account` has chosen.
|
||||
*/
|
||||
function delegates(address account) external view returns (address);
|
||||
|
||||
/**
|
||||
* @dev Delegates votes from the sender to `delegatee`.
|
||||
*/
|
||||
function delegate(address delegatee) external;
|
||||
|
||||
/**
|
||||
* @dev Delegates votes from signer to `delegatee`.
|
||||
*/
|
||||
function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external;
|
||||
}
|
||||
251
lib_openzeppelin_contracts/contracts/governance/utils/Votes.sol
Normal file
251
lib_openzeppelin_contracts/contracts/governance/utils/Votes.sol
Normal file
@@ -0,0 +1,251 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (governance/utils/Votes.sol)
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC5805} from "../../interfaces/IERC5805.sol";
|
||||
import {Context} from "../../utils/Context.sol";
|
||||
import {Nonces} from "../../utils/Nonces.sol";
|
||||
import {EIP712} from "../../utils/cryptography/EIP712.sol";
|
||||
import {Checkpoints} from "../../utils/structs/Checkpoints.sol";
|
||||
import {SafeCast} from "../../utils/math/SafeCast.sol";
|
||||
import {ECDSA} from "../../utils/cryptography/ECDSA.sol";
|
||||
import {Time} from "../../utils/types/Time.sol";
|
||||
|
||||
/**
|
||||
* @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be
|
||||
* transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of
|
||||
* "representative" that will pool delegated voting units from different accounts and can then use it to vote in
|
||||
* decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to
|
||||
* delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative.
|
||||
*
|
||||
* This contract is often combined with a token contract such that voting units correspond to token units. For an
|
||||
* example, see {ERC721Votes}.
|
||||
*
|
||||
* The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed
|
||||
* at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the
|
||||
* cost of this history tracking optional.
|
||||
*
|
||||
* When using this module the derived contract must implement {_getVotingUnits} (for example, make it return
|
||||
* {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the
|
||||
* previous example, it would be included in {ERC721-_update}).
|
||||
*/
|
||||
abstract contract Votes is Context, EIP712, Nonces, IERC5805 {
|
||||
using Checkpoints for Checkpoints.Trace208;
|
||||
|
||||
bytes32 private constant DELEGATION_TYPEHASH =
|
||||
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
|
||||
|
||||
mapping(address account => address) private _delegatee;
|
||||
|
||||
mapping(address delegatee => Checkpoints.Trace208) private _delegateCheckpoints;
|
||||
|
||||
Checkpoints.Trace208 private _totalCheckpoints;
|
||||
|
||||
/**
|
||||
* @dev The clock was incorrectly modified.
|
||||
*/
|
||||
error ERC6372InconsistentClock();
|
||||
|
||||
/**
|
||||
* @dev Lookup to future votes is not available.
|
||||
*/
|
||||
error ERC5805FutureLookup(uint256 timepoint, uint48 clock);
|
||||
|
||||
/**
|
||||
* @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based
|
||||
* checkpoints (and voting), in which case {CLOCK_MODE} should be overridden as well to match.
|
||||
*/
|
||||
function clock() public view virtual returns (uint48) {
|
||||
return Time.blockNumber();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Machine-readable description of the clock as specified in ERC-6372.
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function CLOCK_MODE() public view virtual returns (string memory) {
|
||||
// Check that the clock was not modified
|
||||
if (clock() != Time.blockNumber()) {
|
||||
revert ERC6372InconsistentClock();
|
||||
}
|
||||
return "mode=blocknumber&from=default";
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the current amount of votes that `account` has.
|
||||
*/
|
||||
function getVotes(address account) public view virtual returns (uint256) {
|
||||
return _delegateCheckpoints[account].latest();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is
|
||||
* configured to use block numbers, this will return the value at the end of the corresponding block.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `timepoint` must be in the past. If operating using block numbers, the block must be already mined.
|
||||
*/
|
||||
function getPastVotes(address account, uint256 timepoint) public view virtual returns (uint256) {
|
||||
uint48 currentTimepoint = clock();
|
||||
if (timepoint >= currentTimepoint) {
|
||||
revert ERC5805FutureLookup(timepoint, currentTimepoint);
|
||||
}
|
||||
return _delegateCheckpoints[account].upperLookupRecent(SafeCast.toUint48(timepoint));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is
|
||||
* configured to use block numbers, this will return the value at the end of the corresponding block.
|
||||
*
|
||||
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
|
||||
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
|
||||
* vote.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `timepoint` must be in the past. If operating using block numbers, the block must be already mined.
|
||||
*/
|
||||
function getPastTotalSupply(uint256 timepoint) public view virtual returns (uint256) {
|
||||
uint48 currentTimepoint = clock();
|
||||
if (timepoint >= currentTimepoint) {
|
||||
revert ERC5805FutureLookup(timepoint, currentTimepoint);
|
||||
}
|
||||
return _totalCheckpoints.upperLookupRecent(SafeCast.toUint48(timepoint));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the current total supply of votes.
|
||||
*/
|
||||
function _getTotalSupply() internal view virtual returns (uint256) {
|
||||
return _totalCheckpoints.latest();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the delegate that `account` has chosen.
|
||||
*/
|
||||
function delegates(address account) public view virtual returns (address) {
|
||||
return _delegatee[account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Delegates votes from the sender to `delegatee`.
|
||||
*/
|
||||
function delegate(address delegatee) public virtual {
|
||||
address account = _msgSender();
|
||||
_delegate(account, delegatee);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Delegates votes from signer to `delegatee`.
|
||||
*/
|
||||
function delegateBySig(
|
||||
address delegatee,
|
||||
uint256 nonce,
|
||||
uint256 expiry,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) public virtual {
|
||||
if (block.timestamp > expiry) {
|
||||
revert VotesExpiredSignature(expiry);
|
||||
}
|
||||
address signer = ECDSA.recover(
|
||||
_hashTypedDataV4(keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
|
||||
v,
|
||||
r,
|
||||
s
|
||||
);
|
||||
_useCheckedNonce(signer, nonce);
|
||||
_delegate(signer, delegatee);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Delegate all of `account`'s voting units to `delegatee`.
|
||||
*
|
||||
* Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
|
||||
*/
|
||||
function _delegate(address account, address delegatee) internal virtual {
|
||||
address oldDelegate = delegates(account);
|
||||
_delegatee[account] = delegatee;
|
||||
|
||||
emit DelegateChanged(account, oldDelegate, delegatee);
|
||||
_moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to`
|
||||
* should be zero. Total supply of voting units will be adjusted with mints and burns.
|
||||
*/
|
||||
function _transferVotingUnits(address from, address to, uint256 amount) internal virtual {
|
||||
if (from == address(0)) {
|
||||
_push(_totalCheckpoints, _add, SafeCast.toUint208(amount));
|
||||
}
|
||||
if (to == address(0)) {
|
||||
_push(_totalCheckpoints, _subtract, SafeCast.toUint208(amount));
|
||||
}
|
||||
_moveDelegateVotes(delegates(from), delegates(to), amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Moves delegated votes from one delegate to another.
|
||||
*/
|
||||
function _moveDelegateVotes(address from, address to, uint256 amount) internal virtual {
|
||||
if (from != to && amount > 0) {
|
||||
if (from != address(0)) {
|
||||
(uint256 oldValue, uint256 newValue) = _push(
|
||||
_delegateCheckpoints[from],
|
||||
_subtract,
|
||||
SafeCast.toUint208(amount)
|
||||
);
|
||||
emit DelegateVotesChanged(from, oldValue, newValue);
|
||||
}
|
||||
if (to != address(0)) {
|
||||
(uint256 oldValue, uint256 newValue) = _push(
|
||||
_delegateCheckpoints[to],
|
||||
_add,
|
||||
SafeCast.toUint208(amount)
|
||||
);
|
||||
emit DelegateVotesChanged(to, oldValue, newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Get number of checkpoints for `account`.
|
||||
*/
|
||||
function _numCheckpoints(address account) internal view virtual returns (uint32) {
|
||||
return SafeCast.toUint32(_delegateCheckpoints[account].length());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Get the `pos`-th checkpoint for `account`.
|
||||
*/
|
||||
function _checkpoints(
|
||||
address account,
|
||||
uint32 pos
|
||||
) internal view virtual returns (Checkpoints.Checkpoint208 memory) {
|
||||
return _delegateCheckpoints[account].at(pos);
|
||||
}
|
||||
|
||||
function _push(
|
||||
Checkpoints.Trace208 storage store,
|
||||
function(uint208, uint208) view returns (uint208) op,
|
||||
uint208 delta
|
||||
) private returns (uint208, uint208) {
|
||||
return store.push(clock(), op(store.latest(), delta));
|
||||
}
|
||||
|
||||
function _add(uint208 a, uint208 b) private pure returns (uint208) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
function _subtract(uint208 a, uint208 b) private pure returns (uint208) {
|
||||
return a - b;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Must return the voting units held by an account.
|
||||
*/
|
||||
function _getVotingUnits(address) internal view virtual returns (uint256);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1155.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC1155} from "../token/ERC1155/IERC1155.sol";
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1155MetadataURI.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC1155MetadataURI} from "../token/ERC1155/extensions/IERC1155MetadataURI.sol";
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1155Receiver.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC1155Receiver} from "../token/ERC1155/IERC1155Receiver.sol";
|
||||
17
lib_openzeppelin_contracts/contracts/interfaces/IERC1271.sol
Normal file
17
lib_openzeppelin_contracts/contracts/interfaces/IERC1271.sol
Normal file
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1271.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-1271 standard signature validation method for
|
||||
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
|
||||
*/
|
||||
interface IERC1271 {
|
||||
/**
|
||||
* @dev Should return whether the signature provided is valid for the provided data
|
||||
* @param hash Hash of the data to be signed
|
||||
* @param signature Signature byte array associated with _data
|
||||
*/
|
||||
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
|
||||
}
|
||||
86
lib_openzeppelin_contracts/contracts/interfaces/IERC1363.sol
Normal file
86
lib_openzeppelin_contracts/contracts/interfaces/IERC1363.sol
Normal file
@@ -0,0 +1,86 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1363.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "./IERC20.sol";
|
||||
import {IERC165} from "./IERC165.sol";
|
||||
|
||||
/**
|
||||
* @title IERC1363
|
||||
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
|
||||
*
|
||||
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
|
||||
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
|
||||
*/
|
||||
interface IERC1363 is IERC20, IERC165 {
|
||||
/*
|
||||
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
|
||||
* 0xb0202a11 ===
|
||||
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
|
||||
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
|
||||
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
|
||||
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
|
||||
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
|
||||
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
|
||||
*/
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from the caller's account to `to`
|
||||
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
|
||||
* @param to The address which you want to transfer to.
|
||||
* @param value The amount of tokens to be transferred.
|
||||
* @return A boolean value indicating whether the operation succeeded unless throwing.
|
||||
*/
|
||||
function transferAndCall(address to, uint256 value) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from the caller's account to `to`
|
||||
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
|
||||
* @param to The address which you want to transfer to.
|
||||
* @param value The amount of tokens to be transferred.
|
||||
* @param data Additional data with no specified format, sent in call to `to`.
|
||||
* @return A boolean value indicating whether the operation succeeded unless throwing.
|
||||
*/
|
||||
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
|
||||
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
|
||||
* @param from The address which you want to send tokens from.
|
||||
* @param to The address which you want to transfer to.
|
||||
* @param value The amount of tokens to be transferred.
|
||||
* @return A boolean value indicating whether the operation succeeded unless throwing.
|
||||
*/
|
||||
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
|
||||
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
|
||||
* @param from The address which you want to send tokens from.
|
||||
* @param to The address which you want to transfer to.
|
||||
* @param value The amount of tokens to be transferred.
|
||||
* @param data Additional data with no specified format, sent in call to `to`.
|
||||
* @return A boolean value indicating whether the operation succeeded unless throwing.
|
||||
*/
|
||||
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
|
||||
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
|
||||
* @param spender The address which will spend the funds.
|
||||
* @param value The amount of tokens to be spent.
|
||||
* @return A boolean value indicating whether the operation succeeded unless throwing.
|
||||
*/
|
||||
function approveAndCall(address spender, uint256 value) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
|
||||
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
|
||||
* @param spender The address which will spend the funds.
|
||||
* @param value The amount of tokens to be spent.
|
||||
* @param data Additional data with no specified format, sent in call to `spender`.
|
||||
* @return A boolean value indicating whether the operation succeeded unless throwing.
|
||||
*/
|
||||
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1363Receiver.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @title IERC1363Receiver
|
||||
* @dev Interface for any contract that wants to support `transferAndCall` or `transferFromAndCall`
|
||||
* from ERC-1363 token contracts.
|
||||
*/
|
||||
interface IERC1363Receiver {
|
||||
/**
|
||||
* @dev Whenever ERC-1363 tokens are transferred to this contract via `transferAndCall` or `transferFromAndCall`
|
||||
* by `operator` from `from`, this function is called.
|
||||
*
|
||||
* NOTE: To accept the transfer, this must return
|
||||
* `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
|
||||
* (i.e. 0x88a7ca5c, or its own function selector).
|
||||
*
|
||||
* @param operator The address which called `transferAndCall` or `transferFromAndCall` function.
|
||||
* @param from The address which are tokens transferred from.
|
||||
* @param value The amount of tokens transferred.
|
||||
* @param data Additional data with no specified format.
|
||||
* @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` if transfer is allowed unless throwing.
|
||||
*/
|
||||
function onTransferReceived(
|
||||
address operator,
|
||||
address from,
|
||||
uint256 value,
|
||||
bytes calldata data
|
||||
) external returns (bytes4);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1363Spender.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @title ERC1363Spender
|
||||
* @dev Interface for any contract that wants to support `approveAndCall`
|
||||
* from ERC-1363 token contracts.
|
||||
*/
|
||||
interface IERC1363Spender {
|
||||
/**
|
||||
* @dev Whenever an ERC-1363 token `owner` approves this contract via `approveAndCall`
|
||||
* to spend their tokens, this function is called.
|
||||
*
|
||||
* NOTE: To accept the approval, this must return
|
||||
* `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
|
||||
* (i.e. 0x7b04a2d0, or its own function selector).
|
||||
*
|
||||
* @param owner The address which called `approveAndCall` function and previously owned the tokens.
|
||||
* @param value The amount of tokens to be spent.
|
||||
* @param data Additional data with no specified format.
|
||||
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` if approval is allowed unless throwing.
|
||||
*/
|
||||
function onApprovalReceived(address owner, uint256 value, bytes calldata data) external returns (bytes4);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "../utils/introspection/IERC165.sol";
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1820Implementer.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface for an ERC-1820 implementer, as defined in the
|
||||
* https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[ERC].
|
||||
* Used by contracts that will be registered as implementers in the
|
||||
* {IERC1820Registry}.
|
||||
*/
|
||||
interface IERC1820Implementer {
|
||||
/**
|
||||
* @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract
|
||||
* implements `interfaceHash` for `account`.
|
||||
*
|
||||
* See {IERC1820Registry-setInterfaceImplementer}.
|
||||
*/
|
||||
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1820Registry.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the global ERC-1820 Registry, as defined in the
|
||||
* https://eips.ethereum.org/EIPS/eip-1820[ERC]. Accounts may register
|
||||
* implementers for interfaces in this registry, as well as query support.
|
||||
*
|
||||
* Implementers may be shared by multiple accounts, and can also implement more
|
||||
* than a single interface for each account. Contracts can implement interfaces
|
||||
* for themselves, but externally-owned accounts (EOA) must delegate this to a
|
||||
* contract.
|
||||
*
|
||||
* {IERC165} interfaces can also be queried via the registry.
|
||||
*
|
||||
* For an in-depth explanation and source code analysis, see the ERC text.
|
||||
*/
|
||||
interface IERC1820Registry {
|
||||
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
|
||||
|
||||
event ManagerChanged(address indexed account, address indexed newManager);
|
||||
|
||||
/**
|
||||
* @dev Sets `newManager` as the manager for `account`. A manager of an
|
||||
* account is able to set interface implementers for it.
|
||||
*
|
||||
* By default, each account is its own manager. Passing a value of `0x0` in
|
||||
* `newManager` will reset the manager to this initial state.
|
||||
*
|
||||
* Emits a {ManagerChanged} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be the current manager for `account`.
|
||||
*/
|
||||
function setManager(address account, address newManager) external;
|
||||
|
||||
/**
|
||||
* @dev Returns the manager for `account`.
|
||||
*
|
||||
* See {setManager}.
|
||||
*/
|
||||
function getManager(address account) external view returns (address);
|
||||
|
||||
/**
|
||||
* @dev Sets the `implementer` contract as ``account``'s implementer for
|
||||
* `interfaceHash`.
|
||||
*
|
||||
* `account` being the zero address is an alias for the caller's address.
|
||||
* The zero address can also be used in `implementer` to remove an old one.
|
||||
*
|
||||
* See {interfaceHash} to learn how these are created.
|
||||
*
|
||||
* Emits an {InterfaceImplementerSet} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be the current manager for `account`.
|
||||
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
|
||||
* end in 28 zeroes).
|
||||
* - `implementer` must implement {IERC1820Implementer} and return true when
|
||||
* queried for support, unless `implementer` is the caller. See
|
||||
* {IERC1820Implementer-canImplementInterfaceForAddress}.
|
||||
*/
|
||||
function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external;
|
||||
|
||||
/**
|
||||
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
|
||||
* implementer is registered, returns the zero address.
|
||||
*
|
||||
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
|
||||
* zeroes), `account` will be queried for support of it.
|
||||
*
|
||||
* `account` being the zero address is an alias for the caller's address.
|
||||
*/
|
||||
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
|
||||
|
||||
/**
|
||||
* @dev Returns the interface hash for an `interfaceName`, as defined in the
|
||||
* corresponding
|
||||
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the ERC].
|
||||
*/
|
||||
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
|
||||
|
||||
/**
|
||||
* @notice Updates the cache with whether the contract implements an ERC-165 interface or not.
|
||||
* @param account Address of the contract for which to update the cache.
|
||||
* @param interfaceId ERC-165 interface for which to update the cache.
|
||||
*/
|
||||
function updateERC165Cache(address account, bytes4 interfaceId) external;
|
||||
|
||||
/**
|
||||
* @notice Checks whether a contract implements an ERC-165 interface or not.
|
||||
* If the result is not cached a direct lookup on the contract address is performed.
|
||||
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
|
||||
* {updateERC165Cache} with the contract address.
|
||||
* @param account Address of the contract to check.
|
||||
* @param interfaceId ERC-165 interface to check.
|
||||
* @return True if `account` implements `interfaceId`, false otherwise.
|
||||
*/
|
||||
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
|
||||
|
||||
/**
|
||||
* @notice Checks whether a contract implements an ERC-165 interface or not without using or updating the cache.
|
||||
* @param account Address of the contract to check.
|
||||
* @param interfaceId ERC-165 interface to check.
|
||||
* @return True if `account` implements `interfaceId`, false otherwise.
|
||||
*/
|
||||
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
|
||||
}
|
||||
24
lib_openzeppelin_contracts/contracts/interfaces/IERC1967.sol
Normal file
24
lib_openzeppelin_contracts/contracts/interfaces/IERC1967.sol
Normal file
@@ -0,0 +1,24 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
|
||||
*/
|
||||
interface IERC1967 {
|
||||
/**
|
||||
* @dev Emitted when the implementation is upgraded.
|
||||
*/
|
||||
event Upgraded(address indexed implementation);
|
||||
|
||||
/**
|
||||
* @dev Emitted when the admin account has changed.
|
||||
*/
|
||||
event AdminChanged(address previousAdmin, address newAdmin);
|
||||
|
||||
/**
|
||||
* @dev Emitted when the beacon is changed.
|
||||
*/
|
||||
event BeaconUpgraded(address indexed beacon);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "../token/ERC20/IERC20.sol";
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20Metadata.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
|
||||
19
lib_openzeppelin_contracts/contracts/interfaces/IERC2309.sol
Normal file
19
lib_openzeppelin_contracts/contracts/interfaces/IERC2309.sol
Normal file
@@ -0,0 +1,19 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC2309.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev ERC-2309: ERC-721 Consecutive Transfer Extension.
|
||||
*/
|
||||
interface IERC2309 {
|
||||
/**
|
||||
* @dev Emitted when the tokens from `fromTokenId` to `toTokenId` are transferred from `fromAddress` to `toAddress`.
|
||||
*/
|
||||
event ConsecutiveTransfer(
|
||||
uint256 indexed fromTokenId,
|
||||
uint256 toTokenId,
|
||||
address indexed fromAddress,
|
||||
address indexed toAddress
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC2612.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20Permit} from "../token/ERC20/extensions/IERC20Permit.sol";
|
||||
|
||||
interface IERC2612 is IERC20Permit {}
|
||||
23
lib_openzeppelin_contracts/contracts/interfaces/IERC2981.sol
Normal file
23
lib_openzeppelin_contracts/contracts/interfaces/IERC2981.sol
Normal file
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC2981.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "../utils/introspection/IERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface for the NFT Royalty Standard.
|
||||
*
|
||||
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
|
||||
* support for royalty payments across all NFT marketplaces and ecosystem participants.
|
||||
*/
|
||||
interface IERC2981 is IERC165 {
|
||||
/**
|
||||
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
|
||||
* exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
|
||||
*/
|
||||
function royaltyInfo(
|
||||
uint256 tokenId,
|
||||
uint256 salePrice
|
||||
) external view returns (address receiver, uint256 royaltyAmount);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC3156.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC3156FlashBorrower} from "./IERC3156FlashBorrower.sol";
|
||||
import {IERC3156FlashLender} from "./IERC3156FlashLender.sol";
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC3156FlashBorrower.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-3156 FlashBorrower, as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
|
||||
*/
|
||||
interface IERC3156FlashBorrower {
|
||||
/**
|
||||
* @dev Receive a flash loan.
|
||||
* @param initiator The initiator of the loan.
|
||||
* @param token The loan currency.
|
||||
* @param amount The amount of tokens lent.
|
||||
* @param fee The additional amount of tokens to repay.
|
||||
* @param data Arbitrary data structure, intended to contain user-defined parameters.
|
||||
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
|
||||
*/
|
||||
function onFlashLoan(
|
||||
address initiator,
|
||||
address token,
|
||||
uint256 amount,
|
||||
uint256 fee,
|
||||
bytes calldata data
|
||||
) external returns (bytes32);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC3156FlashLender.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC3156FlashBorrower} from "./IERC3156FlashBorrower.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-3156 FlashLender, as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
|
||||
*/
|
||||
interface IERC3156FlashLender {
|
||||
/**
|
||||
* @dev The amount of currency available to be lended.
|
||||
* @param token The loan currency.
|
||||
* @return The amount of `token` that can be borrowed.
|
||||
*/
|
||||
function maxFlashLoan(address token) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev The fee to be charged for a given loan.
|
||||
* @param token The loan currency.
|
||||
* @param amount The amount of tokens lent.
|
||||
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
|
||||
*/
|
||||
function flashFee(address token, uint256 amount) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Initiate a flash loan.
|
||||
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
|
||||
* @param token The loan currency.
|
||||
* @param amount The amount of tokens lent.
|
||||
* @param data Arbitrary data structure, intended to contain user-defined parameters.
|
||||
*/
|
||||
function flashLoan(
|
||||
IERC3156FlashBorrower receiver,
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata data
|
||||
) external returns (bool);
|
||||
}
|
||||
230
lib_openzeppelin_contracts/contracts/interfaces/IERC4626.sol
Normal file
230
lib_openzeppelin_contracts/contracts/interfaces/IERC4626.sol
Normal file
@@ -0,0 +1,230 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "../token/ERC20/IERC20.sol";
|
||||
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
|
||||
*/
|
||||
interface IERC4626 is IERC20, IERC20Metadata {
|
||||
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
|
||||
|
||||
event Withdraw(
|
||||
address indexed sender,
|
||||
address indexed receiver,
|
||||
address indexed owner,
|
||||
uint256 assets,
|
||||
uint256 shares
|
||||
);
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
|
||||
*
|
||||
* - MUST be an ERC-20 token contract.
|
||||
* - MUST NOT revert.
|
||||
*/
|
||||
function asset() external view returns (address assetTokenAddress);
|
||||
|
||||
/**
|
||||
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
|
||||
*
|
||||
* - SHOULD include any compounding that occurs from yield.
|
||||
* - MUST be inclusive of any fees that are charged against assets in the Vault.
|
||||
* - MUST NOT revert.
|
||||
*/
|
||||
function totalAssets() external view returns (uint256 totalManagedAssets);
|
||||
|
||||
/**
|
||||
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
|
||||
* scenario where all the conditions are met.
|
||||
*
|
||||
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
|
||||
* - MUST NOT show any variations depending on the caller.
|
||||
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
|
||||
* - MUST NOT revert.
|
||||
*
|
||||
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
|
||||
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
|
||||
* from.
|
||||
*/
|
||||
function convertToShares(uint256 assets) external view returns (uint256 shares);
|
||||
|
||||
/**
|
||||
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
|
||||
* scenario where all the conditions are met.
|
||||
*
|
||||
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
|
||||
* - MUST NOT show any variations depending on the caller.
|
||||
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
|
||||
* - MUST NOT revert.
|
||||
*
|
||||
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
|
||||
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
|
||||
* from.
|
||||
*/
|
||||
function convertToAssets(uint256 shares) external view returns (uint256 assets);
|
||||
|
||||
/**
|
||||
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
|
||||
* through a deposit call.
|
||||
*
|
||||
* - MUST return a limited value if receiver is subject to some deposit limit.
|
||||
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
|
||||
* - MUST NOT revert.
|
||||
*/
|
||||
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
|
||||
|
||||
/**
|
||||
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
|
||||
* current on-chain conditions.
|
||||
*
|
||||
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
|
||||
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
|
||||
* in the same transaction.
|
||||
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
|
||||
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
|
||||
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
|
||||
* - MUST NOT revert.
|
||||
*
|
||||
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
|
||||
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
|
||||
*/
|
||||
function previewDeposit(uint256 assets) external view returns (uint256 shares);
|
||||
|
||||
/**
|
||||
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
|
||||
*
|
||||
* - MUST emit the Deposit event.
|
||||
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
|
||||
* deposit execution, and are accounted for during deposit.
|
||||
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
|
||||
* approving enough underlying tokens to the Vault contract, etc).
|
||||
*
|
||||
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
|
||||
*/
|
||||
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
|
||||
|
||||
/**
|
||||
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
|
||||
* - MUST return a limited value if receiver is subject to some mint limit.
|
||||
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
|
||||
* - MUST NOT revert.
|
||||
*/
|
||||
function maxMint(address receiver) external view returns (uint256 maxShares);
|
||||
|
||||
/**
|
||||
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
|
||||
* current on-chain conditions.
|
||||
*
|
||||
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
|
||||
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
|
||||
* same transaction.
|
||||
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
|
||||
* would be accepted, regardless if the user has enough tokens approved, etc.
|
||||
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
|
||||
* - MUST NOT revert.
|
||||
*
|
||||
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
|
||||
* share price or some other type of condition, meaning the depositor will lose assets by minting.
|
||||
*/
|
||||
function previewMint(uint256 shares) external view returns (uint256 assets);
|
||||
|
||||
/**
|
||||
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
|
||||
*
|
||||
* - MUST emit the Deposit event.
|
||||
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
|
||||
* execution, and are accounted for during mint.
|
||||
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
|
||||
* approving enough underlying tokens to the Vault contract, etc).
|
||||
*
|
||||
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
|
||||
*/
|
||||
function mint(uint256 shares, address receiver) external returns (uint256 assets);
|
||||
|
||||
/**
|
||||
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
|
||||
* Vault, through a withdraw call.
|
||||
*
|
||||
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
|
||||
* - MUST NOT revert.
|
||||
*/
|
||||
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
|
||||
|
||||
/**
|
||||
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
|
||||
* given current on-chain conditions.
|
||||
*
|
||||
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
|
||||
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
|
||||
* called
|
||||
* in the same transaction.
|
||||
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
|
||||
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
|
||||
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
|
||||
* - MUST NOT revert.
|
||||
*
|
||||
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
|
||||
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
|
||||
*/
|
||||
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
|
||||
|
||||
/**
|
||||
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
|
||||
*
|
||||
* - MUST emit the Withdraw event.
|
||||
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
|
||||
* withdraw execution, and are accounted for during withdraw.
|
||||
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
|
||||
* not having enough shares, etc).
|
||||
*
|
||||
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
|
||||
* Those methods should be performed separately.
|
||||
*/
|
||||
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
|
||||
|
||||
/**
|
||||
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
|
||||
* through a redeem call.
|
||||
*
|
||||
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
|
||||
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
|
||||
* - MUST NOT revert.
|
||||
*/
|
||||
function maxRedeem(address owner) external view returns (uint256 maxShares);
|
||||
|
||||
/**
|
||||
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
|
||||
* given current on-chain conditions.
|
||||
*
|
||||
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
|
||||
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
|
||||
* same transaction.
|
||||
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
|
||||
* redemption would be accepted, regardless if the user has enough shares, etc.
|
||||
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
|
||||
* - MUST NOT revert.
|
||||
*
|
||||
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
|
||||
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
|
||||
*/
|
||||
function previewRedeem(uint256 shares) external view returns (uint256 assets);
|
||||
|
||||
/**
|
||||
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
|
||||
*
|
||||
* - MUST emit the Withdraw event.
|
||||
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
|
||||
* redeem execution, and are accounted for during redeem.
|
||||
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
|
||||
* not having enough shares, etc).
|
||||
*
|
||||
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
|
||||
* Those methods should be performed separately.
|
||||
*/
|
||||
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
|
||||
}
|
||||
20
lib_openzeppelin_contracts/contracts/interfaces/IERC4906.sol
Normal file
20
lib_openzeppelin_contracts/contracts/interfaces/IERC4906.sol
Normal file
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4906.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "./IERC165.sol";
|
||||
import {IERC721} from "./IERC721.sol";
|
||||
|
||||
/// @title ERC-721 Metadata Update Extension
|
||||
interface IERC4906 is IERC165, IERC721 {
|
||||
/// @dev This event emits when the metadata of a token is changed.
|
||||
/// So that the third-party platforms such as NFT market could
|
||||
/// timely update the images and related attributes of the NFT.
|
||||
event MetadataUpdate(uint256 _tokenId);
|
||||
|
||||
/// @dev This event emits when the metadata of a range of tokens is changed.
|
||||
/// So that the third-party platforms such as NFT market could
|
||||
/// timely update the images and related attributes of the NFTs.
|
||||
event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
|
||||
}
|
||||
28
lib_openzeppelin_contracts/contracts/interfaces/IERC5267.sol
Normal file
28
lib_openzeppelin_contracts/contracts/interfaces/IERC5267.sol
Normal file
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
interface IERC5267 {
|
||||
/**
|
||||
* @dev MAY be emitted to signal that the domain could have changed.
|
||||
*/
|
||||
event EIP712DomainChanged();
|
||||
|
||||
/**
|
||||
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
|
||||
* signature.
|
||||
*/
|
||||
function eip712Domain()
|
||||
external
|
||||
view
|
||||
returns (
|
||||
bytes1 fields,
|
||||
string memory name,
|
||||
string memory version,
|
||||
uint256 chainId,
|
||||
address verifyingContract,
|
||||
bytes32 salt,
|
||||
uint256[] memory extensions
|
||||
);
|
||||
}
|
||||
16
lib_openzeppelin_contracts/contracts/interfaces/IERC5313.sol
Normal file
16
lib_openzeppelin_contracts/contracts/interfaces/IERC5313.sol
Normal file
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5313.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface for the Light Contract Ownership Standard.
|
||||
*
|
||||
* A standardized minimal interface required to identify an account that controls a contract
|
||||
*/
|
||||
interface IERC5313 {
|
||||
/**
|
||||
* @dev Gets the address of the owner.
|
||||
*/
|
||||
function owner() external view returns (address);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5805.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IVotes} from "../governance/utils/IVotes.sol";
|
||||
import {IERC6372} from "./IERC6372.sol";
|
||||
|
||||
interface IERC5805 is IERC6372, IVotes {}
|
||||
17
lib_openzeppelin_contracts/contracts/interfaces/IERC6372.sol
Normal file
17
lib_openzeppelin_contracts/contracts/interfaces/IERC6372.sol
Normal file
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC6372.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
interface IERC6372 {
|
||||
/**
|
||||
* @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).
|
||||
*/
|
||||
function clock() external view returns (uint48);
|
||||
|
||||
/**
|
||||
* @dev Description of the clock
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function CLOCK_MODE() external view returns (string memory);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721} from "../token/ERC721/IERC721.sol";
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721Enumerable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721Enumerable} from "../token/ERC721/extensions/IERC721Enumerable.sol";
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721Metadata.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721Metadata} from "../token/ERC721/extensions/IERC721Metadata.sol";
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721Receiver.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721Receiver} from "../token/ERC721/IERC721Receiver.sol";
|
||||
200
lib_openzeppelin_contracts/contracts/interfaces/IERC777.sol
Normal file
200
lib_openzeppelin_contracts/contracts/interfaces/IERC777.sol
Normal file
@@ -0,0 +1,200 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC777.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-777 Token standard as defined in the ERC.
|
||||
*
|
||||
* This contract uses the
|
||||
* https://eips.ethereum.org/EIPS/eip-1820[ERC-1820 registry standard] to let
|
||||
* token holders and recipients react to token movements by using setting implementers
|
||||
* for the associated interfaces in said registry. See {IERC1820Registry} and
|
||||
* {IERC1820Implementer}.
|
||||
*/
|
||||
interface IERC777 {
|
||||
/**
|
||||
* @dev Emitted when `amount` tokens are created by `operator` and assigned to `to`.
|
||||
*
|
||||
* Note that some additional user `data` and `operatorData` can be logged in the event.
|
||||
*/
|
||||
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `operator` destroys `amount` tokens from `account`.
|
||||
*
|
||||
* Note that some additional user `data` and `operatorData` can be logged in the event.
|
||||
*/
|
||||
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `operator` is made operator for `tokenHolder`.
|
||||
*/
|
||||
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `operator` is revoked its operator status for `tokenHolder`.
|
||||
*/
|
||||
event RevokedOperator(address indexed operator, address indexed tokenHolder);
|
||||
|
||||
/**
|
||||
* @dev Returns the name of the token.
|
||||
*/
|
||||
function name() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @dev Returns the symbol of the token, usually a shorter version of the
|
||||
* name.
|
||||
*/
|
||||
function symbol() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @dev Returns the smallest part of the token that is not divisible. This
|
||||
* means all token operations (creation, movement and destruction) must have
|
||||
* amounts that are a multiple of this number.
|
||||
*
|
||||
* For most token contracts, this value will equal 1.
|
||||
*/
|
||||
function granularity() external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the amount of tokens in existence.
|
||||
*/
|
||||
function totalSupply() external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the amount of tokens owned by an account (`owner`).
|
||||
*/
|
||||
function balanceOf(address owner) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Moves `amount` tokens from the caller's account to `recipient`.
|
||||
*
|
||||
* If send or receive hooks are registered for the caller and `recipient`,
|
||||
* the corresponding functions will be called with `data` and empty
|
||||
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
|
||||
*
|
||||
* Emits a {Sent} event.
|
||||
*
|
||||
* Requirements
|
||||
*
|
||||
* - the caller must have at least `amount` tokens.
|
||||
* - `recipient` cannot be the zero address.
|
||||
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
|
||||
* interface.
|
||||
*/
|
||||
function send(address recipient, uint256 amount, bytes calldata data) external;
|
||||
|
||||
/**
|
||||
* @dev Destroys `amount` tokens from the caller's account, reducing the
|
||||
* total supply.
|
||||
*
|
||||
* If a send hook is registered for the caller, the corresponding function
|
||||
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
|
||||
*
|
||||
* Emits a {Burned} event.
|
||||
*
|
||||
* Requirements
|
||||
*
|
||||
* - the caller must have at least `amount` tokens.
|
||||
*/
|
||||
function burn(uint256 amount, bytes calldata data) external;
|
||||
|
||||
/**
|
||||
* @dev Returns true if an account is an operator of `tokenHolder`.
|
||||
* Operators can send and burn tokens on behalf of their owners. All
|
||||
* accounts are their own operator.
|
||||
*
|
||||
* See {operatorSend} and {operatorBurn}.
|
||||
*/
|
||||
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Make an account an operator of the caller.
|
||||
*
|
||||
* See {isOperatorFor}.
|
||||
*
|
||||
* Emits an {AuthorizedOperator} event.
|
||||
*
|
||||
* Requirements
|
||||
*
|
||||
* - `operator` cannot be calling address.
|
||||
*/
|
||||
function authorizeOperator(address operator) external;
|
||||
|
||||
/**
|
||||
* @dev Revoke an account's operator status for the caller.
|
||||
*
|
||||
* See {isOperatorFor} and {defaultOperators}.
|
||||
*
|
||||
* Emits a {RevokedOperator} event.
|
||||
*
|
||||
* Requirements
|
||||
*
|
||||
* - `operator` cannot be calling address.
|
||||
*/
|
||||
function revokeOperator(address operator) external;
|
||||
|
||||
/**
|
||||
* @dev Returns the list of default operators. These accounts are operators
|
||||
* for all token holders, even if {authorizeOperator} was never called on
|
||||
* them.
|
||||
*
|
||||
* This list is immutable, but individual holders may revoke these via
|
||||
* {revokeOperator}, in which case {isOperatorFor} will return false.
|
||||
*/
|
||||
function defaultOperators() external view returns (address[] memory);
|
||||
|
||||
/**
|
||||
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
|
||||
* be an operator of `sender`.
|
||||
*
|
||||
* If send or receive hooks are registered for `sender` and `recipient`,
|
||||
* the corresponding functions will be called with `data` and
|
||||
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
|
||||
*
|
||||
* Emits a {Sent} event.
|
||||
*
|
||||
* Requirements
|
||||
*
|
||||
* - `sender` cannot be the zero address.
|
||||
* - `sender` must have at least `amount` tokens.
|
||||
* - the caller must be an operator for `sender`.
|
||||
* - `recipient` cannot be the zero address.
|
||||
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
|
||||
* interface.
|
||||
*/
|
||||
function operatorSend(
|
||||
address sender,
|
||||
address recipient,
|
||||
uint256 amount,
|
||||
bytes calldata data,
|
||||
bytes calldata operatorData
|
||||
) external;
|
||||
|
||||
/**
|
||||
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
|
||||
* The caller must be an operator of `account`.
|
||||
*
|
||||
* If a send hook is registered for `account`, the corresponding function
|
||||
* will be called with `data` and `operatorData`. See {IERC777Sender}.
|
||||
*
|
||||
* Emits a {Burned} event.
|
||||
*
|
||||
* Requirements
|
||||
*
|
||||
* - `account` cannot be the zero address.
|
||||
* - `account` must have at least `amount` tokens.
|
||||
* - the caller must be an operator for `account`.
|
||||
*/
|
||||
function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external;
|
||||
|
||||
event Sent(
|
||||
address indexed operator,
|
||||
address indexed from,
|
||||
address indexed to,
|
||||
uint256 amount,
|
||||
bytes data,
|
||||
bytes operatorData
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC777Recipient.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-777 Tokens Recipient standard as defined in the ERC.
|
||||
*
|
||||
* Accounts can be notified of {IERC777} tokens being sent to them by having a
|
||||
* contract implement this interface (contract holders can be their own
|
||||
* implementer) and registering it on the
|
||||
* https://eips.ethereum.org/EIPS/eip-1820[ERC-1820 global registry].
|
||||
*
|
||||
* See {IERC1820Registry} and {IERC1820Implementer}.
|
||||
*/
|
||||
interface IERC777Recipient {
|
||||
/**
|
||||
* @dev Called by an {IERC777} token contract whenever tokens are being
|
||||
* moved or created into a registered account (`to`). The type of operation
|
||||
* is conveyed by `from` being the zero address or not.
|
||||
*
|
||||
* This call occurs _after_ the token contract's state is updated, so
|
||||
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
|
||||
*
|
||||
* This function may revert to prevent the operation from being executed.
|
||||
*/
|
||||
function tokensReceived(
|
||||
address operator,
|
||||
address from,
|
||||
address to,
|
||||
uint256 amount,
|
||||
bytes calldata userData,
|
||||
bytes calldata operatorData
|
||||
) external;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC777Sender.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-777 Tokens Sender standard as defined in the ERC.
|
||||
*
|
||||
* {IERC777} Token holders can be notified of operations performed on their
|
||||
* tokens by having a contract implement this interface (contract holders can be
|
||||
* their own implementer) and registering it on the
|
||||
* https://eips.ethereum.org/EIPS/eip-1820[ERC-1820 global registry].
|
||||
*
|
||||
* See {IERC1820Registry} and {IERC1820Implementer}.
|
||||
*/
|
||||
interface IERC777Sender {
|
||||
/**
|
||||
* @dev Called by an {IERC777} token contract whenever a registered holder's
|
||||
* (`from`) tokens are about to be moved or destroyed. The type of operation
|
||||
* is conveyed by `to` being the zero address or not.
|
||||
*
|
||||
* This call occurs _before_ the token contract's state is updated, so
|
||||
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
|
||||
*
|
||||
* This function may revert to prevent the operation from being executed.
|
||||
*/
|
||||
function tokensToSend(
|
||||
address operator,
|
||||
address from,
|
||||
address to,
|
||||
uint256 amount,
|
||||
bytes calldata userData,
|
||||
bytes calldata operatorData
|
||||
) external;
|
||||
}
|
||||
82
lib_openzeppelin_contracts/contracts/interfaces/README.adoc
Normal file
82
lib_openzeppelin_contracts/contracts/interfaces/README.adoc
Normal file
@@ -0,0 +1,82 @@
|
||||
= Interfaces
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/interfaces
|
||||
|
||||
== List of standardized interfaces
|
||||
These interfaces are available as `.sol` files, and also as compiler `.json` ABI files (through the npm package). These
|
||||
are useful to interact with third party contracts that implement them.
|
||||
|
||||
- {IERC20}
|
||||
- {IERC20Errors}
|
||||
- {IERC20Metadata}
|
||||
- {IERC165}
|
||||
- {IERC721}
|
||||
- {IERC721Receiver}
|
||||
- {IERC721Enumerable}
|
||||
- {IERC721Metadata}
|
||||
- {IERC721Errors}
|
||||
- {IERC777}
|
||||
- {IERC777Recipient}
|
||||
- {IERC777Sender}
|
||||
- {IERC1155}
|
||||
- {IERC1155Receiver}
|
||||
- {IERC1155MetadataURI}
|
||||
- {IERC1155Errors}
|
||||
- {IERC1271}
|
||||
- {IERC1363}
|
||||
- {IERC1363Receiver}
|
||||
- {IERC1363Spender}
|
||||
- {IERC1820Implementer}
|
||||
- {IERC1820Registry}
|
||||
- {IERC1822Proxiable}
|
||||
- {IERC2612}
|
||||
- {IERC2981}
|
||||
- {IERC3156FlashLender}
|
||||
- {IERC3156FlashBorrower}
|
||||
- {IERC4626}
|
||||
- {IERC4906}
|
||||
- {IERC5267}
|
||||
- {IERC5313}
|
||||
- {IERC5805}
|
||||
- {IERC6372}
|
||||
|
||||
== Detailed ABI
|
||||
|
||||
{{IERC20Errors}}
|
||||
|
||||
{{IERC721Errors}}
|
||||
|
||||
{{IERC1155Errors}}
|
||||
|
||||
{{IERC1271}}
|
||||
|
||||
{{IERC1363}}
|
||||
|
||||
{{IERC1363Receiver}}
|
||||
|
||||
{{IERC1363Spender}}
|
||||
|
||||
{{IERC1820Implementer}}
|
||||
|
||||
{{IERC1820Registry}}
|
||||
|
||||
{{IERC1822Proxiable}}
|
||||
|
||||
{{IERC2612}}
|
||||
|
||||
{{IERC2981}}
|
||||
|
||||
{{IERC3156FlashLender}}
|
||||
|
||||
{{IERC3156FlashBorrower}}
|
||||
|
||||
{{IERC4626}}
|
||||
|
||||
{{IERC5313}}
|
||||
|
||||
{{IERC5267}}
|
||||
|
||||
{{IERC5805}}
|
||||
|
||||
{{IERC6372}}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
|
||||
* proxy whose upgrades are fully controlled by the current implementation.
|
||||
*/
|
||||
interface IERC1822Proxiable {
|
||||
/**
|
||||
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
|
||||
* address.
|
||||
*
|
||||
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
|
||||
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
|
||||
* function revert if invoked through a proxy.
|
||||
*/
|
||||
function proxiableUUID() external view returns (bytes32);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Standard ERC-20 Errors
|
||||
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
|
||||
*/
|
||||
interface IERC20Errors {
|
||||
/**
|
||||
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
* @param balance Current balance for the interacting account.
|
||||
* @param needed Minimum amount required to perform a transfer.
|
||||
*/
|
||||
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `sender`. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
*/
|
||||
error ERC20InvalidSender(address sender);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `receiver`. Used in transfers.
|
||||
* @param receiver Address to which tokens are being transferred.
|
||||
*/
|
||||
error ERC20InvalidReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
|
||||
* @param spender Address that may be allowed to operate on tokens without being their owner.
|
||||
* @param allowance Amount of tokens a `spender` is allowed to operate with.
|
||||
* @param needed Minimum amount required to perform a transfer.
|
||||
*/
|
||||
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
|
||||
* @param approver Address initiating an approval operation.
|
||||
*/
|
||||
error ERC20InvalidApprover(address approver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
|
||||
* @param spender Address that may be allowed to operate on tokens without being their owner.
|
||||
*/
|
||||
error ERC20InvalidSpender(address spender);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Standard ERC-721 Errors
|
||||
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
|
||||
*/
|
||||
interface IERC721Errors {
|
||||
/**
|
||||
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
|
||||
* Used in balance queries.
|
||||
* @param owner Address of the current owner of a token.
|
||||
*/
|
||||
error ERC721InvalidOwner(address owner);
|
||||
|
||||
/**
|
||||
* @dev Indicates a `tokenId` whose `owner` is the zero address.
|
||||
* @param tokenId Identifier number of a token.
|
||||
*/
|
||||
error ERC721NonexistentToken(uint256 tokenId);
|
||||
|
||||
/**
|
||||
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
* @param tokenId Identifier number of a token.
|
||||
* @param owner Address of the current owner of a token.
|
||||
*/
|
||||
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `sender`. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
*/
|
||||
error ERC721InvalidSender(address sender);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `receiver`. Used in transfers.
|
||||
* @param receiver Address to which tokens are being transferred.
|
||||
*/
|
||||
error ERC721InvalidReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
|
||||
* @param operator Address that may be allowed to operate on tokens without being their owner.
|
||||
* @param tokenId Identifier number of a token.
|
||||
*/
|
||||
error ERC721InsufficientApproval(address operator, uint256 tokenId);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
|
||||
* @param approver Address initiating an approval operation.
|
||||
*/
|
||||
error ERC721InvalidApprover(address approver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
|
||||
* @param operator Address that may be allowed to operate on tokens without being their owner.
|
||||
*/
|
||||
error ERC721InvalidOperator(address operator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Standard ERC-1155 Errors
|
||||
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
|
||||
*/
|
||||
interface IERC1155Errors {
|
||||
/**
|
||||
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
* @param balance Current balance for the interacting account.
|
||||
* @param needed Minimum amount required to perform a transfer.
|
||||
* @param tokenId Identifier number of a token.
|
||||
*/
|
||||
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `sender`. Used in transfers.
|
||||
* @param sender Address whose tokens are being transferred.
|
||||
*/
|
||||
error ERC1155InvalidSender(address sender);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `receiver`. Used in transfers.
|
||||
* @param receiver Address to which tokens are being transferred.
|
||||
*/
|
||||
error ERC1155InvalidReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
|
||||
* @param operator Address that may be allowed to operate on tokens without being their owner.
|
||||
* @param owner Address of the current owner of a token.
|
||||
*/
|
||||
error ERC1155MissingApprovalForAll(address operator, address owner);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
|
||||
* @param approver Address initiating an approval operation.
|
||||
*/
|
||||
error ERC1155InvalidApprover(address approver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
|
||||
* @param operator Address that may be allowed to operate on tokens without being their owner.
|
||||
*/
|
||||
error ERC1155InvalidOperator(address operator);
|
||||
|
||||
/**
|
||||
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
|
||||
* Used in batch transfers.
|
||||
* @param idsLength Length of the array of token identifiers
|
||||
* @param valuesLength Length of the array of token amounts
|
||||
*/
|
||||
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.1) (metatx/ERC2771Context.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Context} from "../utils/Context.sol";
|
||||
|
||||
/**
|
||||
* @dev Context variant with ERC-2771 support.
|
||||
*
|
||||
* WARNING: Avoid using this pattern in contracts that rely in a specific calldata length as they'll
|
||||
* be affected by any forwarder whose `msg.data` is suffixed with the `from` address according to the ERC-2771
|
||||
* specification adding the address size in bytes (20) to the calldata size. An example of an unexpected
|
||||
* behavior could be an unintended fallback (or another function) invocation while trying to invoke the `receive`
|
||||
* function only accessible if `msg.data.length == 0`.
|
||||
*
|
||||
* WARNING: The usage of `delegatecall` in this contract is dangerous and may result in context corruption.
|
||||
* Any forwarded request to this contract triggering a `delegatecall` to itself will result in an invalid {_msgSender}
|
||||
* recovery.
|
||||
*/
|
||||
abstract contract ERC2771Context is Context {
|
||||
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
|
||||
address private immutable _trustedForwarder;
|
||||
|
||||
/**
|
||||
* @dev Initializes the contract with a trusted forwarder, which will be able to
|
||||
* invoke functions on this contract on behalf of other accounts.
|
||||
*
|
||||
* NOTE: The trusted forwarder can be replaced by overriding {trustedForwarder}.
|
||||
*/
|
||||
/// @custom:oz-upgrades-unsafe-allow constructor
|
||||
constructor(address trustedForwarder_) {
|
||||
_trustedForwarder = trustedForwarder_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the trusted forwarder.
|
||||
*/
|
||||
function trustedForwarder() public view virtual returns (address) {
|
||||
return _trustedForwarder;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Indicates whether any particular address is the trusted forwarder.
|
||||
*/
|
||||
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
|
||||
return forwarder == trustedForwarder();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Override for `msg.sender`. Defaults to the original `msg.sender` whenever
|
||||
* a call is not performed by the trusted forwarder or the calldata length is less than
|
||||
* 20 bytes (an address length).
|
||||
*/
|
||||
function _msgSender() internal view virtual override returns (address) {
|
||||
uint256 calldataLength = msg.data.length;
|
||||
uint256 contextSuffixLength = _contextSuffixLength();
|
||||
if (isTrustedForwarder(msg.sender) && calldataLength >= contextSuffixLength) {
|
||||
return address(bytes20(msg.data[calldataLength - contextSuffixLength:]));
|
||||
} else {
|
||||
return super._msgSender();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Override for `msg.data`. Defaults to the original `msg.data` whenever
|
||||
* a call is not performed by the trusted forwarder or the calldata length is less than
|
||||
* 20 bytes (an address length).
|
||||
*/
|
||||
function _msgData() internal view virtual override returns (bytes calldata) {
|
||||
uint256 calldataLength = msg.data.length;
|
||||
uint256 contextSuffixLength = _contextSuffixLength();
|
||||
if (isTrustedForwarder(msg.sender) && calldataLength >= contextSuffixLength) {
|
||||
return msg.data[:calldataLength - contextSuffixLength];
|
||||
} else {
|
||||
return super._msgData();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev ERC-2771 specifies the context as being a single address (20 bytes).
|
||||
*/
|
||||
function _contextSuffixLength() internal view virtual override returns (uint256) {
|
||||
return 20;
|
||||
}
|
||||
}
|
||||
371
lib_openzeppelin_contracts/contracts/metatx/ERC2771Forwarder.sol
Normal file
371
lib_openzeppelin_contracts/contracts/metatx/ERC2771Forwarder.sol
Normal file
@@ -0,0 +1,371 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (metatx/ERC2771Forwarder.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC2771Context} from "./ERC2771Context.sol";
|
||||
import {ECDSA} from "../utils/cryptography/ECDSA.sol";
|
||||
import {EIP712} from "../utils/cryptography/EIP712.sol";
|
||||
import {Nonces} from "../utils/Nonces.sol";
|
||||
import {Address} from "../utils/Address.sol";
|
||||
import {Errors} from "../utils/Errors.sol";
|
||||
|
||||
/**
|
||||
* @dev A forwarder compatible with ERC-2771 contracts. See {ERC2771Context}.
|
||||
*
|
||||
* This forwarder operates on forward requests that include:
|
||||
*
|
||||
* * `from`: An address to operate on behalf of. It is required to be equal to the request signer.
|
||||
* * `to`: The address that should be called.
|
||||
* * `value`: The amount of native token to attach with the requested call.
|
||||
* * `gas`: The amount of gas limit that will be forwarded with the requested call.
|
||||
* * `nonce`: A unique transaction ordering identifier to avoid replayability and request invalidation.
|
||||
* * `deadline`: A timestamp after which the request is not executable anymore.
|
||||
* * `data`: Encoded `msg.data` to send with the requested call.
|
||||
*
|
||||
* Relayers are able to submit batches if they are processing a high volume of requests. With high
|
||||
* throughput, relayers may run into limitations of the chain such as limits on the number of
|
||||
* transactions in the mempool. In these cases the recommendation is to distribute the load among
|
||||
* multiple accounts.
|
||||
*
|
||||
* NOTE: Batching requests includes an optional refund for unused `msg.value` that is achieved by
|
||||
* performing a call with empty calldata. While this is within the bounds of ERC-2771 compliance,
|
||||
* if the refund receiver happens to consider the forwarder a trusted forwarder, it MUST properly
|
||||
* handle `msg.data.length == 0`. `ERC2771Context` in OpenZeppelin Contracts versions prior to 4.9.3
|
||||
* do not handle this properly.
|
||||
*
|
||||
* ==== Security Considerations
|
||||
*
|
||||
* If a relayer submits a forward request, it should be willing to pay up to 100% of the gas amount
|
||||
* specified in the request. This contract does not implement any kind of retribution for this gas,
|
||||
* and it is assumed that there is an out of band incentive for relayers to pay for execution on
|
||||
* behalf of signers. Often, the relayer is operated by a project that will consider it a user
|
||||
* acquisition cost.
|
||||
*
|
||||
* By offering to pay for gas, relayers are at risk of having that gas used by an attacker toward
|
||||
* some other purpose that is not aligned with the expected out of band incentives. If you operate a
|
||||
* relayer, consider whitelisting target contracts and function selectors. When relaying ERC-721 or
|
||||
* ERC-1155 transfers specifically, consider rejecting the use of the `data` field, since it can be
|
||||
* used to execute arbitrary code.
|
||||
*/
|
||||
contract ERC2771Forwarder is EIP712, Nonces {
|
||||
using ECDSA for bytes32;
|
||||
|
||||
struct ForwardRequestData {
|
||||
address from;
|
||||
address to;
|
||||
uint256 value;
|
||||
uint256 gas;
|
||||
uint48 deadline;
|
||||
bytes data;
|
||||
bytes signature;
|
||||
}
|
||||
|
||||
bytes32 internal constant _FORWARD_REQUEST_TYPEHASH =
|
||||
keccak256(
|
||||
"ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,uint48 deadline,bytes data)"
|
||||
);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a `ForwardRequest` is executed.
|
||||
*
|
||||
* NOTE: An unsuccessful forward request could be due to an invalid signature, an expired deadline,
|
||||
* or simply a revert in the requested call. The contract guarantees that the relayer is not able to force
|
||||
* the requested call to run out of gas.
|
||||
*/
|
||||
event ExecutedForwardRequest(address indexed signer, uint256 nonce, bool success);
|
||||
|
||||
/**
|
||||
* @dev The request `from` doesn't match with the recovered `signer`.
|
||||
*/
|
||||
error ERC2771ForwarderInvalidSigner(address signer, address from);
|
||||
|
||||
/**
|
||||
* @dev The `requestedValue` doesn't match with the available `msgValue`.
|
||||
*/
|
||||
error ERC2771ForwarderMismatchedValue(uint256 requestedValue, uint256 msgValue);
|
||||
|
||||
/**
|
||||
* @dev The request `deadline` has expired.
|
||||
*/
|
||||
error ERC2771ForwarderExpiredRequest(uint48 deadline);
|
||||
|
||||
/**
|
||||
* @dev The request target doesn't trust the `forwarder`.
|
||||
*/
|
||||
error ERC2771UntrustfulTarget(address target, address forwarder);
|
||||
|
||||
/**
|
||||
* @dev See {EIP712-constructor}.
|
||||
*/
|
||||
constructor(string memory name) EIP712(name, "1") {}
|
||||
|
||||
/**
|
||||
* @dev Returns `true` if a request is valid for a provided `signature` at the current block timestamp.
|
||||
*
|
||||
* A transaction is considered valid when the target trusts this forwarder, the request hasn't expired
|
||||
* (deadline is not met), and the signer matches the `from` parameter of the signed request.
|
||||
*
|
||||
* NOTE: A request may return false here but it won't cause {executeBatch} to revert if a refund
|
||||
* receiver is provided.
|
||||
*/
|
||||
function verify(ForwardRequestData calldata request) public view virtual returns (bool) {
|
||||
(bool isTrustedForwarder, bool active, bool signerMatch, ) = _validate(request);
|
||||
return isTrustedForwarder && active && signerMatch;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Executes a `request` on behalf of `signature`'s signer using the ERC-2771 protocol. The gas
|
||||
* provided to the requested call may not be exactly the amount requested, but the call will not run
|
||||
* out of gas. Will revert if the request is invalid or the call reverts, in this case the nonce is not consumed.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The request value should be equal to the provided `msg.value`.
|
||||
* - The request should be valid according to {verify}.
|
||||
*/
|
||||
function execute(ForwardRequestData calldata request) public payable virtual {
|
||||
// We make sure that msg.value and request.value match exactly.
|
||||
// If the request is invalid or the call reverts, this whole function
|
||||
// will revert, ensuring value isn't stuck.
|
||||
if (msg.value != request.value) {
|
||||
revert ERC2771ForwarderMismatchedValue(request.value, msg.value);
|
||||
}
|
||||
|
||||
if (!_execute(request, true)) {
|
||||
revert Errors.FailedCall();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Batch version of {execute} with optional refunding and atomic execution.
|
||||
*
|
||||
* In case a batch contains at least one invalid request (see {verify}), the
|
||||
* request will be skipped and the `refundReceiver` parameter will receive back the
|
||||
* unused requested value at the end of the execution. This is done to prevent reverting
|
||||
* the entire batch when a request is invalid or has already been submitted.
|
||||
*
|
||||
* If the `refundReceiver` is the `address(0)`, this function will revert when at least
|
||||
* one of the requests was not valid instead of skipping it. This could be useful if
|
||||
* a batch is required to get executed atomically (at least at the top-level). For example,
|
||||
* refunding (and thus atomicity) can be opt-out if the relayer is using a service that avoids
|
||||
* including reverted transactions.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The sum of the requests' values should be equal to the provided `msg.value`.
|
||||
* - All of the requests should be valid (see {verify}) when `refundReceiver` is the zero address.
|
||||
*
|
||||
* NOTE: Setting a zero `refundReceiver` guarantees an all-or-nothing requests execution only for
|
||||
* the first-level forwarded calls. In case a forwarded request calls to a contract with another
|
||||
* subcall, the second-level call may revert without the top-level call reverting.
|
||||
*/
|
||||
function executeBatch(
|
||||
ForwardRequestData[] calldata requests,
|
||||
address payable refundReceiver
|
||||
) public payable virtual {
|
||||
bool atomic = refundReceiver == address(0);
|
||||
|
||||
uint256 requestsValue;
|
||||
uint256 refundValue;
|
||||
|
||||
for (uint256 i; i < requests.length; ++i) {
|
||||
requestsValue += requests[i].value;
|
||||
bool success = _execute(requests[i], atomic);
|
||||
if (!success) {
|
||||
refundValue += requests[i].value;
|
||||
}
|
||||
}
|
||||
|
||||
// The batch should revert if there's a mismatched msg.value provided
|
||||
// to avoid request value tampering
|
||||
if (requestsValue != msg.value) {
|
||||
revert ERC2771ForwarderMismatchedValue(requestsValue, msg.value);
|
||||
}
|
||||
|
||||
// Some requests with value were invalid (possibly due to frontrunning).
|
||||
// To avoid leaving ETH in the contract this value is refunded.
|
||||
if (refundValue != 0) {
|
||||
// We know refundReceiver != address(0) && requestsValue == msg.value
|
||||
// meaning we can ensure refundValue is not taken from the original contract's balance
|
||||
// and refundReceiver is a known account.
|
||||
Address.sendValue(refundReceiver, refundValue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Validates if the provided request can be executed at current block timestamp with
|
||||
* the given `request.signature` on behalf of `request.signer`.
|
||||
*/
|
||||
function _validate(
|
||||
ForwardRequestData calldata request
|
||||
) internal view virtual returns (bool isTrustedForwarder, bool active, bool signerMatch, address signer) {
|
||||
(bool isValid, address recovered) = _recoverForwardRequestSigner(request);
|
||||
|
||||
return (
|
||||
_isTrustedByTarget(request.to),
|
||||
request.deadline >= block.timestamp,
|
||||
isValid && recovered == request.from,
|
||||
recovered
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns a tuple with the recovered the signer of an EIP712 forward request message hash
|
||||
* and a boolean indicating if the signature is valid.
|
||||
*
|
||||
* NOTE: The signature is considered valid if {ECDSA-tryRecover} indicates no recover error for it.
|
||||
*/
|
||||
function _recoverForwardRequestSigner(
|
||||
ForwardRequestData calldata request
|
||||
) internal view virtual returns (bool, address) {
|
||||
(address recovered, ECDSA.RecoverError err, ) = _hashTypedDataV4(
|
||||
keccak256(
|
||||
abi.encode(
|
||||
_FORWARD_REQUEST_TYPEHASH,
|
||||
request.from,
|
||||
request.to,
|
||||
request.value,
|
||||
request.gas,
|
||||
nonces(request.from),
|
||||
request.deadline,
|
||||
keccak256(request.data)
|
||||
)
|
||||
)
|
||||
).tryRecover(request.signature);
|
||||
|
||||
return (err == ECDSA.RecoverError.NoError, recovered);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Validates and executes a signed request returning the request call `success` value.
|
||||
*
|
||||
* Internal function without msg.value validation.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The caller must have provided enough gas to forward with the call.
|
||||
* - The request must be valid (see {verify}) if the `requireValidRequest` is true.
|
||||
*
|
||||
* Emits an {ExecutedForwardRequest} event.
|
||||
*
|
||||
* IMPORTANT: Using this function doesn't check that all the `msg.value` was sent, potentially
|
||||
* leaving value stuck in the contract.
|
||||
*/
|
||||
function _execute(
|
||||
ForwardRequestData calldata request,
|
||||
bool requireValidRequest
|
||||
) internal virtual returns (bool success) {
|
||||
(bool isTrustedForwarder, bool active, bool signerMatch, address signer) = _validate(request);
|
||||
|
||||
// Need to explicitly specify if a revert is required since non-reverting is default for
|
||||
// batches and reversion is opt-in since it could be useful in some scenarios
|
||||
if (requireValidRequest) {
|
||||
if (!isTrustedForwarder) {
|
||||
revert ERC2771UntrustfulTarget(request.to, address(this));
|
||||
}
|
||||
|
||||
if (!active) {
|
||||
revert ERC2771ForwarderExpiredRequest(request.deadline);
|
||||
}
|
||||
|
||||
if (!signerMatch) {
|
||||
revert ERC2771ForwarderInvalidSigner(signer, request.from);
|
||||
}
|
||||
}
|
||||
|
||||
// Ignore an invalid request because requireValidRequest = false
|
||||
if (isTrustedForwarder && signerMatch && active) {
|
||||
// Nonce should be used before the call to prevent reusing by reentrancy
|
||||
uint256 currentNonce = _useNonce(signer);
|
||||
|
||||
uint256 reqGas = request.gas;
|
||||
address to = request.to;
|
||||
uint256 value = request.value;
|
||||
bytes memory data = abi.encodePacked(request.data, request.from);
|
||||
|
||||
uint256 gasLeft;
|
||||
|
||||
assembly {
|
||||
success := call(reqGas, to, value, add(data, 0x20), mload(data), 0, 0)
|
||||
gasLeft := gas()
|
||||
}
|
||||
|
||||
_checkForwardedGas(gasLeft, request);
|
||||
|
||||
emit ExecutedForwardRequest(signer, currentNonce, success);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns whether the target trusts this forwarder.
|
||||
*
|
||||
* This function performs a static call to the target contract calling the
|
||||
* {ERC2771Context-isTrustedForwarder} function.
|
||||
*/
|
||||
function _isTrustedByTarget(address target) private view returns (bool) {
|
||||
bytes memory encodedParams = abi.encodeCall(ERC2771Context.isTrustedForwarder, (address(this)));
|
||||
|
||||
bool success;
|
||||
uint256 returnSize;
|
||||
uint256 returnValue;
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
// Perform the staticcall and save the result in the scratch space.
|
||||
// | Location | Content | Content (Hex) |
|
||||
// |-----------|----------|--------------------------------------------------------------------|
|
||||
// | | | result ↓ |
|
||||
// | 0x00:0x1F | selector | 0x0000000000000000000000000000000000000000000000000000000000000001 |
|
||||
success := staticcall(gas(), target, add(encodedParams, 0x20), mload(encodedParams), 0, 0x20)
|
||||
returnSize := returndatasize()
|
||||
returnValue := mload(0)
|
||||
}
|
||||
|
||||
return success && returnSize >= 0x20 && returnValue > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Checks if the requested gas was correctly forwarded to the callee.
|
||||
*
|
||||
* As a consequence of https://eips.ethereum.org/EIPS/eip-150[EIP-150]:
|
||||
* - At most `gasleft() - floor(gasleft() / 64)` is forwarded to the callee.
|
||||
* - At least `floor(gasleft() / 64)` is kept in the caller.
|
||||
*
|
||||
* It reverts consuming all the available gas if the forwarded gas is not the requested gas.
|
||||
*
|
||||
* IMPORTANT: The `gasLeft` parameter should be measured exactly at the end of the forwarded call.
|
||||
* Any gas consumed in between will make room for bypassing this check.
|
||||
*/
|
||||
function _checkForwardedGas(uint256 gasLeft, ForwardRequestData calldata request) private pure {
|
||||
// To avoid insufficient gas griefing attacks, as referenced in https://ronan.eth.limo/blog/ethereum-gas-dangers/
|
||||
//
|
||||
// A malicious relayer can attempt to shrink the gas forwarded so that the underlying call reverts out-of-gas
|
||||
// but the forwarding itself still succeeds. In order to make sure that the subcall received sufficient gas,
|
||||
// we will inspect gasleft() after the forwarding.
|
||||
//
|
||||
// Let X be the gas available before the subcall, such that the subcall gets at most X * 63 / 64.
|
||||
// We can't know X after CALL dynamic costs, but we want it to be such that X * 63 / 64 >= req.gas.
|
||||
// Let Y be the gas used in the subcall. gasleft() measured immediately after the subcall will be gasleft() = X - Y.
|
||||
// If the subcall ran out of gas, then Y = X * 63 / 64 and gasleft() = X - Y = X / 64.
|
||||
// Under this assumption req.gas / 63 > gasleft() is true is true if and only if
|
||||
// req.gas / 63 > X / 64, or equivalently req.gas > X * 63 / 64.
|
||||
// This means that if the subcall runs out of gas we are able to detect that insufficient gas was passed.
|
||||
//
|
||||
// We will now also see that req.gas / 63 > gasleft() implies that req.gas >= X * 63 / 64.
|
||||
// The contract guarantees Y <= req.gas, thus gasleft() = X - Y >= X - req.gas.
|
||||
// - req.gas / 63 > gasleft()
|
||||
// - req.gas / 63 >= X - req.gas
|
||||
// - req.gas >= X * 63 / 64
|
||||
// In other words if req.gas < X * 63 / 64 then req.gas / 63 <= gasleft(), thus if the relayer behaves honestly
|
||||
// the forwarding does not revert.
|
||||
if (gasLeft < request.gas / 63) {
|
||||
// We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since
|
||||
// neither revert or assert consume all gas since Solidity 0.8.20
|
||||
// https://docs.soliditylang.org/en/v0.8.20/control-structures.html#panic-via-assert-and-error-via-require
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
invalid()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
17
lib_openzeppelin_contracts/contracts/metatx/README.adoc
Normal file
17
lib_openzeppelin_contracts/contracts/metatx/README.adoc
Normal file
@@ -0,0 +1,17 @@
|
||||
= Meta Transactions
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/metatx
|
||||
|
||||
This directory includes contracts for adding meta-transaction capabilities (i.e. abstracting the execution context from the transaction origin) following the https://eips.ethereum.org/EIPS/eip-2771[ERC-2771 specification].
|
||||
|
||||
- {ERC2771Context}: Provides a mechanism to override the sender and calldata of the execution context (`msg.sender` and `msg.data`) with a custom value specified by a trusted forwarder.
|
||||
- {ERC2771Forwarder}: A production-ready forwarder that relays operation requests signed off-chain by an EOA.
|
||||
|
||||
== Core
|
||||
|
||||
{{ERC2771Context}}
|
||||
|
||||
== Utils
|
||||
|
||||
{{ERC2771Forwarder}}
|
||||
@@ -0,0 +1,34 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {AccessManaged} from "../access/manager/AccessManaged.sol";
|
||||
import {StorageSlot} from "../utils/StorageSlot.sol";
|
||||
|
||||
abstract contract AccessManagedTarget is AccessManaged {
|
||||
event CalledRestricted(address caller);
|
||||
event CalledUnrestricted(address caller);
|
||||
event CalledFallback(address caller);
|
||||
|
||||
function fnRestricted() public restricted {
|
||||
emit CalledRestricted(msg.sender);
|
||||
}
|
||||
|
||||
function fnUnrestricted() public {
|
||||
emit CalledUnrestricted(msg.sender);
|
||||
}
|
||||
|
||||
function setIsConsumingScheduledOp(bool isConsuming, bytes32 slot) external {
|
||||
// Memory layout is 0x....<_consumingSchedule (boolean)><authority (address)>
|
||||
bytes32 mask = bytes32(uint256(1 << 160));
|
||||
if (isConsuming) {
|
||||
StorageSlot.getBytes32Slot(slot).value |= mask;
|
||||
} else {
|
||||
StorageSlot.getBytes32Slot(slot).value &= ~mask;
|
||||
}
|
||||
}
|
||||
|
||||
fallback() external {
|
||||
emit CalledFallback(msg.sender);
|
||||
}
|
||||
}
|
||||
127
lib_openzeppelin_contracts/contracts/mocks/ArraysMock.sol
Normal file
127
lib_openzeppelin_contracts/contracts/mocks/ArraysMock.sol
Normal file
@@ -0,0 +1,127 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Arrays} from "../utils/Arrays.sol";
|
||||
|
||||
contract Uint256ArraysMock {
|
||||
using Arrays for uint256[];
|
||||
|
||||
uint256[] private _array;
|
||||
|
||||
constructor(uint256[] memory array) {
|
||||
_array = array;
|
||||
}
|
||||
|
||||
function findUpperBound(uint256 value) external view returns (uint256) {
|
||||
return _array.findUpperBound(value);
|
||||
}
|
||||
|
||||
function lowerBound(uint256 value) external view returns (uint256) {
|
||||
return _array.lowerBound(value);
|
||||
}
|
||||
|
||||
function upperBound(uint256 value) external view returns (uint256) {
|
||||
return _array.upperBound(value);
|
||||
}
|
||||
|
||||
function lowerBoundMemory(uint256[] memory array, uint256 value) external pure returns (uint256) {
|
||||
return array.lowerBoundMemory(value);
|
||||
}
|
||||
|
||||
function upperBoundMemory(uint256[] memory array, uint256 value) external pure returns (uint256) {
|
||||
return array.upperBoundMemory(value);
|
||||
}
|
||||
|
||||
function unsafeAccess(uint256 pos) external view returns (uint256) {
|
||||
return _array.unsafeAccess(pos).value;
|
||||
}
|
||||
|
||||
function sort(uint256[] memory array) external pure returns (uint256[] memory) {
|
||||
return array.sort();
|
||||
}
|
||||
|
||||
function sortReverse(uint256[] memory array) external pure returns (uint256[] memory) {
|
||||
return array.sort(_reverse);
|
||||
}
|
||||
|
||||
function _reverse(uint256 a, uint256 b) private pure returns (bool) {
|
||||
return a > b;
|
||||
}
|
||||
|
||||
function unsafeSetLength(uint256 newLength) external {
|
||||
_array.unsafeSetLength(newLength);
|
||||
}
|
||||
|
||||
function length() external view returns (uint256) {
|
||||
return _array.length;
|
||||
}
|
||||
}
|
||||
|
||||
contract AddressArraysMock {
|
||||
using Arrays for address[];
|
||||
|
||||
address[] private _array;
|
||||
|
||||
constructor(address[] memory array) {
|
||||
_array = array;
|
||||
}
|
||||
|
||||
function unsafeAccess(uint256 pos) external view returns (address) {
|
||||
return _array.unsafeAccess(pos).value;
|
||||
}
|
||||
|
||||
function sort(address[] memory array) external pure returns (address[] memory) {
|
||||
return array.sort();
|
||||
}
|
||||
|
||||
function sortReverse(address[] memory array) external pure returns (address[] memory) {
|
||||
return array.sort(_reverse);
|
||||
}
|
||||
|
||||
function _reverse(address a, address b) private pure returns (bool) {
|
||||
return uint160(a) > uint160(b);
|
||||
}
|
||||
|
||||
function unsafeSetLength(uint256 newLength) external {
|
||||
_array.unsafeSetLength(newLength);
|
||||
}
|
||||
|
||||
function length() external view returns (uint256) {
|
||||
return _array.length;
|
||||
}
|
||||
}
|
||||
|
||||
contract Bytes32ArraysMock {
|
||||
using Arrays for bytes32[];
|
||||
|
||||
bytes32[] private _array;
|
||||
|
||||
constructor(bytes32[] memory array) {
|
||||
_array = array;
|
||||
}
|
||||
|
||||
function unsafeAccess(uint256 pos) external view returns (bytes32) {
|
||||
return _array.unsafeAccess(pos).value;
|
||||
}
|
||||
|
||||
function sort(bytes32[] memory array) external pure returns (bytes32[] memory) {
|
||||
return array.sort();
|
||||
}
|
||||
|
||||
function sortReverse(bytes32[] memory array) external pure returns (bytes32[] memory) {
|
||||
return array.sort(_reverse);
|
||||
}
|
||||
|
||||
function _reverse(bytes32 a, bytes32 b) private pure returns (bool) {
|
||||
return uint256(a) > uint256(b);
|
||||
}
|
||||
|
||||
function unsafeSetLength(uint256 newLength) external {
|
||||
_array.unsafeSetLength(newLength);
|
||||
}
|
||||
|
||||
function length() external view returns (uint256) {
|
||||
return _array.length;
|
||||
}
|
||||
}
|
||||
69
lib_openzeppelin_contracts/contracts/mocks/AuthorityMock.sol
Normal file
69
lib_openzeppelin_contracts/contracts/mocks/AuthorityMock.sol
Normal file
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IAccessManaged} from "../access/manager/IAccessManaged.sol";
|
||||
import {IAuthority} from "../access/manager/IAuthority.sol";
|
||||
|
||||
contract NotAuthorityMock is IAuthority {
|
||||
function canCall(address /* caller */, address /* target */, bytes4 /* selector */) external pure returns (bool) {
|
||||
revert("AuthorityNoDelayMock: not implemented");
|
||||
}
|
||||
}
|
||||
|
||||
contract AuthorityNoDelayMock is IAuthority {
|
||||
bool _immediate;
|
||||
|
||||
function canCall(
|
||||
address /* caller */,
|
||||
address /* target */,
|
||||
bytes4 /* selector */
|
||||
) external view returns (bool immediate) {
|
||||
return _immediate;
|
||||
}
|
||||
|
||||
function _setImmediate(bool immediate) external {
|
||||
_immediate = immediate;
|
||||
}
|
||||
}
|
||||
|
||||
contract AuthorityDelayMock {
|
||||
bool _immediate;
|
||||
uint32 _delay;
|
||||
|
||||
function canCall(
|
||||
address /* caller */,
|
||||
address /* target */,
|
||||
bytes4 /* selector */
|
||||
) external view returns (bool immediate, uint32 delay) {
|
||||
return (_immediate, _delay);
|
||||
}
|
||||
|
||||
function _setImmediate(bool immediate) external {
|
||||
_immediate = immediate;
|
||||
}
|
||||
|
||||
function _setDelay(uint32 delay) external {
|
||||
_delay = delay;
|
||||
}
|
||||
}
|
||||
|
||||
contract AuthorityNoResponse {
|
||||
function canCall(address /* caller */, address /* target */, bytes4 /* selector */) external view {}
|
||||
}
|
||||
|
||||
contract AuthorityObserveIsConsuming {
|
||||
event ConsumeScheduledOpCalled(address caller, bytes data, bytes4 isConsuming);
|
||||
|
||||
function canCall(
|
||||
address /* caller */,
|
||||
address /* target */,
|
||||
bytes4 /* selector */
|
||||
) external pure returns (bool immediate, uint32 delay) {
|
||||
return (false, 1);
|
||||
}
|
||||
|
||||
function consumeScheduledOp(address caller, bytes memory data) public {
|
||||
emit ConsumeScheduledOpCalled(caller, data, IAccessManaged(msg.sender).isConsumingScheduledOp());
|
||||
}
|
||||
}
|
||||
19
lib_openzeppelin_contracts/contracts/mocks/Base64Dirty.sol
Normal file
19
lib_openzeppelin_contracts/contracts/mocks/Base64Dirty.sol
Normal file
@@ -0,0 +1,19 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Base64} from "../utils/Base64.sol";
|
||||
|
||||
contract Base64Dirty {
|
||||
struct A {
|
||||
uint256 value;
|
||||
}
|
||||
|
||||
function encode(bytes memory input) public pure returns (string memory) {
|
||||
A memory unused = A({value: type(uint256).max});
|
||||
// To silence warning
|
||||
unused;
|
||||
|
||||
return Base64.encode(input);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
contract CallReceiverMock {
|
||||
event MockFunctionCalled();
|
||||
event MockFunctionCalledWithArgs(uint256 a, uint256 b);
|
||||
|
||||
uint256[] private _array;
|
||||
|
||||
function mockFunction() public payable returns (string memory) {
|
||||
emit MockFunctionCalled();
|
||||
|
||||
return "0x1234";
|
||||
}
|
||||
|
||||
function mockFunctionEmptyReturn() public payable {
|
||||
emit MockFunctionCalled();
|
||||
}
|
||||
|
||||
function mockFunctionWithArgs(uint256 a, uint256 b) public payable returns (string memory) {
|
||||
emit MockFunctionCalledWithArgs(a, b);
|
||||
|
||||
return "0x1234";
|
||||
}
|
||||
|
||||
function mockFunctionNonPayable() public returns (string memory) {
|
||||
emit MockFunctionCalled();
|
||||
|
||||
return "0x1234";
|
||||
}
|
||||
|
||||
function mockStaticFunction() public pure returns (string memory) {
|
||||
return "0x1234";
|
||||
}
|
||||
|
||||
function mockFunctionRevertsNoReason() public payable {
|
||||
revert();
|
||||
}
|
||||
|
||||
function mockFunctionRevertsReason() public payable {
|
||||
revert("CallReceiverMock: reverting");
|
||||
}
|
||||
|
||||
function mockFunctionThrows() public payable {
|
||||
assert(false);
|
||||
}
|
||||
|
||||
function mockFunctionOutOfGas() public payable {
|
||||
for (uint256 i = 0; ; ++i) {
|
||||
_array.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
function mockFunctionWritesStorage(bytes32 slot, bytes32 value) public returns (string memory) {
|
||||
assembly {
|
||||
sstore(slot, value)
|
||||
}
|
||||
return "0x1234";
|
||||
}
|
||||
}
|
||||
|
||||
contract CallReceiverMockTrustingForwarder is CallReceiverMock {
|
||||
address private _trustedForwarder;
|
||||
|
||||
constructor(address trustedForwarder_) {
|
||||
_trustedForwarder = trustedForwarder_;
|
||||
}
|
||||
|
||||
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
|
||||
return forwarder == _trustedForwarder;
|
||||
}
|
||||
}
|
||||
35
lib_openzeppelin_contracts/contracts/mocks/ContextMock.sol
Normal file
35
lib_openzeppelin_contracts/contracts/mocks/ContextMock.sol
Normal file
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Context} from "../utils/Context.sol";
|
||||
|
||||
contract ContextMock is Context {
|
||||
event Sender(address sender);
|
||||
|
||||
function msgSender() public {
|
||||
emit Sender(_msgSender());
|
||||
}
|
||||
|
||||
event Data(bytes data, uint256 integerValue, string stringValue);
|
||||
|
||||
function msgData(uint256 integerValue, string memory stringValue) public {
|
||||
emit Data(_msgData(), integerValue, stringValue);
|
||||
}
|
||||
|
||||
event DataShort(bytes data);
|
||||
|
||||
function msgDataShort() public {
|
||||
emit DataShort(_msgData());
|
||||
}
|
||||
}
|
||||
|
||||
contract ContextMockCaller {
|
||||
function callSender(ContextMock context) public {
|
||||
context.msgSender();
|
||||
}
|
||||
|
||||
function callData(ContextMock context, uint256 integerValue, string memory stringValue) public {
|
||||
context.msgData(integerValue, stringValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC1967Utils} from "../proxy/ERC1967/ERC1967Utils.sol";
|
||||
import {StorageSlot} from "../utils/StorageSlot.sol";
|
||||
|
||||
abstract contract Impl {
|
||||
function version() public pure virtual returns (string memory);
|
||||
}
|
||||
|
||||
contract DummyImplementation {
|
||||
uint256 public value;
|
||||
string public text;
|
||||
uint256[] public values;
|
||||
|
||||
function initializeNonPayable() public {
|
||||
value = 10;
|
||||
}
|
||||
|
||||
function initializePayable() public payable {
|
||||
value = 100;
|
||||
}
|
||||
|
||||
function initializeNonPayableWithValue(uint256 _value) public {
|
||||
value = _value;
|
||||
}
|
||||
|
||||
function initializePayableWithValue(uint256 _value) public payable {
|
||||
value = _value;
|
||||
}
|
||||
|
||||
function initialize(uint256 _value, string memory _text, uint256[] memory _values) public {
|
||||
value = _value;
|
||||
text = _text;
|
||||
values = _values;
|
||||
}
|
||||
|
||||
function get() public pure returns (bool) {
|
||||
return true;
|
||||
}
|
||||
|
||||
function version() public pure virtual returns (string memory) {
|
||||
return "V1";
|
||||
}
|
||||
|
||||
function reverts() public pure {
|
||||
require(false, "DummyImplementation reverted");
|
||||
}
|
||||
|
||||
// Use for forcing an unsafe TransparentUpgradeableProxy admin override
|
||||
function unsafeOverrideAdmin(address newAdmin) public {
|
||||
StorageSlot.getAddressSlot(ERC1967Utils.ADMIN_SLOT).value = newAdmin;
|
||||
}
|
||||
}
|
||||
|
||||
contract DummyImplementationV2 is DummyImplementation {
|
||||
function migrate(uint256 newVal) public payable {
|
||||
value = newVal;
|
||||
}
|
||||
|
||||
function version() public pure override returns (string memory) {
|
||||
return "V2";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ECDSA} from "../utils/cryptography/ECDSA.sol";
|
||||
import {EIP712} from "../utils/cryptography/EIP712.sol";
|
||||
|
||||
abstract contract EIP712Verifier is EIP712 {
|
||||
function verify(bytes memory signature, address signer, address mailTo, string memory mailContents) external view {
|
||||
bytes32 digest = _hashTypedDataV4(
|
||||
keccak256(abi.encode(keccak256("Mail(address to,string contents)"), mailTo, keccak256(bytes(mailContents))))
|
||||
);
|
||||
address recoveredSigner = ECDSA.recover(digest, signature);
|
||||
require(recoveredSigner == signer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Ownable} from "../access/Ownable.sol";
|
||||
import {IERC1271} from "../interfaces/IERC1271.sol";
|
||||
import {ECDSA} from "../utils/cryptography/ECDSA.sol";
|
||||
|
||||
contract ERC1271WalletMock is Ownable, IERC1271 {
|
||||
constructor(address originalOwner) Ownable(originalOwner) {}
|
||||
|
||||
function isValidSignature(bytes32 hash, bytes memory signature) public view returns (bytes4 magicValue) {
|
||||
return ECDSA.recover(hash, signature) == owner() ? this.isValidSignature.selector : bytes4(0);
|
||||
}
|
||||
}
|
||||
|
||||
contract ERC1271MaliciousMock is IERC1271 {
|
||||
function isValidSignature(bytes32, bytes memory) public pure returns (bytes4) {
|
||||
assembly {
|
||||
mstore(0, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
|
||||
return(0, 32)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "../../utils/introspection/IERC165.sol";
|
||||
|
||||
/**
|
||||
* https://eips.ethereum.org/EIPS/eip-214#specification
|
||||
* From the specification:
|
||||
* > Any attempts to make state-changing operations inside an execution instance with STATIC set to true will instead
|
||||
* throw an exception.
|
||||
* > These operations include [...], LOG0, LOG1, LOG2, [...]
|
||||
*
|
||||
* therefore, because this contract is staticcall'd we need to not emit events (which is how solidity-coverage works)
|
||||
* solidity-coverage ignores the /mocks folder, so we duplicate its implementation here to avoid instrumenting it
|
||||
*/
|
||||
contract SupportsInterfaceWithLookupMock is IERC165 {
|
||||
/*
|
||||
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
|
||||
*/
|
||||
bytes4 public constant INTERFACE_ID_ERC165 = 0x01ffc9a7;
|
||||
|
||||
/**
|
||||
* @dev A mapping of interface id to whether or not it's supported.
|
||||
*/
|
||||
mapping(bytes4 interfaceId => bool) private _supportedInterfaces;
|
||||
|
||||
/**
|
||||
* @dev A contract implementing SupportsInterfaceWithLookup
|
||||
* implement ERC-165 itself.
|
||||
*/
|
||||
constructor() {
|
||||
_registerInterface(INTERFACE_ID_ERC165);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Implement supportsInterface(bytes4) using a lookup table.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
|
||||
return _supportedInterfaces[interfaceId];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Private method for registering an interface.
|
||||
*/
|
||||
function _registerInterface(bytes4 interfaceId) internal {
|
||||
require(interfaceId != 0xffffffff, "ERC165InterfacesSupported: invalid interface id");
|
||||
_supportedInterfaces[interfaceId] = true;
|
||||
}
|
||||
}
|
||||
|
||||
contract ERC165InterfacesSupported is SupportsInterfaceWithLookupMock {
|
||||
constructor(bytes4[] memory interfaceIds) {
|
||||
for (uint256 i = 0; i < interfaceIds.length; i++) {
|
||||
_registerInterface(interfaceIds[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
contract ERC165MaliciousData {
|
||||
function supportsInterface(bytes4) public pure returns (bool) {
|
||||
assembly {
|
||||
mstore(0, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
|
||||
return(0, 32)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
contract ERC165MissingData {
|
||||
function supportsInterface(bytes4 interfaceId) public view {} // missing return
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
contract ERC165NotSupported {}
|
||||
@@ -0,0 +1,18 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "../../utils/introspection/IERC165.sol";
|
||||
|
||||
contract ERC165ReturnBombMock is IERC165 {
|
||||
function supportsInterface(bytes4 interfaceId) public pure override returns (bool) {
|
||||
if (interfaceId == type(IERC165).interfaceId) {
|
||||
assembly {
|
||||
mstore(0, 1)
|
||||
}
|
||||
}
|
||||
assembly {
|
||||
return(0, 101500)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ContextMock} from "./ContextMock.sol";
|
||||
import {Context} from "../utils/Context.sol";
|
||||
import {Multicall} from "../utils/Multicall.sol";
|
||||
import {ERC2771Context} from "../metatx/ERC2771Context.sol";
|
||||
|
||||
// By inheriting from ERC2771Context, Context's internal functions are overridden automatically
|
||||
contract ERC2771ContextMock is ContextMock, ERC2771Context, Multicall {
|
||||
/// @custom:oz-upgrades-unsafe-allow constructor
|
||||
constructor(address trustedForwarder) ERC2771Context(trustedForwarder) {
|
||||
emit Sender(_msgSender()); // _msgSender() should be accessible during construction
|
||||
}
|
||||
|
||||
function _msgSender() internal view override(Context, ERC2771Context) returns (address) {
|
||||
return ERC2771Context._msgSender();
|
||||
}
|
||||
|
||||
function _msgData() internal view override(Context, ERC2771Context) returns (bytes calldata) {
|
||||
return ERC2771Context._msgData();
|
||||
}
|
||||
|
||||
function _contextSuffixLength() internal view override(Context, ERC2771Context) returns (uint256) {
|
||||
return ERC2771Context._contextSuffixLength();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "../token/ERC20/IERC20.sol";
|
||||
import {IERC3156FlashBorrower} from "../interfaces/IERC3156.sol";
|
||||
import {Address} from "../utils/Address.sol";
|
||||
|
||||
/**
|
||||
* @dev WARNING: this IERC3156FlashBorrower mock implementation is for testing purposes ONLY.
|
||||
* Writing a secure flash lock borrower is not an easy task, and should be done with the utmost care.
|
||||
* This is not an example of how it should be done, and no pattern present in this mock should be considered secure.
|
||||
* Following best practices, always have your contract properly audited before using them to manipulate important funds on
|
||||
* live networks.
|
||||
*/
|
||||
contract ERC3156FlashBorrowerMock is IERC3156FlashBorrower {
|
||||
bytes32 internal constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
|
||||
|
||||
bool immutable _enableApprove;
|
||||
bool immutable _enableReturn;
|
||||
|
||||
event BalanceOf(address token, address account, uint256 value);
|
||||
event TotalSupply(address token, uint256 value);
|
||||
|
||||
constructor(bool enableReturn, bool enableApprove) {
|
||||
_enableApprove = enableApprove;
|
||||
_enableReturn = enableReturn;
|
||||
}
|
||||
|
||||
function onFlashLoan(
|
||||
address /*initiator*/,
|
||||
address token,
|
||||
uint256 amount,
|
||||
uint256 fee,
|
||||
bytes calldata data
|
||||
) public returns (bytes32) {
|
||||
require(msg.sender == token);
|
||||
|
||||
emit BalanceOf(token, address(this), IERC20(token).balanceOf(address(this)));
|
||||
emit TotalSupply(token, IERC20(token).totalSupply());
|
||||
|
||||
if (data.length > 0) {
|
||||
// WARNING: This code is for testing purposes only! Do not use.
|
||||
Address.functionCall(token, data);
|
||||
}
|
||||
|
||||
if (_enableApprove) {
|
||||
IERC20(token).approve(token, amount + fee);
|
||||
}
|
||||
|
||||
return _enableReturn ? _RETURN_VALUE : bytes32(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
contract EtherReceiverMock {
|
||||
bool private _acceptEther;
|
||||
|
||||
function setAcceptEther(bool acceptEther) public {
|
||||
_acceptEther = acceptEther;
|
||||
}
|
||||
|
||||
receive() external payable {
|
||||
if (!_acceptEther) {
|
||||
revert();
|
||||
}
|
||||
}
|
||||
}
|
||||
130
lib_openzeppelin_contracts/contracts/mocks/InitializableMock.sol
Normal file
130
lib_openzeppelin_contracts/contracts/mocks/InitializableMock.sol
Normal file
@@ -0,0 +1,130 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Initializable} from "../proxy/utils/Initializable.sol";
|
||||
|
||||
/**
|
||||
* @title InitializableMock
|
||||
* @dev This contract is a mock to test initializable functionality
|
||||
*/
|
||||
contract InitializableMock is Initializable {
|
||||
bool public initializerRan;
|
||||
bool public onlyInitializingRan;
|
||||
uint256 public x;
|
||||
|
||||
function isInitializing() public view returns (bool) {
|
||||
return _isInitializing();
|
||||
}
|
||||
|
||||
function initialize() public initializer {
|
||||
initializerRan = true;
|
||||
}
|
||||
|
||||
function initializeOnlyInitializing() public onlyInitializing {
|
||||
onlyInitializingRan = true;
|
||||
}
|
||||
|
||||
function initializerNested() public initializer {
|
||||
initialize();
|
||||
}
|
||||
|
||||
function onlyInitializingNested() public initializer {
|
||||
initializeOnlyInitializing();
|
||||
}
|
||||
|
||||
function initializeWithX(uint256 _x) public payable initializer {
|
||||
x = _x;
|
||||
}
|
||||
|
||||
function nonInitializable(uint256 _x) public payable {
|
||||
x = _x;
|
||||
}
|
||||
|
||||
function fail() public pure {
|
||||
require(false, "InitializableMock forced failure");
|
||||
}
|
||||
}
|
||||
|
||||
contract ConstructorInitializableMock is Initializable {
|
||||
bool public initializerRan;
|
||||
bool public onlyInitializingRan;
|
||||
|
||||
constructor() initializer {
|
||||
initialize();
|
||||
initializeOnlyInitializing();
|
||||
}
|
||||
|
||||
function initialize() public initializer {
|
||||
initializerRan = true;
|
||||
}
|
||||
|
||||
function initializeOnlyInitializing() public onlyInitializing {
|
||||
onlyInitializingRan = true;
|
||||
}
|
||||
}
|
||||
|
||||
contract ChildConstructorInitializableMock is ConstructorInitializableMock {
|
||||
bool public childInitializerRan;
|
||||
|
||||
constructor() initializer {
|
||||
childInitialize();
|
||||
}
|
||||
|
||||
function childInitialize() public initializer {
|
||||
childInitializerRan = true;
|
||||
}
|
||||
}
|
||||
|
||||
contract ReinitializerMock is Initializable {
|
||||
uint256 public counter;
|
||||
|
||||
function getInitializedVersion() public view returns (uint64) {
|
||||
return _getInitializedVersion();
|
||||
}
|
||||
|
||||
function initialize() public initializer {
|
||||
doStuff();
|
||||
}
|
||||
|
||||
function reinitialize(uint64 i) public reinitializer(i) {
|
||||
doStuff();
|
||||
}
|
||||
|
||||
function nestedReinitialize(uint64 i, uint64 j) public reinitializer(i) {
|
||||
reinitialize(j);
|
||||
}
|
||||
|
||||
function chainReinitialize(uint64 i, uint64 j) public {
|
||||
reinitialize(i);
|
||||
reinitialize(j);
|
||||
}
|
||||
|
||||
function disableInitializers() public {
|
||||
_disableInitializers();
|
||||
}
|
||||
|
||||
function doStuff() public onlyInitializing {
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
|
||||
contract DisableNew is Initializable {
|
||||
constructor() {
|
||||
_disableInitializers();
|
||||
}
|
||||
}
|
||||
|
||||
contract DisableOld is Initializable {
|
||||
constructor() initializer {}
|
||||
}
|
||||
|
||||
contract DisableBad1 is DisableNew, DisableOld {}
|
||||
|
||||
contract DisableBad2 is Initializable {
|
||||
constructor() initializer {
|
||||
_disableInitializers();
|
||||
}
|
||||
}
|
||||
|
||||
contract DisableOk is DisableOld, DisableNew {}
|
||||
@@ -0,0 +1,44 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import {MerkleTree} from "../utils/structs/MerkleTree.sol";
|
||||
|
||||
contract MerkleTreeMock {
|
||||
using MerkleTree for MerkleTree.Bytes32PushTree;
|
||||
|
||||
MerkleTree.Bytes32PushTree private _tree;
|
||||
|
||||
// This mock only stored the latest root.
|
||||
// Production contract may want to store historical values.
|
||||
bytes32 public root;
|
||||
|
||||
event LeafInserted(bytes32 leaf, uint256 index, bytes32 root);
|
||||
|
||||
function setup(uint8 _depth, bytes32 _zero) public {
|
||||
root = _tree.setup(_depth, _zero);
|
||||
}
|
||||
|
||||
function push(bytes32 leaf) public {
|
||||
(uint256 leafIndex, bytes32 currentRoot) = _tree.push(leaf);
|
||||
emit LeafInserted(leaf, leafIndex, currentRoot);
|
||||
root = currentRoot;
|
||||
}
|
||||
|
||||
function depth() public view returns (uint256) {
|
||||
return _tree.depth();
|
||||
}
|
||||
|
||||
// internal state
|
||||
function nextLeafIndex() public view returns (uint256) {
|
||||
return _tree._nextLeafIndex;
|
||||
}
|
||||
|
||||
function sides(uint256 i) public view returns (bytes32) {
|
||||
return _tree._sides[i];
|
||||
}
|
||||
|
||||
function zeros(uint256 i) public view returns (bytes32) {
|
||||
return _tree._zeros[i];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20MulticallMock} from "./token/ERC20MulticallMock.sol";
|
||||
|
||||
contract MulticallHelper {
|
||||
function checkReturnValues(
|
||||
ERC20MulticallMock multicallToken,
|
||||
address[] calldata recipients,
|
||||
uint256[] calldata amounts
|
||||
) external {
|
||||
bytes[] memory calls = new bytes[](recipients.length);
|
||||
for (uint256 i = 0; i < recipients.length; i++) {
|
||||
calls[i] = abi.encodeCall(multicallToken.transfer, (recipients[i], amounts[i]));
|
||||
}
|
||||
|
||||
bytes[] memory results = multicallToken.multicall(calls);
|
||||
for (uint256 i = 0; i < results.length; i++) {
|
||||
require(abi.decode(results[i], (bool)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Initializable} from "../proxy/utils/Initializable.sol";
|
||||
|
||||
// Sample contracts showing upgradeability with multiple inheritance.
|
||||
// Child contract inherits from Father and Mother contracts, and Father extends from Gramps.
|
||||
//
|
||||
// Human
|
||||
// / \
|
||||
// | Gramps
|
||||
// | |
|
||||
// Mother Father
|
||||
// | |
|
||||
// -- Child --
|
||||
|
||||
/**
|
||||
* Sample base initializable contract that is a human
|
||||
*/
|
||||
contract SampleHuman is Initializable {
|
||||
bool public isHuman;
|
||||
|
||||
function initialize() public initializer {
|
||||
__SampleHuman_init();
|
||||
}
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function __SampleHuman_init() internal onlyInitializing {
|
||||
__SampleHuman_init_unchained();
|
||||
}
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function __SampleHuman_init_unchained() internal onlyInitializing {
|
||||
isHuman = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample base initializable contract that defines a field mother
|
||||
*/
|
||||
contract SampleMother is Initializable, SampleHuman {
|
||||
uint256 public mother;
|
||||
|
||||
function initialize(uint256 value) public initializer {
|
||||
__SampleMother_init(value);
|
||||
}
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function __SampleMother_init(uint256 value) internal onlyInitializing {
|
||||
__SampleHuman_init();
|
||||
__SampleMother_init_unchained(value);
|
||||
}
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function __SampleMother_init_unchained(uint256 value) internal onlyInitializing {
|
||||
mother = value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample base initializable contract that defines a field gramps
|
||||
*/
|
||||
contract SampleGramps is Initializable, SampleHuman {
|
||||
string public gramps;
|
||||
|
||||
function initialize(string memory value) public initializer {
|
||||
__SampleGramps_init(value);
|
||||
}
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function __SampleGramps_init(string memory value) internal onlyInitializing {
|
||||
__SampleHuman_init();
|
||||
__SampleGramps_init_unchained(value);
|
||||
}
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function __SampleGramps_init_unchained(string memory value) internal onlyInitializing {
|
||||
gramps = value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample base initializable contract that defines a field father and extends from gramps
|
||||
*/
|
||||
contract SampleFather is Initializable, SampleGramps {
|
||||
uint256 public father;
|
||||
|
||||
function initialize(string memory _gramps, uint256 _father) public initializer {
|
||||
__SampleFather_init(_gramps, _father);
|
||||
}
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function __SampleFather_init(string memory _gramps, uint256 _father) internal onlyInitializing {
|
||||
__SampleGramps_init(_gramps);
|
||||
__SampleFather_init_unchained(_father);
|
||||
}
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function __SampleFather_init_unchained(uint256 _father) internal onlyInitializing {
|
||||
father = _father;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Child extends from mother, father (gramps)
|
||||
*/
|
||||
contract SampleChild is Initializable, SampleMother, SampleFather {
|
||||
uint256 public child;
|
||||
|
||||
function initialize(uint256 _mother, string memory _gramps, uint256 _father, uint256 _child) public initializer {
|
||||
__SampleChild_init(_mother, _gramps, _father, _child);
|
||||
}
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function __SampleChild_init(
|
||||
uint256 _mother,
|
||||
string memory _gramps,
|
||||
uint256 _father,
|
||||
uint256 _child
|
||||
) internal onlyInitializing {
|
||||
__SampleMother_init(_mother);
|
||||
__SampleFather_init(_gramps, _father);
|
||||
__SampleChild_init_unchained(_child);
|
||||
}
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function __SampleChild_init_unchained(uint256 _child) internal onlyInitializing {
|
||||
child = _child;
|
||||
}
|
||||
}
|
||||
31
lib_openzeppelin_contracts/contracts/mocks/PausableMock.sol
Normal file
31
lib_openzeppelin_contracts/contracts/mocks/PausableMock.sol
Normal file
@@ -0,0 +1,31 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Pausable} from "../utils/Pausable.sol";
|
||||
|
||||
contract PausableMock is Pausable {
|
||||
bool public drasticMeasureTaken;
|
||||
uint256 public count;
|
||||
|
||||
constructor() {
|
||||
drasticMeasureTaken = false;
|
||||
count = 0;
|
||||
}
|
||||
|
||||
function normalProcess() external whenNotPaused {
|
||||
count++;
|
||||
}
|
||||
|
||||
function drasticMeasure() external whenPaused {
|
||||
drasticMeasureTaken = true;
|
||||
}
|
||||
|
||||
function pause() external {
|
||||
_pause();
|
||||
}
|
||||
|
||||
function unpause() external {
|
||||
_unpause();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Context} from "../utils/Context.sol";
|
||||
|
||||
contract ReentrancyAttack is Context {
|
||||
function callSender(bytes calldata data) public {
|
||||
(bool success, ) = _msgSender().call(data);
|
||||
require(success, "ReentrancyAttack: failed call");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ReentrancyGuard} from "../utils/ReentrancyGuard.sol";
|
||||
import {ReentrancyAttack} from "./ReentrancyAttack.sol";
|
||||
|
||||
contract ReentrancyMock is ReentrancyGuard {
|
||||
uint256 public counter;
|
||||
|
||||
constructor() {
|
||||
counter = 0;
|
||||
}
|
||||
|
||||
function callback() external nonReentrant {
|
||||
_count();
|
||||
}
|
||||
|
||||
function countLocalRecursive(uint256 n) public nonReentrant {
|
||||
if (n > 0) {
|
||||
_count();
|
||||
countLocalRecursive(n - 1);
|
||||
}
|
||||
}
|
||||
|
||||
function countThisRecursive(uint256 n) public nonReentrant {
|
||||
if (n > 0) {
|
||||
_count();
|
||||
(bool success, ) = address(this).call(abi.encodeCall(this.countThisRecursive, (n - 1)));
|
||||
require(success, "ReentrancyMock: failed call");
|
||||
}
|
||||
}
|
||||
|
||||
function countAndCall(ReentrancyAttack attacker) public nonReentrant {
|
||||
_count();
|
||||
attacker.callSender(abi.encodeCall(this.callback, ()));
|
||||
}
|
||||
|
||||
function _count() private {
|
||||
counter += 1;
|
||||
}
|
||||
|
||||
function guardedCheckEntered() public nonReentrant {
|
||||
require(_reentrancyGuardEntered());
|
||||
}
|
||||
|
||||
function unguardedCheckNotEntered() public view {
|
||||
require(!_reentrancyGuardEntered());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.24;
|
||||
|
||||
import {ReentrancyGuardTransient} from "../utils/ReentrancyGuardTransient.sol";
|
||||
import {ReentrancyAttack} from "./ReentrancyAttack.sol";
|
||||
|
||||
contract ReentrancyTransientMock is ReentrancyGuardTransient {
|
||||
uint256 public counter;
|
||||
|
||||
constructor() {
|
||||
counter = 0;
|
||||
}
|
||||
|
||||
function callback() external nonReentrant {
|
||||
_count();
|
||||
}
|
||||
|
||||
function countLocalRecursive(uint256 n) public nonReentrant {
|
||||
if (n > 0) {
|
||||
_count();
|
||||
countLocalRecursive(n - 1);
|
||||
}
|
||||
}
|
||||
|
||||
function countThisRecursive(uint256 n) public nonReentrant {
|
||||
if (n > 0) {
|
||||
_count();
|
||||
(bool success, ) = address(this).call(abi.encodeCall(this.countThisRecursive, (n - 1)));
|
||||
require(success, "ReentrancyTransientMock: failed call");
|
||||
}
|
||||
}
|
||||
|
||||
function countAndCall(ReentrancyAttack attacker) public nonReentrant {
|
||||
_count();
|
||||
attacker.callSender(abi.encodeCall(this.callback, ()));
|
||||
}
|
||||
|
||||
function _count() private {
|
||||
counter += 1;
|
||||
}
|
||||
|
||||
function guardedCheckEntered() public nonReentrant {
|
||||
require(_reentrancyGuardEntered());
|
||||
}
|
||||
|
||||
function unguardedCheckNotEntered() public view {
|
||||
require(!_reentrancyGuardEntered());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Initializable} from "../proxy/utils/Initializable.sol";
|
||||
|
||||
contract Implementation1 is Initializable {
|
||||
uint256 internal _value;
|
||||
|
||||
function initialize() public initializer {}
|
||||
|
||||
function setValue(uint256 _number) public {
|
||||
_value = _number;
|
||||
}
|
||||
}
|
||||
|
||||
contract Implementation2 is Initializable {
|
||||
uint256 internal _value;
|
||||
|
||||
function initialize() public initializer {}
|
||||
|
||||
function setValue(uint256 _number) public {
|
||||
_value = _number;
|
||||
}
|
||||
|
||||
function getValue() public view returns (uint256) {
|
||||
return _value;
|
||||
}
|
||||
}
|
||||
|
||||
contract Implementation3 is Initializable {
|
||||
uint256 internal _value;
|
||||
|
||||
function initialize() public initializer {}
|
||||
|
||||
function setValue(uint256 _number) public {
|
||||
_value = _number;
|
||||
}
|
||||
|
||||
function getValue(uint256 _number) public view returns (uint256) {
|
||||
return _value + _number;
|
||||
}
|
||||
}
|
||||
|
||||
contract Implementation4 is Initializable {
|
||||
uint256 internal _value;
|
||||
|
||||
function initialize() public initializer {}
|
||||
|
||||
function setValue(uint256 _number) public {
|
||||
_value = _number;
|
||||
}
|
||||
|
||||
function getValue() public view returns (uint256) {
|
||||
return _value;
|
||||
}
|
||||
|
||||
fallback() external {
|
||||
_value = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Initializable} from "../proxy/utils/Initializable.sol";
|
||||
|
||||
/**
|
||||
* @title MigratableMockV1
|
||||
* @dev This contract is a mock to test initializable functionality through migrations
|
||||
*/
|
||||
contract MigratableMockV1 is Initializable {
|
||||
uint256 public x;
|
||||
|
||||
function initialize(uint256 value) public payable initializer {
|
||||
x = value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @title MigratableMockV2
|
||||
* @dev This contract is a mock to test migratable functionality with params
|
||||
*/
|
||||
contract MigratableMockV2 is MigratableMockV1 {
|
||||
bool internal _migratedV2;
|
||||
uint256 public y;
|
||||
|
||||
function migrate(uint256 value, uint256 anotherValue) public payable {
|
||||
require(!_migratedV2);
|
||||
x = value;
|
||||
y = anotherValue;
|
||||
_migratedV2 = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @title MigratableMockV3
|
||||
* @dev This contract is a mock to test migratable functionality without params
|
||||
*/
|
||||
contract MigratableMockV3 is MigratableMockV2 {
|
||||
bool internal _migratedV3;
|
||||
|
||||
function migrate() public payable {
|
||||
require(!_migratedV3);
|
||||
uint256 oldX = x;
|
||||
x = y;
|
||||
y = oldX;
|
||||
_migratedV3 = true;
|
||||
}
|
||||
}
|
||||
39
lib_openzeppelin_contracts/contracts/mocks/Stateless.sol
Normal file
39
lib_openzeppelin_contracts/contracts/mocks/Stateless.sol
Normal file
@@ -0,0 +1,39 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
// We keep these imports and a dummy contract just to we can run the test suite after transpilation.
|
||||
|
||||
import {Address} from "../utils/Address.sol";
|
||||
import {Arrays} from "../utils/Arrays.sol";
|
||||
import {AuthorityUtils} from "../access/manager/AuthorityUtils.sol";
|
||||
import {Base64} from "../utils/Base64.sol";
|
||||
import {BitMaps} from "../utils/structs/BitMaps.sol";
|
||||
import {Checkpoints} from "../utils/structs/Checkpoints.sol";
|
||||
import {CircularBuffer} from "../utils/structs/CircularBuffer.sol";
|
||||
import {Clones} from "../proxy/Clones.sol";
|
||||
import {Create2} from "../utils/Create2.sol";
|
||||
import {DoubleEndedQueue} from "../utils/structs/DoubleEndedQueue.sol";
|
||||
import {ECDSA} from "../utils/cryptography/ECDSA.sol";
|
||||
import {EnumerableMap} from "../utils/structs/EnumerableMap.sol";
|
||||
import {EnumerableSet} from "../utils/structs/EnumerableSet.sol";
|
||||
import {ERC1155Holder} from "../token/ERC1155/utils/ERC1155Holder.sol";
|
||||
import {ERC165} from "../utils/introspection/ERC165.sol";
|
||||
import {ERC165Checker} from "../utils/introspection/ERC165Checker.sol";
|
||||
import {ERC1967Utils} from "../proxy/ERC1967/ERC1967Utils.sol";
|
||||
import {ERC721Holder} from "../token/ERC721/utils/ERC721Holder.sol";
|
||||
import {Math} from "../utils/math/Math.sol";
|
||||
import {MerkleProof} from "../utils/cryptography/MerkleProof.sol";
|
||||
import {MessageHashUtils} from "../utils/cryptography/MessageHashUtils.sol";
|
||||
import {Panic} from "../utils/Panic.sol";
|
||||
import {Packing} from "../utils/Packing.sol";
|
||||
import {SafeCast} from "../utils/math/SafeCast.sol";
|
||||
import {SafeERC20} from "../token/ERC20/utils/SafeERC20.sol";
|
||||
import {ShortStrings} from "../utils/ShortStrings.sol";
|
||||
import {SignatureChecker} from "../utils/cryptography/SignatureChecker.sol";
|
||||
import {SignedMath} from "../utils/math/SignedMath.sol";
|
||||
import {StorageSlot} from "../utils/StorageSlot.sol";
|
||||
import {Strings} from "../utils/Strings.sol";
|
||||
import {Time} from "../utils/types/Time.sol";
|
||||
|
||||
contract Dummy1234 {}
|
||||
137
lib_openzeppelin_contracts/contracts/mocks/StorageSlotMock.sol
Normal file
137
lib_openzeppelin_contracts/contracts/mocks/StorageSlotMock.sol
Normal file
@@ -0,0 +1,137 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// This file was procedurally generated from scripts/generate/templates/StorageSlotMock.js.
|
||||
|
||||
pragma solidity ^0.8.24;
|
||||
|
||||
import {Multicall} from "../utils/Multicall.sol";
|
||||
import {StorageSlot} from "../utils/StorageSlot.sol";
|
||||
|
||||
contract StorageSlotMock is Multicall {
|
||||
using StorageSlot for *;
|
||||
|
||||
function setAddressSlot(bytes32 slot, address value) public {
|
||||
slot.getAddressSlot().value = value;
|
||||
}
|
||||
|
||||
function setBooleanSlot(bytes32 slot, bool value) public {
|
||||
slot.getBooleanSlot().value = value;
|
||||
}
|
||||
|
||||
function setBytes32Slot(bytes32 slot, bytes32 value) public {
|
||||
slot.getBytes32Slot().value = value;
|
||||
}
|
||||
|
||||
function setUint256Slot(bytes32 slot, uint256 value) public {
|
||||
slot.getUint256Slot().value = value;
|
||||
}
|
||||
|
||||
function setInt256Slot(bytes32 slot, int256 value) public {
|
||||
slot.getInt256Slot().value = value;
|
||||
}
|
||||
|
||||
function getAddressSlot(bytes32 slot) public view returns (address) {
|
||||
return slot.getAddressSlot().value;
|
||||
}
|
||||
|
||||
function getBooleanSlot(bytes32 slot) public view returns (bool) {
|
||||
return slot.getBooleanSlot().value;
|
||||
}
|
||||
|
||||
function getBytes32Slot(bytes32 slot) public view returns (bytes32) {
|
||||
return slot.getBytes32Slot().value;
|
||||
}
|
||||
|
||||
function getUint256Slot(bytes32 slot) public view returns (uint256) {
|
||||
return slot.getUint256Slot().value;
|
||||
}
|
||||
|
||||
function getInt256Slot(bytes32 slot) public view returns (int256) {
|
||||
return slot.getInt256Slot().value;
|
||||
}
|
||||
|
||||
mapping(uint256 key => string) public stringMap;
|
||||
|
||||
function setStringSlot(bytes32 slot, string calldata value) public {
|
||||
slot.getStringSlot().value = value;
|
||||
}
|
||||
|
||||
function setStringStorage(uint256 key, string calldata value) public {
|
||||
stringMap[key].getStringSlot().value = value;
|
||||
}
|
||||
|
||||
function getStringSlot(bytes32 slot) public view returns (string memory) {
|
||||
return slot.getStringSlot().value;
|
||||
}
|
||||
|
||||
function getStringStorage(uint256 key) public view returns (string memory) {
|
||||
return stringMap[key].getStringSlot().value;
|
||||
}
|
||||
|
||||
mapping(uint256 key => bytes) public bytesMap;
|
||||
|
||||
function setBytesSlot(bytes32 slot, bytes calldata value) public {
|
||||
slot.getBytesSlot().value = value;
|
||||
}
|
||||
|
||||
function setBytesStorage(uint256 key, bytes calldata value) public {
|
||||
bytesMap[key].getBytesSlot().value = value;
|
||||
}
|
||||
|
||||
function getBytesSlot(bytes32 slot) public view returns (bytes memory) {
|
||||
return slot.getBytesSlot().value;
|
||||
}
|
||||
|
||||
function getBytesStorage(uint256 key) public view returns (bytes memory) {
|
||||
return bytesMap[key].getBytesSlot().value;
|
||||
}
|
||||
|
||||
event AddressValue(bytes32 slot, address value);
|
||||
|
||||
function tloadAddress(bytes32 slot) public {
|
||||
emit AddressValue(slot, slot.asAddress().tload());
|
||||
}
|
||||
|
||||
function tstore(bytes32 slot, address value) public {
|
||||
slot.asAddress().tstore(value);
|
||||
}
|
||||
|
||||
event BooleanValue(bytes32 slot, bool value);
|
||||
|
||||
function tloadBoolean(bytes32 slot) public {
|
||||
emit BooleanValue(slot, slot.asBoolean().tload());
|
||||
}
|
||||
|
||||
function tstore(bytes32 slot, bool value) public {
|
||||
slot.asBoolean().tstore(value);
|
||||
}
|
||||
|
||||
event Bytes32Value(bytes32 slot, bytes32 value);
|
||||
|
||||
function tloadBytes32(bytes32 slot) public {
|
||||
emit Bytes32Value(slot, slot.asBytes32().tload());
|
||||
}
|
||||
|
||||
function tstore(bytes32 slot, bytes32 value) public {
|
||||
slot.asBytes32().tstore(value);
|
||||
}
|
||||
|
||||
event Uint256Value(bytes32 slot, uint256 value);
|
||||
|
||||
function tloadUint256(bytes32 slot) public {
|
||||
emit Uint256Value(slot, slot.asUint256().tload());
|
||||
}
|
||||
|
||||
function tstore(bytes32 slot, uint256 value) public {
|
||||
slot.asUint256().tstore(value);
|
||||
}
|
||||
|
||||
event Int256Value(bytes32 slot, int256 value);
|
||||
|
||||
function tloadInt256(bytes32 slot) public {
|
||||
emit Int256Value(slot, slot.asInt256().tload());
|
||||
}
|
||||
|
||||
function tstore(bytes32 slot, int256 value) public {
|
||||
slot.asInt256().tstore(value);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user