diff --git a/blockchain/contracts/DAO/governance/extensions/GovernorVotes.sol b/blockchain/contracts/DAO/governance/extensions/GovernorVotes.sol index e1120ff..0bad2f1 100644 --- a/blockchain/contracts/DAO/governance/extensions/GovernorVotes.sol +++ b/blockchain/contracts/DAO/governance/extensions/GovernorVotes.sol @@ -4,7 +4,6 @@ pragma solidity ^0.8.19; import "../Governor.sol"; -import "../../../OpenZeppelin/interfaces/IERC5805.sol"; import "../../IUserRegistry.sol"; /** diff --git a/blockchain/contracts/OpenZeppelin/access/AccessControl.sol b/blockchain/contracts/OpenZeppelin/access/AccessControl.sol deleted file mode 100644 index b12ade3..0000000 --- a/blockchain/contracts/OpenZeppelin/access/AccessControl.sol +++ /dev/null @@ -1,233 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol) - -pragma solidity ^0.8.19; - -import "./IAccessControl.sol"; -import "../utils/Context.sol"; -import "../utils/Strings.sol"; -import "../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 => bool) members; - bytes32 adminRole; - } - - mapping(bytes32 => RoleData) private _roles; - - bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; - - /** - * @dev Modifier that checks that an account has a specific role. Reverts - * with a standardized message including the required role. - * - * The format of the revert reason is given by the following regular expression: - * - * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ - * - * _Available since v4.1._ - */ - 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].members[account]; - } - - /** - * @dev Revert with a standard message if `_msgSender()` is missing `role`. - * Overriding this function changes the behavior of the {onlyRole} modifier. - * - * Format of the revert message is described in {_checkRole}. - * - * _Available since v4.6._ - */ - function _checkRole(bytes32 role) internal view virtual { - _checkRole(role, _msgSender()); - } - - /** - * @dev Revert with a standard message if `account` is missing `role`. - * - * The format of the revert reason is given by the following regular expression: - * - * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ - */ - 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 Grants `role` to `account`. - * - * Internal function without access restriction. - * - * May emit a {RoleGranted} event. - */ - function _grantRole(bytes32 role, address account) internal virtual { - if (!hasRole(role, account)) { - _roles[role].members[account] = true; - emit RoleGranted(role, account, _msgSender()); - } - } - - /** - * @dev Revokes `role` from `account`. - * - * Internal function without access restriction. - * - * May emit a {RoleRevoked} event. - */ - function _revokeRole(bytes32 role, address account) internal virtual { - if (hasRole(role, account)) { - _roles[role].members[account] = false; - emit RoleRevoked(role, account, _msgSender()); - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/access/AccessControlDefaultAdminRules.sol b/blockchain/contracts/OpenZeppelin/access/AccessControlDefaultAdminRules.sol deleted file mode 100644 index e27eaf3..0000000 --- a/blockchain/contracts/OpenZeppelin/access/AccessControlDefaultAdminRules.sol +++ /dev/null @@ -1,397 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControlDefaultAdminRules.sol) - -pragma solidity ^0.8.19; - -import "./AccessControl.sol"; -import "./IAccessControlDefaultAdminRules.sol"; -import "../utils/math/SafeCast.sol"; -import "../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 - * ) {} - * } - * ``` - * - * _Available since v4.9._ - */ -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 { - if (role == DEFAULT_ADMIN_ROLE) { - if (defaultAdmin() != address(0)) { - revert AccessControlEnforcedDefaultAdminRules(); - } - _currentDefaultAdmin = account; - } - super._grantRole(role, account); - } - - /** - * @dev See {AccessControl-_revokeRole}. - */ - function _revokeRole(bytes32 role, address account) internal virtual override { - if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) { - delete _currentDefaultAdmin; - } - 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; - } -} diff --git a/blockchain/contracts/OpenZeppelin/access/AccessControlEnumerable.sol b/blockchain/contracts/OpenZeppelin/access/AccessControlEnumerable.sol deleted file mode 100644 index 297d345..0000000 --- a/blockchain/contracts/OpenZeppelin/access/AccessControlEnumerable.sol +++ /dev/null @@ -1,64 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) - -pragma solidity ^0.8.19; - -import "./IAccessControlEnumerable.sol"; -import "./AccessControl.sol"; -import "../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 => 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 Overload {_grantRole} to track enumerable memberships - */ - function _grantRole(bytes32 role, address account) internal virtual override { - super._grantRole(role, account); - _roleMembers[role].add(account); - } - - /** - * @dev Overload {_revokeRole} to track enumerable memberships - */ - function _revokeRole(bytes32 role, address account) internal virtual override { - super._revokeRole(role, account); - _roleMembers[role].remove(account); - } -} diff --git a/blockchain/contracts/OpenZeppelin/access/IAccessControl.sol b/blockchain/contracts/OpenZeppelin/access/IAccessControl.sol deleted file mode 100644 index 9abc2b7..0000000 --- a/blockchain/contracts/OpenZeppelin/access/IAccessControl.sol +++ /dev/null @@ -1,100 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) - -pragma solidity ^0.8.19; - -/** - * @dev External interface of AccessControl declared to support ERC165 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. - * - * _Available since v3.1._ - */ - 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, an admin role - * bearer except when using {AccessControl-_setupRole}. - */ - 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; -} diff --git a/blockchain/contracts/OpenZeppelin/access/IAccessControlDefaultAdminRules.sol b/blockchain/contracts/OpenZeppelin/access/IAccessControlDefaultAdminRules.sol deleted file mode 100644 index fbecfe1..0000000 --- a/blockchain/contracts/OpenZeppelin/access/IAccessControlDefaultAdminRules.sol +++ /dev/null @@ -1,194 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (access/IAccessControlDefaultAdminRules.sol) - -pragma solidity ^0.8.19; - -import "./IAccessControl.sol"; - -/** - * @dev External interface of AccessControlDefaultAdminRules declared to support ERC165 detection. - * - * _Available since v4.9._ - */ -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); -} diff --git a/blockchain/contracts/OpenZeppelin/access/IAccessControlEnumerable.sol b/blockchain/contracts/OpenZeppelin/access/IAccessControlEnumerable.sol deleted file mode 100644 index 240c611..0000000 --- a/blockchain/contracts/OpenZeppelin/access/IAccessControlEnumerable.sol +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) - -pragma solidity ^0.8.19; - -import "./IAccessControl.sol"; - -/** - * @dev External interface of AccessControlEnumerable declared to support ERC165 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); -} diff --git a/blockchain/contracts/OpenZeppelin/access/Ownable.sol b/blockchain/contracts/OpenZeppelin/access/Ownable.sol deleted file mode 100644 index f439437..0000000 --- a/blockchain/contracts/OpenZeppelin/access/Ownable.sol +++ /dev/null @@ -1,97 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) - -pragma solidity ^0.8.19; - -import "../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. - * - * By default, the owner account will be the one that deploys the contract. This - * can later be changed with {transferOwnership}. - * - * This module is used through inheritance. It will make available the modifier - * `onlyOwner`, which can be applied to your functions to restrict their use to - * the owner. - */ -abstract contract Ownable is Context { - address private _owner; - - /** - * @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 deployer as the initial owner. - */ - constructor(address initialOwner) { - _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); - } -} diff --git a/blockchain/contracts/OpenZeppelin/access/Ownable2Step.sol b/blockchain/contracts/OpenZeppelin/access/Ownable2Step.sol deleted file mode 100644 index 61005b7..0000000 --- a/blockchain/contracts/OpenZeppelin/access/Ownable2Step.sol +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol) - -pragma solidity ^0.8.19; - -import "./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. - * - * By default, the owner account will be the one that deploys the contract. 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); - } -} diff --git a/blockchain/contracts/OpenZeppelin/access/README.adoc b/blockchain/contracts/OpenZeppelin/access/README.adoc deleted file mode 100644 index 117cd7c..0000000 --- a/blockchain/contracts/OpenZeppelin/access/README.adoc +++ /dev/null @@ -1,25 +0,0 @@ -= 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. - -- {AccessControl} provides a general role based access control mechanism. Multiple hierarchical roles can be created and assigned each to multiple accounts. -- {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. - -== Authorization - -{{Ownable}} - -{{Ownable2Step}} - -{{IAccessControl}} - -{{AccessControl}} - -{{IAccessControlEnumerable}} - -{{AccessControlEnumerable}} - -{{AccessControlDefaultAdminRules}} diff --git a/blockchain/contracts/OpenZeppelin/governance/README.adoc b/blockchain/contracts/OpenZeppelin/governance/README.adoc deleted file mode 100644 index 00edfe2..0000000 --- a/blockchain/contracts/OpenZeppelin/governance/README.adoc +++ /dev/null @@ -1,166 +0,0 @@ -= 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. - -* {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. - -* {GovernorCompatibilityBravo}: Extends the interface to be fully `GovernorBravo`-compatible. Note that events are compatible regardless of whether this extension is included or not. - -* {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: - -* <>: Delay (in EIP-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. -* <>: Delay (in EIP-6372 clock) since the proposal starts until voting ends. -* <>: Quorum required for a proposal to be successful. This function includes a `timepoint` argument (see EIP-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 - -{{GovernorTimelockControl}} - -{{GovernorTimelockCompound}} - -{{GovernorSettings}} - -{{GovernorPreventLateQuorum}} - -{{GovernorCompatibilityBravo}} - -== 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. -** *Pending:* An operation that has been scheduled, before the timer expires. -** *Ready:* An operation that has been scheduled, after the timer expires. -** *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. diff --git a/blockchain/contracts/OpenZeppelin/governance/TimelockController.sol b/blockchain/contracts/OpenZeppelin/governance/TimelockController.sol deleted file mode 100644 index a25cd7b..0000000 --- a/blockchain/contracts/OpenZeppelin/governance/TimelockController.sol +++ /dev/null @@ -1,435 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/TimelockController.sol) - -pragma solidity ^0.8.19; - -import "../access/AccessControl.sol"; -import "../token/ERC721/utils/ERC721Holder.sol"; -import "../token/ERC1155/utils/ERC1155Holder.sol"; -import "../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. - * - * _Available since v3.3._ - */ -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 => uint256) private _timestamps; - uint256 private _minDelay; - - enum OperationState { - Unset, - Pending, - 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. - */ - error TimelockUnexpectedOperationState(bytes32 operationId, OperationState expected); - - /** - * @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 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, ERC1155Receiver) returns (bool) { - return super.supportsInterface(interfaceId); - } - - /** - * @dev Returns whether an id correspond to a registered operation. This - * includes both Pending, Ready and Done operations. - */ - function isOperation(bytes32 id) public view virtual returns (bool) { - return getTimestamp(id) > 0; - } - - /** - * @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready". - */ - function isOperationPending(bytes32 id) public view virtual returns (bool) { - return getTimestamp(id) > _DONE_TIMESTAMP; - } - - /** - * @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending". - */ - function isOperationReady(bytes32 id) public view virtual returns (bool) { - uint256 timestamp = getTimestamp(id); - return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; - } - - /** - * @dev Returns whether an operation is done or not. - */ - function isOperationDone(bytes32 id) public view virtual returns (bool) { - return getTimestamp(id) == _DONE_TIMESTAMP; - } - - /** - * @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 the minimum delay 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, 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, OperationState.Pending); - } - 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, 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, 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 { - if (msg.sender != address(this)) { - revert TimelockUnauthorizedCaller(msg.sender); - } - emit MinDelayChange(_minDelay, newDelay); - _minDelay = newDelay; - } -} diff --git a/blockchain/contracts/OpenZeppelin/governance/utils/IVotes.sol b/blockchain/contracts/OpenZeppelin/governance/utils/IVotes.sol deleted file mode 100644 index a8a2085..0000000 --- a/blockchain/contracts/OpenZeppelin/governance/utils/IVotes.sol +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/utils/IVotes.sol) -pragma solidity ^0.8.19; - -/** - * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. - * - * _Available since v4.5._ - */ -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 votes. - */ - event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); - - /** - * @dev Returns the current amount of votes that `account` has. - */ - function getVotes(address account) external view returns (uint256); - - /** - * @dev Returns the amount of votes that `account` had at 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; -} diff --git a/blockchain/contracts/OpenZeppelin/governance/utils/Votes.sol b/blockchain/contracts/OpenZeppelin/governance/utils/Votes.sol deleted file mode 100644 index 09eb4e2..0000000 --- a/blockchain/contracts/OpenZeppelin/governance/utils/Votes.sol +++ /dev/null @@ -1,252 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/utils/Votes.sol) -pragma solidity ^0.8.19; - -import "../../interfaces/IERC5805.sol"; -import "../../utils/Context.sol"; -import "../../utils/Nonces.sol"; -import "../../utils/cryptography/EIP712.sol"; -import "../../utils/structs/Checkpoints.sol"; - -/** - * @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be - * transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of - * "representative" that will pool delegated voting units from different accounts and can then use it to vote in - * decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to - * delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative. - * - * This contract is often combined with a token contract such that voting units correspond to token units. For an - * example, see {ERC721Votes}. - * - * The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed - * at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the - * cost of this history tracking optional. - * - * When using this module the derived contract must implement {_getVotingUnits} (for example, make it return - * {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the - * previous example, it would be included in {ERC721-_beforeTokenTransfer}). - * - * _Available since v4.5._ - */ -abstract contract Votes is Context, EIP712, Nonces, IERC5805 { - using Checkpoints for Checkpoints.Trace224; - - bytes32 private constant _DELEGATION_TYPEHASH = - keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); - - mapping(address => address) private _delegation; - - /// @custom:oz-retyped-from mapping(address => Checkpoints.History) - mapping(address => Checkpoints.Trace224) private _delegateCheckpoints; - - /// @custom:oz-retyped-from Checkpoints.History - Checkpoints.Trace224 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 SafeCast.toUint48(block.number); - } - - /** - * @dev Machine-readable description of the clock as specified in EIP-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() != block.number) { - 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.toUint32(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.toUint32(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 _delegation[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); - _delegation[account] = delegatee; - - emit DelegateChanged(account, oldDelegate, delegatee); - _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account)); - } - - /** - * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to` - * should be zero. Total supply of voting units will be adjusted with mints and burns. - */ - function _transferVotingUnits(address from, address to, uint256 amount) internal virtual { - if (from == address(0)) { - _push(_totalCheckpoints, _add, SafeCast.toUint224(amount)); - } - if (to == address(0)) { - _push(_totalCheckpoints, _subtract, SafeCast.toUint224(amount)); - } - _moveDelegateVotes(delegates(from), delegates(to), amount); - } - - /** - * @dev Moves delegated votes from one delegate to another. - */ - function _moveDelegateVotes(address from, address to, uint256 amount) private { - if (from != to && amount > 0) { - if (from != address(0)) { - (uint256 oldValue, uint256 newValue) = _push( - _delegateCheckpoints[from], - _subtract, - SafeCast.toUint224(amount) - ); - emit DelegateVotesChanged(from, oldValue, newValue); - } - if (to != address(0)) { - (uint256 oldValue, uint256 newValue) = _push( - _delegateCheckpoints[to], - _add, - SafeCast.toUint224(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.Checkpoint224 memory) { - return _delegateCheckpoints[account].at(pos); - } - - function _push( - Checkpoints.Trace224 storage store, - function(uint224, uint224) view returns (uint224) op, - uint224 delta - ) private returns (uint224, uint224) { - return store.push(SafeCast.toUint32(clock()), op(store.latest(), delta)); - } - - function _add(uint224 a, uint224 b) private pure returns (uint224) { - return a + b; - } - - function _subtract(uint224 a, uint224 b) private pure returns (uint224) { - return a - b; - } - - /** - * @dev Must return the voting units held by an account. - */ - function _getVotingUnits(address) internal view virtual returns (uint256); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC1155.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC1155.sol deleted file mode 100644 index 8f7527f..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC1155.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC1155/IERC1155.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC1155MetadataURI.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC1155MetadataURI.sol deleted file mode 100644 index 61b36c2..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC1155MetadataURI.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155MetadataURI.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC1155/extensions/IERC1155MetadataURI.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC1155Receiver.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC1155Receiver.sol deleted file mode 100644 index b5cd186..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC1155Receiver.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155Receiver.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC1155/IERC1155Receiver.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC1271.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC1271.sol deleted file mode 100644 index e7fca30..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC1271.sol +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Interface of the ERC1271 standard signature validation method for - * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. - * - * _Available since v4.1._ - */ -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); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC1363.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC1363.sol deleted file mode 100644 index 95c5b89..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC1363.sol +++ /dev/null @@ -1,80 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1363.sol) - -pragma solidity ^0.8.19; - -import "./IERC20.sol"; -import "./IERC165.sol"; - -/** - * @dev Interface of an ERC1363 compliant contract, as defined in the - * https://eips.ethereum.org/EIPS/eip-1363[EIP]. - * - * Defines a interface for ERC20 tokens that supports executing recipient - * code after `transfer` or `transferFrom`, or spender code after `approve`. - */ -interface IERC1363 is IERC165, IERC20 { - /* - * 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 Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver - * @param to address The address which you want to transfer to - * @param amount uint256 The amount of tokens to be transferred - * @return true unless throwing - */ - function transferAndCall(address to, uint256 amount) external returns (bool); - - /** - * @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver - * @param to address The address which you want to transfer to - * @param amount uint256 The amount of tokens to be transferred - * @param data bytes Additional data with no specified format, sent in call to `to` - * @return true unless throwing - */ - function transferAndCall(address to, uint256 amount, bytes memory data) external returns (bool); - - /** - * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver - * @param from address The address which you want to send tokens from - * @param to address The address which you want to transfer to - * @param amount uint256 The amount of tokens to be transferred - * @return true unless throwing - */ - function transferFromAndCall(address from, address to, uint256 amount) external returns (bool); - - /** - * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver - * @param from address The address which you want to send tokens from - * @param to address The address which you want to transfer to - * @param amount uint256 The amount of tokens to be transferred - * @param data bytes Additional data with no specified format, sent in call to `to` - * @return true unless throwing - */ - function transferFromAndCall(address from, address to, uint256 amount, bytes memory data) external returns (bool); - - /** - * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender - * and then call `onApprovalReceived` on spender. - * @param spender address The address which will spend the funds - * @param amount uint256 The amount of tokens to be spent - */ - function approveAndCall(address spender, uint256 amount) external returns (bool); - - /** - * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender - * and then call `onApprovalReceived` on spender. - * @param spender address The address which will spend the funds - * @param amount uint256 The amount of tokens to be spent - * @param data bytes Additional data with no specified format, sent in call to `spender` - */ - function approveAndCall(address spender, uint256 amount, bytes memory data) external returns (bool); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC1363Receiver.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC1363Receiver.sol deleted file mode 100644 index 70ed857..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC1363Receiver.sol +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1363Receiver.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Interface for any contract that wants to support {IERC1363-transferAndCall} - * or {IERC1363-transferFromAndCall} from {ERC1363} token contracts. - */ -interface IERC1363Receiver { - /* - * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. - * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) - */ - - /** - * @notice Handle the receipt of ERC1363 tokens - * @dev Any ERC1363 smart contract calls this function on the recipient - * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the - * transfer. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the token contract address is always the message sender. - * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function - * @param from address The address which are token transferred from - * @param amount uint256 The amount of tokens transferred - * @param data bytes Additional data with no specified format - * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` unless throwing - */ - function onTransferReceived( - address operator, - address from, - uint256 amount, - bytes memory data - ) external returns (bytes4); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC1363Spender.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC1363Spender.sol deleted file mode 100644 index 0c89e58..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC1363Spender.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1363Spender.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Interface for any contract that wants to support {IERC1363-approveAndCall} - * from {ERC1363} token contracts. - */ -interface IERC1363Spender { - /* - * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. - * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) - */ - - /** - * @notice Handle the approval of ERC1363 tokens - * @dev Any ERC1363 smart contract calls this function on the recipient - * after an `approve`. This function MAY throw to revert and reject the - * approval. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the token contract address is always the message sender. - * @param owner address The address which called `approveAndCall` function - * @param amount uint256 The amount of tokens to be spent - * @param data bytes Additional data with no specified format - * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`unless throwing - */ - function onApprovalReceived(address owner, uint256 amount, bytes memory data) external returns (bytes4); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC165.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC165.sol deleted file mode 100644 index f4d9026..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC165.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) - -pragma solidity ^0.8.19; - -import "../utils/introspection/IERC165.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC1820Implementer.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC1820Implementer.sol deleted file mode 100644 index 6f0ec66..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC1820Implementer.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Implementer.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Interface for an ERC1820 implementer, as defined in the - * https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP]. - * 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); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC1820Registry.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC1820Registry.sol deleted file mode 100644 index d9dd493..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC1820Registry.sol +++ /dev/null @@ -1,112 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.8.0) (utils/introspection/IERC1820Registry.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Interface of the global ERC1820 Registry, as defined in the - * https://eips.ethereum.org/EIPS/eip-1820[EIP]. 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 EIP 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 EIP]. - */ - function interfaceHash(string calldata interfaceName) external pure returns (bytes32); - - /** - * @notice Updates the cache with whether the contract implements an ERC165 interface or not. - * @param account Address of the contract for which to update the cache. - * @param interfaceId ERC165 interface for which to update the cache. - */ - function updateERC165Cache(address account, bytes4 interfaceId) external; - - /** - * @notice Checks whether a contract implements an ERC165 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 ERC165 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 ERC165 interface or not without using or updating the cache. - * @param account Address of the contract to check. - * @param interfaceId ERC165 interface to check. - * @return True if `account` implements `interfaceId`, false otherwise. - */ - function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC1967.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC1967.sol deleted file mode 100644 index 190d86b..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC1967.sol +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol) - -pragma solidity ^0.8.19; - -/** - * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC. - * - * _Available since v4.8.3._ - */ -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); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC20.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC20.sol deleted file mode 100644 index dd559e9..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC20.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC20/IERC20.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC20Metadata.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC20Metadata.sol deleted file mode 100644 index 061fd4a..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC20Metadata.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20Metadata.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC20/extensions/IERC20Metadata.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC2309.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC2309.sol deleted file mode 100644 index 9d88869..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC2309.sol +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.8.0) (interfaces/IERC2309.sol) - -pragma solidity ^0.8.19; - -/** - * @dev ERC-2309: ERC-721 Consecutive Transfer Extension. - * - * _Available since v4.8._ - */ -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 - ); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC2612.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC2612.sol deleted file mode 100644 index 582eea8..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC2612.sol +++ /dev/null @@ -1,8 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC2612.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC20/extensions/IERC20Permit.sol"; - -interface IERC2612 is IERC20Permit {} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC2981.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC2981.sol deleted file mode 100644 index 1b14767..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC2981.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC2981.sol) - -pragma solidity ^0.8.19; - -import "../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. - * - * _Available since v4.5._ - */ -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); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC3156.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC3156.sol deleted file mode 100644 index 280b25b..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC3156.sol +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156.sol) - -pragma solidity ^0.8.19; - -import "./IERC3156FlashBorrower.sol"; -import "./IERC3156FlashLender.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC3156FlashBorrower.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC3156FlashBorrower.sol deleted file mode 100644 index 3f21619..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC3156FlashBorrower.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC3156FlashBorrower.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Interface of the ERC3156 FlashBorrower, as defined in - * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. - * - * _Available since v4.1._ - */ -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); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC3156FlashLender.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC3156FlashLender.sol deleted file mode 100644 index 89a486f..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC3156FlashLender.sol +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashLender.sol) - -pragma solidity ^0.8.19; - -import "./IERC3156FlashBorrower.sol"; - -/** - * @dev Interface of the ERC3156 FlashLender, as defined in - * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. - * - * _Available since v4.1._ - */ -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); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC4626.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC4626.sol deleted file mode 100644 index 946de91..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC4626.sol +++ /dev/null @@ -1,232 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC20/IERC20.sol"; -import "../token/ERC20/extensions/IERC20Metadata.sol"; - -/** - * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in - * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626]. - * - * _Available since v4.7._ - */ -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); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC4906.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC4906.sol deleted file mode 100644 index 96e7092..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC4906.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4906.sol) - -pragma solidity ^0.8.19; - -import "./IERC165.sol"; -import "./IERC721.sol"; - -/// @title EIP-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); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC5267.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC5267.sol deleted file mode 100644 index c19b4a6..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC5267.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol) - -pragma solidity ^0.8.19; - -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 - ); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC5313.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC5313.sol deleted file mode 100644 index 1d17080..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC5313.sol +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5313.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Interface for the Light Contract Ownership Standard. - * - * A standardized minimal interface required to identify an account that controls a contract - * - * _Available since v4.9._ - */ -interface IERC5313 { - /** - * @dev Gets the address of the owner. - */ - function owner() external view returns (address); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC5805.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC5805.sol deleted file mode 100644 index 3c0a3a6..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC5805.sol +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5805.sol) - -pragma solidity ^0.8.19; - -import "../governance/utils/IVotes.sol"; -import "./IERC6372.sol"; - -interface IERC5805 is IERC6372, IVotes {} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC721.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC721.sol deleted file mode 100644 index e840f28..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC721.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC721/IERC721.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC721Enumerable.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC721Enumerable.sol deleted file mode 100644 index fafda59..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC721Enumerable.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Enumerable.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC721/extensions/IERC721Enumerable.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC721Metadata.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC721Metadata.sol deleted file mode 100644 index f14433e..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC721Metadata.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Metadata.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC721/extensions/IERC721Metadata.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC721Receiver.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC721Receiver.sol deleted file mode 100644 index 9e62fa7..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC721Receiver.sol +++ /dev/null @@ -1,6 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Receiver.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC721/IERC721Receiver.sol"; diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC777.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC777.sol deleted file mode 100644 index f868701..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC777.sol +++ /dev/null @@ -1,199 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.19; - -/** - * @dev Interface of the ERC777Token standard as defined in the EIP. - * - * This contract uses the - * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 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 - ); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC777Recipient.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC777Recipient.sol deleted file mode 100644 index be2ab87..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC777Recipient.sol +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.19; - -/** - * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. - * - * 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[ERC1820 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; -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/IERC777Sender.sol b/blockchain/contracts/OpenZeppelin/interfaces/IERC777Sender.sol deleted file mode 100644 index d4172b1..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/IERC777Sender.sol +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.19; - -/** - * @dev Interface of the ERC777TokensSender standard as defined in the EIP. - * - * {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[ERC1820 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; -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/README.adoc b/blockchain/contracts/OpenZeppelin/interfaces/README.adoc deleted file mode 100644 index 4525bc9..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/README.adoc +++ /dev/null @@ -1,73 +0,0 @@ -= 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} -- {IERC20Metadata} -- {IERC165} -- {IERC721} -- {IERC721Receiver} -- {IERC721Enumerable} -- {IERC721Metadata} -- {IERC777} -- {IERC777Recipient} -- {IERC777Sender} -- {IERC1155} -- {IERC1155Receiver} -- {IERC1155MetadataURI} -- {IERC1271} -- {IERC1363} -- {IERC1363Receiver} -- {IERC1363Spender} -- {IERC1820Implementer} -- {IERC1820Registry} -- {IERC1822Proxiable} -- {IERC2612} -- {IERC2981} -- {IERC3156FlashLender} -- {IERC3156FlashBorrower} -- {IERC4626} -- {IERC4906} -- {IERC5267} -- {IERC5313} -- {IERC5805} -- {IERC6372} - -== Detailed ABI - -{{IERC1271}} - -{{IERC1363}} - -{{IERC1363Receiver}} - -{{IERC1363Spender}} - -{{IERC1820Implementer}} - -{{IERC1820Registry}} - -{{IERC1822Proxiable}} - -{{IERC2612}} - -{{IERC2981}} - -{{IERC3156FlashLender}} - -{{IERC3156FlashBorrower}} - -{{IERC4626}} - -{{IERC5313}} - -{{IERC5267}} - -{{IERC5805}} - -{{IERC6372}} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/draft-IERC1822.sol b/blockchain/contracts/OpenZeppelin/interfaces/draft-IERC1822.sol deleted file mode 100644 index f452b5e..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/draft-IERC1822.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) - -pragma solidity ^0.8.19; - -/** - * @dev ERC1822: 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); -} diff --git a/blockchain/contracts/OpenZeppelin/interfaces/draft-IERC6093.sol b/blockchain/contracts/OpenZeppelin/interfaces/draft-IERC6093.sol deleted file mode 100644 index cebda56..0000000 --- a/blockchain/contracts/OpenZeppelin/interfaces/draft-IERC6093.sol +++ /dev/null @@ -1,162 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.19; - -/** - * @dev Standard ERC20 Errors - * Interface of the ERC6093 custom errors for ERC20 tokens - * as defined in https://eips.ethereum.org/EIPS/eip-6093 - */ -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 ERC721 Errors - * Interface of the ERC6093 custom errors for ERC721 tokens - * as defined in https://eips.ethereum.org/EIPS/eip-6093 - */ -interface IERC721Errors { - /** - * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-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 ERC1155 Errors - * Interface of the ERC6093 custom errors for ERC1155 tokens - * as defined in https://eips.ethereum.org/EIPS/eip-6093 - */ -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. - */ - 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 ERC1155InsufficientApprovalForAll(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); -} diff --git a/blockchain/contracts/OpenZeppelin/security/Pausable.sol b/blockchain/contracts/OpenZeppelin/security/Pausable.sol deleted file mode 100644 index dc0afa6..0000000 --- a/blockchain/contracts/OpenZeppelin/security/Pausable.sol +++ /dev/null @@ -1,119 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) - -pragma solidity ^0.8.19; - -import "../utils/Context.sol"; - -/** - * @dev Contract module which allows children to implement an emergency stop - * mechanism that can be triggered by an authorized account. - * - * This module is used through inheritance. It will make available the - * modifiers `whenNotPaused` and `whenPaused`, which can be applied to - * the functions of your contract. Note that they will not be pausable by - * simply including this module, only once the modifiers are put in place. - */ -abstract contract Pausable is Context { - bool private _paused; - - /** - * @dev Emitted when the pause is triggered by `account`. - */ - event Paused(address account); - - /** - * @dev Emitted when the pause is lifted by `account`. - */ - event Unpaused(address account); - - /** - * @dev The operation failed because the contract is paused. - */ - error EnforcedPause(); - - /** - * @dev The operation failed because the contract is not paused. - */ - error ExpectedPause(); - - /** - * @dev Initializes the contract in unpaused state. - */ - constructor() { - _paused = false; - } - - /** - * @dev Modifier to make a function callable only when the contract is not paused. - * - * Requirements: - * - * - The contract must not be paused. - */ - modifier whenNotPaused() { - _requireNotPaused(); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is paused. - * - * Requirements: - * - * - The contract must be paused. - */ - modifier whenPaused() { - _requirePaused(); - _; - } - - /** - * @dev Returns true if the contract is paused, and false otherwise. - */ - function paused() public view virtual returns (bool) { - return _paused; - } - - /** - * @dev Throws if the contract is paused. - */ - function _requireNotPaused() internal view virtual { - if (paused()) { - revert EnforcedPause(); - } - } - - /** - * @dev Throws if the contract is not paused. - */ - function _requirePaused() internal view virtual { - if (!paused()) { - revert ExpectedPause(); - } - } - - /** - * @dev Triggers stopped state. - * - * Requirements: - * - * - The contract must not be paused. - */ - function _pause() internal virtual whenNotPaused { - _paused = true; - emit Paused(_msgSender()); - } - - /** - * @dev Returns to normal state. - * - * Requirements: - * - * - The contract must be paused. - */ - function _unpause() internal virtual whenPaused { - _paused = false; - emit Unpaused(_msgSender()); - } -} diff --git a/blockchain/contracts/OpenZeppelin/security/README.adoc b/blockchain/contracts/OpenZeppelin/security/README.adoc deleted file mode 100644 index 7f4799e..0000000 --- a/blockchain/contracts/OpenZeppelin/security/README.adoc +++ /dev/null @@ -1,17 +0,0 @@ -= Security - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/security - -These contracts aim to cover common security practices. - -* {ReentrancyGuard}: A modifier that can prevent reentrancy during certain functions. -* {Pausable}: A common emergency response mechanism that can pause functionality while a remediation is pending. - -TIP: For an overview on reentrancy and the possible mechanisms to prevent it, read our article https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. - -== Contracts - -{{ReentrancyGuard}} - -{{Pausable}} diff --git a/blockchain/contracts/OpenZeppelin/security/ReentrancyGuard.sol b/blockchain/contracts/OpenZeppelin/security/ReentrancyGuard.sol deleted file mode 100644 index 40ae5b0..0000000 --- a/blockchain/contracts/OpenZeppelin/security/ReentrancyGuard.sol +++ /dev/null @@ -1,84 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Contract module that helps prevent reentrant calls to a function. - * - * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier - * available, which can be applied to functions to make sure there are no nested - * (reentrant) calls to them. - * - * Note that because there is a single `nonReentrant` guard, functions marked as - * `nonReentrant` may not call one another. This can be worked around by making - * those functions `private`, and then adding `external` `nonReentrant` entry - * points to them. - * - * TIP: If you would like to learn more about reentrancy and alternative ways - * to protect against it, check out our blog post - * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. - */ -abstract contract ReentrancyGuard { - // Booleans are more expensive than uint256 or any type that takes up a full - // word because each write operation emits an extra SLOAD to first read the - // slot's contents, replace the bits taken up by the boolean, and then write - // back. This is the compiler's defense against contract upgrades and - // pointer aliasing, and it cannot be disabled. - - // The values being non-zero value makes deployment a bit more expensive, - // but in exchange the refund on every call to nonReentrant will be lower in - // amount. Since refunds are capped to a percentage of the total - // transaction's gas, it is best to keep them low in cases like this one, to - // increase the likelihood of the full refund coming into effect. - uint256 private constant _NOT_ENTERED = 1; - uint256 private constant _ENTERED = 2; - - uint256 private _status; - - /** - * @dev Unauthorized reentrant call. - */ - error ReentrancyGuardReentrantCall(); - - constructor() { - _status = _NOT_ENTERED; - } - - /** - * @dev Prevents a contract from calling itself, directly or indirectly. - * Calling a `nonReentrant` function from another `nonReentrant` - * function is not supported. It is possible to prevent this from happening - * by making the `nonReentrant` function external, and making it call a - * `private` function that does the actual work. - */ - modifier nonReentrant() { - _nonReentrantBefore(); - _; - _nonReentrantAfter(); - } - - function _nonReentrantBefore() private { - // On the first call to nonReentrant, _status will be _NOT_ENTERED - if (_status == _ENTERED) { - revert ReentrancyGuardReentrantCall(); - } - - // Any calls to nonReentrant after this point will fail - _status = _ENTERED; - } - - function _nonReentrantAfter() private { - // By storing the original value once again, a refund is triggered (see - // https://eips.ethereum.org/EIPS/eip-2200) - _status = _NOT_ENTERED; - } - - /** - * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a - * `nonReentrant` function in the call stack. - */ - function _reentrancyGuardEntered() internal view returns (bool) { - return _status == _ENTERED; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/ERC1155.sol b/blockchain/contracts/OpenZeppelin/token/ERC1155/ERC1155.sol deleted file mode 100644 index 9129992..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/ERC1155.sol +++ /dev/null @@ -1,428 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/ERC1155.sol) - -pragma solidity ^0.8.19; - -import "./IERC1155.sol"; -import "./IERC1155Receiver.sol"; -import "./extensions/IERC1155MetadataURI.sol"; -import "../../utils/Context.sol"; -import "../../utils/introspection/ERC165.sol"; -import "../../utils/Arrays.sol"; -import "../../interfaces/draft-IERC6093.sol"; - -/** - * @dev Implementation of the basic standard multi-token. - * See https://eips.ethereum.org/EIPS/eip-1155 - * Originally based on code by Enjin: https://github.com/enjin/erc-1155 - * - * _Available since v3.1._ - */ -abstract contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, IERC1155Errors { - using Arrays for uint256[]; - using Arrays for address[]; - - // Mapping from token ID to account balances - mapping(uint256 => mapping(address => uint256)) private _balances; - - // Mapping from account to operator approvals - mapping(address => mapping(address => bool)) private _operatorApprovals; - - // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json - string private _uri; - - /** - * @dev See {_setURI}. - */ - constructor(string memory uri_) { - _setURI(uri_); - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { - return - interfaceId == type(IERC1155).interfaceId || - interfaceId == type(IERC1155MetadataURI).interfaceId || - super.supportsInterface(interfaceId); - } - - /** - * @dev See {IERC1155MetadataURI-uri}. - * - * This implementation returns the same URI for *all* token types. It relies - * on the token type ID substitution mechanism - * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. - * - * Clients calling this function must replace the `\{id\}` substring with the - * actual token type ID. - */ - function uri(uint256) public view virtual returns (string memory) { - return _uri; - } - - /** - * @dev See {IERC1155-balanceOf}. - * - * Requirements: - * - * - `account` cannot be the zero address. - */ - function balanceOf(address account, uint256 id) public view virtual returns (uint256) { - return _balances[id][account]; - } - - /** - * @dev See {IERC1155-balanceOfBatch}. - * - * Requirements: - * - * - `accounts` and `ids` must have the same length. - */ - function balanceOfBatch( - address[] memory accounts, - uint256[] memory ids - ) public view virtual returns (uint256[] memory) { - if (accounts.length != ids.length) { - revert ERC1155InvalidArrayLength(ids.length, accounts.length); - } - - uint256[] memory batchBalances = new uint256[](accounts.length); - - for (uint256 i = 0; i < accounts.length; ++i) { - batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i)); - } - - return batchBalances; - } - - /** - * @dev See {IERC1155-setApprovalForAll}. - */ - function setApprovalForAll(address operator, bool approved) public virtual { - _setApprovalForAll(_msgSender(), operator, approved); - } - - /** - * @dev See {IERC1155-isApprovedForAll}. - */ - function isApprovedForAll(address account, address operator) public view virtual returns (bool) { - return _operatorApprovals[account][operator]; - } - - /** - * @dev See {IERC1155-safeTransferFrom}. - */ - function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) public virtual { - if (from != _msgSender() && !isApprovedForAll(from, _msgSender())) { - revert ERC1155InsufficientApprovalForAll(_msgSender(), from); - } - _safeTransferFrom(from, to, id, amount, data); - } - - /** - * @dev See {IERC1155-safeBatchTransferFrom}. - */ - function safeBatchTransferFrom( - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) public virtual { - if (from != _msgSender() && !isApprovedForAll(from, _msgSender())) { - revert ERC1155InsufficientApprovalForAll(_msgSender(), from); - } - _safeBatchTransferFrom(from, to, ids, amounts, data); - } - - /** - * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. Will mint (or burn) if `from` (or `to`) is the zero address. - * - * Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise. - * - * Requirements: - * - * - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received} - * or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value. - */ - function _update( - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual { - if (ids.length != amounts.length) { - revert ERC1155InvalidArrayLength(ids.length, amounts.length); - } - - address operator = _msgSender(); - - for (uint256 i = 0; i < ids.length; ++i) { - uint256 id = ids.unsafeMemoryAccess(i); - uint256 amount = amounts.unsafeMemoryAccess(i); - - if (from != address(0)) { - uint256 fromBalance = _balances[id][from]; - if (fromBalance < amount) { - revert ERC1155InsufficientBalance(from, fromBalance, amount, id); - } - unchecked { - _balances[id][from] = fromBalance - amount; - } - } - - if (to != address(0)) { - _balances[id][to] += amount; - } - } - - if (ids.length == 1) { - uint256 id = ids.unsafeMemoryAccess(0); - uint256 amount = amounts.unsafeMemoryAccess(0); - emit TransferSingle(operator, from, to, id, amount); - if (to != address(0)) { - _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); - } - } else { - emit TransferBatch(operator, from, to, ids, amounts); - if (to != address(0)) { - _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); - } - } - } - - /** - * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. - * - * Emits a {TransferSingle} event. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - `from` must have a balance of tokens of type `id` of at least `amount`. - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the - * acceptance magic value. - */ - function _safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) internal { - if (to == address(0)) { - revert ERC1155InvalidReceiver(address(0)); - } - if (from == address(0)) { - revert ERC1155InvalidSender(address(0)); - } - (uint256[] memory ids, uint256[] memory amounts) = _asSingletonArrays(id, amount); - _update(from, to, ids, amounts, data); - } - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. - * - * Emits a {TransferBatch} event. - * - * Requirements: - * - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the - * acceptance magic value. - */ - function _safeBatchTransferFrom( - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal { - if (to == address(0)) { - revert ERC1155InvalidReceiver(address(0)); - } - if (from == address(0)) { - revert ERC1155InvalidSender(address(0)); - } - _update(from, to, ids, amounts, data); - } - - /** - * @dev Sets a new URI for all token types, by relying on the token type ID - * substitution mechanism - * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. - * - * By this mechanism, any occurrence of the `\{id\}` substring in either the - * URI or any of the amounts in the JSON file at said URI will be replaced by - * clients with the token type ID. - * - * For example, the `https://token-cdn-domain/\{id\}.json` URI would be - * interpreted by clients as - * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` - * for token type ID 0x4cce0. - * - * See {uri}. - * - * Because these URIs cannot be meaningfully represented by the {URI} event, - * this function emits no events. - */ - function _setURI(string memory newuri) internal virtual { - _uri = newuri; - } - - /** - * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. - * - * Emits a {TransferSingle} event. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the - * acceptance magic value. - */ - function _mint(address to, uint256 id, uint256 amount, bytes memory data) internal { - if (to == address(0)) { - revert ERC1155InvalidReceiver(address(0)); - } - (uint256[] memory ids, uint256[] memory amounts) = _asSingletonArrays(id, amount); - _update(address(0), to, ids, amounts, data); - } - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. - * - * Emits a {TransferBatch} event. - * - * Requirements: - * - * - `ids` and `amounts` must have the same length. - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the - * acceptance magic value. - */ - function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal { - if (to == address(0)) { - revert ERC1155InvalidReceiver(address(0)); - } - _update(address(0), to, ids, amounts, data); - } - - /** - * @dev Destroys `amount` tokens of token type `id` from `from` - * - * Emits a {TransferSingle} event. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `from` must have at least `amount` tokens of token type `id`. - */ - function _burn(address from, uint256 id, uint256 amount) internal { - if (from == address(0)) { - revert ERC1155InvalidSender(address(0)); - } - (uint256[] memory ids, uint256[] memory amounts) = _asSingletonArrays(id, amount); - _update(from, address(0), ids, amounts, ""); - } - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. - * - * Emits a {TransferBatch} event. - * - * Requirements: - * - * - `ids` and `amounts` must have the same length. - */ - function _burnBatch(address from, uint256[] memory ids, uint256[] memory amounts) internal { - if (from == address(0)) { - revert ERC1155InvalidSender(address(0)); - } - _update(from, address(0), ids, amounts, ""); - } - - /** - * @dev Approve `operator` to operate on all of `owner` tokens - * - * Emits an {ApprovalForAll} event. - */ - function _setApprovalForAll(address owner, address operator, bool approved) internal virtual { - if (owner == operator) { - revert ERC1155InvalidOperator(operator); - } - _operatorApprovals[owner][operator] = approved; - emit ApprovalForAll(owner, operator, approved); - } - - function _doSafeTransferAcceptanceCheck( - address operator, - address from, - address to, - uint256 id, - uint256 amount, - bytes memory data - ) private { - if (to.code.length > 0) { - try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { - if (response != IERC1155Receiver.onERC1155Received.selector) { - // Tokens rejected - revert ERC1155InvalidReceiver(to); - } - } catch (bytes memory reason) { - if (reason.length == 0) { - // non-ERC1155Receiver implementer - revert ERC1155InvalidReceiver(to); - } else { - /// @solidity memory-safe-assembly - assembly { - revert(add(32, reason), mload(reason)) - } - } - } - } - } - - function _doSafeBatchTransferAcceptanceCheck( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) private { - if (to.code.length > 0) { - try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( - bytes4 response - ) { - if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { - // Tokens rejected - revert ERC1155InvalidReceiver(to); - } - } catch (bytes memory reason) { - if (reason.length == 0) { - // non-ERC1155Receiver implementer - revert ERC1155InvalidReceiver(to); - } else { - /// @solidity memory-safe-assembly - assembly { - revert(add(32, reason), mload(reason)) - } - } - } - } - } - - function _asSingletonArrays( - uint256 element1, - uint256 element2 - ) private pure returns (uint256[] memory array1, uint256[] memory array2) { - /// @solidity memory-safe-assembly - assembly { - array1 := mload(0x40) - mstore(array1, 1) - mstore(add(array1, 0x20), element1) - - array2 := add(array1, 0x40) - mstore(array2, 1) - mstore(add(array2, 0x20), element2) - - mstore(0x40, add(array2, 0x40)) - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/IERC1155.sol b/blockchain/contracts/OpenZeppelin/token/ERC1155/IERC1155.sol deleted file mode 100644 index 16b2b71..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/IERC1155.sol +++ /dev/null @@ -1,130 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/IERC1155.sol) - -pragma solidity ^0.8.19; - -import "../../utils/introspection/IERC165.sol"; - -/** - * @dev Required interface of an ERC1155 compliant contract, as defined in the - * https://eips.ethereum.org/EIPS/eip-1155[EIP]. - * - * _Available since v3.1._ - */ -interface IERC1155 is IERC165 { - /** - * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. - */ - event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); - - /** - * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all - * transfers. - */ - event TransferBatch( - address indexed operator, - address indexed from, - address indexed to, - uint256[] ids, - uint256[] values - ); - - /** - * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to - * `approved`. - */ - event ApprovalForAll(address indexed account, address indexed operator, bool approved); - - /** - * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. - * - * If an {URI} event was emitted for `id`, the standard - * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value - * returned by {IERC1155MetadataURI-uri}. - */ - event URI(string value, uint256 indexed id); - - /** - * @dev Returns the amount of tokens of token type `id` owned by `account`. - * - * Requirements: - * - * - `account` cannot be the zero address. - */ - function balanceOf(address account, uint256 id) external view returns (uint256); - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. - * - * Requirements: - * - * - `accounts` and `ids` must have the same length. - */ - function balanceOfBatch( - address[] calldata accounts, - uint256[] calldata ids - ) external view returns (uint256[] memory); - - /** - * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, - * - * Emits an {ApprovalForAll} event. - * - * Requirements: - * - * - `operator` cannot be the caller. - */ - function setApprovalForAll(address operator, bool approved) external; - - /** - * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. - * - * See {setApprovalForAll}. - */ - function isApprovedForAll(address account, address operator) external view returns (bool); - - /** - * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. - * - * WARNING: This function can potentially allow a reentrancy attack when transferring tokens - * to an untrusted contract, when invoking {onERC1155Received} on the receiver. - * Ensure to follow the checks-effects-interactions pattern and consider employing - * reentrancy guards when interacting with untrusted contracts. - * - * Emits a {TransferSingle} event. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}. - * - `from` must have a balance of tokens of type `id` of at least `amount`. - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the - * acceptance magic value. - */ - function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; - - /** - * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. - * - * - * WARNING: This function can potentially allow a reentrancy attack when transferring tokens - * to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver. - * Ensure to follow the checks-effects-interactions pattern and consider employing - * reentrancy guards when interacting with untrusted contracts. - * - * Emits a {TransferBatch} event. - * - * Requirements: - * - * - `ids` and `amounts` must have the same length. - * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the - * acceptance magic value. - */ - function safeBatchTransferFrom( - address from, - address to, - uint256[] calldata ids, - uint256[] calldata amounts, - bytes calldata data - ) external; -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/IERC1155Receiver.sol b/blockchain/contracts/OpenZeppelin/token/ERC1155/IERC1155Receiver.sol deleted file mode 100644 index a272f61..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/IERC1155Receiver.sol +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) - -pragma solidity ^0.8.19; - -import "../../utils/introspection/IERC165.sol"; - -/** - * @dev _Available since v3.1._ - */ -interface IERC1155Receiver is IERC165 { - /** - * @dev Handles the receipt of a single ERC1155 token type. This function is - * called at the end of a `safeTransferFrom` after the balance has been updated. - * - * NOTE: To accept the transfer, this must return - * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` - * (i.e. 0xf23a6e61, or its own function selector). - * - * @param operator The address which initiated the transfer (i.e. msg.sender) - * @param from The address which previously owned the token - * @param id The ID of the token being transferred - * @param value The amount of tokens being transferred - * @param data Additional data with no specified format - * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed - */ - function onERC1155Received( - address operator, - address from, - uint256 id, - uint256 value, - bytes calldata data - ) external returns (bytes4); - - /** - * @dev Handles the receipt of a multiple ERC1155 token types. This function - * is called at the end of a `safeBatchTransferFrom` after the balances have - * been updated. - * - * NOTE: To accept the transfer(s), this must return - * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` - * (i.e. 0xbc197c81, or its own function selector). - * - * @param operator The address which initiated the batch transfer (i.e. msg.sender) - * @param from The address which previously owned the token - * @param ids An array containing ids of each token being transferred (order and length must match values array) - * @param values An array containing amounts of each token being transferred (order and length must match ids array) - * @param data Additional data with no specified format - * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed - */ - function onERC1155BatchReceived( - address operator, - address from, - uint256[] calldata ids, - uint256[] calldata values, - bytes calldata data - ) external returns (bytes4); -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/README.adoc b/blockchain/contracts/OpenZeppelin/token/ERC1155/README.adoc deleted file mode 100644 index 48c7faa..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/README.adoc +++ /dev/null @@ -1,43 +0,0 @@ -= ERC 1155 - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc1155 - -This set of interfaces and contracts are all related to the https://eips.ethereum.org/EIPS/eip-1155[ERC1155 Multi Token Standard]. - -The EIP consists of three interfaces which fulfill different roles, found here as {IERC1155}, {IERC1155MetadataURI} and {IERC1155Receiver}. - -{ERC1155} implements the mandatory {IERC1155} interface, as well as the optional extension {IERC1155MetadataURI}, by relying on the substitution mechanism to use the same URI for all token types, dramatically reducing gas costs. - -Additionally there are multiple custom extensions, including: - -* designation of addresses that can pause token transfers for all users ({ERC1155Pausable}). -* destruction of own tokens ({ERC1155Burnable}). - -NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC1155 (such as <>) and expose them as external functions in the way they prefer. - -== Core - -{{IERC1155}} - -{{IERC1155MetadataURI}} - -{{ERC1155}} - -{{IERC1155Receiver}} - -{{ERC1155Receiver}} - -== Extensions - -{{ERC1155Pausable}} - -{{ERC1155Burnable}} - -{{ERC1155Supply}} - -{{ERC1155URIStorage}} - -== Utilities - -{{ERC1155Holder}} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155Burnable.sol b/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155Burnable.sol deleted file mode 100644 index ff099cb..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155Burnable.sol +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/extensions/ERC1155Burnable.sol) - -pragma solidity ^0.8.19; - -import "../ERC1155.sol"; - -/** - * @dev Extension of {ERC1155} that allows token holders to destroy both their - * own tokens and those that they have been approved to use. - * - * _Available since v3.1._ - */ -abstract contract ERC1155Burnable is ERC1155 { - function burn(address account, uint256 id, uint256 value) public virtual { - if (account != _msgSender() && !isApprovedForAll(account, _msgSender())) { - revert ERC1155InsufficientApprovalForAll(_msgSender(), account); - } - - _burn(account, id, value); - } - - function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual { - if (account != _msgSender() && !isApprovedForAll(account, _msgSender())) { - revert ERC1155InsufficientApprovalForAll(_msgSender(), account); - } - - _burnBatch(account, ids, values); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155Pausable.sol b/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155Pausable.sol deleted file mode 100644 index f835706..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155Pausable.sol +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.8.2) (token/ERC1155/extensions/ERC1155Pausable.sol) - -pragma solidity ^0.8.19; - -import "../ERC1155.sol"; -import "../../../security/Pausable.sol"; - -/** - * @dev ERC1155 token with pausable token transfers, minting and burning. - * - * Useful for scenarios such as preventing trades until the end of an evaluation - * period, or having an emergency switch for freezing all token transfers in the - * event of a large bug. - * - * IMPORTANT: This contract does not include public pause and unpause functions. In - * addition to inheriting this contract, you must define both functions, invoking the - * {Pausable-_pause} and {Pausable-_unpause} internal functions, with appropriate - * access control, e.g. using {AccessControl} or {Ownable}. Not doing so will - * make the contract unpausable. - * - * _Available since v3.1._ - */ -abstract contract ERC1155Pausable is ERC1155, Pausable { - /** - * @dev See {ERC1155-_update}. - * - * Requirements: - * - * - the contract must not be paused. - */ - function _update( - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual override whenNotPaused { - super._update(from, to, ids, amounts, data); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155Supply.sol b/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155Supply.sol deleted file mode 100644 index f32fbb7..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155Supply.sol +++ /dev/null @@ -1,82 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol) - -pragma solidity ^0.8.19; - -import "../ERC1155.sol"; - -/** - * @dev Extension of ERC1155 that adds tracking of total supply per id. - * - * Useful for scenarios where Fungible and Non-fungible tokens have to be - * clearly identified. Note: While a totalSupply of 1 might mean the - * corresponding is an NFT, there is no guarantees that no other token with the - * same id are not going to be minted. - * - * NOTE: This contract implies a global limit of 2**256 - 1 to the number of tokens - * that can be minted. - */ -abstract contract ERC1155Supply is ERC1155 { - mapping(uint256 => uint256) private _totalSupply; - uint256 private _totalSupplyAll; - - /** - * @dev Total amount of tokens in with a given id. - */ - function totalSupply(uint256 id) public view virtual returns (uint256) { - return _totalSupply[id]; - } - - /** - * @dev Total amount of tokens. - */ - function totalSupply() public view virtual returns (uint256) { - return _totalSupplyAll; - } - - /** - * @dev Indicates whether any token exist with a given id, or not. - */ - function exists(uint256 id) public view virtual returns (bool) { - return totalSupply(id) > 0; - } - - /** - * @dev See {ERC1155-_update}. - */ - function _update( - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual override { - if (from == address(0)) { - uint256 totalMintAmount = 0; - for (uint256 i = 0; i < ids.length; ++i) { - uint256 amount = amounts[i]; - _totalSupply[ids[i]] += amount; - totalMintAmount += amount; - } - _totalSupplyAll += totalMintAmount; - } - - if (to == address(0)) { - uint256 totalBurnAmount = 0; - for (uint256 i = 0; i < ids.length; ++i) { - uint256 id = ids[i]; - uint256 amount = amounts[i]; - _totalSupply[id] -= amount; - unchecked { - // Overflow not possible: sum(amounts[i]) <= sum(totalSupply(i)) <= totalSupplyAll - totalBurnAmount += amount; - } - } - unchecked { - // Overflow not possible: totalBurnAmount = sum(amounts[i]) <= sum(totalSupply(i)) <= totalSupplyAll - _totalSupplyAll -= totalBurnAmount; - } - } - super._update(from, to, ids, amounts, data); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155URIStorage.sol b/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155URIStorage.sol deleted file mode 100644 index 79782a4..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/ERC1155URIStorage.sol +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155URIStorage.sol) - -pragma solidity ^0.8.19; - -import "../../../utils/Strings.sol"; -import "../ERC1155.sol"; - -/** - * @dev ERC1155 token with storage based token URI management. - * Inspired by the ERC721URIStorage extension - * - * _Available since v4.6._ - */ -abstract contract ERC1155URIStorage is ERC1155 { - using Strings for uint256; - - // Optional base URI - string private _baseURI = ""; - - // Optional mapping for token URIs - mapping(uint256 => string) private _tokenURIs; - - /** - * @dev See {IERC1155MetadataURI-uri}. - * - * This implementation returns the concatenation of the `_baseURI` - * and the token-specific uri if the latter is set - * - * This enables the following behaviors: - * - * - if `_tokenURIs[tokenId]` is set, then the result is the concatenation - * of `_baseURI` and `_tokenURIs[tokenId]` (keep in mind that `_baseURI` - * is empty per default); - * - * - if `_tokenURIs[tokenId]` is NOT set then we fallback to `super.uri()` - * which in most cases will contain `ERC1155._uri`; - * - * - if `_tokenURIs[tokenId]` is NOT set, and if the parents do not have a - * uri value set, then the result is empty. - */ - function uri(uint256 tokenId) public view virtual override returns (string memory) { - string memory tokenURI = _tokenURIs[tokenId]; - - // If token URI is set, concatenate base URI and tokenURI (via string.concat). - return bytes(tokenURI).length > 0 ? string.concat(_baseURI, tokenURI) : super.uri(tokenId); - } - - /** - * @dev Sets `tokenURI` as the tokenURI of `tokenId`. - */ - function _setURI(uint256 tokenId, string memory tokenURI) internal virtual { - _tokenURIs[tokenId] = tokenURI; - emit URI(uri(tokenId), tokenId); - } - - /** - * @dev Sets `baseURI` as the `_baseURI` for all tokens - */ - function _setBaseURI(string memory baseURI) internal virtual { - _baseURI = baseURI; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/IERC1155MetadataURI.sol b/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/IERC1155MetadataURI.sol deleted file mode 100644 index 2c99899..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/extensions/IERC1155MetadataURI.sol +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) - -pragma solidity ^0.8.19; - -import "../IERC1155.sol"; - -/** - * @dev Interface of the optional ERC1155MetadataExtension interface, as defined - * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. - * - * _Available since v3.1._ - */ -interface IERC1155MetadataURI is IERC1155 { - /** - * @dev Returns the URI for token type `id`. - * - * If the `\{id\}` substring is present in the URI, it must be replaced by - * clients with the actual token type ID. - */ - function uri(uint256 id) external view returns (string memory); -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/utils/ERC1155Holder.sol b/blockchain/contracts/OpenZeppelin/token/ERC1155/utils/ERC1155Holder.sol deleted file mode 100644 index d24a1a5..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/utils/ERC1155Holder.sol +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol) - -pragma solidity ^0.8.19; - -import "./ERC1155Receiver.sol"; - -/** - * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens. - * - * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be - * stuck. - * - * @dev _Available since v3.1._ - */ -abstract contract ERC1155Holder is ERC1155Receiver { - function onERC1155Received( - address, - address, - uint256, - uint256, - bytes memory - ) public virtual override returns (bytes4) { - return this.onERC1155Received.selector; - } - - function onERC1155BatchReceived( - address, - address, - uint256[] memory, - uint256[] memory, - bytes memory - ) public virtual override returns (bytes4) { - return this.onERC1155BatchReceived.selector; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC1155/utils/ERC1155Receiver.sol b/blockchain/contracts/OpenZeppelin/token/ERC1155/utils/ERC1155Receiver.sol deleted file mode 100644 index 6fb2149..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC1155/utils/ERC1155Receiver.sol +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol) - -pragma solidity ^0.8.19; - -import "../IERC1155Receiver.sol"; -import "../../../utils/introspection/ERC165.sol"; - -/** - * @dev _Available since v3.1._ - */ -abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { - return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/ERC20.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/ERC20.sol deleted file mode 100644 index aacfe79..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/ERC20.sol +++ /dev/null @@ -1,343 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) - -pragma solidity ^0.8.19; - -import "./IERC20.sol"; -import "./extensions/IERC20Metadata.sol"; -import "../../utils/Context.sol"; -import "../../interfaces/draft-IERC6093.sol"; - -/** - * @dev Implementation of the {IERC20} interface. - * - * This implementation is agnostic to the way tokens are created. This means - * that a supply mechanism has to be added in a derived contract using {_mint}. - * - * TIP: For a detailed writeup see our guide - * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How - * to implement supply mechanisms]. - * - * The default value of {decimals} is 18. To change this, you should override - * this function so it returns a different value. - * - * We have followed general OpenZeppelin Contracts guidelines: functions revert - * instead returning `false` on failure. This behavior is nonetheless - * conventional and does not conflict with the expectations of ERC20 - * applications. - * - * Additionally, an {Approval} event is emitted on calls to {transferFrom}. - * This allows applications to reconstruct the allowance for all accounts just - * by listening to said events. Other implementations of the EIP may not emit - * these events, as it isn't required by the specification. - * - * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} - * functions have been added to mitigate the well-known issues around setting - * allowances. See {IERC20-approve}. - */ -abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors { - mapping(address => uint256) private _balances; - - mapping(address => mapping(address => uint256)) private _allowances; - - uint256 private _totalSupply; - - string private _name; - string private _symbol; - - /** - * @dev Indicates a failed `decreaseAllowance` request. - */ - error ERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); - - /** - * @dev Sets the values for {name} and {symbol}. - * - * All two of these values are immutable: they can only be set once during - * construction. - */ - constructor(string memory name_, string memory symbol_) { - _name = name_; - _symbol = symbol_; - } - - /** - * @dev Returns the name of the token. - */ - function name() public view virtual returns (string memory) { - return _name; - } - - /** - * @dev Returns the symbol of the token, usually a shorter version of the - * name. - */ - function symbol() public view virtual returns (string memory) { - return _symbol; - } - - /** - * @dev Returns the number of decimals used to get its user representation. - * For example, if `decimals` equals `2`, a balance of `505` tokens should - * be displayed to a user as `5.05` (`505 / 10 ** 2`). - * - * Tokens usually opt for a value of 18, imitating the relationship between - * Ether and Wei. This is the default value returned by this function, unless - * it's overridden. - * - * NOTE: This information is only used for _display_ purposes: it in - * no way affects any of the arithmetic of the contract, including - * {IERC20-balanceOf} and {IERC20-transfer}. - */ - function decimals() public view virtual returns (uint8) { - return 18; - } - - /** - * @dev See {IERC20-totalSupply}. - */ - function totalSupply() public view virtual returns (uint256) { - return _totalSupply; - } - - /** - * @dev See {IERC20-balanceOf}. - */ - function balanceOf(address account) public view virtual returns (uint256) { - return _balances[account]; - } - - /** - * @dev See {IERC20-transfer}. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - the caller must have a balance of at least `amount`. - */ - function transfer(address to, uint256 amount) public virtual returns (bool) { - address owner = _msgSender(); - _transfer(owner, to, amount); - return true; - } - - /** - * @dev See {IERC20-allowance}. - */ - function allowance(address owner, address spender) public view virtual returns (uint256) { - return _allowances[owner][spender]; - } - - /** - * @dev See {IERC20-approve}. - * - * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on - * `transferFrom`. This is semantically equivalent to an infinite approval. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function approve(address spender, uint256 amount) public virtual returns (bool) { - address owner = _msgSender(); - _approve(owner, spender, amount); - return true; - } - - /** - * @dev See {IERC20-transferFrom}. - * - * Emits an {Approval} event indicating the updated allowance. This is not - * required by the EIP. See the note at the beginning of {ERC20}. - * - * NOTE: Does not update the allowance if the current allowance - * is the maximum `uint256`. - * - * Requirements: - * - * - `from` and `to` cannot be the zero address. - * - `from` must have a balance of at least `amount`. - * - the caller must have allowance for ``from``'s tokens of at least - * `amount`. - */ - function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) { - address spender = _msgSender(); - _spendAllowance(from, spender, amount); - _transfer(from, to, amount); - return true; - } - - /** - * @dev Atomically increases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { - address owner = _msgSender(); - _approve(owner, spender, allowance(owner, spender) + addedValue); - return true; - } - - /** - * @dev Atomically decreases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `spender` must have allowance for the caller of at least - * `requestedDecrease`. - */ - function decreaseAllowance(address spender, uint256 requestedDecrease) public virtual returns (bool) { - address owner = _msgSender(); - uint256 currentAllowance = allowance(owner, spender); - if (currentAllowance < requestedDecrease) { - revert ERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); - } - unchecked { - _approve(owner, spender, currentAllowance - requestedDecrease); - } - - return true; - } - - /** - * @dev Moves `amount` of tokens from `from` to `to`. - * - * This internal function is equivalent to {transfer}, and can be used to - * e.g. implement automatic token fees, slashing mechanisms, etc. - * - * Emits a {Transfer} event. - * - * NOTE: This function is not virtual, {_update} should be overridden instead. - */ - function _transfer(address from, address to, uint256 amount) internal { - if (from == address(0)) { - revert ERC20InvalidSender(address(0)); - } - if (to == address(0)) { - revert ERC20InvalidReceiver(address(0)); - } - _update(from, to, amount); - } - - /** - * @dev Transfers `amount` of tokens from `from` to `to`, or alternatively mints (or burns) if `from` (or `to`) is - * the zero address. All customizations to transfers, mints, and burns should be done by overriding this function. - * - * Emits a {Transfer} event. - */ - function _update(address from, address to, uint256 amount) internal virtual { - if (from == address(0)) { - _totalSupply += amount; - } else { - uint256 fromBalance = _balances[from]; - if (fromBalance < amount) { - revert ERC20InsufficientBalance(from, fromBalance, amount); - } - unchecked { - // Overflow not possible: amount <= fromBalance <= totalSupply. - _balances[from] = fromBalance - amount; - } - } - - if (to == address(0)) { - unchecked { - // Overflow not possible: amount <= totalSupply or amount <= fromBalance <= totalSupply. - _totalSupply -= amount; - } - } else { - unchecked { - // Overflow not possible: balance + amount is at most totalSupply, which we know fits into a uint256. - _balances[to] += amount; - } - } - - emit Transfer(from, to, amount); - } - - /** - * @dev Creates `amount` tokens and assigns them to `account`, by transferring it from address(0). - * Relies on the `_update` mechanism - * - * Emits a {Transfer} event with `from` set to the zero address. - * - * NOTE: This function is not virtual, {_update} should be overridden instead. - */ - function _mint(address account, uint256 amount) internal { - if (account == address(0)) { - revert ERC20InvalidReceiver(address(0)); - } - _update(address(0), account, amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, by transferring it to address(0). - * Relies on the `_update` mechanism. - * - * Emits a {Transfer} event with `to` set to the zero address. - * - * NOTE: This function is not virtual, {_update} should be overridden instead - */ - function _burn(address account, uint256 amount) internal { - if (account == address(0)) { - revert ERC20InvalidSender(address(0)); - } - _update(account, address(0), amount); - } - - /** - * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. - * - * This internal function is equivalent to `approve`, and can be used to - * e.g. set automatic allowances for certain subsystems, etc. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `owner` cannot be the zero address. - * - `spender` cannot be the zero address. - */ - function _approve(address owner, address spender, uint256 amount) internal virtual { - if (owner == address(0)) { - revert ERC20InvalidApprover(address(0)); - } - if (spender == address(0)) { - revert ERC20InvalidSpender(address(0)); - } - _allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } - - /** - * @dev Updates `owner` s allowance for `spender` based on spent `amount`. - * - * Does not update the allowance amount in case of infinite allowance. - * Revert if not enough allowance is available. - * - * Might emit an {Approval} event. - */ - function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { - uint256 currentAllowance = allowance(owner, spender); - if (currentAllowance != type(uint256).max) { - if (currentAllowance < amount) { - revert ERC20InsufficientAllowance(spender, currentAllowance, amount); - } - unchecked { - _approve(owner, spender, currentAllowance - amount); - } - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/IERC20.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/IERC20.sol deleted file mode 100644 index a19535a..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/IERC20.sol +++ /dev/null @@ -1,78 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Interface of the ERC20 standard as defined in the EIP. - */ -interface IERC20 { - /** - * @dev Emitted when `value` tokens are moved from one account (`from`) to - * another (`to`). - * - * Note that `value` may be zero. - */ - event Transfer(address indexed from, address indexed to, uint256 value); - - /** - * @dev Emitted when the allowance of a `spender` for an `owner` is set by - * a call to {approve}. `value` is the new allowance. - */ - event Approval(address indexed owner, address indexed spender, uint256 value); - - /** - * @dev Returns the amount of tokens in existence. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns the amount of tokens owned by `account`. - */ - function balanceOf(address account) external view returns (uint256); - - /** - * @dev Moves `amount` tokens from the caller's account to `to`. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transfer(address to, uint256 amount) external returns (bool); - - /** - * @dev Returns the remaining number of tokens that `spender` will be - * allowed to spend on behalf of `owner` through {transferFrom}. This is - * zero by default. - * - * This value changes when {approve} or {transferFrom} are called. - */ - function allowance(address owner, address spender) external view returns (uint256); - - /** - * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * IMPORTANT: Beware that changing an allowance with this method brings the risk - * that someone may use both the old and the new allowance by unfortunate - * transaction ordering. One possible solution to mitigate this race - * condition is to first reduce the spender's allowance to 0 and set the - * desired value afterwards: - * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 - * - * Emits an {Approval} event. - */ - function approve(address spender, uint256 amount) external returns (bool); - - /** - * @dev Moves `amount` tokens from `from` to `to` using the - * allowance mechanism. `amount` is then deducted from the caller's - * allowance. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transferFrom(address from, address to, uint256 amount) external returns (bool); -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/README.adoc b/blockchain/contracts/OpenZeppelin/token/ERC20/README.adoc deleted file mode 100644 index 9482b58..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/README.adoc +++ /dev/null @@ -1,65 +0,0 @@ -= ERC 20 - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc20 - -This set of interfaces, contracts, and utilities are all related to the https://eips.ethereum.org/EIPS/eip-20[ERC20 Token Standard]. - -TIP: For an overview of ERC20 tokens and a walk through on how to create a token contract read our xref:ROOT:erc20.adoc[ERC20 guide]. - -There are a few core contracts that implement the behavior specified in the EIP: - -* {IERC20}: the interface all ERC20 implementations should conform to. -* {IERC20Metadata}: the extended ERC20 interface including the <>, <> and <> functions. -* {ERC20}: the implementation of the ERC20 interface, including the <>, <> and <> optional standard extension to the base interface. - -Additionally there are multiple custom extensions, including: - -* {ERC20Burnable}: destruction of own tokens. -* {ERC20Capped}: enforcement of a cap to the total supply when minting tokens. -* {ERC20Pausable}: ability to pause token transfers. -* {ERC20Permit}: gasless approval of tokens (standardized as ERC2612). -* {ERC20FlashMint}: token level support for flash loans through the minting and burning of ephemeral tokens (standardized as ERC3156). -* {ERC20Votes}: support for voting and vote delegation. -* {ERC20Wrapper}: wrapper to create an ERC20 backed by another ERC20, with deposit and withdraw methods. Useful in conjunction with {ERC20Votes}. -* {ERC4626}: tokenized vault that manages shares (represented as ERC20) that are backed by assets (another ERC20). - -Finally, there are some utilities to interact with ERC20 contracts in various ways: - -* {SafeERC20}: a wrapper around the interface that eliminates the need to handle boolean return values. - -Other utilities that support ERC20 assets can be found in codebase: - -* ERC20 tokens can be timelocked (held tokens for a beneficiary until a specified time) or vested (released following a given schedule) using a {VestingWallet}. - -NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC20 (such as <>) and expose them as external functions in the way they prefer. - -== Core - -{{IERC20}} - -{{IERC20Metadata}} - -{{ERC20}} - -== Extensions - -{{ERC20Burnable}} - -{{ERC20Capped}} - -{{ERC20Pausable}} - -{{ERC20Permit}} - -{{ERC20Votes}} - -{{ERC20Wrapper}} - -{{ERC20FlashMint}} - -{{ERC4626}} - -== Utilities - -{{SafeERC20}} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Burnable.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Burnable.sol deleted file mode 100644 index cae186b..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Burnable.sol +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) - -pragma solidity ^0.8.19; - -import "../ERC20.sol"; -import "../../../utils/Context.sol"; - -/** - * @dev Extension of {ERC20} that allows token holders to destroy both their own - * tokens and those that they have an allowance for, in a way that can be - * recognized off-chain (via event analysis). - */ -abstract contract ERC20Burnable is Context, ERC20 { - /** - * @dev Destroys `amount` tokens from the caller. - * - * See {ERC20-_burn}. - */ - function burn(uint256 amount) public virtual { - _burn(_msgSender(), amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, deducting from the caller's - * allowance. - * - * See {ERC20-_burn} and {ERC20-allowance}. - * - * Requirements: - * - * - the caller must have allowance for ``accounts``'s tokens of at least - * `amount`. - */ - function burnFrom(address account, uint256 amount) public virtual { - _spendAllowance(account, _msgSender(), amount); - _burn(account, amount); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Capped.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Capped.sol deleted file mode 100644 index 41e9ce5..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Capped.sol +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Capped.sol) - -pragma solidity ^0.8.19; - -import "../ERC20.sol"; - -/** - * @dev Extension of {ERC20} that adds a cap to the supply of tokens. - */ -abstract contract ERC20Capped is ERC20 { - uint256 private immutable _cap; - - /** - * @dev Total supply cap has been exceeded. - */ - error ERC20ExceededCap(uint256 increasedSupply, uint256 cap); - - /** - * @dev The supplied cap is not a valid cap. - */ - error ERC20InvalidCap(uint256 cap); - - /** - * @dev Sets the value of the `cap`. This value is immutable, it can only be - * set once during construction. - */ - constructor(uint256 cap_) { - if (cap_ == 0) { - revert ERC20InvalidCap(0); - } - _cap = cap_; - } - - /** - * @dev Returns the cap on the token's total supply. - */ - function cap() public view virtual returns (uint256) { - return _cap; - } - - /** - * @dev See {ERC20-_update}. - */ - function _update(address from, address to, uint256 amount) internal virtual override { - super._update(from, to, amount); - - if (from == address(0)) { - uint256 maxSupply = cap(); - uint256 supply = totalSupply(); - if (supply > maxSupply) { - revert ERC20ExceededCap(supply, maxSupply); - } - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20FlashMint.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20FlashMint.sol deleted file mode 100644 index 09c20ba..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20FlashMint.sol +++ /dev/null @@ -1,128 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/extensions/ERC20FlashMint.sol) - -pragma solidity ^0.8.19; - -import "../../../interfaces/IERC3156FlashBorrower.sol"; -import "../../../interfaces/IERC3156FlashLender.sol"; -import "../ERC20.sol"; - -/** - * @dev Implementation of the ERC3156 Flash loans extension, as defined in - * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. - * - * Adds the {flashLoan} method, which provides flash loan support at the token - * level. By default there is no fee, but this can be changed by overriding {flashFee}. - * - * _Available since v4.1._ - */ -abstract contract ERC20FlashMint is ERC20, IERC3156FlashLender { - bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); - - /** - * @dev The loan token is not valid. - */ - error ERC3156UnsupportedToken(address token); - - /** - * @dev The requested loan exceeds the max loan amount for `token`. - */ - error ERC3156ExceededMaxLoan(uint256 maxLoan); - - /** - * @dev The receiver of a flashloan is not a valid {onFlashLoan} implementer. - */ - error ERC3156InvalidReceiver(address receiver); - - /** - * @dev Returns the maximum amount of tokens available for loan. - * @param token The address of the token that is requested. - * @return The amount of token that can be loaned. - */ - function maxFlashLoan(address token) public view virtual returns (uint256) { - return token == address(this) ? type(uint256).max - totalSupply() : 0; - } - - /** - * @dev Returns the fee applied when doing flash loans. This function calls - * the {_flashFee} function which returns the fee applied when doing flash - * loans. - * @param token The token to be flash loaned. - * @param amount The amount of tokens to be loaned. - * @return The fees applied to the corresponding flash loan. - */ - function flashFee(address token, uint256 amount) public view virtual returns (uint256) { - if (token != address(this)) { - revert ERC3156UnsupportedToken(token); - } - return _flashFee(token, amount); - } - - /** - * @dev Returns the fee applied when doing flash loans. By default this - * implementation has 0 fees. This function can be overloaded to make - * the flash loan mechanism deflationary. - * @param token The token to be flash loaned. - * @param amount The amount of tokens to be loaned. - * @return The fees applied to the corresponding flash loan. - */ - function _flashFee(address token, uint256 amount) internal view virtual returns (uint256) { - // silence warning about unused variable without the addition of bytecode. - token; - amount; - return 0; - } - - /** - * @dev Returns the receiver address of the flash fee. By default this - * implementation returns the address(0) which means the fee amount will be burnt. - * This function can be overloaded to change the fee receiver. - * @return The address for which the flash fee will be sent to. - */ - function _flashFeeReceiver() internal view virtual returns (address) { - return address(0); - } - - /** - * @dev Performs a flash loan. New tokens are minted and sent to the - * `receiver`, who is required to implement the {IERC3156FlashBorrower} - * interface. By the end of the flash loan, the receiver is expected to own - * amount + fee tokens and have them approved back to the token contract itself so - * they can be burned. - * @param receiver The receiver of the flash loan. Should implement the - * {IERC3156FlashBorrower-onFlashLoan} interface. - * @param token The token to be flash loaned. Only `address(this)` is - * supported. - * @param amount The amount of tokens to be loaned. - * @param data An arbitrary datafield that is passed to the receiver. - * @return `true` if the flash loan was successful. - */ - // This function can reenter, but it doesn't pose a risk because it always preserves the property that the amount - // minted at the beginning is always recovered and burned at the end, or else the entire function will revert. - // slither-disable-next-line reentrancy-no-eth - function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data - ) public virtual returns (bool) { - uint256 maxLoan = maxFlashLoan(token); - if (amount > maxLoan) { - revert ERC3156ExceededMaxLoan(maxLoan); - } - uint256 fee = flashFee(token, amount); - _mint(address(receiver), amount); - if (receiver.onFlashLoan(msg.sender, token, amount, fee, data) != _RETURN_VALUE) { - revert ERC3156InvalidReceiver(address(receiver)); - } - address flashFeeReceiver = _flashFeeReceiver(); - _spendAllowance(address(receiver), address(this), amount + fee); - if (fee == 0 || flashFeeReceiver == address(0)) { - _burn(address(receiver), amount + fee); - } else { - _burn(address(receiver), amount); - _transfer(address(receiver), flashFeeReceiver, fee); - } - return true; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Pausable.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Pausable.sol deleted file mode 100644 index 5ef50f9..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Pausable.sol +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Pausable.sol) - -pragma solidity ^0.8.19; - -import "../ERC20.sol"; -import "../../../security/Pausable.sol"; - -/** - * @dev ERC20 token with pausable token transfers, minting and burning. - * - * Useful for scenarios such as preventing trades until the end of an evaluation - * period, or having an emergency switch for freezing all token transfers in the - * event of a large bug. - * - * IMPORTANT: This contract does not include public pause and unpause functions. In - * addition to inheriting this contract, you must define both functions, invoking the - * {Pausable-_pause} and {Pausable-_unpause} internal functions, with appropriate - * access control, e.g. using {AccessControl} or {Ownable}. Not doing so will - * make the contract unpausable. - */ -abstract contract ERC20Pausable is ERC20, Pausable { - /** - * @dev See {ERC20-_update}. - * - * Requirements: - * - * - the contract must not be paused. - */ - function _update(address from, address to, uint256 amount) internal virtual override whenNotPaused { - super._update(from, to, amount); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Permit.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Permit.sol deleted file mode 100644 index 4378eb7..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Permit.sol +++ /dev/null @@ -1,86 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Permit.sol) - -pragma solidity ^0.8.19; - -import "./IERC20Permit.sol"; -import "../ERC20.sol"; -import "../../../utils/cryptography/ECDSA.sol"; -import "../../../utils/cryptography/EIP712.sol"; -import "../../../utils/Nonces.sol"; - -/** - * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in - * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. - * - * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by - * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't - * need to send a transaction, and thus is not required to hold Ether at all. - * - * _Available since v3.4._ - */ -abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces { - // solhint-disable-next-line var-name-mixedcase - bytes32 private constant _PERMIT_TYPEHASH = - keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); - - /** - * @dev Permit deadline has expired. - */ - error ERC2612ExpiredSignature(uint256 deadline); - - /** - * @dev Mismatched signature. - */ - error ERC2612InvalidSigner(address signer, address owner); - - /** - * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. - * - * It's a good idea to use the same `name` that is defined as the ERC20 token name. - */ - constructor(string memory name) EIP712(name, "1") {} - - /** - * @dev See {IERC20Permit-permit}. - */ - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual { - if (block.timestamp > deadline) { - revert ERC2612ExpiredSignature(deadline); - } - - bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); - - bytes32 hash = _hashTypedDataV4(structHash); - - address signer = ECDSA.recover(hash, v, r, s); - if (signer != owner) { - revert ERC2612InvalidSigner(signer, owner); - } - - _approve(owner, spender, value); - } - - /** - * @dev See {IERC20Permit-nonces}. - */ - function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) { - return super.nonces(owner); - } - - /** - * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. - */ - // solhint-disable-next-line func-name-mixedcase - function DOMAIN_SEPARATOR() external view virtual returns (bytes32) { - return _domainSeparatorV4(); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Votes.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Votes.sol deleted file mode 100644 index 98f798e..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Votes.sol +++ /dev/null @@ -1,75 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Votes.sol) - -pragma solidity ^0.8.19; - -import "../ERC20.sol"; -import "../../../governance/utils/Votes.sol"; -import "../../../utils/math/SafeCast.sol"; - -/** - * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, - * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. - * - * NOTE: This contract does not provide interface compatibility with Compound's COMP token. - * - * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either - * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting - * power can be queried through the public accessors {getVotes} and {getPastVotes}. - * - * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it - * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. - * - * _Available since v4.2._ - */ -abstract contract ERC20Votes is ERC20, Votes { - /** - * @dev Total supply cap has been exceeded, introducing a risk of votes overflowing. - */ - error ERC20ExceededSafeSupply(uint256 increasedSupply, uint256 cap); - - /** - * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). - */ - function _maxSupply() internal view virtual returns (uint224) { - return type(uint224).max; - } - - /** - * @dev Move voting power when tokens are transferred. - * - * Emits a {IVotes-DelegateVotesChanged} event. - */ - function _update(address from, address to, uint256 amount) internal virtual override { - super._update(from, to, amount); - if (from == address(0)) { - uint256 supply = totalSupply(); - uint256 cap = _maxSupply(); - if (supply > cap) { - revert ERC20ExceededSafeSupply(supply, cap); - } - } - _transferVotingUnits(from, to, amount); - } - - /** - * @dev Returns the balance of `account`. - */ - function _getVotingUnits(address account) internal view virtual override returns (uint256) { - return balanceOf(account); - } - - /** - * @dev Get number of checkpoints for `account`. - */ - function numCheckpoints(address account) public view virtual returns (uint32) { - return _numCheckpoints(account); - } - - /** - * @dev Get the `pos`-th checkpoint for `account`. - */ - function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoints.Checkpoint224 memory) { - return _checkpoints(account, pos); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Wrapper.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Wrapper.sol deleted file mode 100644 index 389965e..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC20Wrapper.sol +++ /dev/null @@ -1,82 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Wrapper.sol) - -pragma solidity ^0.8.19; - -import "../ERC20.sol"; -import "../utils/SafeERC20.sol"; - -/** - * @dev Extension of the ERC20 token contract to support token wrapping. - * - * Users can deposit and withdraw "underlying tokens" and receive a matching number of "wrapped tokens". This is useful - * in conjunction with other modules. For example, combining this wrapping mechanism with {ERC20Votes} will allow the - * wrapping of an existing "basic" ERC20 into a governance token. - * - * _Available since v4.2._ - */ -abstract contract ERC20Wrapper is ERC20 { - IERC20 private immutable _underlying; - - /** - * @dev The underlying token couldn't be wrapped. - */ - error ERC20InvalidUnderlying(address token); - - constructor(IERC20 underlyingToken) { - if (underlyingToken == this) { - revert ERC20InvalidUnderlying(address(this)); - } - _underlying = underlyingToken; - } - - /** - * @dev See {ERC20-decimals}. - */ - function decimals() public view virtual override returns (uint8) { - try IERC20Metadata(address(_underlying)).decimals() returns (uint8 value) { - return value; - } catch { - return super.decimals(); - } - } - - /** - * @dev Returns the address of the underlying ERC-20 token that is being wrapped. - */ - function underlying() public view returns (IERC20) { - return _underlying; - } - - /** - * @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens. - */ - function depositFor(address account, uint256 amount) public virtual returns (bool) { - address sender = _msgSender(); - if (sender == address(this)) { - revert ERC20InvalidSender(address(this)); - } - SafeERC20.safeTransferFrom(_underlying, sender, address(this), amount); - _mint(account, amount); - return true; - } - - /** - * @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens. - */ - function withdrawTo(address account, uint256 amount) public virtual returns (bool) { - _burn(_msgSender(), amount); - SafeERC20.safeTransfer(_underlying, account, amount); - return true; - } - - /** - * @dev Mint wrapped token to cover any underlyingTokens that would have been transferred by mistake. Internal - * function that can be exposed with access control if desired. - */ - function _recover(address account) internal virtual returns (uint256) { - uint256 value = _underlying.balanceOf(address(this)) - totalSupply(); - _mint(account, value); - return value; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC4626.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC4626.sol deleted file mode 100644 index 9ea6789..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/ERC4626.sol +++ /dev/null @@ -1,288 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC4626.sol) - -pragma solidity ^0.8.19; - -import "../ERC20.sol"; -import "../utils/SafeERC20.sol"; -import "../../../interfaces/IERC4626.sol"; -import "../../../utils/math/Math.sol"; - -/** - * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in - * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626]. - * - * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for - * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends - * the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this - * contract and not the "assets" token which is an independent contract. - * - * [CAUTION] - * ==== - * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning - * with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation - * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial - * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may - * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by - * verifying the amount received is as expected, using a wrapper that performs these checks such as - * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router]. - * - * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()` - * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault - * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself - * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset - * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's - * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more - * expensive than it is profitable. More details about the underlying math can be found - * xref:erc4626.adoc#inflation-attack[here]. - * - * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued - * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets - * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience - * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the - * `_convertToShares` and `_convertToAssets` functions. - * - * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide]. - * ==== - * - * _Available since v4.7._ - */ -abstract contract ERC4626 is ERC20, IERC4626 { - using Math for uint256; - - IERC20 private immutable _asset; - uint8 private immutable _underlyingDecimals; - - /** - * @dev Attempted to deposit more assets than the max amount for `receiver`. - */ - error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max); - - /** - * @dev Attempted to mint more shares than the max amount for `receiver`. - */ - error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max); - - /** - * @dev Attempted to withdraw more assets than the max amount for `receiver`. - */ - error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max); - - /** - * @dev Attempted to redeem more shares than the max amount for `receiver`. - */ - error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max); - - /** - * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777). - */ - constructor(IERC20 asset_) { - (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_); - _underlyingDecimals = success ? assetDecimals : 18; - _asset = asset_; - } - - /** - * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way. - */ - function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) { - (bool success, bytes memory encodedDecimals) = address(asset_).staticcall( - abi.encodeCall(IERC20Metadata.decimals, ()) - ); - if (success && encodedDecimals.length >= 32) { - uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256)); - if (returnedDecimals <= type(uint8).max) { - return (true, uint8(returnedDecimals)); - } - } - return (false, 0); - } - - /** - * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This - * "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the - * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals. - * - * See {IERC20Metadata-decimals}. - */ - function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) { - return _underlyingDecimals + _decimalsOffset(); - } - - /** @dev See {IERC4626-asset}. */ - function asset() public view virtual returns (address) { - return address(_asset); - } - - /** @dev See {IERC4626-totalAssets}. */ - function totalAssets() public view virtual returns (uint256) { - return _asset.balanceOf(address(this)); - } - - /** @dev See {IERC4626-convertToShares}. */ - function convertToShares(uint256 assets) public view virtual returns (uint256) { - return _convertToShares(assets, Math.Rounding.Down); - } - - /** @dev See {IERC4626-convertToAssets}. */ - function convertToAssets(uint256 shares) public view virtual returns (uint256) { - return _convertToAssets(shares, Math.Rounding.Down); - } - - /** @dev See {IERC4626-maxDeposit}. */ - function maxDeposit(address) public view virtual returns (uint256) { - return type(uint256).max; - } - - /** @dev See {IERC4626-maxMint}. */ - function maxMint(address) public view virtual returns (uint256) { - return type(uint256).max; - } - - /** @dev See {IERC4626-maxWithdraw}. */ - function maxWithdraw(address owner) public view virtual returns (uint256) { - return _convertToAssets(balanceOf(owner), Math.Rounding.Down); - } - - /** @dev See {IERC4626-maxRedeem}. */ - function maxRedeem(address owner) public view virtual returns (uint256) { - return balanceOf(owner); - } - - /** @dev See {IERC4626-previewDeposit}. */ - function previewDeposit(uint256 assets) public view virtual returns (uint256) { - return _convertToShares(assets, Math.Rounding.Down); - } - - /** @dev See {IERC4626-previewMint}. */ - function previewMint(uint256 shares) public view virtual returns (uint256) { - return _convertToAssets(shares, Math.Rounding.Up); - } - - /** @dev See {IERC4626-previewWithdraw}. */ - function previewWithdraw(uint256 assets) public view virtual returns (uint256) { - return _convertToShares(assets, Math.Rounding.Up); - } - - /** @dev See {IERC4626-previewRedeem}. */ - function previewRedeem(uint256 shares) public view virtual returns (uint256) { - return _convertToAssets(shares, Math.Rounding.Down); - } - - /** @dev See {IERC4626-deposit}. */ - function deposit(uint256 assets, address receiver) public virtual returns (uint256) { - uint256 maxAssets = maxDeposit(receiver); - if (assets > maxAssets) { - revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets); - } - - uint256 shares = previewDeposit(assets); - _deposit(_msgSender(), receiver, assets, shares); - - return shares; - } - - /** @dev See {IERC4626-mint}. - * - * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero. - * In this case, the shares will be minted without requiring any assets to be deposited. - */ - function mint(uint256 shares, address receiver) public virtual returns (uint256) { - uint256 maxShares = maxMint(receiver); - if (shares > maxShares) { - revert ERC4626ExceededMaxMint(receiver, shares, maxShares); - } - - uint256 assets = previewMint(shares); - _deposit(_msgSender(), receiver, assets, shares); - - return assets; - } - - /** @dev See {IERC4626-withdraw}. */ - function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) { - uint256 maxAssets = maxWithdraw(owner); - if (assets > maxAssets) { - revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets); - } - - uint256 shares = previewWithdraw(assets); - _withdraw(_msgSender(), receiver, owner, assets, shares); - - return shares; - } - - /** @dev See {IERC4626-redeem}. */ - function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) { - uint256 maxShares = maxRedeem(owner); - if (shares > maxShares) { - revert ERC4626ExceededMaxRedeem(owner, shares, maxShares); - } - - uint256 assets = previewRedeem(shares); - _withdraw(_msgSender(), receiver, owner, assets, shares); - - return assets; - } - - /** - * @dev Internal conversion function (from assets to shares) with support for rounding direction. - */ - function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) { - return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding); - } - - /** - * @dev Internal conversion function (from shares to assets) with support for rounding direction. - */ - function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) { - return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding); - } - - /** - * @dev Deposit/mint common workflow. - */ - function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual { - // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the - // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer, - // calls the vault, which is assumed not malicious. - // - // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the - // assets are transferred and before the shares are minted, which is a valid state. - // slither-disable-next-line reentrancy-no-eth - SafeERC20.safeTransferFrom(_asset, caller, address(this), assets); - _mint(receiver, shares); - - emit Deposit(caller, receiver, assets, shares); - } - - /** - * @dev Withdraw/redeem common workflow. - */ - function _withdraw( - address caller, - address receiver, - address owner, - uint256 assets, - uint256 shares - ) internal virtual { - if (caller != owner) { - _spendAllowance(owner, caller, shares); - } - - // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the - // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer, - // calls the vault, which is assumed not malicious. - // - // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the - // shares are burned and after the assets are transferred, which is a valid state. - _burn(owner, shares); - SafeERC20.safeTransfer(_asset, receiver, assets); - - emit Withdraw(caller, receiver, owner, assets, shares); - } - - function _decimalsOffset() internal view virtual returns (uint8) { - return 0; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/IERC20Metadata.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/IERC20Metadata.sol deleted file mode 100644 index 1cf7e0b..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/IERC20Metadata.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) - -pragma solidity ^0.8.19; - -import "../IERC20.sol"; - -/** - * @dev Interface for the optional metadata functions from the ERC20 standard. - * - * _Available since v4.1._ - */ -interface IERC20Metadata is IERC20 { - /** - * @dev Returns the name of the token. - */ - function name() external view returns (string memory); - - /** - * @dev Returns the symbol of the token. - */ - function symbol() external view returns (string memory); - - /** - * @dev Returns the decimals places of the token. - */ - function decimals() external view returns (uint8); -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/IERC20Permit.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/IERC20Permit.sol deleted file mode 100644 index eb3e3f0..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/extensions/IERC20Permit.sol +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in - * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. - * - * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by - * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't - * need to send a transaction, and thus is not required to hold Ether at all. - */ -interface IERC20Permit { - /** - * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, - * given ``owner``'s signed approval. - * - * IMPORTANT: The same issues {IERC20-approve} has related to transaction - * ordering also apply here. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `deadline` must be a timestamp in the future. - * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` - * over the EIP712-formatted function arguments. - * - the signature must use ``owner``'s current nonce (see {nonces}). - * - * For more information on the signature format, see the - * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP - * section]. - */ - function permit( - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) external; - - /** - * @dev Returns the current nonce for `owner`. This value must be - * included whenever a signature is generated for {permit}. - * - * Every successful call to {permit} increases ``owner``'s nonce by one. This - * prevents a signature from being used multiple times. - */ - function nonces(address owner) external view returns (uint256); - - /** - * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. - */ - // solhint-disable-next-line func-name-mixedcase - function DOMAIN_SEPARATOR() external view returns (bytes32); -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC20/utils/SafeERC20.sol b/blockchain/contracts/OpenZeppelin/token/ERC20/utils/SafeERC20.sol deleted file mode 100644 index 599307e..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC20/utils/SafeERC20.sol +++ /dev/null @@ -1,140 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol) - -pragma solidity ^0.8.19; - -import "../IERC20.sol"; -import "../extensions/IERC20Permit.sol"; -import "../../../utils/Address.sol"; - -/** - * @title SafeERC20 - * @dev Wrappers around ERC20 operations that throw on failure (when the token - * contract returns false). Tokens that return no value (and instead revert or - * throw on failure) are also supported, non-reverting calls are assumed to be - * successful. - * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, - * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. - */ -library SafeERC20 { - using Address for address; - - /** - * @dev An operation with an ERC20 token failed. - */ - error SafeERC20FailedOperation(address token); - - /** - * @dev Indicates a failed `decreaseAllowance` request. - */ - error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); - - /** - * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, - * non-reverting calls are assumed to be successful. - */ - function safeTransfer(IERC20 token, address to, uint256 value) internal { - _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value))); - } - - /** - * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the - * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. - */ - function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { - _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value))); - } - - /** - * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, - * non-reverting calls are assumed to be successful. - */ - function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { - uint256 oldAllowance = token.allowance(address(this), spender); - forceApprove(token, spender, oldAllowance + value); - } - - /** - * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no value, - * non-reverting calls are assumed to be successful. - */ - function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal { - unchecked { - uint256 currentAllowance = token.allowance(address(this), spender); - if (currentAllowance < requestedDecrease) { - revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); - } - forceApprove(token, spender, currentAllowance - requestedDecrease); - } - } - - /** - * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, - * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to - * 0 before setting it to a non-zero value. - */ - function forceApprove(IERC20 token, address spender, uint256 value) internal { - bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value)); - - if (!_callOptionalReturnBool(token, approvalCall)) { - _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0))); - _callOptionalReturn(token, approvalCall); - } - } - - /** - * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. - * Revert on invalid signature. - */ - function safePermit( - IERC20Permit token, - address owner, - address spender, - uint256 value, - uint256 deadline, - uint8 v, - bytes32 r, - bytes32 s - ) internal { - uint256 nonceBefore = token.nonces(owner); - token.permit(owner, spender, value, deadline, v, r, s); - uint256 nonceAfter = token.nonces(owner); - if (nonceAfter != nonceBefore + 1) { - revert SafeERC20FailedOperation(address(token)); - } - } - - /** - * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement - * on the return value: the return value is optional (but if data is returned, it must not be false). - * @param token The token targeted by the call. - * @param data The call data (encoded using abi.encode or one of its variants). - */ - function _callOptionalReturn(IERC20 token, bytes memory data) private { - // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since - // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that - // the target address contains contract code and also asserts for success in the low-level call. - - bytes memory returndata = address(token).functionCall(data); - if (returndata.length != 0 && !abi.decode(returndata, (bool))) { - revert SafeERC20FailedOperation(address(token)); - } - } - - /** - * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement - * on the return value: the return value is optional (but if data is returned, it must not be false). - * @param token The token targeted by the call. - * @param data The call data (encoded using abi.encode or one of its variants). - * - * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. - */ - function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { - // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since - // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false - // and not revert is the subcall reverts. - - (bool success, bytes memory returndata) = address(token).call(data); - return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/ERC721.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/ERC721.sol deleted file mode 100644 index 21ed958..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/ERC721.sol +++ /dev/null @@ -1,492 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol) - -pragma solidity ^0.8.19; - -import "./IERC721.sol"; -import "./IERC721Receiver.sol"; -import "./extensions/IERC721Metadata.sol"; -import "../../utils/Context.sol"; -import "../../utils/Strings.sol"; -import "../../utils/introspection/ERC165.sol"; -import "../../interfaces/draft-IERC6093.sol"; - -/** - * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including - * the Metadata extension, but not including the Enumerable extension, which is available separately as - * {ERC721Enumerable}. - */ -abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors { - using Strings for uint256; - - // Token name - string private _name; - - // Token symbol - string private _symbol; - - // Mapping from token ID to owner address - mapping(uint256 => address) private _owners; - - // Mapping owner address to token count - mapping(address => uint256) private _balances; - - // Mapping from token ID to approved address - mapping(uint256 => address) private _tokenApprovals; - - // Mapping from owner to operator approvals - mapping(address => mapping(address => bool)) private _operatorApprovals; - - /** - * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. - */ - constructor(string memory name_, string memory symbol_) { - _name = name_; - _symbol = symbol_; - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { - return - interfaceId == type(IERC721).interfaceId || - interfaceId == type(IERC721Metadata).interfaceId || - super.supportsInterface(interfaceId); - } - - /** - * @dev See {IERC721-balanceOf}. - */ - function balanceOf(address owner) public view virtual returns (uint256) { - if (owner == address(0)) { - revert ERC721InvalidOwner(address(0)); - } - return _balances[owner]; - } - - /** - * @dev See {IERC721-ownerOf}. - */ - function ownerOf(uint256 tokenId) public view virtual returns (address) { - address owner = _ownerOf(tokenId); - if (owner == address(0)) { - revert ERC721NonexistentToken(tokenId); - } - return owner; - } - - /** - * @dev See {IERC721Metadata-name}. - */ - function name() public view virtual returns (string memory) { - return _name; - } - - /** - * @dev See {IERC721Metadata-symbol}. - */ - function symbol() public view virtual returns (string memory) { - return _symbol; - } - - /** - * @dev See {IERC721Metadata-tokenURI}. - */ - function tokenURI(uint256 tokenId) public view virtual returns (string memory) { - _requireMinted(tokenId); - - string memory baseURI = _baseURI(); - return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : ""; - } - - /** - * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each - * token will be the concatenation of the `baseURI` and the `tokenId`. Empty - * by default, can be overridden in child contracts. - */ - function _baseURI() internal view virtual returns (string memory) { - return ""; - } - - /** - * @dev See {IERC721-approve}. - */ - function approve(address to, uint256 tokenId) public virtual { - address owner = ownerOf(tokenId); - if (to == owner) { - revert ERC721InvalidOperator(owner); - } - - if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { - revert ERC721InvalidApprover(_msgSender()); - } - - _approve(to, tokenId); - } - - /** - * @dev See {IERC721-getApproved}. - */ - function getApproved(uint256 tokenId) public view virtual returns (address) { - _requireMinted(tokenId); - - return _tokenApprovals[tokenId]; - } - - /** - * @dev See {IERC721-setApprovalForAll}. - */ - function setApprovalForAll(address operator, bool approved) public virtual { - _setApprovalForAll(_msgSender(), operator, approved); - } - - /** - * @dev See {IERC721-isApprovedForAll}. - */ - function isApprovedForAll(address owner, address operator) public view virtual returns (bool) { - return _operatorApprovals[owner][operator]; - } - - /** - * @dev See {IERC721-transferFrom}. - */ - function transferFrom(address from, address to, uint256 tokenId) public virtual { - if (!_isApprovedOrOwner(_msgSender(), tokenId)) { - revert ERC721InsufficientApproval(_msgSender(), tokenId); - } - - _transfer(from, to, tokenId); - } - - /** - * @dev See {IERC721-safeTransferFrom}. - */ - function safeTransferFrom(address from, address to, uint256 tokenId) public virtual { - safeTransferFrom(from, to, tokenId, ""); - } - - /** - * @dev See {IERC721-safeTransferFrom}. - */ - function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual { - if (!_isApprovedOrOwner(_msgSender(), tokenId)) { - revert ERC721InsufficientApproval(_msgSender(), tokenId); - } - _safeTransfer(from, to, tokenId, data); - } - - /** - * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients - * are aware of the ERC721 protocol to prevent tokens from being forever locked. - * - * `data` is additional data, it has no specified format and it is sent in call to `to`. - * - * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. - * implement alternative mechanisms to perform token transfer, such as signature-based. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `tokenId` token must exist and be owned by `from`. - * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. - * - * Emits a {Transfer} event. - */ - function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual { - _transfer(from, to, tokenId); - if (!_checkOnERC721Received(from, to, tokenId, data)) { - revert ERC721InvalidReceiver(to); - } - } - - /** - * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist - */ - function _ownerOf(uint256 tokenId) internal view virtual returns (address) { - return _owners[tokenId]; - } - - /** - * @dev Returns whether `tokenId` exists. - * - * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. - * - * Tokens start existing when they are minted (`_mint`), - * and stop existing when they are burned (`_burn`). - */ - function _exists(uint256 tokenId) internal view virtual returns (bool) { - return _ownerOf(tokenId) != address(0); - } - - /** - * @dev Returns whether `spender` is allowed to manage `tokenId`. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { - address owner = ownerOf(tokenId); - return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); - } - - /** - * @dev Safely mints `tokenId` and transfers it to `to`. - * - * Requirements: - * - * - `tokenId` must not exist. - * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. - * - * Emits a {Transfer} event. - */ - function _safeMint(address to, uint256 tokenId) internal virtual { - _safeMint(to, tokenId, ""); - } - - /** - * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is - * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. - */ - function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual { - _mint(to, tokenId); - if (!_checkOnERC721Received(address(0), to, tokenId, data)) { - revert ERC721InvalidReceiver(to); - } - } - - /** - * @dev Mints `tokenId` and transfers it to `to`. - * - * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible - * - * Requirements: - * - * - `tokenId` must not exist. - * - `to` cannot be the zero address. - * - * Emits a {Transfer} event. - */ - function _mint(address to, uint256 tokenId) internal virtual { - if (to == address(0)) { - revert ERC721InvalidReceiver(address(0)); - } - if (_exists(tokenId)) { - revert ERC721InvalidSender(address(0)); - } - - _beforeTokenTransfer(address(0), to, tokenId, 1); - - // Check that tokenId was not minted by `_beforeTokenTransfer` hook - if (_exists(tokenId)) { - revert ERC721InvalidSender(address(0)); - } - - unchecked { - // Will not overflow unless all 2**256 token ids are minted to the same owner. - // Given that tokens are minted one by one, it is impossible in practice that - // this ever happens. Might change if we allow batch minting. - // The ERC fails to describe this case. - _balances[to] += 1; - } - - _owners[tokenId] = to; - - emit Transfer(address(0), to, tokenId); - - _afterTokenTransfer(address(0), to, tokenId, 1); - } - - /** - * @dev Destroys `tokenId`. - * The approval is cleared when the token is burned. - * This is an internal function that does not check if the sender is authorized to operate on the token. - * - * Requirements: - * - * - `tokenId` must exist. - * - * Emits a {Transfer} event. - */ - function _burn(uint256 tokenId) internal virtual { - address owner = ownerOf(tokenId); - - _beforeTokenTransfer(owner, address(0), tokenId, 1); - - // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook - owner = ownerOf(tokenId); - - // Clear approvals - delete _tokenApprovals[tokenId]; - - // Decrease balance with checked arithmetic, because an `ownerOf` override may - // invalidate the assumption that `_balances[from] >= 1`. - _balances[owner] -= 1; - - delete _owners[tokenId]; - - emit Transfer(owner, address(0), tokenId); - - _afterTokenTransfer(owner, address(0), tokenId, 1); - } - - /** - * @dev Transfers `tokenId` from `from` to `to`. - * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. - * - * Requirements: - * - * - `to` cannot be the zero address. - * - `tokenId` token must be owned by `from`. - * - * Emits a {Transfer} event. - */ - function _transfer(address from, address to, uint256 tokenId) internal virtual { - address owner = ownerOf(tokenId); - if (owner != from) { - revert ERC721IncorrectOwner(from, tokenId, owner); - } - if (to == address(0)) { - revert ERC721InvalidReceiver(address(0)); - } - - _beforeTokenTransfer(from, to, tokenId, 1); - - // Check that tokenId was not transferred by `_beforeTokenTransfer` hook - owner = ownerOf(tokenId); - if (owner != from) { - revert ERC721IncorrectOwner(from, tokenId, owner); - } - - // Clear approvals from the previous owner - delete _tokenApprovals[tokenId]; - - // Decrease balance with checked arithmetic, because an `ownerOf` override may - // invalidate the assumption that `_balances[from] >= 1`. - _balances[from] -= 1; - - unchecked { - // `_balances[to]` could overflow in the conditions described in `_mint`. That would require - // all 2**256 token ids to be minted, which in practice is impossible. - _balances[to] += 1; - } - - _owners[tokenId] = to; - - emit Transfer(from, to, tokenId); - - _afterTokenTransfer(from, to, tokenId, 1); - } - - /** - * @dev Approve `to` to operate on `tokenId` - * - * Emits an {Approval} event. - */ - function _approve(address to, uint256 tokenId) internal virtual { - _tokenApprovals[tokenId] = to; - emit Approval(ownerOf(tokenId), to, tokenId); - } - - /** - * @dev Approve `operator` to operate on all of `owner` tokens - * - * Emits an {ApprovalForAll} event. - */ - function _setApprovalForAll(address owner, address operator, bool approved) internal virtual { - if (owner == operator) { - revert ERC721InvalidOperator(owner); - } - _operatorApprovals[owner][operator] = approved; - emit ApprovalForAll(owner, operator, approved); - } - - /** - * @dev Reverts if the `tokenId` has not been minted yet. - */ - function _requireMinted(uint256 tokenId) internal view virtual { - if (!_exists(tokenId)) { - revert ERC721NonexistentToken(tokenId); - } - } - - /** - * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. - * The call is not executed if the target address is not a contract. - * - * @param from address representing the previous owner of the given token ID - * @param to target address that will receive the tokens - * @param tokenId uint256 ID of the token to be transferred - * @param data bytes optional data to send along with the call - * @return bool whether the call correctly returned the expected magic value - */ - function _checkOnERC721Received( - address from, - address to, - uint256 tokenId, - bytes memory data - ) private returns (bool) { - if (to.code.length > 0) { - try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) { - return retval == IERC721Receiver.onERC721Received.selector; - } catch (bytes memory reason) { - if (reason.length == 0) { - revert ERC721InvalidReceiver(to); - } else { - /// @solidity memory-safe-assembly - assembly { - revert(add(32, reason), mload(reason)) - } - } - } - } else { - return true; - } - } - - /** - * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is - * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1. - * - * Calling conditions: - * - * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`. - * - When `from` is zero, the tokens will be minted for `to`. - * - When `to` is zero, ``from``'s tokens will be burned. - * - `from` and `to` are never both zero. - * - `batchSize` is non-zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {} - - /** - * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is - * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1. - * - * Calling conditions: - * - * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`. - * - When `from` is zero, the tokens were minted for `to`. - * - When `to` is zero, ``from``'s tokens were burned. - * - `from` and `to` are never both zero. - * - `batchSize` is non-zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {} - - /** - * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override. - * - * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant - * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such - * that `ownerOf(tokenId)` is `a`. - */ - // solhint-disable-next-line func-name-mixedcase - function __unsafe_increaseBalance(address account, uint256 amount) internal { - _balances[account] += amount; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/IERC721.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/IERC721.sol deleted file mode 100644 index ba4c108..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/IERC721.sol +++ /dev/null @@ -1,132 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol) - -pragma solidity ^0.8.19; - -import "../../utils/introspection/IERC165.sol"; - -/** - * @dev Required interface of an ERC721 compliant contract. - */ -interface IERC721 is IERC165 { - /** - * @dev Emitted when `tokenId` token is transferred from `from` to `to`. - */ - event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); - - /** - * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. - */ - event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); - - /** - * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. - */ - event ApprovalForAll(address indexed owner, address indexed operator, bool approved); - - /** - * @dev Returns the number of tokens in ``owner``'s account. - */ - function balanceOf(address owner) external view returns (uint256 balance); - - /** - * @dev Returns the owner of the `tokenId` token. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function ownerOf(uint256 tokenId) external view returns (address owner); - - /** - * @dev Safely transfers `tokenId` token from `from` to `to`. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `tokenId` token must exist and be owned by `from`. - * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. - * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. - * - * Emits a {Transfer} event. - */ - function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; - - /** - * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients - * are aware of the ERC721 protocol to prevent tokens from being forever locked. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `tokenId` token must exist and be owned by `from`. - * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}. - * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. - * - * Emits a {Transfer} event. - */ - function safeTransferFrom(address from, address to, uint256 tokenId) external; - - /** - * @dev Transfers `tokenId` token from `from` to `to`. - * - * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721 - * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must - * understand this adds an external call which potentially creates a reentrancy vulnerability. - * - * Requirements: - * - * - `from` cannot be the zero address. - * - `to` cannot be the zero address. - * - `tokenId` token must be owned by `from`. - * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. - * - * Emits a {Transfer} event. - */ - function transferFrom(address from, address to, uint256 tokenId) external; - - /** - * @dev Gives permission to `to` to transfer `tokenId` token to another account. - * The approval is cleared when the token is transferred. - * - * Only a single account can be approved at a time, so approving the zero address clears previous approvals. - * - * Requirements: - * - * - The caller must own the token or be an approved operator. - * - `tokenId` must exist. - * - * Emits an {Approval} event. - */ - function approve(address to, uint256 tokenId) external; - - /** - * @dev Approve or remove `operator` as an operator for the caller. - * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. - * - * Requirements: - * - * - The `operator` cannot be the caller. - * - * Emits an {ApprovalForAll} event. - */ - function setApprovalForAll(address operator, bool approved) external; - - /** - * @dev Returns the account approved for `tokenId` token. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function getApproved(uint256 tokenId) external view returns (address operator); - - /** - * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. - * - * See {setApprovalForAll} - */ - function isApprovedForAll(address owner, address operator) external view returns (bool); -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/IERC721Receiver.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/IERC721Receiver.sol deleted file mode 100644 index 3839b6f..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/IERC721Receiver.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) - -pragma solidity ^0.8.19; - -/** - * @title ERC721 token receiver interface - * @dev Interface for any contract that wants to support safeTransfers - * from ERC721 asset contracts. - */ -interface IERC721Receiver { - /** - * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} - * by `operator` from `from`, this function is called. - * - * It must return its Solidity selector to confirm the token transfer. - * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. - * - * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. - */ - function onERC721Received( - address operator, - address from, - uint256 tokenId, - bytes calldata data - ) external returns (bytes4); -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/README.adoc b/blockchain/contracts/OpenZeppelin/token/ERC721/README.adoc deleted file mode 100644 index 40ae919..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/README.adoc +++ /dev/null @@ -1,67 +0,0 @@ -= ERC 721 - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc721 - -This set of interfaces, contracts, and utilities are all related to the https://eips.ethereum.org/EIPS/eip-721[ERC721 Non-Fungible Token Standard]. - -TIP: For a walk through on how to create an ERC721 token read our xref:ROOT:erc721.adoc[ERC721 guide]. - -The EIP specifies four interfaces: - -* {IERC721}: Core functionality required in all compliant implementation. -* {IERC721Metadata}: Optional extension that adds name, symbol, and token URI, almost always included. -* {IERC721Enumerable}: Optional extension that allows enumerating the tokens on chain, often not included since it requires large gas overhead. -* {IERC721Receiver}: An interface that must be implemented by contracts if they want to accept tokens through `safeTransferFrom`. - -OpenZeppelin Contracts provides implementations of all four interfaces: - -* {ERC721}: The core and metadata extensions, with a base URI mechanism. -* {ERC721Enumerable}: The enumerable extension. -* {ERC721Holder}: A bare bones implementation of the receiver interface. - -Additionally there are a few of other extensions: - -* {ERC721Consecutive}: An implementation of https://eips.ethereum.org/EIPS/eip-2309[ERC2309] for minting batchs of tokens during construction, in accordance with ERC721. -* {ERC721URIStorage}: A more flexible but more expensive way of storing metadata. -* {ERC721Votes}: Support for voting and vote delegation. -* {ERC721Royalty}: A way to signal royalty information following ERC2981. -* {ERC721Pausable}: A primitive to pause contract operation. -* {ERC721Burnable}: A way for token holders to burn their own tokens. -* {ERC721Wrapper}: Wrapper to create an ERC721 backed by another ERC721, with deposit and withdraw methods. Useful in conjunction with {ERC721Votes}. - -NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC721 (such as <>) and expose them as external functions in the way they prefer. - -== Core - -{{IERC721}} - -{{IERC721Metadata}} - -{{IERC721Enumerable}} - -{{ERC721}} - -{{ERC721Enumerable}} - -{{IERC721Receiver}} - -== Extensions - -{{ERC721Pausable}} - -{{ERC721Burnable}} - -{{ERC721Consecutive}} - -{{ERC721URIStorage}} - -{{ERC721Votes}} - -{{ERC721Royalty}} - -{{ERC721Wrapper}} - -== Utilities - -{{ERC721Holder}} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Burnable.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Burnable.sol deleted file mode 100644 index 217f039..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Burnable.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Burnable.sol) - -pragma solidity ^0.8.19; - -import "../ERC721.sol"; -import "../../../utils/Context.sol"; - -/** - * @title ERC721 Burnable Token - * @dev ERC721 Token that can be burned (destroyed). - */ -abstract contract ERC721Burnable is Context, ERC721 { - /** - * @dev Burns `tokenId`. See {ERC721-_burn}. - * - * Requirements: - * - * - The caller must own `tokenId` or be an approved operator. - */ - function burn(uint256 tokenId) public virtual { - if (!_isApprovedOrOwner(_msgSender(), tokenId)) { - revert ERC721InsufficientApproval(_msgSender(), tokenId); - } - _burn(tokenId); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Consecutive.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Consecutive.sol deleted file mode 100644 index f1308cd..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Consecutive.sol +++ /dev/null @@ -1,195 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/extensions/ERC721Consecutive.sol) - -pragma solidity ^0.8.19; - -import "../ERC721.sol"; -import "../../../interfaces/IERC2309.sol"; -import "../../../utils/structs/BitMaps.sol"; -import "../../../utils/structs/Checkpoints.sol"; - -/** - * @dev Implementation of the ERC2309 "Consecutive Transfer Extension" as defined in - * https://eips.ethereum.org/EIPS/eip-2309[EIP-2309]. - * - * This extension allows the minting of large batches of tokens, during contract construction only. For upgradeable - * contracts this implies that batch minting is only available during proxy deployment, and not in subsequent upgrades. - * These batches are limited to 5000 tokens at a time by default to accommodate off-chain indexers. - * - * Using this extension removes the ability to mint single tokens during contract construction. This ability is - * regained after construction. During construction, only batch minting is allowed. - * - * IMPORTANT: This extension bypasses the hooks {_beforeTokenTransfer} and {_afterTokenTransfer} for tokens minted in - * batch. The hooks will be only called once per batch, so you should take `batchSize` parameter into consideration - * when relying on hooks. - * - * IMPORTANT: When overriding {_afterTokenTransfer}, be careful about call ordering. {ownerOf} may return invalid - * values during the {_afterTokenTransfer} execution if the super call is not called first. To be safe, execute the - * super call before your custom logic. - * - * _Available since v4.8._ - */ -abstract contract ERC721Consecutive is IERC2309, ERC721 { - using BitMaps for BitMaps.BitMap; - using Checkpoints for Checkpoints.Trace160; - - Checkpoints.Trace160 private _sequentialOwnership; - BitMaps.BitMap private _sequentialBurn; - - /** - * @dev Batch mint is restricted to the constructor. - * Any batch mint not emitting the {IERC721-Transfer} event outside of the constructor - * is non-ERC721 compliant. - */ - error ERC721ForbiddenBatchMint(); - - /** - * @dev Exceeds the max amount of mints per batch. - */ - error ERC721ExceededMaxBatchMint(uint256 batchSize, uint256 maxBatch); - - /** - * @dev Individual minting is not allowed. - */ - error ERC721ForbiddenMint(); - - /** - * @dev Batch burn is not supported. - */ - error ERC721ForbiddenBatchBurn(); - - /** - * @dev Maximum size of a batch of consecutive tokens. This is designed to limit stress on off-chain indexing - * services that have to record one entry per token, and have protections against "unreasonably large" batches of - * tokens. - * - * NOTE: Overriding the default value of 5000 will not cause on-chain issues, but may result in the asset not being - * correctly supported by off-chain indexing services (including marketplaces). - */ - function _maxBatchSize() internal view virtual returns (uint96) { - return 5000; - } - - /** - * @dev See {ERC721-_ownerOf}. Override that checks the sequential ownership structure for tokens that have - * been minted as part of a batch, and not yet transferred. - */ - function _ownerOf(uint256 tokenId) internal view virtual override returns (address) { - address owner = super._ownerOf(tokenId); - - // If token is owned by the core, or beyond consecutive range, return base value - if (owner != address(0) || tokenId > type(uint96).max || tokenId < _firstConsecutiveId()) { - return owner; - } - - // Otherwise, check the token was not burned, and fetch ownership from the anchors - // Note: no need for safe cast, we know that tokenId <= type(uint96).max - return _sequentialBurn.get(tokenId) ? address(0) : address(_sequentialOwnership.lowerLookup(uint96(tokenId))); - } - - /** - * @dev Mint a batch of tokens of length `batchSize` for `to`. Returns the token id of the first token minted in the - * batch; if `batchSize` is 0, returns the number of consecutive ids minted so far. - * - * Requirements: - * - * - `batchSize` must not be greater than {_maxBatchSize}. - * - The function is called in the constructor of the contract (directly or indirectly). - * - * CAUTION: Does not emit a `Transfer` event. This is ERC721 compliant as long as it is done inside of the - * constructor, which is enforced by this function. - * - * CAUTION: Does not invoke `onERC721Received` on the receiver. - * - * Emits a {IERC2309-ConsecutiveTransfer} event. - */ - function _mintConsecutive(address to, uint96 batchSize) internal virtual returns (uint96) { - uint96 next = _nextConsecutiveId(); - - // minting a batch of size 0 is a no-op - if (batchSize > 0) { - if (address(this).code.length > 0) { - revert ERC721ForbiddenBatchMint(); - } - if (to == address(0)) { - revert ERC721InvalidReceiver(address(0)); - } - - uint256 maxBatchSize = _maxBatchSize(); - if (batchSize > maxBatchSize) { - revert ERC721ExceededMaxBatchMint(batchSize, maxBatchSize); - } - - // hook before - _beforeTokenTransfer(address(0), to, next, batchSize); - - // push an ownership checkpoint & emit event - uint96 last = next + batchSize - 1; - _sequentialOwnership.push(last, uint160(to)); - - // The invariant required by this function is preserved because the new sequentialOwnership checkpoint - // is attributing ownership of `batchSize` new tokens to account `to`. - __unsafe_increaseBalance(to, batchSize); - - emit ConsecutiveTransfer(next, last, address(0), to); - - // hook after - _afterTokenTransfer(address(0), to, next, batchSize); - } - - return next; - } - - /** - * @dev See {ERC721-_mint}. Override version that restricts normal minting to after construction. - * - * WARNING: Using {ERC721Consecutive} prevents using {_mint} during construction in favor of {_mintConsecutive}. - * After construction, {_mintConsecutive} is no longer available and {_mint} becomes available. - */ - function _mint(address to, uint256 tokenId) internal virtual override { - if (address(this).code.length == 0) { - revert ERC721ForbiddenMint(); - } - super._mint(to, tokenId); - } - - /** - * @dev See {ERC721-_afterTokenTransfer}. Burning of tokens that have been sequentially minted must be explicit. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 firstTokenId, - uint256 batchSize - ) internal virtual override { - if ( - to == address(0) && // if we burn - firstTokenId >= _firstConsecutiveId() && - firstTokenId < _nextConsecutiveId() && - !_sequentialBurn.get(firstTokenId) - ) // and the token was never marked as burnt - { - if (batchSize != 1) { - revert ERC721ForbiddenBatchBurn(); - } - _sequentialBurn.set(firstTokenId); - } - super._afterTokenTransfer(from, to, firstTokenId, batchSize); - } - - /** - * @dev Used to offset the first token id in {_nextConsecutiveId} - */ - function _firstConsecutiveId() internal view virtual returns (uint96) { - return 0; - } - - /** - * @dev Returns the next tokenId to mint using {_mintConsecutive}. It will return {_firstConsecutiveId} - * if no consecutive tokenId has been minted before. - */ - function _nextConsecutiveId() private view returns (uint96) { - (bool exists, uint96 latestId, ) = _sequentialOwnership.latestCheckpoint(); - return exists ? latestId + 1 : _firstConsecutiveId(); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Enumerable.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Enumerable.sol deleted file mode 100644 index 18e2ba5..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Enumerable.sol +++ /dev/null @@ -1,177 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Enumerable.sol) - -pragma solidity ^0.8.19; - -import "../ERC721.sol"; -import "./IERC721Enumerable.sol"; - -/** - * @dev This implements an optional extension of {ERC721} defined in the EIP that adds enumerability - * of all the token ids in the contract as well as all token ids owned by each account. - * - * CAUTION: `ERC721` extensions that implement custom `balanceOf` logic, such as `ERC721Consecutive`, - * interfere with enumerability and should not be used together with `ERC721Enumerable`. - */ -abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { - // Mapping from owner to list of owned token IDs - mapping(address => mapping(uint256 => uint256)) private _ownedTokens; - - // Mapping from token ID to index of the owner tokens list - mapping(uint256 => uint256) private _ownedTokensIndex; - - // Array with all token ids, used for enumeration - uint256[] private _allTokens; - - // Mapping from token id to position in the allTokens array - mapping(uint256 => uint256) private _allTokensIndex; - - /** - * @dev An `owner`'s token query was out of bounds for `index`. - * - * NOTE: The owner being `address(0)` indicates a global out of bounds index. - */ - error ERC721OutOfBoundsIndex(address owner, uint256 index); - - /** - * @dev Batch mint is not allowed. - */ - error ERC721EnumerableForbiddenBatchMint(); - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { - return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. - */ - function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) { - if (index >= balanceOf(owner)) { - revert ERC721OutOfBoundsIndex(owner, index); - } - return _ownedTokens[owner][index]; - } - - /** - * @dev See {IERC721Enumerable-totalSupply}. - */ - function totalSupply() public view virtual returns (uint256) { - return _allTokens.length; - } - - /** - * @dev See {IERC721Enumerable-tokenByIndex}. - */ - function tokenByIndex(uint256 index) public view virtual returns (uint256) { - if (index >= totalSupply()) { - revert ERC721OutOfBoundsIndex(address(0), index); - } - return _allTokens[index]; - } - - /** - * @dev See {ERC721-_beforeTokenTransfer}. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 firstTokenId, - uint256 batchSize - ) internal virtual override { - super._beforeTokenTransfer(from, to, firstTokenId, batchSize); - - if (batchSize > 1) { - // Will only trigger during construction. Batch transferring (minting) is not available afterwards. - revert ERC721EnumerableForbiddenBatchMint(); - } - - uint256 tokenId = firstTokenId; - - if (from == address(0)) { - _addTokenToAllTokensEnumeration(tokenId); - } else if (from != to) { - _removeTokenFromOwnerEnumeration(from, tokenId); - } - if (to == address(0)) { - _removeTokenFromAllTokensEnumeration(tokenId); - } else if (to != from) { - _addTokenToOwnerEnumeration(to, tokenId); - } - } - - /** - * @dev Private function to add a token to this extension's ownership-tracking data structures. - * @param to address representing the new owner of the given token ID - * @param tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { - uint256 length = balanceOf(to); - _ownedTokens[to][length] = tokenId; - _ownedTokensIndex[tokenId] = length; - } - - /** - * @dev Private function to add a token to this extension's token tracking data structures. - * @param tokenId uint256 ID of the token to be added to the tokens list - */ - function _addTokenToAllTokensEnumeration(uint256 tokenId) private { - _allTokensIndex[tokenId] = _allTokens.length; - _allTokens.push(tokenId); - } - - /** - * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that - * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for - * gas optimizations e.g. when performing a transfer operation (avoiding double writes). - * This has O(1) time complexity, but alters the order of the _ownedTokens array. - * @param from address representing the previous owner of the given token ID - * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { - // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and - // then delete the last slot (swap and pop). - - uint256 lastTokenIndex = balanceOf(from) - 1; - uint256 tokenIndex = _ownedTokensIndex[tokenId]; - - // When the token to delete is the last token, the swap operation is unnecessary - if (tokenIndex != lastTokenIndex) { - uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; - - _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token - _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index - } - - // This also deletes the contents at the last position of the array - delete _ownedTokensIndex[tokenId]; - delete _ownedTokens[from][lastTokenIndex]; - } - - /** - * @dev Private function to remove a token from this extension's token tracking data structures. - * This has O(1) time complexity, but alters the order of the _allTokens array. - * @param tokenId uint256 ID of the token to be removed from the tokens list - */ - function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { - // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and - // then delete the last slot (swap and pop). - - uint256 lastTokenIndex = _allTokens.length - 1; - uint256 tokenIndex = _allTokensIndex[tokenId]; - - // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so - // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding - // an 'if' statement (like in _removeTokenFromOwnerEnumeration) - uint256 lastTokenId = _allTokens[lastTokenIndex]; - - _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token - _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index - - // This also deletes the contents at the last position of the array - delete _allTokensIndex[tokenId]; - _allTokens.pop(); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Pausable.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Pausable.sol deleted file mode 100644 index a9472c5..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Pausable.sol +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.8.2) (token/ERC721/extensions/ERC721Pausable.sol) - -pragma solidity ^0.8.19; - -import "../ERC721.sol"; -import "../../../security/Pausable.sol"; - -/** - * @dev ERC721 token with pausable token transfers, minting and burning. - * - * Useful for scenarios such as preventing trades until the end of an evaluation - * period, or having an emergency switch for freezing all token transfers in the - * event of a large bug. - * - * IMPORTANT: This contract does not include public pause and unpause functions. In - * addition to inheriting this contract, you must define both functions, invoking the - * {Pausable-_pause} and {Pausable-_unpause} internal functions, with appropriate - * access control, e.g. using {AccessControl} or {Ownable}. Not doing so will - * make the contract unpausable. - */ -abstract contract ERC721Pausable is ERC721, Pausable { - /** - * @dev See {ERC721-_beforeTokenTransfer}. - * - * Requirements: - * - * - the contract must not be paused. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 firstTokenId, - uint256 batchSize - ) internal virtual override { - super._beforeTokenTransfer(from, to, firstTokenId, batchSize); - - _requireNotPaused(); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Royalty.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Royalty.sol deleted file mode 100644 index 7d6ef6c..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Royalty.sol +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Royalty.sol) - -pragma solidity ^0.8.19; - -import "../ERC721.sol"; -import "../../common/ERC2981.sol"; -import "../../../utils/introspection/ERC165.sol"; - -/** - * @dev Extension of ERC721 with the ERC2981 NFT Royalty Standard, a standardized way to retrieve royalty payment - * information. - * - * Royalty information can be specified globally for all token ids via {ERC2981-_setDefaultRoyalty}, and/or individually for - * specific token ids via {ERC2981-_setTokenRoyalty}. The latter takes precedence over the first. - * - * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See - * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to - * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. - * - * _Available since v4.5._ - */ -abstract contract ERC721Royalty is ERC2981, ERC721 { - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { - return super.supportsInterface(interfaceId); - } - - /** - * @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token. - */ - function _burn(uint256 tokenId) internal virtual override { - super._burn(tokenId); - _resetTokenRoyalty(tokenId); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721URIStorage.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721URIStorage.sol deleted file mode 100644 index ae625fc..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721URIStorage.sol +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/extensions/ERC721URIStorage.sol) - -pragma solidity ^0.8.19; - -import "../ERC721.sol"; -import "../../../interfaces/IERC4906.sol"; - -/** - * @dev ERC721 token with storage based token URI management. - */ -abstract contract ERC721URIStorage is IERC4906, ERC721 { - using Strings for uint256; - - // Optional mapping for token URIs - mapping(uint256 => string) private _tokenURIs; - - /** - * @dev See {IERC165-supportsInterface} - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { - return interfaceId == bytes4(0x49064906) || super.supportsInterface(interfaceId); - } - - /** - * @dev See {IERC721Metadata-tokenURI}. - */ - function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { - _requireMinted(tokenId); - - string memory _tokenURI = _tokenURIs[tokenId]; - string memory base = _baseURI(); - - // If there is no base URI, return the token URI. - if (bytes(base).length == 0) { - return _tokenURI; - } - // If both are set, concatenate the baseURI and tokenURI (via string.concat). - if (bytes(_tokenURI).length > 0) { - return string.concat(base, _tokenURI); - } - - return super.tokenURI(tokenId); - } - - /** - * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. - * - * Emits {MetadataUpdate}. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { - if (!_exists(tokenId)) { - revert ERC721NonexistentToken(tokenId); - } - _tokenURIs[tokenId] = _tokenURI; - - emit MetadataUpdate(tokenId); - } - - /** - * @dev See {ERC721-_burn}. This override additionally checks to see if a - * token-specific URI was set for the token, and if so, it deletes the token URI from - * the storage mapping. - */ - function _burn(uint256 tokenId) internal virtual override { - super._burn(tokenId); - - if (bytes(_tokenURIs[tokenId]).length != 0) { - delete _tokenURIs[tokenId]; - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Votes.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Votes.sol deleted file mode 100644 index 89b2e07..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Votes.sol +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/extensions/ERC721Votes.sol) - -pragma solidity ^0.8.19; - -import "../ERC721.sol"; -import "../../../governance/utils/Votes.sol"; - -/** - * @dev Extension of ERC721 to support voting and delegation as implemented by {Votes}, where each individual NFT counts - * as 1 vote unit. - * - * Tokens do not count as votes until they are delegated, because votes must be tracked which incurs an additional cost - * on every transfer. Token holders can either delegate to a trusted representative who will decide how to make use of - * the votes in governance decisions, or they can delegate to themselves to be their own representative. - * - * _Available since v4.5._ - */ -abstract contract ERC721Votes is ERC721, Votes { - /** - * @dev See {ERC721-_afterTokenTransfer}. Adjusts votes when tokens are transferred. - * - * Emits a {IVotes-DelegateVotesChanged} event. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 firstTokenId, - uint256 batchSize - ) internal virtual override { - _transferVotingUnits(from, to, batchSize); - super._afterTokenTransfer(from, to, firstTokenId, batchSize); - } - - /** - * @dev Returns the balance of `account`. - * - * WARNING: Overriding this function will likely result in incorrect vote tracking. - */ - function _getVotingUnits(address account) internal view virtual override returns (uint256) { - return balanceOf(account); - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Wrapper.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Wrapper.sol deleted file mode 100644 index 47a42c1..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/ERC721Wrapper.sol +++ /dev/null @@ -1,104 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/extensions/ERC721Wrapper.sol) - -pragma solidity ^0.8.19; - -import "../ERC721.sol"; - -/** - * @dev Extension of the ERC721 token contract to support token wrapping. - * - * Users can deposit and withdraw an "underlying token" and receive a "wrapped token" with a matching tokenId. This is useful - * in conjunction with other modules. For example, combining this wrapping mechanism with {ERC721Votes} will allow the - * wrapping of an existing "basic" ERC721 into a governance token. - * - * _Available since v4.9.0_ - */ -abstract contract ERC721Wrapper is ERC721, IERC721Receiver { - IERC721 private immutable _underlying; - - /** - * @dev The received ERC721 token couldn't be wrapped. - */ - error ERC721UnsupportedToken(address token); - - constructor(IERC721 underlyingToken) { - _underlying = underlyingToken; - } - - /** - * @dev Allow a user to deposit underlying tokens and mint the corresponding tokenIds. - */ - function depositFor(address account, uint256[] memory tokenIds) public virtual returns (bool) { - uint256 length = tokenIds.length; - for (uint256 i = 0; i < length; ++i) { - uint256 tokenId = tokenIds[i]; - - // This is an "unsafe" transfer that doesn't call any hook on the receiver. With underlying() being trusted - // (by design of this contract) and no other contracts expected to be called from there, we are safe. - // slither-disable-next-line reentrancy-no-eth - underlying().transferFrom(_msgSender(), address(this), tokenId); - _safeMint(account, tokenId); - } - - return true; - } - - /** - * @dev Allow a user to burn wrapped tokens and withdraw the corresponding tokenIds of the underlying tokens. - */ - function withdrawTo(address account, uint256[] memory tokenIds) public virtual returns (bool) { - uint256 length = tokenIds.length; - for (uint256 i = 0; i < length; ++i) { - uint256 tokenId = tokenIds[i]; - if (!_isApprovedOrOwner(_msgSender(), tokenId)) { - revert ERC721InsufficientApproval(_msgSender(), tokenId); - } - _burn(tokenId); - // Checks were already performed at this point, and there's no way to retake ownership or approval from - // the wrapped tokenId after this point, so it's safe to remove the reentrancy check for the next line. - // slither-disable-next-line reentrancy-no-eth - underlying().safeTransferFrom(address(this), account, tokenId); - } - - return true; - } - - /** - * @dev Overrides {IERC721Receiver-onERC721Received} to allow minting on direct ERC721 transfers to - * this contract. - * - * In case there's data attached, it validates that the operator is this contract, so only trusted data - * is accepted from {depositFor}. - * - * WARNING: Doesn't work with unsafe transfers (eg. {IERC721-transferFrom}). Use {ERC721Wrapper-_recover} - * for recovering in that scenario. - */ - function onERC721Received(address, address from, uint256 tokenId, bytes memory) public virtual returns (bytes4) { - if (address(underlying()) != _msgSender()) { - revert ERC721UnsupportedToken(_msgSender()); - } - _safeMint(from, tokenId); - return IERC721Receiver.onERC721Received.selector; - } - - /** - * @dev Mint a wrapped token to cover any underlyingToken that would have been transferred by mistake. Internal - * function that can be exposed with access control if desired. - */ - function _recover(address account, uint256 tokenId) internal virtual returns (uint256) { - address owner = underlying().ownerOf(tokenId); - if (owner != address(this)) { - revert ERC721IncorrectOwner(address(this), tokenId, owner); - } - _safeMint(account, tokenId); - return tokenId; - } - - /** - * @dev Returns the underlying token. - */ - function underlying() public view virtual returns (IERC721) { - return _underlying; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/IERC721Enumerable.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/IERC721Enumerable.sol deleted file mode 100644 index d5fe633..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/IERC721Enumerable.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) - -pragma solidity ^0.8.19; - -import "../IERC721.sol"; - -/** - * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension - * @dev See https://eips.ethereum.org/EIPS/eip-721 - */ -interface IERC721Enumerable is IERC721 { - /** - * @dev Returns the total amount of tokens stored by the contract. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns a token ID owned by `owner` at a given `index` of its token list. - * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. - */ - function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); - - /** - * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. - * Use along with {totalSupply} to enumerate all tokens. - */ - function tokenByIndex(uint256 index) external view returns (uint256); -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/IERC721Metadata.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/IERC721Metadata.sol deleted file mode 100644 index 0b08581..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/extensions/IERC721Metadata.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) - -pragma solidity ^0.8.19; - -import "../IERC721.sol"; - -/** - * @title ERC-721 Non-Fungible Token Standard, optional metadata extension - * @dev See https://eips.ethereum.org/EIPS/eip-721 - */ -interface IERC721Metadata is IERC721 { - /** - * @dev Returns the token collection name. - */ - function name() external view returns (string memory); - - /** - * @dev Returns the token collection symbol. - */ - function symbol() external view returns (string memory); - - /** - * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. - */ - function tokenURI(uint256 tokenId) external view returns (string memory); -} diff --git a/blockchain/contracts/OpenZeppelin/token/ERC721/utils/ERC721Holder.sol b/blockchain/contracts/OpenZeppelin/token/ERC721/utils/ERC721Holder.sol deleted file mode 100644 index a3ee8b5..0000000 --- a/blockchain/contracts/OpenZeppelin/token/ERC721/utils/ERC721Holder.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/utils/ERC721Holder.sol) - -pragma solidity ^0.8.19; - -import "../IERC721Receiver.sol"; - -/** - * @dev Implementation of the {IERC721Receiver} interface. - * - * Accepts all token transfers. - * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. - */ -abstract contract ERC721Holder is IERC721Receiver { - /** - * @dev See {IERC721Receiver-onERC721Received}. - * - * Always returns `IERC721Receiver.onERC721Received.selector`. - */ - function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) { - return this.onERC721Received.selector; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/common/ERC2981.sol b/blockchain/contracts/OpenZeppelin/token/common/ERC2981.sol deleted file mode 100644 index 21869ee..0000000 --- a/blockchain/contracts/OpenZeppelin/token/common/ERC2981.sol +++ /dev/null @@ -1,139 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (token/common/ERC2981.sol) - -pragma solidity ^0.8.19; - -import "../../interfaces/IERC2981.sol"; -import "../../utils/introspection/ERC165.sol"; - -/** - * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. - * - * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for - * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. - * - * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the - * fee is specified in basis points by default. - * - * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See - * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to - * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. - * - * _Available since v4.5._ - */ -abstract contract ERC2981 is IERC2981, ERC165 { - struct RoyaltyInfo { - address receiver; - uint96 royaltyFraction; - } - - RoyaltyInfo private _defaultRoyaltyInfo; - mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; - - /** - * @dev The default royalty set is invalid (eg. (numerator / denominator) >= 1). - */ - error ERC2981InvalidDefaultRoyalty(uint256 numerator, uint256 denominator); - - /** - * @dev The default royalty receiver is invalid. - */ - error ERC2981InvalidDefaultRoyaltyReceiver(address receiver); - - /** - * @dev The royalty set for an specific `tokenId` is invalid (eg. (numerator / denominator) >= 1). - */ - error ERC2981InvalidTokenRoyalty(uint256 tokenId, uint256 numerator, uint256 denominator); - - /** - * @dev The royalty receiver for `tokenId` is invalid. - */ - error ERC2981InvalidTokenRoyaltyReceiver(uint256 tokenId, address receiver); - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { - return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @inheritdoc IERC2981 - */ - function royaltyInfo(uint256 tokenId, uint256 salePrice) public view virtual returns (address, uint256) { - RoyaltyInfo memory royalty = _tokenRoyaltyInfo[tokenId]; - - if (royalty.receiver == address(0)) { - royalty = _defaultRoyaltyInfo; - } - - uint256 royaltyAmount = (salePrice * royalty.royaltyFraction) / _feeDenominator(); - - return (royalty.receiver, royaltyAmount); - } - - /** - * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a - * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an - * override. - */ - function _feeDenominator() internal pure virtual returns (uint96) { - return 10000; - } - - /** - * @dev Sets the royalty information that all ids in this contract will default to. - * - * Requirements: - * - * - `receiver` cannot be the zero address. - * - `feeNumerator` cannot be greater than the fee denominator. - */ - function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { - uint256 denominator = _feeDenominator(); - if (feeNumerator > denominator) { - // Royalty fee will exceed the sale price - revert ERC2981InvalidDefaultRoyalty(feeNumerator, denominator); - } - if (receiver == address(0)) { - revert ERC2981InvalidDefaultRoyaltyReceiver(address(0)); - } - - _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); - } - - /** - * @dev Removes default royalty information. - */ - function _deleteDefaultRoyalty() internal virtual { - delete _defaultRoyaltyInfo; - } - - /** - * @dev Sets the royalty information for a specific token id, overriding the global default. - * - * Requirements: - * - * - `receiver` cannot be the zero address. - * - `feeNumerator` cannot be greater than the fee denominator. - */ - function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) internal virtual { - uint256 denominator = _feeDenominator(); - if (feeNumerator > denominator) { - // Royalty fee will exceed the sale price - revert ERC2981InvalidTokenRoyalty(tokenId, feeNumerator, denominator); - } - if (receiver == address(0)) { - revert ERC2981InvalidTokenRoyaltyReceiver(tokenId, address(0)); - } - - _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); - } - - /** - * @dev Resets royalty information for the token id back to the global default. - */ - function _resetTokenRoyalty(uint256 tokenId) internal virtual { - delete _tokenRoyaltyInfo[tokenId]; - } -} diff --git a/blockchain/contracts/OpenZeppelin/token/common/README.adoc b/blockchain/contracts/OpenZeppelin/token/common/README.adoc deleted file mode 100644 index af61674..0000000 --- a/blockchain/contracts/OpenZeppelin/token/common/README.adoc +++ /dev/null @@ -1,10 +0,0 @@ -= Common (Tokens) - -Functionality that is common to multiple token standards. - -* {ERC2981}: NFT Royalties compatible with both ERC721 and ERC1155. -** For ERC721 consider {ERC721Royalty} which clears the royalty information from storage on burn. - -== Contracts - -{{ERC2981}} diff --git a/blockchain/contracts/OpenZeppelin/utils/Arrays.sol b/blockchain/contracts/OpenZeppelin/utils/Arrays.sol deleted file mode 100644 index f4ef456..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/Arrays.sol +++ /dev/null @@ -1,127 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/Arrays.sol) - -pragma solidity ^0.8.19; - -import "./StorageSlot.sol"; -import "./math/Math.sol"; - -/** - * @dev Collection of functions related to array types. - */ -library Arrays { - using StorageSlot for bytes32; - - /** - * @dev Searches a sorted `array` and returns the first index that contains - * a value greater or equal to `element`. If no such index exists (i.e. all - * values in the array are strictly less than `element`), the array length is - * returned. Time complexity O(log n). - * - * `array` is expected to be sorted in ascending order, and to contain no - * repeated elements. - */ - function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { - if (array.length == 0) { - return 0; - } - - uint256 low = 0; - uint256 high = array.length; - - while (low < high) { - uint256 mid = Math.average(low, high); - - // Note that mid will always be strictly less than high (i.e. it will be a valid array index) - // because Math.average rounds down (it does integer division with truncation). - if (unsafeAccess(array, mid).value > element) { - high = mid; - } else { - low = mid + 1; - } - } - - // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. - if (low > 0 && unsafeAccess(array, low - 1).value == element) { - return low - 1; - } else { - return low; - } - } - - /** - * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. - * - * WARNING: Only use if you are certain `pos` is lower than the array length. - */ - function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) { - bytes32 slot; - // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` - // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. - - /// @solidity memory-safe-assembly - assembly { - mstore(0, arr.slot) - slot := add(keccak256(0, 0x20), pos) - } - return slot.getAddressSlot(); - } - - /** - * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. - * - * WARNING: Only use if you are certain `pos` is lower than the array length. - */ - function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) { - bytes32 slot; - // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` - // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. - - /// @solidity memory-safe-assembly - assembly { - mstore(0, arr.slot) - slot := add(keccak256(0, 0x20), pos) - } - return slot.getBytes32Slot(); - } - - /** - * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. - * - * WARNING: Only use if you are certain `pos` is lower than the array length. - */ - function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) { - bytes32 slot; - // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` - // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. - - /// @solidity memory-safe-assembly - assembly { - mstore(0, arr.slot) - slot := add(keccak256(0, 0x20), pos) - } - return slot.getUint256Slot(); - } - - /** - * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. - * - * WARNING: Only use if you are certain `pos` is lower than the array length. - */ - function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) { - assembly { - res := mload(add(add(arr, 0x20), mul(pos, 0x20))) - } - } - - /** - * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. - * - * WARNING: Only use if you are certain `pos` is lower than the array length. - */ - function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) { - assembly { - res := mload(add(add(arr, 0x20), mul(pos, 0x20))) - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/Base64.sol b/blockchain/contracts/OpenZeppelin/utils/Base64.sol deleted file mode 100644 index 9ba6def..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/Base64.sol +++ /dev/null @@ -1,92 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Provides a set of functions to operate with Base64 strings. - * - * _Available since v4.5._ - */ -library Base64 { - /** - * @dev Base64 Encoding/Decoding Table - */ - string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - /** - * @dev Converts a `bytes` to its Bytes64 `string` representation. - */ - function encode(bytes memory data) internal pure returns (string memory) { - /** - * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence - * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol - */ - if (data.length == 0) return ""; - - // Loads the table into memory - string memory table = _TABLE; - - // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter - // and split into 4 numbers of 6 bits. - // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up - // - `data.length + 2` -> Round up - // - `/ 3` -> Number of 3-bytes chunks - // - `4 *` -> 4 characters for each chunk - string memory result = new string(4 * ((data.length + 2) / 3)); - - /// @solidity memory-safe-assembly - assembly { - // Prepare the lookup table (skip the first "length" byte) - let tablePtr := add(table, 1) - - // Prepare result pointer, jump over length - let resultPtr := add(result, 32) - - // Run over the input, 3 bytes at a time - for { - let dataPtr := data - let endPtr := add(data, mload(data)) - } lt(dataPtr, endPtr) { - - } { - // Advance 3 bytes - dataPtr := add(dataPtr, 3) - let input := mload(dataPtr) - - // To write each character, shift the 3 bytes (18 bits) chunk - // 4 times in blocks of 6 bits for each character (18, 12, 6, 0) - // and apply logical AND with 0x3F which is the number of - // the previous character in the ASCII table prior to the Base64 Table - // The result is then added to the table to get the character to write, - // and finally write it in the result pointer but with a left shift - // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits - - mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - - mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - - mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - - mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - } - - // When data `bytes` is not exactly 3 bytes long - // it is padded with `=` characters at the end - switch mod(mload(data), 3) - case 1 { - mstore8(sub(resultPtr, 1), 0x3d) - mstore8(sub(resultPtr, 2), 0x3d) - } - case 2 { - mstore8(sub(resultPtr, 1), 0x3d) - } - } - - return result; - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/Context.sol b/blockchain/contracts/OpenZeppelin/utils/Context.sol deleted file mode 100644 index 2d51798..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/Context.sol +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/Context.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Provides information about the current execution context, including the - * sender of the transaction and its data. While these are generally available - * via msg.sender and msg.data, they should not be accessed in such a direct - * manner, since when dealing with meta-transactions the account sending and - * paying for execution may not be the actual sender (as far as an application - * is concerned). - * - * This contract is only required for intermediate, library-like contracts. - */ -abstract contract Context { - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/Create2.sol b/blockchain/contracts/OpenZeppelin/utils/Create2.sol deleted file mode 100644 index 24d27ea..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/Create2.sol +++ /dev/null @@ -1,96 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/Create2.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. - * `CREATE2` can be used to compute in advance the address where a smart - * contract will be deployed, which allows for interesting new mechanisms known - * as 'counterfactual interactions'. - * - * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more - * information. - */ -library Create2 { - /** - * @dev Not enough balance for performing a CREATE2 deploy. - */ - error Create2InsufficientBalance(uint256 balance, uint256 needed); - - /** - * @dev There's no code to deploy. - */ - error Create2EmptyBytecode(); - - /** - * @dev The deployment failed. - */ - error Create2FailedDeployment(); - - /** - * @dev Deploys a contract using `CREATE2`. The address where the contract - * will be deployed can be known in advance via {computeAddress}. - * - * The bytecode for a contract can be obtained from Solidity with - * `type(contractName).creationCode`. - * - * Requirements: - * - * - `bytecode` must not be empty. - * - `salt` must have not been used for `bytecode` already. - * - the factory must have a balance of at least `amount`. - * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. - */ - function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) { - if (address(this).balance < amount) { - revert Create2InsufficientBalance(address(this).balance, amount); - } - if (bytecode.length == 0) { - revert Create2EmptyBytecode(); - } - /// @solidity memory-safe-assembly - assembly { - addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) - } - if (addr == address(0)) { - revert Create2FailedDeployment(); - } - } - - /** - * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the - * `bytecodeHash` or `salt` will result in a new destination address. - */ - function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { - return computeAddress(salt, bytecodeHash, address(this)); - } - - /** - * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at - * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. - */ - function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) { - /// @solidity memory-safe-assembly - assembly { - let ptr := mload(0x40) // Get free memory pointer - - // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... | - // |-------------------|---------------------------------------------------------------------------| - // | bytecodeHash | CCCCCCCCCCCCC...CC | - // | salt | BBBBBBBBBBBBB...BB | - // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA | - // | 0xFF | FF | - // |-------------------|---------------------------------------------------------------------------| - // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC | - // | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ | - - mstore(add(ptr, 0x40), bytecodeHash) - mstore(add(ptr, 0x20), salt) - mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes - let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff - mstore8(start, 0xff) - addr := keccak256(start, 85) - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/Multicall.sol b/blockchain/contracts/OpenZeppelin/utils/Multicall.sol deleted file mode 100644 index 8e0ef81..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/Multicall.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/Multicall.sol) - -pragma solidity ^0.8.19; - -import "./Address.sol"; - -/** - * @dev Provides a function to batch together multiple calls in a single external call. - * - * _Available since v4.1._ - */ -abstract contract Multicall { - /** - * @dev Receives and executes a batch of function calls on this contract. - * @custom:oz-upgrades-unsafe-allow-reachable delegatecall - */ - function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) { - results = new bytes[](data.length); - for (uint256 i = 0; i < data.length; i++) { - results[i] = Address.functionDelegateCall(address(this), data[i]); - } - return results; - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/Nonces.sol b/blockchain/contracts/OpenZeppelin/utils/Nonces.sol deleted file mode 100644 index f8ea1df..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/Nonces.sol +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.19; - -/** - * @dev Provides tracking nonces for addresses. Nonces will only increment. - */ -abstract contract Nonces { - /** - * @dev The nonce used for an `account` is not the expected current nonce. - */ - error InvalidAccountNonce(address account, uint256 currentNonce); - - mapping(address => uint256) private _nonces; - - /** - * @dev Returns an address nonce. - */ - function nonces(address owner) public view virtual returns (uint256) { - return _nonces[owner]; - } - - /** - * @dev Consumes a nonce. - * - * Returns the current value and increments nonce. - */ - function _useNonce(address owner) internal virtual returns (uint256) { - // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be - // decremented or reset. This guarantees that the nonce never overflows. - unchecked { - // It is important to do x++ and not ++x here. - return _nonces[owner]++; - } - } - - /** - * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`. - */ - function _useCheckedNonce(address owner, uint256 nonce) internal virtual returns (uint256) { - uint256 current = _useNonce(owner); - if (nonce != current) { - revert InvalidAccountNonce(owner, current); - } - return current; - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/README.adoc b/blockchain/contracts/OpenZeppelin/utils/README.adoc deleted file mode 100644 index aa5182b..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/README.adoc +++ /dev/null @@ -1,83 +0,0 @@ -= Utilities - -[.readme-notice] -NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/utils - -Miscellaneous contracts and libraries containing utility functions you can use to improve security, work with new data types, or safely use low-level primitives. - -The {Address}, {Arrays}, {Base64} and {Strings} libraries provide more operations related to these native data types, while {SafeCast} adds ways to safely convert between the different signed and unsigned numeric types. -{Multicall} provides a function to batch together multiple calls in a single external call. - -For new data types: - - * {EnumerableMap}: like Solidity's https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] type, but with key-value _enumeration_: this will let you know how many entries a mapping has, and iterate over them (which is not possible with `mapping`). - * {EnumerableSet}: like {EnumerableMap}, but for https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets]. Can be used to store privileged accounts, issued IDs, etc. - -[NOTE] -==== -Because Solidity does not support generic types, {EnumerableMap} and {EnumerableSet} are specialized to a limited number of key-value types. - -As of v3.0, {EnumerableMap} supports `uint256 -> address` (`UintToAddressMap`), and {EnumerableSet} supports `address` and `uint256` (`AddressSet` and `UintSet`). -==== - -Finally, {Create2} contains all necessary utilities to safely use the https://blog.openzeppelin.com/getting-the-most-out-of-create2/[`CREATE2` EVM opcode], without having to deal with low-level assembly. - -== Math - -{{Math}} - -{{SignedMath}} - -{{SafeCast}} - -== Cryptography - -{{ECDSA}} - -{{SignatureChecker}} - -{{MerkleProof}} - -{{EIP712}} - -== Introspection - -This set of interfaces and contracts deal with https://en.wikipedia.org/wiki/Type_introspection[type introspection] of contracts, that is, examining which functions can be called on them. This is usually referred to as a contract's _interface_. - -Ethereum contracts have no native concept of an interface, so applications must usually simply trust they are not making an incorrect call. For trusted setups this is a non-issue, but often unknown and untrusted third-party addresses need to be interacted with. There may even not be any direct calls to them! (e.g. `ERC20` tokens may be sent to a contract that lacks a way to transfer them out of it, locking them forever). In these cases, a contract _declaring_ its interface can be very helpful in preventing errors. - -{{IERC165}} - -{{ERC165}} - -{{ERC165Checker}} - -== Data Structures - -{{BitMaps}} - -{{EnumerableMap}} - -{{EnumerableSet}} - -{{DoubleEndedQueue}} - -{{Checkpoints}} - -== Libraries - -{{Create2}} - -{{Address}} - -{{Arrays}} - -{{Base64}} - -{{Strings}} - -{{ShortStrings}} - -{{StorageSlot}} - -{{Multicall}} diff --git a/blockchain/contracts/OpenZeppelin/utils/ShortStrings.sol b/blockchain/contracts/OpenZeppelin/utils/ShortStrings.sol deleted file mode 100644 index a6cb1e6..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/ShortStrings.sol +++ /dev/null @@ -1,122 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol) - -pragma solidity ^0.8.19; - -import "./StorageSlot.sol"; - -// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | -// | length | 0x BB | -type ShortString is bytes32; - -/** - * @dev This library provides functions to convert short memory strings - * into a `ShortString` type that can be used as an immutable variable. - * - * Strings of arbitrary length can be optimized using this library if - * they are short enough (up to 31 bytes) by packing them with their - * length (1 byte) in a single EVM word (32 bytes). Additionally, a - * fallback mechanism can be used for every other case. - * - * Usage example: - * - * ```solidity - * contract Named { - * using ShortStrings for *; - * - * ShortString private immutable _name; - * string private _nameFallback; - * - * constructor(string memory contractName) { - * _name = contractName.toShortStringWithFallback(_nameFallback); - * } - * - * function name() external view returns (string memory) { - * return _name.toStringWithFallback(_nameFallback); - * } - * } - * ``` - */ -library ShortStrings { - // Used as an identifier for strings longer than 31 bytes. - bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF; - - error StringTooLong(string str); - error InvalidShortString(); - - /** - * @dev Encode a string of at most 31 chars into a `ShortString`. - * - * This will trigger a `StringTooLong` error is the input string is too long. - */ - function toShortString(string memory str) internal pure returns (ShortString) { - bytes memory bstr = bytes(str); - if (bstr.length > 31) { - revert StringTooLong(str); - } - return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length)); - } - - /** - * @dev Decode a `ShortString` back to a "normal" string. - */ - function toString(ShortString sstr) internal pure returns (string memory) { - uint256 len = byteLength(sstr); - // using `new string(len)` would work locally but is not memory safe. - string memory str = new string(32); - /// @solidity memory-safe-assembly - assembly { - mstore(str, len) - mstore(add(str, 0x20), sstr) - } - return str; - } - - /** - * @dev Return the length of a `ShortString`. - */ - function byteLength(ShortString sstr) internal pure returns (uint256) { - uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF; - if (result > 31) { - revert InvalidShortString(); - } - return result; - } - - /** - * @dev Encode a string into a `ShortString`, or write it to storage if it is too long. - */ - function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) { - if (bytes(value).length < 32) { - return toShortString(value); - } else { - StorageSlot.getStringSlot(store).value = value; - return ShortString.wrap(_FALLBACK_SENTINEL); - } - } - - /** - * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}. - */ - function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) { - if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) { - return toString(value); - } else { - return store; - } - } - - /** - * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}. - * - * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of - * actual characters as the UTF-8 encoding of a single character can span over multiple bytes. - */ - function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) { - if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) { - return byteLength(value); - } else { - return bytes(store).length; - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/StorageSlot.sol b/blockchain/contracts/OpenZeppelin/utils/StorageSlot.sol deleted file mode 100644 index b0e9189..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/StorageSlot.sol +++ /dev/null @@ -1,138 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol) -// This file was procedurally generated from scripts/generate/templates/StorageSlot.js. - -pragma solidity ^0.8.19; - -/** - * @dev Library for reading and writing primitive types to specific storage slots. - * - * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. - * This library helps with reading and writing to such slots without the need for inline assembly. - * - * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. - * - * Example usage to set ERC1967 implementation slot: - * ```solidity - * contract ERC1967 { - * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; - * - * function _getImplementation() internal view returns (address) { - * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; - * } - * - * function _setImplementation(address newImplementation) internal { - * require(newImplementation.code.length > 0); - * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; - * } - * } - * ``` - * - * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._ - * _Available since v4.9 for `string`, `bytes`._ - */ -library StorageSlot { - struct AddressSlot { - address value; - } - - struct BooleanSlot { - bool value; - } - - struct Bytes32Slot { - bytes32 value; - } - - struct Uint256Slot { - uint256 value; - } - - struct StringSlot { - string value; - } - - struct BytesSlot { - bytes value; - } - - /** - * @dev Returns an `AddressSlot` with member `value` located at `slot`. - */ - function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `BooleanSlot` with member `value` located at `slot`. - */ - function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. - */ - function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `Uint256Slot` with member `value` located at `slot`. - */ - function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `StringSlot` with member `value` located at `slot`. - */ - function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `StringSlot` representation of the string storage pointer `store`. - */ - function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := store.slot - } - } - - /** - * @dev Returns an `BytesSlot` with member `value` located at `slot`. - */ - function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. - */ - function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := store.slot - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/Strings.sol b/blockchain/contracts/OpenZeppelin/utils/Strings.sol deleted file mode 100644 index afbf463..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/Strings.sol +++ /dev/null @@ -1,93 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol) - -pragma solidity ^0.8.19; - -import "./math/Math.sol"; -import "./math/SignedMath.sol"; - -/** - * @dev String operations. - */ -library Strings { - bytes16 private constant _SYMBOLS = "0123456789abcdef"; - uint8 private constant _ADDRESS_LENGTH = 20; - - /** - * @dev The `value` string doesn't fit in the specified `length`. - */ - error StringsInsufficientHexLength(uint256 value, uint256 length); - - /** - * @dev Converts a `uint256` to its ASCII `string` decimal representation. - */ - function toString(uint256 value) internal pure returns (string memory) { - unchecked { - uint256 length = Math.log10(value) + 1; - string memory buffer = new string(length); - uint256 ptr; - /// @solidity memory-safe-assembly - assembly { - ptr := add(buffer, add(32, length)) - } - while (true) { - ptr--; - /// @solidity memory-safe-assembly - assembly { - mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) - } - value /= 10; - if (value == 0) break; - } - return buffer; - } - } - - /** - * @dev Converts a `int256` to its ASCII `string` decimal representation. - */ - function toStringSigned(int256 value) internal pure returns (string memory) { - return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value))); - } - - /** - * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. - */ - function toHexString(uint256 value) internal pure returns (string memory) { - unchecked { - return toHexString(value, Math.log256(value) + 1); - } - } - - /** - * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. - */ - function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { - uint256 localValue = value; - bytes memory buffer = new bytes(2 * length + 2); - buffer[0] = "0"; - buffer[1] = "x"; - for (uint256 i = 2 * length + 1; i > 1; --i) { - buffer[i] = _SYMBOLS[localValue & 0xf]; - localValue >>= 4; - } - if (localValue != 0) { - revert StringsInsufficientHexLength(value, length); - } - return string(buffer); - } - - /** - * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. - */ - function toHexString(address addr) internal pure returns (string memory) { - return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); - } - - /** - * @dev Returns true if the two strings are equal. - */ - function equal(string memory a, string memory b) internal pure returns (bool) { - return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b)); - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/cryptography/ECDSA.sol b/blockchain/contracts/OpenZeppelin/utils/cryptography/ECDSA.sol deleted file mode 100644 index b8f1aff..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/cryptography/ECDSA.sol +++ /dev/null @@ -1,239 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol) - -pragma solidity ^0.8.19; - -import "../Strings.sol"; - -/** - * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. - * - * These functions can be used to verify that a message was signed by the holder - * of the private keys of a given address. - */ -library ECDSA { - enum RecoverError { - NoError, - InvalidSignature, - InvalidSignatureLength, - InvalidSignatureS - } - - /** - * @dev The signature derives the `address(0)`. - */ - error ECDSAInvalidSignature(); - - /** - * @dev The signature has an invalid length. - */ - error ECDSAInvalidSignatureLength(uint256 length); - - /** - * @dev The signature has an S value that is in the upper half order. - */ - error ECDSAInvalidSignatureS(bytes32 s); - - function _throwError(RecoverError error, bytes32 errorArg) private pure { - if (error == RecoverError.NoError) { - return; // no error: do nothing - } else if (error == RecoverError.InvalidSignature) { - revert ECDSAInvalidSignature(); - } else if (error == RecoverError.InvalidSignatureLength) { - revert ECDSAInvalidSignatureLength(uint256(errorArg)); - } else if (error == RecoverError.InvalidSignatureS) { - revert ECDSAInvalidSignatureS(errorArg); - } - } - - /** - * @dev Returns the address that signed a hashed message (`hash`) with - * `signature` or error string. This address can then be used for verification purposes. - * - * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: - * this function rejects them by requiring the `s` value to be in the lower - * half order, and the `v` value to be either 27 or 28. - * - * IMPORTANT: `hash` _must_ be the result of a hash operation for the - * verification to be secure: it is possible to craft signatures that - * recover to arbitrary addresses for non-hashed data. A safe way to ensure - * this is by receiving a hash of the original message (which may otherwise - * be too long), and then calling {toEthSignedMessageHash} on it. - * - * Documentation for signature generation: - * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] - * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] - * - * _Available since v4.3._ - */ - function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) { - if (signature.length == 65) { - bytes32 r; - bytes32 s; - uint8 v; - // ecrecover takes the signature parameters, and the only way to get them - // currently is to use assembly. - /// @solidity memory-safe-assembly - assembly { - r := mload(add(signature, 0x20)) - s := mload(add(signature, 0x40)) - v := byte(0, mload(add(signature, 0x60))) - } - return tryRecover(hash, v, r, s); - } else { - return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length)); - } - } - - /** - * @dev Returns the address that signed a hashed message (`hash`) with - * `signature`. This address can then be used for verification purposes. - * - * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: - * this function rejects them by requiring the `s` value to be in the lower - * half order, and the `v` value to be either 27 or 28. - * - * IMPORTANT: `hash` _must_ be the result of a hash operation for the - * verification to be secure: it is possible to craft signatures that - * recover to arbitrary addresses for non-hashed data. A safe way to ensure - * this is by receiving a hash of the original message (which may otherwise - * be too long), and then calling {toEthSignedMessageHash} on it. - */ - function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { - (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature); - _throwError(error, errorArg); - return recovered; - } - - /** - * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. - * - * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] - * - * _Available since v4.3._ - */ - function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) { - unchecked { - bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); - // We do not check for an overflow here since the shift operation results in 0 or 1. - uint8 v = uint8((uint256(vs) >> 255) + 27); - return tryRecover(hash, v, r, s); - } - } - - /** - * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. - * - * _Available since v4.2._ - */ - function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { - (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs); - _throwError(error, errorArg); - return recovered; - } - - /** - * @dev Overload of {ECDSA-tryRecover} that receives the `v`, - * `r` and `s` signature fields separately. - * - * _Available since v4.3._ - */ - function tryRecover( - bytes32 hash, - uint8 v, - bytes32 r, - bytes32 s - ) internal pure returns (address, RecoverError, bytes32) { - // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature - // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines - // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most - // signatures from current libraries generate a unique signature with an s-value in the lower half order. - // - // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value - // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or - // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept - // these malleable signatures as well. - if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { - return (address(0), RecoverError.InvalidSignatureS, s); - } - - // If the signature is valid (and not malleable), return the signer address - address signer = ecrecover(hash, v, r, s); - if (signer == address(0)) { - return (address(0), RecoverError.InvalidSignature, bytes32(0)); - } - - return (signer, RecoverError.NoError, bytes32(0)); - } - - /** - * @dev Overload of {ECDSA-recover} that receives the `v`, - * `r` and `s` signature fields separately. - */ - function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { - (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s); - _throwError(error, errorArg); - return recovered; - } - - /** - * @dev Returns an Ethereum Signed Message, created from a `hash`. This - * produces hash corresponding to the one signed with the - * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] - * JSON-RPC method as part of EIP-191. - * - * See {recover}. - */ - function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) { - // 32 is the length in bytes of hash, - // enforced by the type signature above - /// @solidity memory-safe-assembly - assembly { - mstore(0x00, "\x19Ethereum Signed Message:\n32") - mstore(0x1c, hash) - message := keccak256(0x00, 0x3c) - } - } - - /** - * @dev Returns an Ethereum Signed Message, created from `s`. This - * produces hash corresponding to the one signed with the - * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] - * JSON-RPC method as part of EIP-191. - * - * See {recover}. - */ - function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { - return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); - } - - /** - * @dev Returns an Ethereum Signed Typed Data, created from a - * `domainSeparator` and a `structHash`. This produces hash corresponding - * to the one signed with the - * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] - * JSON-RPC method as part of EIP-712. - * - * See {recover}. - */ - function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) { - /// @solidity memory-safe-assembly - assembly { - let ptr := mload(0x40) - mstore(ptr, hex"19_01") - mstore(add(ptr, 0x02), domainSeparator) - mstore(add(ptr, 0x22), structHash) - data := keccak256(ptr, 0x42) - } - } - - /** - * @dev Returns an Ethereum Signed Data with intended validator, created from a - * `validator` and `data` according to the version 0 of EIP-191. - * - * See {recover}. - */ - function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { - return keccak256(abi.encodePacked(hex"19_00", validator, data)); - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/cryptography/EIP712.sol b/blockchain/contracts/OpenZeppelin/utils/cryptography/EIP712.sol deleted file mode 100644 index 2628014..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/cryptography/EIP712.sol +++ /dev/null @@ -1,167 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol) - -pragma solidity ^0.8.19; - -import "./ECDSA.sol"; -import "../ShortStrings.sol"; -import "../../interfaces/IERC5267.sol"; - -/** - * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. - * - * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, - * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding - * they need in their contracts using a combination of `abi.encode` and `keccak256`. - * - * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding - * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA - * ({_hashTypedDataV4}). - * - * The implementation of the domain separator was designed to be as efficient as possible while still properly updating - * the chain id to protect against replay attacks on an eventual fork of the chain. - * - * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method - * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. - * - * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain - * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the - * separator from the immutable values, which is cheaper than accessing a cached version in cold storage. - * - * _Available since v3.4._ - * - * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment - */ -abstract contract EIP712 is IERC5267 { - using ShortStrings for *; - - bytes32 private constant _TYPE_HASH = - keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); - - // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to - // invalidate the cached domain separator if the chain id changes. - bytes32 private immutable _cachedDomainSeparator; - uint256 private immutable _cachedChainId; - address private immutable _cachedThis; - - bytes32 private immutable _hashedName; - bytes32 private immutable _hashedVersion; - - ShortString private immutable _name; - ShortString private immutable _version; - string private _nameFallback; - string private _versionFallback; - - /** - * @dev Initializes the domain separator and parameter caches. - * - * The meaning of `name` and `version` is specified in - * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: - * - * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. - * - `version`: the current major version of the signing domain. - * - * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart - * contract upgrade]. - */ - constructor(string memory name, string memory version) { - _name = name.toShortStringWithFallback(_nameFallback); - _version = version.toShortStringWithFallback(_versionFallback); - _hashedName = keccak256(bytes(name)); - _hashedVersion = keccak256(bytes(version)); - - _cachedChainId = block.chainid; - _cachedDomainSeparator = _buildDomainSeparator(); - _cachedThis = address(this); - } - - /** - * @dev Returns the domain separator for the current chain. - */ - function _domainSeparatorV4() internal view returns (bytes32) { - if (address(this) == _cachedThis && block.chainid == _cachedChainId) { - return _cachedDomainSeparator; - } else { - return _buildDomainSeparator(); - } - } - - function _buildDomainSeparator() private view returns (bytes32) { - return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this))); - } - - /** - * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this - * function returns the hash of the fully encoded EIP712 message for this domain. - * - * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: - * - * ```solidity - * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( - * keccak256("Mail(address to,string contents)"), - * mailTo, - * keccak256(bytes(mailContents)) - * ))); - * address signer = ECDSA.recover(digest, signature); - * ``` - */ - function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { - return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); - } - - /** - * @dev See {EIP-5267}. - * - * _Available since v4.9._ - */ - function eip712Domain() - public - view - virtual - returns ( - bytes1 fields, - string memory name, - string memory version, - uint256 chainId, - address verifyingContract, - bytes32 salt, - uint256[] memory extensions - ) - { - return ( - hex"0f", // 01111 - _EIP712Name(), - _EIP712Version(), - block.chainid, - address(this), - bytes32(0), - new uint256[](0) - ); - } - - /** - * @dev The name parameter for the EIP712 domain. - * - * NOTE: By default this function reads _name which is an immutable value. - * It only reads from storage if necessary (in case the value is too large to fit in a ShortString). - * - * _Available since v5.0._ - */ - // solhint-disable-next-line func-name-mixedcase - function _EIP712Name() internal view returns (string memory) { - return _name.toStringWithFallback(_nameFallback); - } - - /** - * @dev The version parameter for the EIP712 domain. - * - * NOTE: By default this function reads _version which is an immutable value. - * It only reads from storage if necessary (in case the value is too large to fit in a ShortString). - * - * _Available since v5.0._ - */ - // solhint-disable-next-line func-name-mixedcase - function _EIP712Version() internal view returns (string memory) { - return _version.toStringWithFallback(_versionFallback); - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/cryptography/MerkleProof.sol b/blockchain/contracts/OpenZeppelin/utils/cryptography/MerkleProof.sol deleted file mode 100644 index 94586ff..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/cryptography/MerkleProof.sol +++ /dev/null @@ -1,240 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.2) (utils/cryptography/MerkleProof.sol) - -pragma solidity ^0.8.19; - -/** - * @dev These functions deal with verification of Merkle Tree proofs. - * - * The tree and the proofs can be generated using our - * https://github.com/OpenZeppelin/merkle-tree[JavaScript library]. - * You will find a quickstart guide in the readme. - * - * WARNING: You should avoid using leaf values that are 64 bytes long prior to - * hashing, or use a hash function other than keccak256 for hashing leaves. - * This is because the concatenation of a sorted pair of internal nodes in - * the merkle tree could be reinterpreted as a leaf value. - * OpenZeppelin's JavaScript library generates merkle trees that are safe - * against this attack out of the box. - */ -library MerkleProof { - /** - *@dev The multiproof provided is not valid. - */ - error MerkleProofInvalidMultiproof(); - - /** - * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree - * defined by `root`. For this, a `proof` must be provided, containing - * sibling hashes on the branch from the leaf to the root of the tree. Each - * pair of leaves and each pair of pre-images are assumed to be sorted. - */ - function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { - return processProof(proof, leaf) == root; - } - - /** - * @dev Calldata version of {verify} - * - * _Available since v4.7._ - */ - function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { - return processProofCalldata(proof, leaf) == root; - } - - /** - * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up - * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt - * hash matches the root of the tree. When processing the proof, the pairs - * of leafs & pre-images are assumed to be sorted. - * - * _Available since v4.4._ - */ - function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { - bytes32 computedHash = leaf; - for (uint256 i = 0; i < proof.length; i++) { - computedHash = _hashPair(computedHash, proof[i]); - } - return computedHash; - } - - /** - * @dev Calldata version of {processProof} - * - * _Available since v4.7._ - */ - function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { - bytes32 computedHash = leaf; - for (uint256 i = 0; i < proof.length; i++) { - computedHash = _hashPair(computedHash, proof[i]); - } - return computedHash; - } - - /** - * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by - * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}. - * - * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. - * - * _Available since v4.7._ - */ - function multiProofVerify( - bytes32[] memory proof, - bool[] memory proofFlags, - bytes32 root, - bytes32[] memory leaves - ) internal pure returns (bool) { - return processMultiProof(proof, proofFlags, leaves) == root; - } - - /** - * @dev Calldata version of {multiProofVerify} - * - * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. - * - * _Available since v4.7._ - */ - function multiProofVerifyCalldata( - bytes32[] calldata proof, - bool[] calldata proofFlags, - bytes32 root, - bytes32[] memory leaves - ) internal pure returns (bool) { - return processMultiProofCalldata(proof, proofFlags, leaves) == root; - } - - /** - * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction - * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another - * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false - * respectively. - * - * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree - * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the - * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer). - * - * _Available since v4.7._ - */ - function processMultiProof( - bytes32[] memory proof, - bool[] memory proofFlags, - bytes32[] memory leaves - ) internal pure returns (bytes32 merkleRoot) { - // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by - // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the - // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of - // the merkle tree. - uint256 leavesLen = leaves.length; - uint256 proofLen = proof.length; - uint256 totalHashes = proofFlags.length; - - // Check proof validity. - if (leavesLen + proofLen - 1 != totalHashes) { - revert MerkleProofInvalidMultiproof(); - } - - // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using - // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". - bytes32[] memory hashes = new bytes32[](totalHashes); - uint256 leafPos = 0; - uint256 hashPos = 0; - uint256 proofPos = 0; - // At each step, we compute the next hash using two values: - // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we - // get the next hash. - // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the - // `proof` array. - for (uint256 i = 0; i < totalHashes; i++) { - bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; - bytes32 b = proofFlags[i] - ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) - : proof[proofPos++]; - hashes[i] = _hashPair(a, b); - } - - if (totalHashes > 0) { - if (proofPos != proofLen) { - revert MerkleProofInvalidMultiproof(); - } - unchecked { - return hashes[totalHashes - 1]; - } - } else if (leavesLen > 0) { - return leaves[0]; - } else { - return proof[0]; - } - } - - /** - * @dev Calldata version of {processMultiProof}. - * - * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. - * - * _Available since v4.7._ - */ - function processMultiProofCalldata( - bytes32[] calldata proof, - bool[] calldata proofFlags, - bytes32[] memory leaves - ) internal pure returns (bytes32 merkleRoot) { - // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by - // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the - // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of - // the merkle tree. - uint256 leavesLen = leaves.length; - uint256 proofLen = proof.length; - uint256 totalHashes = proofFlags.length; - - // Check proof validity. - if (leavesLen + proofLen - 1 != totalHashes) { - revert MerkleProofInvalidMultiproof(); - } - - // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using - // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". - bytes32[] memory hashes = new bytes32[](totalHashes); - uint256 leafPos = 0; - uint256 hashPos = 0; - uint256 proofPos = 0; - // At each step, we compute the next hash using two values: - // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we - // get the next hash. - // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the - // `proof` array. - for (uint256 i = 0; i < totalHashes; i++) { - bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; - bytes32 b = proofFlags[i] - ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) - : proof[proofPos++]; - hashes[i] = _hashPair(a, b); - } - - if (totalHashes > 0) { - if (proofPos != proofLen) { - revert MerkleProofInvalidMultiproof(); - } - unchecked { - return hashes[totalHashes - 1]; - } - } else if (leavesLen > 0) { - return leaves[0]; - } else { - return proof[0]; - } - } - - function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { - return a < b ? _efficientHash(a, b) : _efficientHash(b, a); - } - - function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { - /// @solidity memory-safe-assembly - assembly { - mstore(0x00, a) - mstore(0x20, b) - value := keccak256(0x00, 0x40) - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/cryptography/SignatureChecker.sol b/blockchain/contracts/OpenZeppelin/utils/cryptography/SignatureChecker.sol deleted file mode 100644 index 25fdee5..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/cryptography/SignatureChecker.sol +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/SignatureChecker.sol) - -pragma solidity ^0.8.19; - -import "./ECDSA.sol"; -import "../../interfaces/IERC1271.sol"; - -/** - * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA - * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like - * Argent and Gnosis Safe. - * - * _Available since v4.1._ - */ -library SignatureChecker { - /** - * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the - * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. - * - * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus - * change through time. It could return true at block N and false at block N+1 (or the opposite). - */ - function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) { - (address recovered, ECDSA.RecoverError error, ) = ECDSA.tryRecover(hash, signature); - return - (error == ECDSA.RecoverError.NoError && recovered == signer) || - isValidERC1271SignatureNow(signer, hash, signature); - } - - /** - * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated - * against the signer smart contract using ERC1271. - * - * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus - * change through time. It could return true at block N and false at block N+1 (or the opposite). - */ - function isValidERC1271SignatureNow( - address signer, - bytes32 hash, - bytes memory signature - ) internal view returns (bool) { - (bool success, bytes memory result) = signer.staticcall( - abi.encodeCall(IERC1271.isValidSignature, (hash, signature)) - ); - return (success && - result.length >= 32 && - abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector)); - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/introspection/ERC165.sol b/blockchain/contracts/OpenZeppelin/utils/introspection/ERC165.sol deleted file mode 100644 index 1119130..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/introspection/ERC165.sol +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) - -pragma solidity ^0.8.19; - -import "./IERC165.sol"; - -/** - * @dev Implementation of the {IERC165} interface. - * - * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check - * for the additional interface id that will be supported. For example: - * - * ```solidity - * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); - * } - * ``` - */ -abstract contract ERC165 is IERC165 { - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { - return interfaceId == type(IERC165).interfaceId; - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/introspection/ERC165Checker.sol b/blockchain/contracts/OpenZeppelin/utils/introspection/ERC165Checker.sol deleted file mode 100644 index c27b2f1..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/introspection/ERC165Checker.sol +++ /dev/null @@ -1,126 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/introspection/ERC165Checker.sol) - -pragma solidity ^0.8.19; - -import "./IERC165.sol"; - -/** - * @dev Library used to query support of an interface declared via {IERC165}. - * - * Note that these functions return the actual result of the query: they do not - * `revert` if an interface is not supported. It is up to the caller to decide - * what to do in these cases. - */ -library ERC165Checker { - // As per the EIP-165 spec, no interface should ever match 0xffffffff - bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; - - /** - * @dev Returns true if `account` supports the {IERC165} interface. - */ - function supportsERC165(address account) internal view returns (bool) { - // Any contract that implements ERC165 must explicitly indicate support of - // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid - return - supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) && - !supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID); - } - - /** - * @dev Returns true if `account` supports the interface defined by - * `interfaceId`. Support for {IERC165} itself is queried automatically. - * - * See {IERC165-supportsInterface}. - */ - function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { - // query support of both ERC165 as per the spec and support of _interfaceId - return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId); - } - - /** - * @dev Returns a boolean array where each value corresponds to the - * interfaces passed in and whether they're supported or not. This allows - * you to batch check interfaces for a contract where your expectation - * is that some interfaces may not be supported. - * - * See {IERC165-supportsInterface}. - * - * _Available since v3.4._ - */ - function getSupportedInterfaces( - address account, - bytes4[] memory interfaceIds - ) internal view returns (bool[] memory) { - // an array of booleans corresponding to interfaceIds and whether they're supported or not - bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); - - // query support of ERC165 itself - if (supportsERC165(account)) { - // query support of each interface in interfaceIds - for (uint256 i = 0; i < interfaceIds.length; i++) { - interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]); - } - } - - return interfaceIdsSupported; - } - - /** - * @dev Returns true if `account` supports all the interfaces defined in - * `interfaceIds`. Support for {IERC165} itself is queried automatically. - * - * Batch-querying can lead to gas savings by skipping repeated checks for - * {IERC165} support. - * - * See {IERC165-supportsInterface}. - */ - function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { - // query support of ERC165 itself - if (!supportsERC165(account)) { - return false; - } - - // query support of each interface in interfaceIds - for (uint256 i = 0; i < interfaceIds.length; i++) { - if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) { - return false; - } - } - - // all interfaces supported - return true; - } - - /** - * @notice Query if a contract implements an interface, does not check ERC165 support - * @param account The address of the contract to query for support of an interface - * @param interfaceId The interface identifier, as specified in ERC-165 - * @return true if the contract at account indicates support of the interface with - * identifier interfaceId, false otherwise - * @dev Assumes that account contains a contract that supports ERC165, otherwise - * the behavior of this method is undefined. This precondition can be checked - * with {supportsERC165}. - * - * Some precompiled contracts will falsely indicate support for a given interface, so caution - * should be exercised when using this function. - * - * Interface identification is specified in ERC-165. - */ - function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) { - // prepare call - bytes memory encodedParams = abi.encodeCall(IERC165.supportsInterface, (interfaceId)); - - // perform static call - bool success; - uint256 returnSize; - uint256 returnValue; - assembly { - success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20) - returnSize := returndatasize() - returnValue := mload(0x00) - } - - return success && returnSize >= 0x20 && returnValue > 0; - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/introspection/IERC165.sol b/blockchain/contracts/OpenZeppelin/utils/introspection/IERC165.sol deleted file mode 100644 index da6f186..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/introspection/IERC165.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Interface of the ERC165 standard, as defined in the - * https://eips.ethereum.org/EIPS/eip-165[EIP]. - * - * Implementers can declare support of contract interfaces, which can then be - * queried by others ({ERC165Checker}). - * - * For an implementation, see {ERC165}. - */ -interface IERC165 { - /** - * @dev Returns true if this contract implements the interface defined by - * `interfaceId`. See the corresponding - * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] - * to learn more about how these ids are created. - * - * This function call must use less than 30 000 gas. - */ - function supportsInterface(bytes4 interfaceId) external view returns (bool); -} diff --git a/blockchain/contracts/OpenZeppelin/utils/math/Math.sol b/blockchain/contracts/OpenZeppelin/utils/math/Math.sol deleted file mode 100644 index d372295..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/math/Math.sol +++ /dev/null @@ -1,417 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Standard math utilities missing in the Solidity language. - */ -library Math { - /** - * @dev Muldiv operation overflow. - */ - error MathOverflowedMulDiv(); - - enum Rounding { - Down, // Toward negative infinity - Up, // Toward infinity - Zero // Toward zero - } - - /** - * @dev Returns the addition of two unsigned integers, with an overflow flag. - * - * _Available since v5.0._ - */ - function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - uint256 c = a + b; - if (c < a) return (false, 0); - return (true, c); - } - } - - /** - * @dev Returns the subtraction of two unsigned integers, with an overflow flag. - * - * _Available since v5.0._ - */ - function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - if (b > a) return (false, 0); - return (true, a - b); - } - } - - /** - * @dev Returns the multiplication of two unsigned integers, with an overflow flag. - * - * _Available since v5.0._ - */ - function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - // Gas optimization: this is cheaper than requiring 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 - if (a == 0) return (true, 0); - uint256 c = a * b; - if (c / a != b) return (false, 0); - return (true, c); - } - } - - /** - * @dev Returns the division of two unsigned integers, with a division by zero flag. - * - * _Available since v5.0._ - */ - function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - if (b == 0) return (false, 0); - return (true, a / b); - } - } - - /** - * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. - * - * _Available since v5.0._ - */ - function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - if (b == 0) return (false, 0); - return (true, a % b); - } - } - - /** - * @dev Returns the largest of two numbers. - */ - function max(uint256 a, uint256 b) internal pure returns (uint256) { - return a > b ? a : b; - } - - /** - * @dev Returns the smallest of two numbers. - */ - function min(uint256 a, uint256 b) internal pure returns (uint256) { - return a < b ? a : b; - } - - /** - * @dev Returns the average of two numbers. The result is rounded towards - * zero. - */ - function average(uint256 a, uint256 b) internal pure returns (uint256) { - // (a + b) / 2 can overflow. - return (a & b) + (a ^ b) / 2; - } - - /** - * @dev Returns the ceiling of the division of two numbers. - * - * This differs from standard division with `/` in that it rounds up instead - * of rounding down. - */ - function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { - if (b == 0) { - // Guarantee the same behavior as in a regular Solidity division. - return a / b; - } - - // (a + b - 1) / b can overflow on addition, so we distribute. - return a == 0 ? 0 : (a - 1) / b + 1; - } - - /** - * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 - * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) - * with further edits by Uniswap Labs also under MIT license. - */ - function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { - unchecked { - // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use - // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 - // variables such that product = prod1 * 2^256 + prod0. - uint256 prod0; // Least significant 256 bits of the product - uint256 prod1; // Most significant 256 bits of the product - assembly { - let mm := mulmod(x, y, not(0)) - prod0 := mul(x, y) - prod1 := sub(sub(mm, prod0), lt(mm, prod0)) - } - - // Handle non-overflow cases, 256 by 256 division. - if (prod1 == 0) { - // Solidity will revert if denominator == 0, unlike the div opcode on its own. - // The surrounding unchecked block does not change this fact. - // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. - return prod0 / denominator; - } - - // Make sure the result is less than 2^256. Also prevents denominator == 0. - if (denominator <= prod1) { - revert MathOverflowedMulDiv(); - } - - /////////////////////////////////////////////// - // 512 by 256 division. - /////////////////////////////////////////////// - - // Make division exact by subtracting the remainder from [prod1 prod0]. - uint256 remainder; - assembly { - // Compute remainder using mulmod. - remainder := mulmod(x, y, denominator) - - // Subtract 256 bit number from 512 bit number. - prod1 := sub(prod1, gt(remainder, prod0)) - prod0 := sub(prod0, remainder) - } - - // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. - // See https://cs.stackexchange.com/q/138556/92363. - - // Does not overflow because the denominator cannot be zero at this stage in the function. - uint256 twos = denominator & (~denominator + 1); - assembly { - // Divide denominator by twos. - denominator := div(denominator, twos) - - // Divide [prod1 prod0] by twos. - prod0 := div(prod0, twos) - - // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. - twos := add(div(sub(0, twos), twos), 1) - } - - // Shift in bits from prod1 into prod0. - prod0 |= prod1 * twos; - - // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such - // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for - // four bits. That is, denominator * inv = 1 mod 2^4. - uint256 inverse = (3 * denominator) ^ 2; - - // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works - // in modular arithmetic, doubling the correct bits in each step. - inverse *= 2 - denominator * inverse; // inverse mod 2^8 - inverse *= 2 - denominator * inverse; // inverse mod 2^16 - inverse *= 2 - denominator * inverse; // inverse mod 2^32 - inverse *= 2 - denominator * inverse; // inverse mod 2^64 - inverse *= 2 - denominator * inverse; // inverse mod 2^128 - inverse *= 2 - denominator * inverse; // inverse mod 2^256 - - // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. - // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is - // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 - // is no longer required. - result = prod0 * inverse; - return result; - } - } - - /** - * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. - */ - function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { - uint256 result = mulDiv(x, y, denominator); - if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { - result += 1; - } - return result; - } - - /** - * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. - * - * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). - */ - function sqrt(uint256 a) internal pure returns (uint256) { - if (a == 0) { - return 0; - } - - // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. - // - // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have - // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. - // - // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` - // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` - // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` - // - // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. - uint256 result = 1 << (log2(a) >> 1); - - // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, - // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at - // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision - // into the expected uint128 result. - unchecked { - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - return min(result, a / result); - } - } - - /** - * @notice Calculates sqrt(a), following the selected rounding direction. - */ - function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = sqrt(a); - return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); - } - } - - /** - * @dev Return the log in base 2, rounded down, of a positive value. - * Returns 0 if given 0. - */ - function log2(uint256 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >> 128 > 0) { - value >>= 128; - result += 128; - } - if (value >> 64 > 0) { - value >>= 64; - result += 64; - } - if (value >> 32 > 0) { - value >>= 32; - result += 32; - } - if (value >> 16 > 0) { - value >>= 16; - result += 16; - } - if (value >> 8 > 0) { - value >>= 8; - result += 8; - } - if (value >> 4 > 0) { - value >>= 4; - result += 4; - } - if (value >> 2 > 0) { - value >>= 2; - result += 2; - } - if (value >> 1 > 0) { - result += 1; - } - } - return result; - } - - /** - * @dev Return the log in base 2, following the selected rounding direction, of a positive value. - * Returns 0 if given 0. - */ - function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = log2(value); - return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); - } - } - - /** - * @dev Return the log in base 10, rounded down, of a positive value. - * Returns 0 if given 0. - */ - function log10(uint256 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >= 10 ** 64) { - value /= 10 ** 64; - result += 64; - } - if (value >= 10 ** 32) { - value /= 10 ** 32; - result += 32; - } - if (value >= 10 ** 16) { - value /= 10 ** 16; - result += 16; - } - if (value >= 10 ** 8) { - value /= 10 ** 8; - result += 8; - } - if (value >= 10 ** 4) { - value /= 10 ** 4; - result += 4; - } - if (value >= 10 ** 2) { - value /= 10 ** 2; - result += 2; - } - if (value >= 10 ** 1) { - result += 1; - } - } - return result; - } - - /** - * @dev Return the log in base 10, following the selected rounding direction, of a positive value. - * Returns 0 if given 0. - */ - function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = log10(value); - return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); - } - } - - /** - * @dev Return the log in base 256, rounded down, of a positive value. - * Returns 0 if given 0. - * - * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. - */ - function log256(uint256 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >> 128 > 0) { - value >>= 128; - result += 16; - } - if (value >> 64 > 0) { - value >>= 64; - result += 8; - } - if (value >> 32 > 0) { - value >>= 32; - result += 4; - } - if (value >> 16 > 0) { - value >>= 16; - result += 2; - } - if (value >> 8 > 0) { - result += 1; - } - } - return result; - } - - /** - * @dev Return the log in base 256, following the selected rounding direction, of a positive value. - * Returns 0 if given 0. - */ - function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = log256(value); - return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/math/SignedMath.sol b/blockchain/contracts/OpenZeppelin/utils/math/SignedMath.sol deleted file mode 100644 index 8041353..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/math/SignedMath.sol +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) - -pragma solidity ^0.8.19; - -/** - * @dev Standard signed math utilities missing in the Solidity language. - */ -library SignedMath { - /** - * @dev Returns the largest of two signed numbers. - */ - function max(int256 a, int256 b) internal pure returns (int256) { - return a > b ? a : b; - } - - /** - * @dev Returns the smallest of two signed numbers. - */ - function min(int256 a, int256 b) internal pure returns (int256) { - return a < b ? a : b; - } - - /** - * @dev Returns the average of two signed numbers without overflow. - * The result is rounded towards zero. - */ - function average(int256 a, int256 b) internal pure returns (int256) { - // Formula from the book "Hacker's Delight" - int256 x = (a & b) + ((a ^ b) >> 1); - return x + (int256(uint256(x) >> 255) & (a ^ b)); - } - - /** - * @dev Returns the absolute unsigned value of a signed value. - */ - function abs(int256 n) internal pure returns (uint256) { - unchecked { - // must be unchecked in order to support `n = type(int256).min` - return uint256(n >= 0 ? n : -n); - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/structs/BitMaps.sol b/blockchain/contracts/OpenZeppelin/utils/structs/BitMaps.sol deleted file mode 100644 index 9786c7f..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/structs/BitMaps.sol +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/BitMaps.sol) -pragma solidity ^0.8.19; - -/** - * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. - * Largely inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor]. - */ -library BitMaps { - struct BitMap { - mapping(uint256 => uint256) _data; - } - - /** - * @dev Returns whether the bit at `index` is set. - */ - function get(BitMap storage bitmap, uint256 index) internal view returns (bool) { - uint256 bucket = index >> 8; - uint256 mask = 1 << (index & 0xff); - return bitmap._data[bucket] & mask != 0; - } - - /** - * @dev Sets the bit at `index` to the boolean `value`. - */ - function setTo(BitMap storage bitmap, uint256 index, bool value) internal { - if (value) { - set(bitmap, index); - } else { - unset(bitmap, index); - } - } - - /** - * @dev Sets the bit at `index`. - */ - function set(BitMap storage bitmap, uint256 index) internal { - uint256 bucket = index >> 8; - uint256 mask = 1 << (index & 0xff); - bitmap._data[bucket] |= mask; - } - - /** - * @dev Unsets the bit at `index`. - */ - function unset(BitMap storage bitmap, uint256 index) internal { - uint256 bucket = index >> 8; - uint256 mask = 1 << (index & 0xff); - bitmap._data[bucket] &= ~mask; - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/structs/Checkpoints.sol b/blockchain/contracts/OpenZeppelin/utils/structs/Checkpoints.sol deleted file mode 100644 index 7608d78..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/structs/Checkpoints.sol +++ /dev/null @@ -1,394 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/Checkpoints.sol) -// This file was procedurally generated from scripts/generate/templates/Checkpoints.js. - -pragma solidity ^0.8.19; - -import "../math/Math.sol"; -import "../math/SafeCast.sol"; - -/** - * @dev This library defines the `History` struct, for checkpointing values as they change at different points in - * time, and later looking up past values by block number. See {Votes} as an example. - * - * To create a history of checkpoints define a variable type `Checkpoints.History` in your contract, and store a new - * checkpoint for the current transaction block using the {push} function. - * - * _Available since v4.5._ - */ -library Checkpoints { - /** - * @dev A value was attempted to be inserted on a past checkpoint. - */ - error CheckpointUnorderedInsertion(); - - struct Trace224 { - Checkpoint224[] _checkpoints; - } - - struct Checkpoint224 { - uint32 _key; - uint224 _value; - } - - /** - * @dev Pushes a (`key`, `value`) pair into a Trace224 so that it is stored as the checkpoint. - * - * Returns previous value and new value. - */ - function push(Trace224 storage self, uint32 key, uint224 value) internal returns (uint224, uint224) { - return _insert(self._checkpoints, key, value); - } - - /** - * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if there is none. - */ - function lowerLookup(Trace224 storage self, uint32 key) internal view returns (uint224) { - uint256 len = self._checkpoints.length; - uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len); - return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value; - } - - /** - * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none. - */ - function upperLookup(Trace224 storage self, uint32 key) internal view returns (uint224) { - uint256 len = self._checkpoints.length; - uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len); - return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; - } - - /** - * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none. - * - * NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high keys). - */ - function upperLookupRecent(Trace224 storage self, uint32 key) internal view returns (uint224) { - uint256 len = self._checkpoints.length; - - uint256 low = 0; - uint256 high = len; - - if (len > 5) { - uint256 mid = len - Math.sqrt(len); - if (key < _unsafeAccess(self._checkpoints, mid)._key) { - high = mid; - } else { - low = mid + 1; - } - } - - uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high); - - return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; - } - - /** - * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints. - */ - function latest(Trace224 storage self) internal view returns (uint224) { - uint256 pos = self._checkpoints.length; - return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; - } - - /** - * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value - * in the most recent checkpoint. - */ - function latestCheckpoint(Trace224 storage self) internal view returns (bool exists, uint32 _key, uint224 _value) { - uint256 pos = self._checkpoints.length; - if (pos == 0) { - return (false, 0, 0); - } else { - Checkpoint224 memory ckpt = _unsafeAccess(self._checkpoints, pos - 1); - return (true, ckpt._key, ckpt._value); - } - } - - /** - * @dev Returns the number of checkpoint. - */ - function length(Trace224 storage self) internal view returns (uint256) { - return self._checkpoints.length; - } - - /** - * @dev Returns checkpoint at given position. - */ - function at(Trace224 storage self, uint32 pos) internal view returns (Checkpoint224 memory) { - return self._checkpoints[pos]; - } - - /** - * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint, - * or by updating the last one. - */ - function _insert(Checkpoint224[] storage self, uint32 key, uint224 value) private returns (uint224, uint224) { - uint256 pos = self.length; - - if (pos > 0) { - // Copying to memory is important here. - Checkpoint224 memory last = _unsafeAccess(self, pos - 1); - - // Checkpoint keys must be non-decreasing. - if (last._key > key) { - revert CheckpointUnorderedInsertion(); - } - - // Update or push new checkpoint - if (last._key == key) { - _unsafeAccess(self, pos - 1)._value = value; - } else { - self.push(Checkpoint224({_key: key, _value: value})); - } - return (last._value, value); - } else { - self.push(Checkpoint224({_key: key, _value: value})); - return (0, value); - } - } - - /** - * @dev Return the index of the last (most recent) checkpoint with key lower or equal than the search key, or `high` if there is none. - * `low` and `high` define a section where to do the search, with inclusive `low` and exclusive `high`. - * - * WARNING: `high` should not be greater than the array's length. - */ - function _upperBinaryLookup( - Checkpoint224[] storage self, - uint32 key, - uint256 low, - uint256 high - ) private view returns (uint256) { - while (low < high) { - uint256 mid = Math.average(low, high); - if (_unsafeAccess(self, mid)._key > key) { - high = mid; - } else { - low = mid + 1; - } - } - return high; - } - - /** - * @dev Return the index of the first (oldest) checkpoint with key is greater or equal than the search key, or `high` if there is none. - * `low` and `high` define a section where to do the search, with inclusive `low` and exclusive `high`. - * - * WARNING: `high` should not be greater than the array's length. - */ - function _lowerBinaryLookup( - Checkpoint224[] storage self, - uint32 key, - uint256 low, - uint256 high - ) private view returns (uint256) { - while (low < high) { - uint256 mid = Math.average(low, high); - if (_unsafeAccess(self, mid)._key < key) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - - /** - * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. - */ - function _unsafeAccess( - Checkpoint224[] storage self, - uint256 pos - ) private pure returns (Checkpoint224 storage result) { - assembly { - mstore(0, self.slot) - result.slot := add(keccak256(0, 0x20), pos) - } - } - - struct Trace160 { - Checkpoint160[] _checkpoints; - } - - struct Checkpoint160 { - uint96 _key; - uint160 _value; - } - - /** - * @dev Pushes a (`key`, `value`) pair into a Trace160 so that it is stored as the checkpoint. - * - * Returns previous value and new value. - */ - function push(Trace160 storage self, uint96 key, uint160 value) internal returns (uint160, uint160) { - return _insert(self._checkpoints, key, value); - } - - /** - * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if there is none. - */ - function lowerLookup(Trace160 storage self, uint96 key) internal view returns (uint160) { - uint256 len = self._checkpoints.length; - uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len); - return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value; - } - - /** - * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none. - */ - function upperLookup(Trace160 storage self, uint96 key) internal view returns (uint160) { - uint256 len = self._checkpoints.length; - uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len); - return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; - } - - /** - * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none. - * - * NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high keys). - */ - function upperLookupRecent(Trace160 storage self, uint96 key) internal view returns (uint160) { - uint256 len = self._checkpoints.length; - - uint256 low = 0; - uint256 high = len; - - if (len > 5) { - uint256 mid = len - Math.sqrt(len); - if (key < _unsafeAccess(self._checkpoints, mid)._key) { - high = mid; - } else { - low = mid + 1; - } - } - - uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high); - - return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; - } - - /** - * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints. - */ - function latest(Trace160 storage self) internal view returns (uint160) { - uint256 pos = self._checkpoints.length; - return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; - } - - /** - * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value - * in the most recent checkpoint. - */ - function latestCheckpoint(Trace160 storage self) internal view returns (bool exists, uint96 _key, uint160 _value) { - uint256 pos = self._checkpoints.length; - if (pos == 0) { - return (false, 0, 0); - } else { - Checkpoint160 memory ckpt = _unsafeAccess(self._checkpoints, pos - 1); - return (true, ckpt._key, ckpt._value); - } - } - - /** - * @dev Returns the number of checkpoint. - */ - function length(Trace160 storage self) internal view returns (uint256) { - return self._checkpoints.length; - } - - /** - * @dev Returns checkpoint at given position. - */ - function at(Trace160 storage self, uint32 pos) internal view returns (Checkpoint160 memory) { - return self._checkpoints[pos]; - } - - /** - * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint, - * or by updating the last one. - */ - function _insert(Checkpoint160[] storage self, uint96 key, uint160 value) private returns (uint160, uint160) { - uint256 pos = self.length; - - if (pos > 0) { - // Copying to memory is important here. - Checkpoint160 memory last = _unsafeAccess(self, pos - 1); - - // Checkpoint keys must be non-decreasing. - if (last._key > key) { - revert CheckpointUnorderedInsertion(); - } - - // Update or push new checkpoint - if (last._key == key) { - _unsafeAccess(self, pos - 1)._value = value; - } else { - self.push(Checkpoint160({_key: key, _value: value})); - } - return (last._value, value); - } else { - self.push(Checkpoint160({_key: key, _value: value})); - return (0, value); - } - } - - /** - * @dev Return the index of the last (most recent) checkpoint with key lower or equal than the search key, or `high` if there is none. - * `low` and `high` define a section where to do the search, with inclusive `low` and exclusive `high`. - * - * WARNING: `high` should not be greater than the array's length. - */ - function _upperBinaryLookup( - Checkpoint160[] storage self, - uint96 key, - uint256 low, - uint256 high - ) private view returns (uint256) { - while (low < high) { - uint256 mid = Math.average(low, high); - if (_unsafeAccess(self, mid)._key > key) { - high = mid; - } else { - low = mid + 1; - } - } - return high; - } - - /** - * @dev Return the index of the first (oldest) checkpoint with key is greater or equal than the search key, or `high` if there is none. - * `low` and `high` define a section where to do the search, with inclusive `low` and exclusive `high`. - * - * WARNING: `high` should not be greater than the array's length. - */ - function _lowerBinaryLookup( - Checkpoint160[] storage self, - uint96 key, - uint256 low, - uint256 high - ) private view returns (uint256) { - while (low < high) { - uint256 mid = Math.average(low, high); - if (_unsafeAccess(self, mid)._key < key) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - - /** - * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. - */ - function _unsafeAccess( - Checkpoint160[] storage self, - uint256 pos - ) private pure returns (Checkpoint160 storage result) { - assembly { - mstore(0, self.slot) - result.slot := add(keccak256(0, 0x20), pos) - } - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/structs/DoubleEndedQueue.sol b/blockchain/contracts/OpenZeppelin/utils/structs/DoubleEndedQueue.sol deleted file mode 100644 index 69db700..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/structs/DoubleEndedQueue.sol +++ /dev/null @@ -1,170 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/DoubleEndedQueue.sol) -pragma solidity ^0.8.19; - -import "../math/SafeCast.sol"; - -/** - * @dev A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends of - * the sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and - * FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes {clear}, given that - * the existing queue contents are left in storage. - * - * The struct is called `Bytes32Deque`. Other types can be cast to and from `bytes32`. This data structure can only be - * used in storage, and not in memory. - * ```solidity - * DoubleEndedQueue.Bytes32Deque queue; - * ``` - * - * _Available since v4.6._ - */ -library DoubleEndedQueue { - /** - * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty. - */ - error QueueEmpty(); - - /** - * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds. - */ - error QueueOutOfBounds(); - - /** - * @dev Indices are signed integers because the queue can grow in any direction. They are 128 bits so begin and end - * are packed in a single storage slot for efficient access. Since the items are added one at a time we can safely - * assume that these 128-bit indices will not overflow, and use unchecked arithmetic. - * - * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to - * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and - * lead to unexpected behavior. - * - * Indices are in the range [begin, end) which means the first item is at data[begin] and the last item is at - * data[end - 1]. - */ - struct Bytes32Deque { - int128 _begin; - int128 _end; - mapping(int128 => bytes32) _data; - } - - /** - * @dev Inserts an item at the end of the queue. - */ - function pushBack(Bytes32Deque storage deque, bytes32 value) internal { - int128 backIndex = deque._end; - deque._data[backIndex] = value; - unchecked { - deque._end = backIndex + 1; - } - } - - /** - * @dev Removes the item at the end of the queue and returns it. - * - * Reverts with `QueueEmpty` if the queue is empty. - */ - function popBack(Bytes32Deque storage deque) internal returns (bytes32 value) { - if (empty(deque)) revert QueueEmpty(); - int128 backIndex; - unchecked { - backIndex = deque._end - 1; - } - value = deque._data[backIndex]; - delete deque._data[backIndex]; - deque._end = backIndex; - } - - /** - * @dev Inserts an item at the beginning of the queue. - */ - function pushFront(Bytes32Deque storage deque, bytes32 value) internal { - int128 frontIndex; - unchecked { - frontIndex = deque._begin - 1; - } - deque._data[frontIndex] = value; - deque._begin = frontIndex; - } - - /** - * @dev Removes the item at the beginning of the queue and returns it. - * - * Reverts with `QueueEmpty` if the queue is empty. - */ - function popFront(Bytes32Deque storage deque) internal returns (bytes32 value) { - if (empty(deque)) revert QueueEmpty(); - int128 frontIndex = deque._begin; - value = deque._data[frontIndex]; - delete deque._data[frontIndex]; - unchecked { - deque._begin = frontIndex + 1; - } - } - - /** - * @dev Returns the item at the beginning of the queue. - * - * Reverts with `QueueEmpty` if the queue is empty. - */ - function front(Bytes32Deque storage deque) internal view returns (bytes32 value) { - if (empty(deque)) revert QueueEmpty(); - int128 frontIndex = deque._begin; - return deque._data[frontIndex]; - } - - /** - * @dev Returns the item at the end of the queue. - * - * Reverts with `QueueEmpty` if the queue is empty. - */ - function back(Bytes32Deque storage deque) internal view returns (bytes32 value) { - if (empty(deque)) revert QueueEmpty(); - int128 backIndex; - unchecked { - backIndex = deque._end - 1; - } - return deque._data[backIndex]; - } - - /** - * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at - * `length(deque) - 1`. - * - * Reverts with `QueueOutOfBounds` if the index is out of bounds. - */ - function at(Bytes32Deque storage deque, uint256 index) internal view returns (bytes32 value) { - // int256(deque._begin) is a safe upcast - int128 idx = SafeCast.toInt128(int256(deque._begin) + SafeCast.toInt256(index)); - if (idx >= deque._end) revert QueueOutOfBounds(); - return deque._data[idx]; - } - - /** - * @dev Resets the queue back to being empty. - * - * NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses - * out on potential gas refunds. - */ - function clear(Bytes32Deque storage deque) internal { - deque._begin = 0; - deque._end = 0; - } - - /** - * @dev Returns the number of items in the queue. - */ - function length(Bytes32Deque storage deque) internal view returns (uint256) { - // The interface preserves the invariant that begin <= end so we assume this will not overflow. - // We also assume there are at most int256.max items in the queue. - unchecked { - return uint256(int256(deque._end) - int256(deque._begin)); - } - } - - /** - * @dev Returns true if the queue is empty. - */ - function empty(Bytes32Deque storage deque) internal view returns (bool) { - return deque._end <= deque._begin; - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/structs/EnumerableMap.sol b/blockchain/contracts/OpenZeppelin/utils/structs/EnumerableMap.sol deleted file mode 100644 index a474e82..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/structs/EnumerableMap.sol +++ /dev/null @@ -1,537 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableMap.sol) -// This file was procedurally generated from scripts/generate/templates/EnumerableMap.js. - -pragma solidity ^0.8.19; - -import "./EnumerableSet.sol"; - -/** - * @dev Library for managing an enumerable variant of Solidity's - * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] - * type. - * - * Maps have the following properties: - * - * - Entries are added, removed, and checked for existence in constant time - * (O(1)). - * - Entries are enumerated in O(n). No guarantees are made on the ordering. - * - * ```solidity - * contract Example { - * // Add the library methods - * using EnumerableMap for EnumerableMap.UintToAddressMap; - * - * // Declare a set state variable - * EnumerableMap.UintToAddressMap private myMap; - * } - * ``` - * - * The following map types are supported: - * - * - `uint256 -> address` (`UintToAddressMap`) since v3.0.0 - * - `address -> uint256` (`AddressToUintMap`) since v4.6.0 - * - `bytes32 -> bytes32` (`Bytes32ToBytes32Map`) since v4.6.0 - * - `uint256 -> uint256` (`UintToUintMap`) since v4.7.0 - * - `bytes32 -> uint256` (`Bytes32ToUintMap`) since v4.7.0 - * - * [WARNING] - * ==== - * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure - * unusable. - * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. - * - * In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an - * array of EnumerableMap. - * ==== - */ -library EnumerableMap { - using EnumerableSet for EnumerableSet.Bytes32Set; - - // To implement this library for multiple types with as little code - // repetition as possible, we write it in terms of a generic Map type with - // bytes32 keys and values. - // The Map implementation uses private functions, and user-facing - // implementations (such as Uint256ToAddressMap) are just wrappers around - // the underlying Map. - // This means that we can only create new EnumerableMaps for types that fit - // in bytes32. - - /** - * @dev Query for a nonexistent map key. - */ - error EnumerableMapNonexistentKey(bytes32 key); - - struct Bytes32ToBytes32Map { - // Storage of keys - EnumerableSet.Bytes32Set _keys; - mapping(bytes32 => bytes32) _values; - } - - /** - * @dev Adds a key-value pair to a map, or updates the value for an existing - * key. O(1). - * - * Returns true if the key was added to the map, that is if it was not - * already present. - */ - function set(Bytes32ToBytes32Map storage map, bytes32 key, bytes32 value) internal returns (bool) { - map._values[key] = value; - return map._keys.add(key); - } - - /** - * @dev Removes a key-value pair from a map. O(1). - * - * Returns true if the key was removed from the map, that is if it was present. - */ - function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) { - delete map._values[key]; - return map._keys.remove(key); - } - - /** - * @dev Returns true if the key is in the map. O(1). - */ - function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) { - return map._keys.contains(key); - } - - /** - * @dev Returns the number of key-value pairs in the map. O(1). - */ - function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) { - return map._keys.length(); - } - - /** - * @dev Returns the key-value pair stored at position `index` in the map. O(1). - * - * Note that there are no guarantees on the ordering of entries inside the - * array, and it may change when more entries are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32, bytes32) { - bytes32 key = map._keys.at(index); - return (key, map._values[key]); - } - - /** - * @dev Tries to returns the value associated with `key`. O(1). - * Does not revert if `key` is not in the map. - */ - function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool, bytes32) { - bytes32 value = map._values[key]; - if (value == bytes32(0)) { - return (contains(map, key), bytes32(0)); - } else { - return (true, value); - } - } - - /** - * @dev Returns the value associated with `key`. O(1). - * - * Requirements: - * - * - `key` must be in the map. - */ - function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) { - bytes32 value = map._values[key]; - if (value == 0 && !contains(map, key)) { - revert EnumerableMapNonexistentKey(key); - } - return value; - } - - /** - * @dev Return the an array containing all the keys - * - * 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 map grows to a point where copying to memory consumes too much gas to fit in a block. - */ - function keys(Bytes32ToBytes32Map storage map) internal view returns (bytes32[] memory) { - return map._keys.values(); - } - - // UintToUintMap - - struct UintToUintMap { - Bytes32ToBytes32Map _inner; - } - - /** - * @dev Adds a key-value pair to a map, or updates the value for an existing - * key. O(1). - * - * Returns true if the key was added to the map, that is if it was not - * already present. - */ - function set(UintToUintMap storage map, uint256 key, uint256 value) internal returns (bool) { - return set(map._inner, bytes32(key), bytes32(value)); - } - - /** - * @dev Removes a value from a map. O(1). - * - * Returns true if the key was removed from the map, that is if it was present. - */ - function remove(UintToUintMap storage map, uint256 key) internal returns (bool) { - return remove(map._inner, bytes32(key)); - } - - /** - * @dev Returns true if the key is in the map. O(1). - */ - function contains(UintToUintMap storage map, uint256 key) internal view returns (bool) { - return contains(map._inner, bytes32(key)); - } - - /** - * @dev Returns the number of elements in the map. O(1). - */ - function length(UintToUintMap storage map) internal view returns (uint256) { - return length(map._inner); - } - - /** - * @dev Returns the element stored at position `index` in the map. O(1). - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(UintToUintMap storage map, uint256 index) internal view returns (uint256, uint256) { - (bytes32 key, bytes32 value) = at(map._inner, index); - return (uint256(key), uint256(value)); - } - - /** - * @dev Tries to returns the value associated with `key`. O(1). - * Does not revert if `key` is not in the map. - */ - function tryGet(UintToUintMap storage map, uint256 key) internal view returns (bool, uint256) { - (bool success, bytes32 value) = tryGet(map._inner, bytes32(key)); - return (success, uint256(value)); - } - - /** - * @dev Returns the value associated with `key`. O(1). - * - * Requirements: - * - * - `key` must be in the map. - */ - function get(UintToUintMap storage map, uint256 key) internal view returns (uint256) { - return uint256(get(map._inner, bytes32(key))); - } - - /** - * @dev Return the an array containing all the keys - * - * 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 map grows to a point where copying to memory consumes too much gas to fit in a block. - */ - function keys(UintToUintMap storage map) internal view returns (uint256[] memory) { - bytes32[] memory store = keys(map._inner); - uint256[] memory result; - - /// @solidity memory-safe-assembly - assembly { - result := store - } - - return result; - } - - // UintToAddressMap - - struct UintToAddressMap { - Bytes32ToBytes32Map _inner; - } - - /** - * @dev Adds a key-value pair to a map, or updates the value for an existing - * key. O(1). - * - * Returns true if the key was added to the map, that is if it was not - * already present. - */ - function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { - return set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); - } - - /** - * @dev Removes a value from a map. O(1). - * - * Returns true if the key was removed from the map, that is if it was present. - */ - function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { - return remove(map._inner, bytes32(key)); - } - - /** - * @dev Returns true if the key is in the map. O(1). - */ - function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { - return contains(map._inner, bytes32(key)); - } - - /** - * @dev Returns the number of elements in the map. O(1). - */ - function length(UintToAddressMap storage map) internal view returns (uint256) { - return length(map._inner); - } - - /** - * @dev Returns the element stored at position `index` in the map. O(1). - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { - (bytes32 key, bytes32 value) = at(map._inner, index); - return (uint256(key), address(uint160(uint256(value)))); - } - - /** - * @dev Tries to returns the value associated with `key`. O(1). - * Does not revert if `key` is not in the map. - */ - function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { - (bool success, bytes32 value) = tryGet(map._inner, bytes32(key)); - return (success, address(uint160(uint256(value)))); - } - - /** - * @dev Returns the value associated with `key`. O(1). - * - * Requirements: - * - * - `key` must be in the map. - */ - function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { - return address(uint160(uint256(get(map._inner, bytes32(key))))); - } - - /** - * @dev Return the an array containing all the keys - * - * 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 map grows to a point where copying to memory consumes too much gas to fit in a block. - */ - function keys(UintToAddressMap storage map) internal view returns (uint256[] memory) { - bytes32[] memory store = keys(map._inner); - uint256[] memory result; - - /// @solidity memory-safe-assembly - assembly { - result := store - } - - return result; - } - - // AddressToUintMap - - struct AddressToUintMap { - Bytes32ToBytes32Map _inner; - } - - /** - * @dev Adds a key-value pair to a map, or updates the value for an existing - * key. O(1). - * - * Returns true if the key was added to the map, that is if it was not - * already present. - */ - function set(AddressToUintMap storage map, address key, uint256 value) internal returns (bool) { - return set(map._inner, bytes32(uint256(uint160(key))), bytes32(value)); - } - - /** - * @dev Removes a value from a map. O(1). - * - * Returns true if the key was removed from the map, that is if it was present. - */ - function remove(AddressToUintMap storage map, address key) internal returns (bool) { - return remove(map._inner, bytes32(uint256(uint160(key)))); - } - - /** - * @dev Returns true if the key is in the map. O(1). - */ - function contains(AddressToUintMap storage map, address key) internal view returns (bool) { - return contains(map._inner, bytes32(uint256(uint160(key)))); - } - - /** - * @dev Returns the number of elements in the map. O(1). - */ - function length(AddressToUintMap storage map) internal view returns (uint256) { - return length(map._inner); - } - - /** - * @dev Returns the element stored at position `index` in the map. O(1). - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) { - (bytes32 key, bytes32 value) = at(map._inner, index); - return (address(uint160(uint256(key))), uint256(value)); - } - - /** - * @dev Tries to returns the value associated with `key`. O(1). - * Does not revert if `key` is not in the map. - */ - function tryGet(AddressToUintMap storage map, address key) internal view returns (bool, uint256) { - (bool success, bytes32 value) = tryGet(map._inner, bytes32(uint256(uint160(key)))); - return (success, uint256(value)); - } - - /** - * @dev Returns the value associated with `key`. O(1). - * - * Requirements: - * - * - `key` must be in the map. - */ - function get(AddressToUintMap storage map, address key) internal view returns (uint256) { - return uint256(get(map._inner, bytes32(uint256(uint160(key))))); - } - - /** - * @dev Return the an array containing all the keys - * - * 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 map grows to a point where copying to memory consumes too much gas to fit in a block. - */ - function keys(AddressToUintMap storage map) internal view returns (address[] memory) { - bytes32[] memory store = keys(map._inner); - address[] memory result; - - /// @solidity memory-safe-assembly - assembly { - result := store - } - - return result; - } - - // Bytes32ToUintMap - - struct Bytes32ToUintMap { - Bytes32ToBytes32Map _inner; - } - - /** - * @dev Adds a key-value pair to a map, or updates the value for an existing - * key. O(1). - * - * Returns true if the key was added to the map, that is if it was not - * already present. - */ - function set(Bytes32ToUintMap storage map, bytes32 key, uint256 value) internal returns (bool) { - return set(map._inner, key, bytes32(value)); - } - - /** - * @dev Removes a value from a map. O(1). - * - * Returns true if the key was removed from the map, that is if it was present. - */ - function remove(Bytes32ToUintMap storage map, bytes32 key) internal returns (bool) { - return remove(map._inner, key); - } - - /** - * @dev Returns true if the key is in the map. O(1). - */ - function contains(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool) { - return contains(map._inner, key); - } - - /** - * @dev Returns the number of elements in the map. O(1). - */ - function length(Bytes32ToUintMap storage map) internal view returns (uint256) { - return length(map._inner); - } - - /** - * @dev Returns the element stored at position `index` in the map. O(1). - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(Bytes32ToUintMap storage map, uint256 index) internal view returns (bytes32, uint256) { - (bytes32 key, bytes32 value) = at(map._inner, index); - return (key, uint256(value)); - } - - /** - * @dev Tries to returns the value associated with `key`. O(1). - * Does not revert if `key` is not in the map. - */ - function tryGet(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool, uint256) { - (bool success, bytes32 value) = tryGet(map._inner, key); - return (success, uint256(value)); - } - - /** - * @dev Returns the value associated with `key`. O(1). - * - * Requirements: - * - * - `key` must be in the map. - */ - function get(Bytes32ToUintMap storage map, bytes32 key) internal view returns (uint256) { - return uint256(get(map._inner, key)); - } - - /** - * @dev Return the an array containing all the keys - * - * 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 map grows to a point where copying to memory consumes too much gas to fit in a block. - */ - function keys(Bytes32ToUintMap storage map) internal view returns (bytes32[] memory) { - bytes32[] memory store = keys(map._inner); - bytes32[] memory result; - - /// @solidity memory-safe-assembly - assembly { - result := store - } - - return result; - } -} diff --git a/blockchain/contracts/OpenZeppelin/utils/structs/EnumerableSet.sol b/blockchain/contracts/OpenZeppelin/utils/structs/EnumerableSet.sol deleted file mode 100644 index b10b3cd..0000000 --- a/blockchain/contracts/OpenZeppelin/utils/structs/EnumerableSet.sol +++ /dev/null @@ -1,378 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol) -// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. - -pragma solidity ^0.8.19; - -/** - * @dev Library for managing - * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive - * types. - * - * Sets have the following properties: - * - * - Elements are added, removed, and checked for existence in constant time - * (O(1)). - * - Elements are enumerated in O(n). No guarantees are made on the ordering. - * - * ```solidity - * contract Example { - * // Add the library methods - * using EnumerableSet for EnumerableSet.AddressSet; - * - * // Declare a set state variable - * EnumerableSet.AddressSet private mySet; - * } - * ``` - * - * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) - * and `uint256` (`UintSet`) are supported. - * - * [WARNING] - * ==== - * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure - * unusable. - * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. - * - * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an - * array of EnumerableSet. - * ==== - */ -library EnumerableSet { - // To implement this library for multiple types with as little code - // repetition as possible, we write it in terms of a generic Set type with - // bytes32 values. - // The Set implementation uses private functions, and user-facing - // implementations (such as AddressSet) are just wrappers around the - // underlying Set. - // This means that we can only create new EnumerableSets for types that fit - // in bytes32. - - struct Set { - // Storage of set values - bytes32[] _values; - // Position of the value in the `values` array, plus 1 because index 0 - // means a value is not in the set. - mapping(bytes32 => uint256) _indexes; - } - - /** - * @dev Add a value to a set. O(1). - * - * Returns true if the value was added to the set, that is if it was not - * already present. - */ - function _add(Set storage set, bytes32 value) private returns (bool) { - if (!_contains(set, value)) { - set._values.push(value); - // The value is stored at length-1, but we add 1 to all indexes - // and use 0 as a sentinel value - set._indexes[value] = set._values.length; - return true; - } else { - return false; - } - } - - /** - * @dev Removes a value from a set. O(1). - * - * Returns true if the value was removed from the set, that is if it was - * present. - */ - function _remove(Set storage set, bytes32 value) private returns (bool) { - // We read and store the value's index to prevent multiple reads from the same storage slot - uint256 valueIndex = set._indexes[value]; - - if (valueIndex != 0) { - // Equivalent to contains(set, value) - // To delete an element from the _values array in O(1), we swap the element to delete with the last one in - // the array, and then remove the last element (sometimes called as 'swap and pop'). - // This modifies the order of the array, as noted in {at}. - - uint256 toDeleteIndex = valueIndex - 1; - uint256 lastIndex = set._values.length - 1; - - if (lastIndex != toDeleteIndex) { - bytes32 lastValue = set._values[lastIndex]; - - // Move the last value to the index where the value to delete is - set._values[toDeleteIndex] = lastValue; - // Update the index for the moved value - set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex - } - - // Delete the slot where the moved value was stored - set._values.pop(); - - // Delete the index for the deleted slot - delete set._indexes[value]; - - return true; - } else { - return false; - } - } - - /** - * @dev Returns true if the value is in the set. O(1). - */ - function _contains(Set storage set, bytes32 value) private view returns (bool) { - return set._indexes[value] != 0; - } - - /** - * @dev Returns the number of values on the set. O(1). - */ - function _length(Set storage set) private view returns (uint256) { - return set._values.length; - } - - /** - * @dev Returns the value stored at position `index` in the set. O(1). - * - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function _at(Set storage set, uint256 index) private view returns (bytes32) { - return set._values[index]; - } - - /** - * @dev Return the entire set in an array - * - * 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 _values(Set storage set) private view returns (bytes32[] memory) { - return set._values; - } - - // Bytes32Set - - struct Bytes32Set { - Set _inner; - } - - /** - * @dev Add a value to a set. O(1). - * - * Returns true if the value was added to the set, that is if it was not - * already present. - */ - function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { - return _add(set._inner, value); - } - - /** - * @dev Removes a value from a set. O(1). - * - * Returns true if the value was removed from the set, that is if it was - * present. - */ - function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { - return _remove(set._inner, value); - } - - /** - * @dev Returns true if the value is in the set. O(1). - */ - function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { - return _contains(set._inner, value); - } - - /** - * @dev Returns the number of values in the set. O(1). - */ - function length(Bytes32Set storage set) internal view returns (uint256) { - return _length(set._inner); - } - - /** - * @dev Returns the value stored at position `index` in the set. O(1). - * - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { - return _at(set._inner, index); - } - - /** - * @dev Return the entire set in an array - * - * 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 values(Bytes32Set storage set) internal view returns (bytes32[] memory) { - bytes32[] memory store = _values(set._inner); - bytes32[] memory result; - - /// @solidity memory-safe-assembly - assembly { - result := store - } - - return result; - } - - // AddressSet - - struct AddressSet { - Set _inner; - } - - /** - * @dev Add a value to a set. O(1). - * - * Returns true if the value was added to the set, that is if it was not - * already present. - */ - function add(AddressSet storage set, address value) internal returns (bool) { - return _add(set._inner, bytes32(uint256(uint160(value)))); - } - - /** - * @dev Removes a value from a set. O(1). - * - * Returns true if the value was removed from the set, that is if it was - * present. - */ - function remove(AddressSet storage set, address value) internal returns (bool) { - return _remove(set._inner, bytes32(uint256(uint160(value)))); - } - - /** - * @dev Returns true if the value is in the set. O(1). - */ - function contains(AddressSet storage set, address value) internal view returns (bool) { - return _contains(set._inner, bytes32(uint256(uint160(value)))); - } - - /** - * @dev Returns the number of values in the set. O(1). - */ - function length(AddressSet storage set) internal view returns (uint256) { - return _length(set._inner); - } - - /** - * @dev Returns the value stored at position `index` in the set. O(1). - * - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(AddressSet storage set, uint256 index) internal view returns (address) { - return address(uint160(uint256(_at(set._inner, index)))); - } - - /** - * @dev Return the entire set in an array - * - * 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 values(AddressSet storage set) internal view returns (address[] memory) { - bytes32[] memory store = _values(set._inner); - address[] memory result; - - /// @solidity memory-safe-assembly - assembly { - result := store - } - - return result; - } - - // UintSet - - struct UintSet { - Set _inner; - } - - /** - * @dev Add a value to a set. O(1). - * - * Returns true if the value was added to the set, that is if it was not - * already present. - */ - function add(UintSet storage set, uint256 value) internal returns (bool) { - return _add(set._inner, bytes32(value)); - } - - /** - * @dev Removes a value from a set. O(1). - * - * Returns true if the value was removed from the set, that is if it was - * present. - */ - function remove(UintSet storage set, uint256 value) internal returns (bool) { - return _remove(set._inner, bytes32(value)); - } - - /** - * @dev Returns true if the value is in the set. O(1). - */ - function contains(UintSet storage set, uint256 value) internal view returns (bool) { - return _contains(set._inner, bytes32(value)); - } - - /** - * @dev Returns the number of values in the set. O(1). - */ - function length(UintSet storage set) internal view returns (uint256) { - return _length(set._inner); - } - - /** - * @dev Returns the value stored at position `index` in the set. O(1). - * - * Note that there are no guarantees on the ordering of values inside the - * array, and it may change when more values are added or removed. - * - * Requirements: - * - * - `index` must be strictly less than {length}. - */ - function at(UintSet storage set, uint256 index) internal view returns (uint256) { - return uint256(_at(set._inner, index)); - } - - /** - * @dev Return the entire set in an array - * - * 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 values(UintSet storage set) internal view returns (uint256[] memory) { - bytes32[] memory store = _values(set._inner); - uint256[] memory result; - - /// @solidity memory-safe-assembly - assembly { - result := store - } - - return result; - } -} diff --git a/blockchain/contracts/OpenZeppelin/vendor/compound/ICompoundTimelock.sol b/blockchain/contracts/OpenZeppelin/vendor/compound/ICompoundTimelock.sol deleted file mode 100644 index 1b04290..0000000 --- a/blockchain/contracts/OpenZeppelin/vendor/compound/ICompoundTimelock.sol +++ /dev/null @@ -1,86 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.6.0) (vendor/compound/ICompoundTimelock.sol) - -pragma solidity ^0.8.19; - -/** - * https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol[Compound's timelock] interface - */ -interface ICompoundTimelock { - event NewAdmin(address indexed newAdmin); - event NewPendingAdmin(address indexed newPendingAdmin); - event NewDelay(uint256 indexed newDelay); - event CancelTransaction( - bytes32 indexed txHash, - address indexed target, - uint256 value, - string signature, - bytes data, - uint256 eta - ); - event ExecuteTransaction( - bytes32 indexed txHash, - address indexed target, - uint256 value, - string signature, - bytes data, - uint256 eta - ); - event QueueTransaction( - bytes32 indexed txHash, - address indexed target, - uint256 value, - string signature, - bytes data, - uint256 eta - ); - - receive() external payable; - - // solhint-disable-next-line func-name-mixedcase - function GRACE_PERIOD() external view returns (uint256); - - // solhint-disable-next-line func-name-mixedcase - function MINIMUM_DELAY() external view returns (uint256); - - // solhint-disable-next-line func-name-mixedcase - function MAXIMUM_DELAY() external view returns (uint256); - - function admin() external view returns (address); - - function pendingAdmin() external view returns (address); - - function delay() external view returns (uint256); - - function queuedTransactions(bytes32) external view returns (bool); - - function setDelay(uint256) external; - - function acceptAdmin() external; - - function setPendingAdmin(address) external; - - function queueTransaction( - address target, - uint256 value, - string memory signature, - bytes memory data, - uint256 eta - ) external returns (bytes32); - - function cancelTransaction( - address target, - uint256 value, - string memory signature, - bytes memory data, - uint256 eta - ) external; - - function executeTransaction( - address target, - uint256 value, - string memory signature, - bytes memory data, - uint256 eta - ) external payable returns (bytes memory); -} diff --git a/blockchain/governance.old/Governor.sol b/blockchain/governance.old/Governor.sol deleted file mode 100644 index a8654ac..0000000 --- a/blockchain/governance.old/Governor.sol +++ /dev/null @@ -1,771 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.1) (governance/Governor.sol) - -pragma solidity ^0.8.19; - -import "../token/ERC721/IERC721Receiver.sol"; -import "../token/ERC1155/IERC1155Receiver.sol"; -import "../utils/cryptography/ECDSA.sol"; -import "../utils/cryptography/EIP712.sol"; -import "../utils/introspection/ERC165.sol"; -import "../utils/math/SafeCast.sol"; -import "../utils/structs/DoubleEndedQueue.sol"; -import "../utils/Address.sol"; -import "../utils/Context.sol"; -import "./IGovernor.sol"; - -/** - * @dev Core of the governance system, designed to be extended though 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 - * - * _Available since v4.3._ - */ -abstract contract Governor is Context, ERC165, EIP712, IGovernor, IERC721Receiver, IERC1155Receiver { - using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque; - - bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); - bytes32 public constant EXTENDED_BALLOT_TYPEHASH = - keccak256("ExtendedBallot(uint256 proposalId,uint8 support,string reason,bytes params)"); - - // solhint-disable var-name-mixedcase - struct ProposalCore { - // --- start retyped from Timers.BlockNumber at offset 0x00 --- - uint64 voteStart; - address proposer; - bytes4 __gap_unused0; - // --- start retyped from Timers.BlockNumber at offset 0x20 --- - uint64 voteEnd; - bytes24 __gap_unused1; - // --- Remaining fields starting at offset 0x40 --------------- - bool executed; - bool canceled; - } - // solhint-enable var-name-mixedcase - - bytes32 private constant _ALL_PROPOSAL_STATES_BITMAP = bytes32((2 ** (uint8(type(ProposalState).max) + 1)) - 1); - string private _name; - - /// @custom:oz-retyped-from mapping(uint256 => Governor.ProposalCore) - mapping(uint256 => 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 {_beforeExecute}, - // consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. 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() { - 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 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) { - bytes4 governorCancelId = this.cancel.selector ^ this.proposalProposer.selector; - - bytes4 governorParamsId = this.castVoteWithReasonAndParams.selector ^ - this.castVoteWithReasonAndParamsBySig.selector ^ - this.getVotesWithParams.selector; - - // The original interface id in v4.3. - bytes4 governor43Id = type(IGovernor).interfaceId ^ - type(IERC6372).interfaceId ^ - governorCancelId ^ - governorParamsId; - - // An updated interface id in v4.6, with params added. - bytes4 governor46Id = type(IGovernor).interfaceId ^ type(IERC6372).interfaceId ^ governorCancelId; - - // For the updated interface id in v4.9, we use governorCancelId directly. - - return - interfaceId == governor43Id || - interfaceId == governor46Id || - interfaceId == governorCancelId || - interfaceId == type(IERC1155Receiver).interfaceId || - super.supportsInterface(interfaceId); - } - - /** - * @dev See {IGovernor-name}. - */ - function name() public view virtual override returns (string memory) { - return _name; - } - - /** - * @dev See {IGovernor-version}. - */ - function version() public view virtual override 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 override returns (uint256) { - return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash))); - } - - /** - * @dev See {IGovernor-state}. - */ - function state(uint256 proposalId) public view virtual override returns (ProposalState) { - ProposalCore storage proposal = _proposals[proposalId]; - - if (proposal.executed) { - return ProposalState.Executed; - } - - if (proposal.canceled) { - 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; - } - - if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) { - return ProposalState.Succeeded; - } else { - return ProposalState.Defeated; - } - } - - /** - * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_. - */ - function proposalThreshold() public view virtual returns (uint256) { - return 0; - } - - /** - * @dev See {IGovernor-proposalSnapshot}. - */ - function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) { - return _proposals[proposalId].voteStart; - } - - /** - * @dev See {IGovernor-proposalDeadline}. - */ - function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) { - return _proposals[proposalId].voteEnd; - } - - /** - * @dev Returns the account that created a given proposal. - */ - function proposalProposer(uint256 proposalId) public view virtual override returns (address) { - return _proposals[proposalId].proposer; - } - - /** - * @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 override returns (uint256) { - address proposer = _msgSender(); - require(_isValidDescriptionForProposer(proposer, description), "Governor: proposer restricted"); - - uint256 currentTimepoint = clock(); - - // Avoid stack too deep - { - uint256 proposerVotes = getVotes(proposer, currentTimepoint - 1); - uint256 votesThreshold = proposalThreshold(); - if (proposerVotes < votesThreshold) { - revert GovernorInsufficientProposerVotes(proposer, proposerVotes, votesThreshold); - } - } - - uint256 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 = currentTimepoint + votingDelay(); - uint256 deadline = snapshot + votingPeriod(); - - _proposals[proposalId] = ProposalCore({ - proposer: proposer, - voteStart: SafeCast.toUint64(snapshot), - voteEnd: SafeCast.toUint64(deadline), - executed: false, - canceled: false, - __gap_unused0: 0, - __gap_unused1: 0 - }); - - emit ProposalCreated( - proposalId, - proposer, - targets, - values, - new string[](targets.length), - calldatas, - snapshot, - deadline, - description - ); - - return proposalId; - } - - /** - * @dev See {IGovernor-execute}. - */ - function execute( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public payable virtual override returns (uint256) { - uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); - - ProposalState currentState = state(proposalId); - if (currentState != ProposalState.Succeeded && currentState != ProposalState.Queued) { - revert GovernorUnexpectedProposalState( - proposalId, - currentState, - _encodeStateBitmap(ProposalState.Succeeded) | _encodeStateBitmap(ProposalState.Queued) - ); - } - _proposals[proposalId].executed = true; - - emit ProposalExecuted(proposalId); - - _beforeExecute(proposalId, targets, values, calldatas, descriptionHash); - _execute(proposalId, targets, values, calldatas, descriptionHash); - _afterExecute(proposalId, targets, values, calldatas, descriptionHash); - - return proposalId; - } - - /** - * @dev See {IGovernor-cancel}. - */ - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public virtual override returns (uint256) { - uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); - ProposalState currentState = state(proposalId); - if (currentState != ProposalState.Pending) { - revert GovernorUnexpectedProposalState(proposalId, currentState, _encodeStateBitmap(ProposalState.Pending)); - } - if (_msgSender() != proposalProposer(proposalId)) { - revert GovernorOnlyProposer(_msgSender()); - } - return _cancel(targets, values, calldatas, descriptionHash); - } - - /** - * @dev Internal execution mechanism. Can be overridden to implement different execution mechanism - */ - function _execute( - 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 Hook before execution is triggered. - */ - function _beforeExecute( - uint256 /* proposalId */, - address[] memory targets, - uint256[] memory /* values */, - bytes[] memory calldatas, - bytes32 /*descriptionHash*/ - ) internal virtual { - if (_executor() != address(this)) { - for (uint256 i = 0; i < targets.length; ++i) { - if (targets[i] == address(this)) { - _governanceCall.pushBack(keccak256(calldatas[i])); - } - } - } - } - - /** - * @dev Hook after execution is triggered. - */ - function _afterExecute( - uint256 /* proposalId */, - address[] memory /* targets */, - uint256[] memory /* values */, - bytes[] memory /* calldatas */, - bytes32 /*descriptionHash*/ - ) internal virtual { - if (_executor() != address(this)) { - if (!_governanceCall.empty()) { - _governanceCall.clear(); - } - } - } - - /** - * @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as - * canceled to allow distinguishing it from executed proposals. - * - * 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); - - ProposalState currentState = state(proposalId); - - bytes32 forbiddenStates = _encodeStateBitmap(ProposalState.Canceled) | - _encodeStateBitmap(ProposalState.Expired) | - _encodeStateBitmap(ProposalState.Executed); - if (forbiddenStates & _encodeStateBitmap(currentState) != 0) { - revert GovernorUnexpectedProposalState( - proposalId, - currentState, - _ALL_PROPOSAL_STATES_BITMAP ^ forbiddenStates - ); - } - _proposals[proposalId].canceled = true; - - emit ProposalCanceled(proposalId); - - return proposalId; - } - - /** - * @dev See {IGovernor-getVotes}. - */ - function getVotes(address account, uint256 timepoint) public view virtual override returns (uint256) { - return _getVotes(account, timepoint, _defaultParams()); - } - - /** - * @dev See {IGovernor-getVotesWithParams}. - */ - function getVotesWithParams( - address account, - uint256 timepoint, - bytes memory params - ) public view virtual override returns (uint256) { - return _getVotes(account, timepoint, params); - } - - /** - * @dev See {IGovernor-castVote}. - */ - function castVote(uint256 proposalId, uint8 support) public virtual override 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 override 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 override returns (uint256) { - address voter = _msgSender(); - return _castVote(proposalId, voter, support, reason, params); - } - - /** - * @dev See {IGovernor-castVoteBySig}. - */ - function castVoteBySig( - uint256 proposalId, - uint8 support, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual override returns (uint256) { - address voter = ECDSA.recover( - _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))), - v, - r, - s - ); - return _castVote(proposalId, voter, support, ""); - } - - /** - * @dev See {IGovernor-castVoteWithReasonAndParamsBySig}. - */ - function castVoteWithReasonAndParamsBySig( - uint256 proposalId, - uint8 support, - string calldata reason, - bytes memory params, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual override returns (uint256) { - address voter = ECDSA.recover( - _hashTypedDataV4( - keccak256( - abi.encode( - EXTENDED_BALLOT_TYPEHASH, - proposalId, - support, - keccak256(bytes(reason)), - keccak256(params) - ) - ) - ), - v, - r, - s - ); - - 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) { - ProposalCore storage proposal = _proposals[proposalId]; - ProposalState currentState = state(proposalId); - if (currentState != ProposalState.Active) { - revert GovernorUnexpectedProposalState(proposalId, currentState, _encodeStateBitmap(ProposalState.Active)); - } - - uint256 weight = _getVotes(account, proposal.voteStart, 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 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); - } - } - } -} diff --git a/blockchain/governance.old/IGovernor.sol b/blockchain/governance.old/IGovernor.sol deleted file mode 100644 index 5b51f08..0000000 --- a/blockchain/governance.old/IGovernor.sol +++ /dev/null @@ -1,370 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/IGovernor.sol) - -pragma solidity ^0.8.19; - -import "../interfaces/IERC165.sol"; -import "../interfaces/IERC6372.sol"; - -/** - * @dev Interface of the {Governor} core. - * - * _Available since v4.3._ - */ -abstract contract 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 operate on a proposal. - */ - error GovernorInsufficientProposerVotes(address proposer, uint256 votes, uint256 threshold); - - /** - * @dev The vote type used is not valid for the corresponding counting module. - */ - error GovernorInvalidVoteType(); - - /** - * @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 canceled. - */ - event ProposalCanceled(uint256 proposalId); - - /** - * @dev Emitted when a proposal is executed. - */ - event ProposalExecuted(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 ERC712 domain separator). - */ - function name() public view virtual returns (string memory); - - /** - * @notice module:core - * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" - */ - function version() public view virtual returns (string memory); - - /** - * @notice module:core - * @dev See {IERC6372} - */ - function clock() public view virtual returns (uint48); - - /** - * @notice module:core - * @dev See EIP-6372. - */ - // solhint-disable-next-line func-name-mixedcase - function CLOCK_MODE() public view virtual 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() public view virtual 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 - ) public pure virtual returns (uint256); - - /** - * @notice module:core - * @dev Current state of a proposal, following Compound's convention - */ - function state(uint256 proposalId) public view virtual returns (ProposalState); - - /** - * @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) public view virtual 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) public view virtual returns (uint256); - - /** - * @notice module:core - * @dev The account that created a proposal. - */ - function proposalProposer(uint256 proposalId) public view virtual returns (address); - - /** - * @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 EIP-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. - */ - function votingDelay() public view virtual 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 EIP-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. - */ - function votingPeriod() public view virtual 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) public view virtual 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) public view virtual 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 - ) public view virtual returns (uint256); - - /** - * @notice module:voting - * @dev Returns whether `account` has cast a vote on `proposalId`. - */ - function hasVoted(uint256 proposalId, address account) public view virtual 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. - */ - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public virtual 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. - * - * Emits a {ProposalExecuted} event. - * - * Note: some module 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 - ) public payable virtual 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 - ) public virtual returns (uint256 proposalId); - - /** - * @dev Cast a vote - * - * Emits a {VoteCast} event. - */ - function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); - - /** - * @dev Cast a vote with a reason - * - * Emits a {VoteCast} event. - */ - function castVoteWithReason( - uint256 proposalId, - uint8 support, - string calldata reason - ) public virtual 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 - ) public virtual returns (uint256 balance); - - /** - * @dev Cast a vote using the user's cryptographic signature. - * - * Emits a {VoteCast} event. - */ - function castVoteBySig( - uint256 proposalId, - uint8 support, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual returns (uint256 balance); - - /** - * @dev Cast a vote with a reason and additional encoded parameters using the user's cryptographic signature. - * - * Emits a {VoteCast} or {VoteCastWithParams} event depending on the length of params. - */ - function castVoteWithReasonAndParamsBySig( - uint256 proposalId, - uint8 support, - string calldata reason, - bytes memory params, - uint8 v, - bytes32 r, - bytes32 s - ) public virtual returns (uint256 balance); -} diff --git a/blockchain/governance.old/README.adoc b/blockchain/governance.old/README.adoc deleted file mode 100644 index 00edfe2..0000000 --- a/blockchain/governance.old/README.adoc +++ /dev/null @@ -1,166 +0,0 @@ -= 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. - -* {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. - -* {GovernorCompatibilityBravo}: Extends the interface to be fully `GovernorBravo`-compatible. Note that events are compatible regardless of whether this extension is included or not. - -* {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: - -* <>: Delay (in EIP-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. -* <>: Delay (in EIP-6372 clock) since the proposal starts until voting ends. -* <>: Quorum required for a proposal to be successful. This function includes a `timepoint` argument (see EIP-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 - -{{GovernorTimelockControl}} - -{{GovernorTimelockCompound}} - -{{GovernorSettings}} - -{{GovernorPreventLateQuorum}} - -{{GovernorCompatibilityBravo}} - -== 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. -** *Pending:* An operation that has been scheduled, before the timer expires. -** *Ready:* An operation that has been scheduled, after the timer expires. -** *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. diff --git a/blockchain/governance.old/TimelockController.sol b/blockchain/governance.old/TimelockController.sol deleted file mode 100644 index a25cd7b..0000000 --- a/blockchain/governance.old/TimelockController.sol +++ /dev/null @@ -1,435 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/TimelockController.sol) - -pragma solidity ^0.8.19; - -import "../access/AccessControl.sol"; -import "../token/ERC721/utils/ERC721Holder.sol"; -import "../token/ERC1155/utils/ERC1155Holder.sol"; -import "../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. - * - * _Available since v3.3._ - */ -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 => uint256) private _timestamps; - uint256 private _minDelay; - - enum OperationState { - Unset, - Pending, - 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. - */ - error TimelockUnexpectedOperationState(bytes32 operationId, OperationState expected); - - /** - * @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 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, ERC1155Receiver) returns (bool) { - return super.supportsInterface(interfaceId); - } - - /** - * @dev Returns whether an id correspond to a registered operation. This - * includes both Pending, Ready and Done operations. - */ - function isOperation(bytes32 id) public view virtual returns (bool) { - return getTimestamp(id) > 0; - } - - /** - * @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready". - */ - function isOperationPending(bytes32 id) public view virtual returns (bool) { - return getTimestamp(id) > _DONE_TIMESTAMP; - } - - /** - * @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending". - */ - function isOperationReady(bytes32 id) public view virtual returns (bool) { - uint256 timestamp = getTimestamp(id); - return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; - } - - /** - * @dev Returns whether an operation is done or not. - */ - function isOperationDone(bytes32 id) public view virtual returns (bool) { - return getTimestamp(id) == _DONE_TIMESTAMP; - } - - /** - * @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 the minimum delay 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, 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, OperationState.Pending); - } - 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, 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, 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 { - if (msg.sender != address(this)) { - revert TimelockUnauthorizedCaller(msg.sender); - } - emit MinDelayChange(_minDelay, newDelay); - _minDelay = newDelay; - } -} diff --git a/blockchain/governance.old/compatibility/GovernorCompatibilityBravo.sol b/blockchain/governance.old/compatibility/GovernorCompatibilityBravo.sol deleted file mode 100644 index 8d6d9cc..0000000 --- a/blockchain/governance.old/compatibility/GovernorCompatibilityBravo.sol +++ /dev/null @@ -1,335 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/compatibility/GovernorCompatibilityBravo.sol) - -pragma solidity ^0.8.19; - -import "../../utils/math/SafeCast.sol"; -import "../extensions/IGovernorTimelock.sol"; -import "../Governor.sol"; -import "./IGovernorCompatibilityBravo.sol"; - -/** - * @dev Compatibility layer that implements GovernorBravo compatibility on top of {Governor}. - * - * This compatibility layer includes a voting system and requires a {IGovernorTimelock} compatible module to be added - * through inheritance. It does not include token bindings, nor does it include any variable upgrade patterns. - * - * NOTE: When using this module, you may need to enable the Solidity optimizer to avoid hitting the contract size limit. - * - * _Available since v4.3._ - */ -abstract contract GovernorCompatibilityBravo is IGovernorTimelock, IGovernorCompatibilityBravo, Governor { - enum VoteType { - Against, - For, - Abstain - } - - struct ProposalDetails { - address[] targets; - uint256[] values; - string[] signatures; - bytes[] calldatas; - uint256 forVotes; - uint256 againstVotes; - uint256 abstainVotes; - mapping(address => Receipt) receipts; - bytes32 descriptionHash; - } - - mapping(uint256 => ProposalDetails) private _proposalDetails; - - // solhint-disable-next-line func-name-mixedcase - function COUNTING_MODE() public pure virtual override returns (string memory) { - return "support=bravo&quorum=bravo"; - } - - // ============================================== Proposal lifecycle ============================================== - /** - * @dev See {IGovernor-propose}. - */ - function propose( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - string memory description - ) public virtual override(IGovernor, Governor) returns (uint256) { - // Stores the proposal details (if not already present) and executes the propose logic from the core. - _storeProposal(targets, values, new string[](calldatas.length), calldatas, description); - return super.propose(targets, values, calldatas, description); - } - - /** - * @dev See {IGovernorCompatibilityBravo-propose}. - */ - function propose( - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas, - string memory description - ) public virtual override returns (uint256) { - if (signatures.length != calldatas.length) { - revert GovernorInvalidSignaturesLength(signatures.length, calldatas.length); - } - // Stores the full proposal and fallback to the public (possibly overridden) propose. The fallback is done - // after the full proposal is stored, so the store operation included in the fallback will be skipped. Here we - // call `propose` and not `super.propose` to make sure if a child contract override `propose`, whatever code - // is added there is also executed when calling this alternative interface. - _storeProposal(targets, values, signatures, calldatas, description); - return propose(targets, values, _encodeCalldata(signatures, calldatas), description); - } - - /** - * @dev See {IGovernorCompatibilityBravo-queue}. - */ - function queue(uint256 proposalId) public virtual override { - ( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) = _getProposalParameters(proposalId); - - queue(targets, values, calldatas, descriptionHash); - } - - /** - * @dev See {IGovernorCompatibilityBravo-execute}. - */ - function execute(uint256 proposalId) public payable virtual override { - ( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) = _getProposalParameters(proposalId); - - execute(targets, values, calldatas, descriptionHash); - } - - /** - * @dev Cancel a proposal with GovernorBravo logic. - */ - function cancel(uint256 proposalId) public virtual override { - ( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) = _getProposalParameters(proposalId); - - cancel(targets, values, calldatas, descriptionHash); - } - - /** - * @dev Cancel a proposal with GovernorBravo logic. At any moment a proposal can be cancelled, either by the - * proposer, or by third parties if the proposer's voting power has dropped below the proposal threshold. - */ - function cancel( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public virtual override(IGovernor, Governor) returns (uint256) { - uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); - address proposer = proposalProposer(proposalId); - - uint256 proposerVotes = getVotes(proposer, clock() - 1); - uint256 votesThreshold = proposalThreshold(); - if (_msgSender() != proposer && proposerVotes >= votesThreshold) { - revert GovernorInsufficientProposerVotes(proposer, proposerVotes, votesThreshold); - } - - return _cancel(targets, values, calldatas, descriptionHash); - } - - /** - * @dev Encodes calldatas with optional function signature. - */ - function _encodeCalldata( - string[] memory signatures, - bytes[] memory calldatas - ) private pure returns (bytes[] memory) { - bytes[] memory fullcalldatas = new bytes[](calldatas.length); - for (uint256 i = 0; i < fullcalldatas.length; ++i) { - fullcalldatas[i] = bytes(signatures[i]).length == 0 - ? calldatas[i] - : bytes.concat(abi.encodeWithSignature(signatures[i]), calldatas[i]); - } - - return fullcalldatas; - } - - /** - * @dev Retrieve proposal parameters by id, with fully encoded calldatas. - */ - function _getProposalParameters( - uint256 proposalId - ) - private - view - returns (address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) - { - ProposalDetails storage details = _proposalDetails[proposalId]; - return ( - details.targets, - details.values, - _encodeCalldata(details.signatures, details.calldatas), - details.descriptionHash - ); - } - - /** - * @dev Store proposal metadata (if not already present) for later lookup. - */ - function _storeProposal( - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas, - string memory description - ) private { - bytes32 descriptionHash = keccak256(bytes(description)); - uint256 proposalId = hashProposal(targets, values, _encodeCalldata(signatures, calldatas), descriptionHash); - - ProposalDetails storage details = _proposalDetails[proposalId]; - if (details.descriptionHash == bytes32(0)) { - details.targets = targets; - details.values = values; - details.signatures = signatures; - details.calldatas = calldatas; - details.descriptionHash = descriptionHash; - } - } - - // ==================================================== Views ===================================================== - /** - * @dev See {IGovernorCompatibilityBravo-proposals}. - */ - function proposals( - uint256 proposalId - ) - public - view - virtual - override - returns ( - uint256 id, - address proposer, - uint256 eta, - uint256 startBlock, - uint256 endBlock, - uint256 forVotes, - uint256 againstVotes, - uint256 abstainVotes, - bool canceled, - bool executed - ) - { - id = proposalId; - proposer = proposalProposer(proposalId); - eta = proposalEta(proposalId); - startBlock = proposalSnapshot(proposalId); - endBlock = proposalDeadline(proposalId); - - ProposalDetails storage details = _proposalDetails[proposalId]; - forVotes = details.forVotes; - againstVotes = details.againstVotes; - abstainVotes = details.abstainVotes; - - ProposalState currentState = state(proposalId); - canceled = currentState == ProposalState.Canceled; - executed = currentState == ProposalState.Executed; - } - - /** - * @dev See {IGovernorCompatibilityBravo-getActions}. - */ - function getActions( - uint256 proposalId - ) - public - view - virtual - override - returns ( - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas - ) - { - ProposalDetails storage details = _proposalDetails[proposalId]; - return (details.targets, details.values, details.signatures, details.calldatas); - } - - /** - * @dev See {IGovernorCompatibilityBravo-getReceipt}. - */ - function getReceipt(uint256 proposalId, address voter) public view virtual override returns (Receipt memory) { - return _proposalDetails[proposalId].receipts[voter]; - } - - /** - * @dev See {IGovernorCompatibilityBravo-quorumVotes}. - */ - function quorumVotes() public view virtual override returns (uint256) { - return quorum(clock() - 1); - } - - // ==================================================== Voting ==================================================== - /** - * @dev See {IGovernor-hasVoted}. - */ - function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) { - return _proposalDetails[proposalId].receipts[account].hasVoted; - } - - /** - * @dev See {Governor-_quorumReached}. In this module, only forVotes count toward the quorum. - */ - function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) { - ProposalDetails storage details = _proposalDetails[proposalId]; - return quorum(proposalSnapshot(proposalId)) <= details.forVotes; - } - - /** - * @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) { - ProposalDetails storage details = _proposalDetails[proposalId]; - return details.forVotes > details.againstVotes; - } - - /** - * @dev See {Governor-_countVote}. In this module, the support follows Governor Bravo. - */ - function _countVote( - uint256 proposalId, - address account, - uint8 support, - uint256 weight, - bytes memory // params - ) internal virtual override { - ProposalDetails storage details = _proposalDetails[proposalId]; - Receipt storage receipt = details.receipts[account]; - - if (receipt.hasVoted) { - revert GovernorAlreadyCastVote(account); - } - receipt.hasVoted = true; - receipt.support = support; - receipt.votes = SafeCast.toUint96(weight); - - if (support == uint8(VoteType.Against)) { - details.againstVotes += weight; - } else if (support == uint8(VoteType.For)) { - details.forVotes += weight; - } else if (support == uint8(VoteType.Abstain)) { - details.abstainVotes += weight; - } else { - revert GovernorInvalidVoteType(); - } - } -} diff --git a/blockchain/governance.old/compatibility/IGovernorCompatibilityBravo.sol b/blockchain/governance.old/compatibility/IGovernorCompatibilityBravo.sol deleted file mode 100644 index 197936a..0000000 --- a/blockchain/governance.old/compatibility/IGovernorCompatibilityBravo.sol +++ /dev/null @@ -1,123 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/compatibility/IGovernorCompatibilityBravo.sol) - -pragma solidity ^0.8.19; - -import "../IGovernor.sol"; - -/** - * @dev Interface extension that adds missing functions to the {Governor} core to provide `GovernorBravo` compatibility. - * - * _Available since v4.3._ - */ -abstract contract IGovernorCompatibilityBravo is IGovernor { - /** - * @dev Mismatch between the parameters length for a proposal call. - */ - error GovernorInvalidSignaturesLength(uint256 signatures, uint256 calldatas); - - /** - * @dev Proposal structure from Compound Governor Bravo. Not actually used by the compatibility layer, as - * {{proposal}} returns a very different structure. - */ - struct Proposal { - uint256 id; - address proposer; - uint256 eta; - address[] targets; - uint256[] values; - string[] signatures; - bytes[] calldatas; - uint256 startBlock; - uint256 endBlock; - uint256 forVotes; - uint256 againstVotes; - uint256 abstainVotes; - bool canceled; - bool executed; - mapping(address => Receipt) receipts; - } - - /** - * @dev Receipt structure from Compound Governor Bravo - */ - struct Receipt { - bool hasVoted; - uint8 support; - uint96 votes; - } - - /** - * @dev Part of the Governor Bravo's interface. - */ - function quorumVotes() public view virtual returns (uint256); - - /** - * @dev Part of the Governor Bravo's interface: _"The official record of all proposals ever proposed"_. - */ - function proposals( - uint256 - ) - public - view - virtual - returns ( - uint256 id, - address proposer, - uint256 eta, - uint256 startBlock, - uint256 endBlock, - uint256 forVotes, - uint256 againstVotes, - uint256 abstainVotes, - bool canceled, - bool executed - ); - - /** - * @dev Part of the Governor Bravo's interface: _"Function used to propose a new proposal"_. - */ - function propose( - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas, - string memory description - ) public virtual returns (uint256); - - /** - * @dev Part of the Governor Bravo's interface: _"Queues a proposal of state succeeded"_. - */ - function queue(uint256 proposalId) public virtual; - - /** - * @dev Part of the Governor Bravo's interface: _"Executes a queued proposal if eta has passed"_. - */ - function execute(uint256 proposalId) public payable virtual; - - /** - * @dev Cancels a proposal only if the sender is the proposer or the proposer delegates' voting power dropped below the proposal threshold. - */ - function cancel(uint256 proposalId) public virtual; - - /** - * @dev Part of the Governor Bravo's interface: _"Gets actions of a proposal"_. - */ - function getActions( - uint256 proposalId - ) - public - view - virtual - returns ( - address[] memory targets, - uint256[] memory values, - string[] memory signatures, - bytes[] memory calldatas - ); - - /** - * @dev Part of the Governor Bravo's interface: _"Gets the receipt for a voter on a given proposal"_. - */ - function getReceipt(uint256 proposalId, address voter) public view virtual returns (Receipt memory); -} diff --git a/blockchain/governance.old/extensions/GovernorCountingSimple.sol b/blockchain/governance.old/extensions/GovernorCountingSimple.sol deleted file mode 100644 index 315f4ad..0000000 --- a/blockchain/governance.old/extensions/GovernorCountingSimple.sol +++ /dev/null @@ -1,102 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorCountingSimple.sol) - -pragma solidity ^0.8.19; - -import "../Governor.sol"; - -/** - * @dev Extension of {Governor} for simple, 3 options, vote counting. - * - * _Available since v4.3._ - */ -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 => bool) hasVoted; - } - - mapping(uint256 => 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(); - } - } -} diff --git a/blockchain/governance.old/extensions/GovernorPreventLateQuorum.sol b/blockchain/governance.old/extensions/GovernorPreventLateQuorum.sol deleted file mode 100644 index abb8112..0000000 --- a/blockchain/governance.old/extensions/GovernorPreventLateQuorum.sol +++ /dev/null @@ -1,105 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorPreventLateQuorum.sol) - -pragma solidity ^0.8.19; - -import "../Governor.sol"; -import "../../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. - * - * _Available since v4.5._ - */ -abstract contract GovernorPreventLateQuorum is Governor { - uint64 private _voteExtension; - - /// @custom:oz-retyped-from mapping(uint256 => Timers.BlockNumber) - mapping(uint256 => uint64) 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(uint64 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)) { - uint64 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 (uint64) { - 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(uint64 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(uint64 newVoteExtension) internal virtual { - emit LateQuorumVoteExtensionSet(_voteExtension, newVoteExtension); - _voteExtension = newVoteExtension; - } -} diff --git a/blockchain/governance.old/extensions/GovernorSettings.sol b/blockchain/governance.old/extensions/GovernorSettings.sol deleted file mode 100644 index 64e081c..0000000 --- a/blockchain/governance.old/extensions/GovernorSettings.sol +++ /dev/null @@ -1,112 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorSettings.sol) - -pragma solidity ^0.8.19; - -import "../Governor.sol"; - -/** - * @dev Extension of {Governor} for settings updatable through governance. - * - * _Available since v4.4._ - */ -abstract contract GovernorSettings is Governor { - uint256 private _votingDelay; - uint256 private _votingPeriod; - uint256 private _proposalThreshold; - - event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay); - event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod); - event ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold); - - /** - * @dev Initialize the governance parameters. - */ - constructor(uint256 initialVotingDelay, uint256 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(uint256 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(uint256 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(uint256 newVotingDelay) internal virtual { - emit VotingDelaySet(_votingDelay, newVotingDelay); - _votingDelay = newVotingDelay; - } - - /** - * @dev Internal setter for the voting period. - * - * Emits a {VotingPeriodSet} event. - */ - function _setVotingPeriod(uint256 newVotingPeriod) internal virtual { - // voting period must be at least one block long - 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; - } -} diff --git a/blockchain/governance.old/extensions/GovernorTimelockCompound.sol b/blockchain/governance.old/extensions/GovernorTimelockCompound.sol deleted file mode 100644 index 21439b4..0000000 --- a/blockchain/governance.old/extensions/GovernorTimelockCompound.sol +++ /dev/null @@ -1,198 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorTimelockCompound.sol) - -pragma solidity ^0.8.19; - -import "./IGovernorTimelock.sol"; -import "../Governor.sol"; -import "../../utils/math/SafeCast.sol"; -import "../../vendor/compound/ICompoundTimelock.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. - * - * _Available since v4.3._ - */ -abstract contract GovernorTimelockCompound is IGovernorTimelock, Governor { - ICompoundTimelock private _timelock; - - /// @custom:oz-retyped-from mapping(uint256 => GovernorTimelockCompound.ProposalTimelock) - mapping(uint256 => uint64) private _proposalTimelocks; - - /** - * @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 See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) { - return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @dev Overridden version of the {Governor-state} function with added support for the `Queued` and `Expired` state. - */ - function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) { - ProposalState currentState = super.state(proposalId); - - if (currentState != ProposalState.Succeeded) { - return currentState; - } - - uint256 eta = proposalEta(proposalId); - if (eta == 0) { - return currentState; - } else if (block.timestamp >= eta + _timelock.GRACE_PERIOD()) { - return ProposalState.Expired; - } else { - return ProposalState.Queued; - } - } - - /** - * @dev Public accessor to check the address of the timelock - */ - function timelock() public view virtual override returns (address) { - return address(_timelock); - } - - /** - * @dev Public accessor to check the eta of a queued proposal - */ - function proposalEta(uint256 proposalId) public view virtual override returns (uint256) { - return _proposalTimelocks[proposalId]; - } - - /** - * @dev Function to queue a proposal to the timelock. - */ - function queue( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public virtual override returns (uint256) { - uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); - - ProposalState currentState = state(proposalId); - if (currentState != ProposalState.Succeeded) { - revert GovernorUnexpectedProposalState( - proposalId, - currentState, - _encodeStateBitmap(ProposalState.Succeeded) - ); - } - - uint256 eta = block.timestamp + _timelock.delay(); - _proposalTimelocks[proposalId] = SafeCast.toUint64(eta); - - for (uint256 i = 0; i < targets.length; ++i) { - if (_timelock.queuedTransactions(keccak256(abi.encode(targets[i], values[i], "", calldatas[i], eta)))) { - revert GovernorAlreadyQueuedProposal(proposalId); - } - _timelock.queueTransaction(targets[i], values[i], "", calldatas[i], eta); - } - - emit ProposalQueued(proposalId, eta); - - return proposalId; - } - - /** - * @dev Overridden execute function that run the already queued proposal through the timelock. - */ - function _execute( - uint256 proposalId, - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 /*descriptionHash*/ - ) internal virtual override { - uint256 eta = proposalEta(proposalId); - if (eta == 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], eta); - } - } - - /** - * @dev Overridden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as 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 eta = proposalEta(proposalId); - if (eta > 0) { - // update state first - delete _proposalTimelocks[proposalId]; - // do external call later - for (uint256 i = 0; i < targets.length; ++i) { - _timelock.cancelTransaction(targets[i], values[i], "", calldatas[i], eta); - } - } - - 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; - } -} diff --git a/blockchain/governance.old/extensions/GovernorTimelockControl.sol b/blockchain/governance.old/extensions/GovernorTimelockControl.sol deleted file mode 100644 index fadbcc7..0000000 --- a/blockchain/governance.old/extensions/GovernorTimelockControl.sol +++ /dev/null @@ -1,181 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorTimelockControl.sol) - -pragma solidity ^0.8.19; - -import "./IGovernorTimelock.sol"; -import "../Governor.sol"; -import "../TimelockController.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) 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. - * - * WARNING: Setting up the TimelockController to have additional proposers besides the governor is very risky, as it - * grants them powers that they must be trusted or known not to use: 1) {onlyGovernance} functions like {relay} are - * available to them through the timelock, and 2) approved governance proposals can be blocked by them, effectively - * executing a Denial of Service attack. This risk will be mitigated in a future release. - * - * _Available since v4.3._ - */ -abstract contract GovernorTimelockControl is IGovernorTimelock, Governor { - TimelockController private _timelock; - mapping(uint256 => 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 See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) { - return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId); - } - - /** - * @dev Overridden version of the {Governor-state} function with added support for the `Queued` state. - */ - function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) { - ProposalState currentState = super.state(proposalId); - - if (currentState != ProposalState.Succeeded) { - return currentState; - } - - // core tracks execution, so we just have to check if successful proposal have been queued. - bytes32 queueid = _timelockIds[proposalId]; - if (queueid == bytes32(0)) { - return currentState; - } else 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 override returns (address) { - return address(_timelock); - } - - /** - * @dev Public accessor to check the eta of a queued proposal - */ - function proposalEta(uint256 proposalId) public view virtual override returns (uint256) { - uint256 eta = _timelock.getTimestamp(_timelockIds[proposalId]); - return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value - } - - /** - * @dev Function to queue a proposal to the timelock. - */ - function queue( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public virtual override returns (uint256) { - uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); - - ProposalState currentState = state(proposalId); - if (currentState != ProposalState.Succeeded) { - revert GovernorUnexpectedProposalState( - proposalId, - currentState, - _encodeStateBitmap(ProposalState.Succeeded) - ); - } - - uint256 delay = _timelock.getMinDelay(); - _timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, descriptionHash); - _timelock.scheduleBatch(targets, values, calldatas, 0, descriptionHash, delay); - - emit ProposalQueued(proposalId, block.timestamp + delay); - - return proposalId; - } - - /** - * @dev Overridden execute function that run the already queued proposal through the timelock. - */ - function _execute( - 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, descriptionHash); - // cleanup for refund - delete _timelockIds[proposalId]; - } - - /** - * @dev Overridden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as 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; - } -} diff --git a/blockchain/governance.old/extensions/GovernorVotes.sol b/blockchain/governance.old/extensions/GovernorVotes.sol deleted file mode 100644 index 5d8318f..0000000 --- a/blockchain/governance.old/extensions/GovernorVotes.sol +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorVotes.sol) - -pragma solidity ^0.8.19; - -import "../Governor.sol"; -import "../../interfaces/IERC5805.sol"; - -/** - * @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token, or since v4.5 an {ERC721Votes} token. - * - * _Available since v4.3._ - */ -abstract contract GovernorVotes is Governor { - IERC5805 public immutable token; - - constructor(IVotes tokenAddress) { - token = IERC5805(address(tokenAddress)); - } - - /** - * @dev Clock (as specified in EIP-6372) is set to match the token's clock. Fallback to block numbers if the token - * does not implement EIP-6372. - */ - function clock() public view virtual override returns (uint48) { - try token.clock() returns (uint48 timepoint) { - return timepoint; - } catch { - return SafeCast.toUint48(block.number); - } - } - - /** - * @dev Machine-readable description of the clock as specified in EIP-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); - } -} diff --git a/blockchain/governance.old/extensions/GovernorVotesQuorumFraction.sol b/blockchain/governance.old/extensions/GovernorVotesQuorumFraction.sol deleted file mode 100644 index 0094fec..0000000 --- a/blockchain/governance.old/extensions/GovernorVotesQuorumFraction.sol +++ /dev/null @@ -1,112 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorVotesQuorumFraction.sol) - -pragma solidity ^0.8.19; - -import "./GovernorVotes.sol"; -import "../../utils/math/SafeCast.sol"; -import "../../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. - * - * _Available since v4.3._ - */ -abstract contract GovernorVotesQuorumFraction is GovernorVotes { - using Checkpoints for Checkpoints.Trace224; - - /// @custom:oz-retyped-from Checkpoints.History - Checkpoints.Trace224 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) { - // If history is empty, fallback to old storage - uint256 length = _quorumNumeratorHistory._checkpoints.length; - - // Optimistic search, check the latest checkpoint - Checkpoints.Checkpoint224 memory latest = _quorumNumeratorHistory._checkpoints[length - 1]; - if (latest._key <= timepoint) { - return latest._value; - } - - // Otherwise, do the binary search - return _quorumNumeratorHistory.upperLookupRecent(SafeCast.toUint32(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(SafeCast.toUint32(clock()), SafeCast.toUint224(newQuorumNumerator)); - - emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); - } -} diff --git a/blockchain/governance.old/extensions/IGovernorTimelock.sol b/blockchain/governance.old/extensions/IGovernorTimelock.sol deleted file mode 100644 index c514294..0000000 --- a/blockchain/governance.old/extensions/IGovernorTimelock.sol +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.4.1 (governance/extensions/IGovernorTimelock.sol) - -pragma solidity ^0.8.19; - -import "../IGovernor.sol"; - -/** - * @dev Extension of the {IGovernor} for timelock supporting modules. - * - * _Available since v4.3._ - */ -abstract contract IGovernorTimelock is IGovernor { - /** - * @dev The proposal hasn't been queued yet. - */ - error GovernorNotQueuedProposal(uint256 proposalId); - - /** - * @dev The proposal has already been queued. - */ - error GovernorAlreadyQueuedProposal(uint256 proposalId); - - event ProposalQueued(uint256 proposalId, uint256 eta); - - function timelock() public view virtual returns (address); - - function proposalEta(uint256 proposalId) public view virtual returns (uint256); - - function queue( - address[] memory targets, - uint256[] memory values, - bytes[] memory calldatas, - bytes32 descriptionHash - ) public virtual returns (uint256 proposalId); -} diff --git a/blockchain/governance.old/utils/IVotes.sol b/blockchain/governance.old/utils/IVotes.sol deleted file mode 100644 index a8a2085..0000000 --- a/blockchain/governance.old/utils/IVotes.sol +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/utils/IVotes.sol) -pragma solidity ^0.8.19; - -/** - * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. - * - * _Available since v4.5._ - */ -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 votes. - */ - event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); - - /** - * @dev Returns the current amount of votes that `account` has. - */ - function getVotes(address account) external view returns (uint256); - - /** - * @dev Returns the amount of votes that `account` had at 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; -} diff --git a/blockchain/governance.old/utils/Votes.sol b/blockchain/governance.old/utils/Votes.sol deleted file mode 100644 index 09eb4e2..0000000 --- a/blockchain/governance.old/utils/Votes.sol +++ /dev/null @@ -1,252 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v4.9.0) (governance/utils/Votes.sol) -pragma solidity ^0.8.19; - -import "../../interfaces/IERC5805.sol"; -import "../../utils/Context.sol"; -import "../../utils/Nonces.sol"; -import "../../utils/cryptography/EIP712.sol"; -import "../../utils/structs/Checkpoints.sol"; - -/** - * @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be - * transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of - * "representative" that will pool delegated voting units from different accounts and can then use it to vote in - * decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to - * delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative. - * - * This contract is often combined with a token contract such that voting units correspond to token units. For an - * example, see {ERC721Votes}. - * - * The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed - * at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the - * cost of this history tracking optional. - * - * When using this module the derived contract must implement {_getVotingUnits} (for example, make it return - * {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the - * previous example, it would be included in {ERC721-_beforeTokenTransfer}). - * - * _Available since v4.5._ - */ -abstract contract Votes is Context, EIP712, Nonces, IERC5805 { - using Checkpoints for Checkpoints.Trace224; - - bytes32 private constant _DELEGATION_TYPEHASH = - keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); - - mapping(address => address) private _delegation; - - /// @custom:oz-retyped-from mapping(address => Checkpoints.History) - mapping(address => Checkpoints.Trace224) private _delegateCheckpoints; - - /// @custom:oz-retyped-from Checkpoints.History - Checkpoints.Trace224 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 SafeCast.toUint48(block.number); - } - - /** - * @dev Machine-readable description of the clock as specified in EIP-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() != block.number) { - 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.toUint32(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.toUint32(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 _delegation[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); - _delegation[account] = delegatee; - - emit DelegateChanged(account, oldDelegate, delegatee); - _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account)); - } - - /** - * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to` - * should be zero. Total supply of voting units will be adjusted with mints and burns. - */ - function _transferVotingUnits(address from, address to, uint256 amount) internal virtual { - if (from == address(0)) { - _push(_totalCheckpoints, _add, SafeCast.toUint224(amount)); - } - if (to == address(0)) { - _push(_totalCheckpoints, _subtract, SafeCast.toUint224(amount)); - } - _moveDelegateVotes(delegates(from), delegates(to), amount); - } - - /** - * @dev Moves delegated votes from one delegate to another. - */ - function _moveDelegateVotes(address from, address to, uint256 amount) private { - if (from != to && amount > 0) { - if (from != address(0)) { - (uint256 oldValue, uint256 newValue) = _push( - _delegateCheckpoints[from], - _subtract, - SafeCast.toUint224(amount) - ); - emit DelegateVotesChanged(from, oldValue, newValue); - } - if (to != address(0)) { - (uint256 oldValue, uint256 newValue) = _push( - _delegateCheckpoints[to], - _add, - SafeCast.toUint224(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.Checkpoint224 memory) { - return _delegateCheckpoints[account].at(pos); - } - - function _push( - Checkpoints.Trace224 storage store, - function(uint224, uint224) view returns (uint224) op, - uint224 delta - ) private returns (uint224, uint224) { - return store.push(SafeCast.toUint32(clock()), op(store.latest(), delta)); - } - - function _add(uint224 a, uint224 b) private pure returns (uint224) { - return a + b; - } - - function _subtract(uint224 a, uint224 b) private pure returns (uint224) { - return a - b; - } - - /** - * @dev Must return the voting units held by an account. - */ - function _getVotingUnits(address) internal view virtual returns (uint256); -}