// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
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 override 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(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(account),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @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 override 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 override 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 override 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 `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @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());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
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 override 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 override 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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).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 override 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 override 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);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
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);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override 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(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(account),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @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 override 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 override 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 override 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 `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @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());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: BSD
pragma solidity ^0.8.4;
/// @title Clone
/// @author zefram.eth
/// @notice Provides helper functions for reading immutable args from calldata
contract Clone {
/// @notice Reads an immutable arg with type address
/// @param argOffset The offset of the arg in the packed data
/// @return arg The arg value
function _getArgAddress(uint256 argOffset)
internal
pure
returns (address arg)
{
uint256 offset = _getImmutableArgsOffset();
assembly {
arg := shr(0x60, calldataload(add(offset, argOffset)))
}
}
/// @notice Reads an immutable arg with type uint256
/// @param argOffset The offset of the arg in the packed data
/// @return arg The arg value
function _getArgUint256(uint256 argOffset)
internal
pure
returns (uint256 arg)
{
uint256 offset = _getImmutableArgsOffset();
// solhint-disable-next-line no-inline-assembly
assembly {
arg := calldataload(add(offset, argOffset))
}
}
/// @notice Reads an immutable arg with type uint64
/// @param argOffset The offset of the arg in the packed data
/// @return arg The arg value
function _getArgUint64(uint256 argOffset)
internal
pure
returns (uint64 arg)
{
uint256 offset = _getImmutableArgsOffset();
// solhint-disable-next-line no-inline-assembly
assembly {
arg := shr(0xc0, calldataload(add(offset, argOffset)))
}
}
/// @notice Reads an immutable arg with type uint8
/// @param argOffset The offset of the arg in the packed data
/// @return arg The arg value
function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) {
uint256 offset = _getImmutableArgsOffset();
// solhint-disable-next-line no-inline-assembly
assembly {
arg := shr(0xf8, calldataload(add(offset, argOffset)))
}
}
/// @return offset The offset of the packed immutable args in calldata
function _getImmutableArgsOffset() internal pure returns (uint256 offset) {
// solhint-disable-next-line no-inline-assembly
assembly {
offset := sub(
calldatasize(),
add(shr(240, calldataload(sub(calldatasize(), 2))), 2)
)
}
}
}
// SPDX-License-Identifier: BSD
pragma solidity ^0.8.4;
/// @title ClonesWithImmutableArgs
/// @author wighawag, zefram.eth
/// @notice Enables creating clone contracts with immutable args
library ClonesWithImmutableArgs {
error CreateFail();
/// @notice Creates a clone proxy of the implementation contract, with immutable args
/// @dev data cannot exceed 65535 bytes, since 2 bytes are used to store the data length
/// @param implementation The implementation contract to clone
/// @param data Encoded immutable args
/// @return instance The address of the created clone
function clone(address implementation, bytes memory data)
internal
returns (address instance)
{
// unrealistic for memory ptr or data length to exceed 256 bits
unchecked {
uint256 extraLength = data.length + 2; // +2 bytes for telling how much data there is appended to the call
uint256 creationSize = 0x43 + extraLength;
uint256 runSize = creationSize - 11;
uint256 dataPtr;
uint256 ptr;
// solhint-disable-next-line no-inline-assembly
assembly {
ptr := mload(0x40)
// -------------------------------------------------------------------------------------------------------------
// CREATION (11 bytes)
// -------------------------------------------------------------------------------------------------------------
// 3d | RETURNDATASIZE | 0 | –
// 61 runtime | PUSH2 runtime (r) | r 0 | –
mstore(
ptr,
0x3d61000000000000000000000000000000000000000000000000000000000000
)
mstore(add(ptr, 0x02), shl(240, runSize)) // size of the contract running bytecode (16 bits)
// creation size = 0b
// 80 | DUP1 | r r 0 | –
// 60 creation | PUSH1 creation (c) | c r r 0 | –
// 3d | RETURNDATASIZE | 0 c r r 0 | –
// 39 | CODECOPY | r 0 | [0-2d]: runtime code
// 81 | DUP2 | 0 c 0 | [0-2d]: runtime code
// f3 | RETURN | 0 | [0-2d]: runtime code
mstore(
add(ptr, 0x04),
0x80600b3d3981f300000000000000000000000000000000000000000000000000
)
// -------------------------------------------------------------------------------------------------------------
// RUNTIME
// -------------------------------------------------------------------------------------------------------------
// 36 | CALLDATASIZE | cds | –
// 3d | RETURNDATASIZE | 0 cds | –
// 3d | RETURNDATASIZE | 0 0 cds | –
// 37 | CALLDATACOPY | – | [0, cds] = calldata
// 61 | PUSH2 extra | extra | [0, cds] = calldata
mstore(
add(ptr, 0x0b),
0x363d3d3761000000000000000000000000000000000000000000000000000000
)
mstore(add(ptr, 0x10), shl(240, extraLength))
// 60 0x38 | PUSH1 0x38 | 0x38 extra | [0, cds] = calldata // 0x38 (56) is runtime size - data
// 36 | CALLDATASIZE | cds 0x38 extra | [0, cds] = calldata
// 39 | CODECOPY | _ | [0, cds] = calldata
// 3d | RETURNDATASIZE | 0 | [0, cds] = calldata
// 3d | RETURNDATASIZE | 0 0 | [0, cds] = calldata
// 3d | RETURNDATASIZE | 0 0 0 | [0, cds] = calldata
// 36 | CALLDATASIZE | cds 0 0 0 | [0, cds] = calldata
// 61 extra | PUSH2 extra | extra cds 0 0 0 | [0, cds] = calldata
mstore(
add(ptr, 0x12),
0x603836393d3d3d36610000000000000000000000000000000000000000000000
)
mstore(add(ptr, 0x1b), shl(240, extraLength))
// 01 | ADD | cds+extra 0 0 0 | [0, cds] = calldata
// 3d | RETURNDATASIZE | 0 cds 0 0 0 | [0, cds] = calldata
// 73 addr | PUSH20 0x123… | addr 0 cds 0 0 0 | [0, cds] = calldata
mstore(
add(ptr, 0x1d),
0x013d730000000000000000000000000000000000000000000000000000000000
)
mstore(add(ptr, 0x20), shl(0x60, implementation))
// 5a | GAS | gas addr 0 cds 0 0 0 | [0, cds] = calldata
// f4 | DELEGATECALL | success 0 | [0, cds] = calldata
// 3d | RETURNDATASIZE | rds success 0 | [0, cds] = calldata
// 82 | DUP3 | 0 rds success 0 | [0, cds] = calldata
// 80 | DUP1 | 0 0 rds success 0 | [0, cds] = calldata
// 3e | RETURNDATACOPY | success 0 | [0, rds] = return data (there might be some irrelevant leftovers in memory [rds, cds] when rds < cds)
// 90 | SWAP1 | 0 success | [0, rds] = return data
// 3d | RETURNDATASIZE | rds 0 success | [0, rds] = return data
// 91 | SWAP2 | success 0 rds | [0, rds] = return data
// 60 0x36 | PUSH1 0x36 | 0x36 sucess 0 rds | [0, rds] = return data
// 57 | JUMPI | 0 rds | [0, rds] = return data
// fd | REVERT | – | [0, rds] = return data
// 5b | JUMPDEST | 0 rds | [0, rds] = return data
// f3 | RETURN | – | [0, rds] = return data
mstore(
add(ptr, 0x34),
0x5af43d82803e903d91603657fd5bf30000000000000000000000000000000000
)
}
// -------------------------------------------------------------------------------------------------------------
// APPENDED DATA (Accessible from extcodecopy)
// (but also send as appended data to the delegatecall)
// -------------------------------------------------------------------------------------------------------------
extraLength -= 2;
uint256 counter = extraLength;
uint256 copyPtr = ptr + 0x43;
// solhint-disable-next-line no-inline-assembly
assembly {
dataPtr := add(data, 32)
}
for (; counter >= 32; counter -= 32) {
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(copyPtr, mload(dataPtr))
}
copyPtr += 32;
dataPtr += 32;
}
uint256 mask = ~(256**(32 - counter) - 1);
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(copyPtr, and(mload(dataPtr), mask))
}
copyPtr += counter;
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(copyPtr, shl(240, extraLength))
}
// solhint-disable-next-line no-inline-assembly
assembly {
instance := create(0, ptr, creationSize)
}
if (instance == address(0)) {
revert CreateFail();
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
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);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.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);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// 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.0;
/**
* @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;
}
}
// 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.0;
/**
* @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 EnumerableSetUpgradeable {
// 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;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.18;
/// @title Errors
/// @notice Library containing all custom errors the protocol may revert with.
library Errors {
//// MASTER REGISTRY ////
/// @notice Thrown when the registry name given is empty.
error NameEmpty();
/// @notice Thrown when the registry address given is empty.
error AddressEmpty();
/// @notice Thrown when the registry name is found when calling addRegistry().
error RegistryNameFound(bytes32 name);
/// @notice Thrown when the registry name is not found but is expected to be.
error RegistryNameNotFound(bytes32 name);
/// @notice Thrown when the registry address is not found but is expected to be.
error RegistryAddressNotFound(address registryAddress);
/// @notice Thrown when the registry name and version is not found but is expected to be.
error RegistryNameVersionNotFound(bytes32 name, uint256 version);
/// @notice Thrown when a duplicate registry address is found.
error DuplicateRegistryAddress(address registryAddress);
//// YEARN STAKING DELEGATE ////
/// @notice Error for when an address is zero which is not allowed.
error ZeroAddress();
/// @notice Error for when an amount is zero which is not allowed.
error ZeroAmount();
/// @notice Error for when a reward split is invalid.
error InvalidRewardSplit();
/// @notice Error for when the treasury percentage is too high.
error TreasuryPctTooHigh();
/// @notice Error for when perpetual lock is enabled and an action cannot be taken.
error PerpetualLockEnabled();
/// @notice Error for when perpetual lock is disabled and an action cannot be taken.
error PerpetualLockDisabled();
/// @notice Error for when swap and lock settings are not set.
error SwapAndLockNotSet();
/// @notice Error for when gauge rewards have already been added.
error GaugeRewardsAlreadyAdded();
/// @notice Error for when gauge rewards have not yet been added.
error GaugeRewardsNotYetAdded();
/// @notice Error for when execution of an action is not allowed.
error ExecutionNotAllowed();
/// @notice Error for when execution of an action has failed.
error ExecutionFailed();
/// @notice Error for when Cove YFI reward forwarder is not set.
error CoveYfiRewardForwarderNotSet();
//// STAKING DELEGATE REWARDS ////
/// @notice Error for when a rescue operation is not allowed.
error RescueNotAllowed();
/// @notice Error for when the previous rewards period has not been completed.
error PreviousRewardsPeriodNotCompleted();
/// @notice Error for when only the staking delegate can update a user's balance.
error OnlyStakingDelegateCanUpdateUserBalance();
/// @notice Error for when only the staking delegate can add a staking token.
error OnlyStakingDelegateCanAddStakingToken();
/// @notice Error for when only the reward distributor can notify the reward amount.
error OnlyRewardDistributorCanNotifyRewardAmount();
/// @notice Error for when a staking token has already been added.
error StakingTokenAlreadyAdded();
/// @notice Error for when a staking token has not been added.
error StakingTokenNotAdded();
/// @notice Error for when the reward rate is too low.
error RewardRateTooLow();
/// @notice Error for when the reward duration cannot be zero.
error RewardDurationCannotBeZero();
//// WRAPPED STRATEGY CURVE SWAPPER ////
/// @notice Error for when slippage is too high.
error SlippageTooHigh();
/// @notice Error for when invalid tokens are received.
error InvalidTokensReceived();
/// CURVE ROUTER SWAPPER ///
/*
* @notice Error for when the from token is invalid.
* @param intendedFromToken The intended from token address.
* @param actualFromToken The actual from token address received.
*/
error InvalidFromToken(address intendedFromToken, address actualFromToken);
/*
* @notice Error for when the to token is invalid.
* @param intendedToToken The intended to token address.
* @param actualToToken The actual to token address received.
*/
error InvalidToToken(address intendedToToken, address actualToToken);
/// @notice Error for when the expected amount is zero.
error ExpectedAmountZero();
/// @notice Error for when swap parameters are invalid.
error InvalidSwapParams();
/// SWAP AND LOCK ///
/// @notice Error for when the same address is used in a context where it is not allowed.
error SameAddress();
//// COVEYFI ////
/// @notice Error for when only minting is enabled.
error OnlyMintingEnabled();
/// RESCUABLE ///
/// @notice Error for when an ETH transfer of zero is attempted.
error ZeroEthTransfer();
/// @notice Error for when an ETH transfer fails.
error EthTransferFailed();
/// @notice Error for when a token transfer of zero is attempted.
error ZeroTokenTransfer();
/// GAUGE REWARD RECEIVER ///
/// @notice Error for when an action is not authorized.
error NotAuthorized();
/// @notice Error for when rescuing a reward token is not allowed.
error CannotRescueRewardToken();
/// DYFI REDEEMER ///
/// @notice Error for when an array length is invalid.
error InvalidArrayLength();
/// @notice Error for when a price feed is outdated.
error PriceFeedOutdated();
/// @notice Error for when a price feed round is incorrect.
error PriceFeedIncorrectRound();
/// @notice Error for when a price feed returns a zero price.
error PriceFeedReturnedZeroPrice();
/// @notice Error for when there is no DYFI to redeem.
error NoDYfiToRedeem();
/// @notice Error for when an ETH transfer for caller reward fails.
error CallerRewardEthTransferFailed();
/// COVE YEARN GAUGE FACTORY ///
/// @notice Error for when a gauge has already been deployed.
error GaugeAlreadyDeployed();
/// @notice Error for when a gauge has not been deployed.
error GaugeNotDeployed();
/// MINICHEF V3 ////
/// @notice Error for when an LP token is invalid.
error InvalidLPToken();
/// @notice Error for when an LP token has not been added.
error LPTokenNotAdded();
/// @notice Error for when an LP token does not match the pool ID.
error LPTokenDoesNotMatchPoolId();
/// @notice Error for when there is an insufficient balance.
error InsufficientBalance();
/// @notice Error for when an LP token has already been added.
error LPTokenAlreadyAdded();
/// @notice Error for when the reward rate is too high.
error RewardRateTooHigh();
/// Yearn4626RouterExt ///
/// @notice Error for when there are insufficient shares.
error InsufficientShares();
/// @notice Error for when the 'to' address is invalid.
error InvalidTo();
/// @notice Error esure the has enough remaining gas.
error InsufficientGas();
/// TESTING ///
/// @notice Error for when there is not enough balance to take away.
error TakeAwayNotEnoughBalance();
/// @notice Error for when a strategy has not been added to a vault.
error StrategyNotAddedToVault();
/// COVE TOKEN ///
/// @notice Error for when a transfer is attempted before it is allowed.
error TransferNotAllowedYet();
/// @notice Error for when an address is being added as both a sender and a receiver.
error CannotBeBothSenderAndReceiver();
/// @notice Error for when an unpause is attempted too early.
error UnpauseTooEarly();
/// @notice Error for when the pause period is too long.
error PausePeriodTooLong();
/// @notice Error for when minting is attempted too early.
error MintingAllowedTooEarly();
/// @notice Error for when the mint amount exceeds the cap.
error InflationTooLarge();
/*
* @notice Error for when an unauthorized account attempts an action requiring a specific role.
* @param account The account attempting the unauthorized action.
* @param neededRole The role required for the action.
*/
error AccessControlEnumerableUnauthorizedAccount(address account, bytes32 neededRole);
/// @notice Error for when an action is unauthorized.
error Unauthorized();
/// @notice Error for when a pause is expected but not enacted.
error ExpectedPause();
/// COVE YEARN GAUGE FACTORY ///
/// @notice Error for when an address is not a contract.
error AddressNotContract();
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { Clone } from "lib/clones-with-immutable-args/src/Clone.sol";
import { IGauge } from "src/interfaces/deps/yearn/veYFI/IGauge.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { StakingDelegateRewards } from "src/StakingDelegateRewards.sol";
import { AccessControlEnumerableUpgradeable } from
"@openzeppelin-upgradeable/contracts/access/AccessControlEnumerableUpgradeable.sol";
import { Rescuable } from "src/Rescuable.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol";
import { Errors } from "src/libraries/Errors.sol";
import { IYearnStakingDelegate } from "src/interfaces/IYearnStakingDelegate.sol";
/**
* @title GaugeRewardReceiver
* @notice Contract to receive rewards from a Yearn gauge and distribute them according to specified splits.
* @dev Inherits from Clone and ReentrancyGuardUpgradeable for creating clones acts and preventing reentrancy attacks.
*/
contract GaugeRewardReceiver is Clone, Rescuable, ReentrancyGuardUpgradeable, AccessControlEnumerableUpgradeable {
// Libraries
using SafeERC20 for IERC20;
/**
* @notice Initializes the contract by disabling initializers from the Clone pattern.
*/
// slither-disable-next-line locked-ether
constructor() payable {
_disableInitializers();
}
/**
* @notice Initializes the GaugeRewardReceiver contract.
* @param admin_ The address of the owner of the contract.
*/
function initialize(address admin_) external initializer {
__ReentrancyGuard_init();
_grantRole(DEFAULT_ADMIN_ROLE, admin_);
// _transferOwnership(owner_);
IERC20(rewardToken()).forceApprove(stakingDelegateRewards(), type(uint256).max);
}
/**
* @notice Harvest rewards from the gauge and distribute to treasury, compound, and veYFI
* @param swapAndLock Address of the SwapAndLock contract.
* @param treasury Address of the treasury to receive a portion of the rewards.
* @param coveYfiRewardForwarder Address of the CoveYfiRewardForwarder contract.
* @param rewardSplit Struct containing the split percentages for lock, treasury, and user rewards.
* @return userRewardsAmount The amount of rewards harvested for the user.
*/
function harvest(
address swapAndLock,
address treasury,
address coveYfiRewardForwarder,
IYearnStakingDelegate.RewardSplit calldata rewardSplit
)
external
nonReentrant
returns (uint256)
{
if (msg.sender != stakingDelegate()) {
revert Errors.NotAuthorized();
}
if (rewardSplit.treasury + rewardSplit.coveYfi + rewardSplit.user + rewardSplit.lock != 1e18) {
revert Errors.InvalidRewardSplit();
}
// Read pending dYFI rewards from the gauge
// Yearn's gauge implementation always returns true
// Ref: https://github.com/yearn/veYFI/blob/master/contracts/Gauge.sol#L493
// slither-disable-next-line unused-return
IGauge(gauge()).getReward(stakingDelegate());
uint256 totalRewardsAmount = IERC20(rewardToken()).balanceOf(address(this));
// Calculate the amount of rewards to distribute
uint256 treasuryAmount = totalRewardsAmount * uint256(rewardSplit.treasury) / 1e18;
uint256 coveYfiAmount = totalRewardsAmount * uint256(rewardSplit.coveYfi) / 1e18;
uint256 swapAndLockAmount = totalRewardsAmount * uint256(rewardSplit.lock) / 1e18;
uint256 userAmount = totalRewardsAmount - swapAndLockAmount - treasuryAmount - coveYfiAmount;
// Transfer rewards to the treasury
if (rewardSplit.treasury != 0) {
IERC20(rewardToken()).safeTransfer(treasury, treasuryAmount);
}
// Transfer rewards to the coveYFI reward forwarder
if (coveYfiAmount != 0) {
IERC20(rewardToken()).safeTransfer(coveYfiRewardForwarder, coveYfiAmount);
}
// Transfer rewards to the swap and lock contract
if (swapAndLockAmount != 0) {
IERC20(rewardToken()).safeTransfer(swapAndLock, swapAndLockAmount);
}
// Transfer rewards to the staking delegate rewards contract
if (userAmount != 0) {
StakingDelegateRewards(stakingDelegateRewards()).notifyRewardAmount(gauge(), userAmount);
}
return totalRewardsAmount;
}
/**
* @notice Rescue tokens from the contract. May only be called by the owner. Token cannot be the reward token.
* @param token address of the token to rescue.
* @param to address to send the rescued tokens to.
* @param amount amount of tokens to rescue.
*/
function rescue(IERC20 token, address to, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (address(token) == rewardToken()) {
revert Errors.CannotRescueRewardToken();
}
_rescue(token, to, amount);
}
/**
* @notice Get the address of the staking delegate from the contract's immutable arguments.
* @return The address of the staking delegate.
*/
function stakingDelegate() public pure returns (address) {
return _getArgAddress(0);
}
/**
* @notice Get the address of the gauge from the contract's immutable arguments.
* @return The address of the gauge.
*/
function gauge() public pure returns (address) {
return _getArgAddress(20);
}
/**
* @notice Get the address of the reward token from the contract's immutable arguments.
* @return The address of the reward token.
*/
function rewardToken() public pure returns (address) {
return _getArgAddress(40);
}
/**
* @notice Get the address of the staking delegate rewards contract from the contract's immutable arguments.
* @return The address of the staking delegate rewards contract.
*/
function stakingDelegateRewards() public pure returns (address) {
return _getArgAddress(60);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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 `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @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 `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IBaseGauge {
function queueNewRewards(uint256 _amount) external returns (bool);
function earned(address _account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
interface IDYfiRewardPool {
function claim() external returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @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 IERC165Upgradeable {
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @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.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
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].
*
* CAUTION: See Security Considerations above.
*/
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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.0;
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
import "./IBaseGauge.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
interface IGauge is IBaseGauge, IERC4626 {
function initialize(address _stakingToken, address _owner) external;
function boostedBalanceOf(address _account) external view returns (uint256);
function getReward(address _account) external returns (bool);
function setRecipient(address _recipient) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
interface ISnapshotDelegateRegistry {
function setDelegate(bytes32 id, address delegate) external;
function delegation(address account, bytes32 id) external view returns (address);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.18;
import { IAccessControlEnumerable } from "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
interface IStakingDelegateRewards is IAccessControlEnumerable {
function getReward(address stakingToken) external;
function setRewardReceiver(address receiver) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVotingYFI is IERC20 {
event ModifyLock(address indexed sender, address indexed user, uint256 amount, uint256 locktime, uint256 ts);
event Withdraw(address indexed user, uint256 amount, uint256 ts);
event Penalty(address indexed user, uint256 amount, uint256 ts);
event Supply(uint256 oldSupply, uint256 newSupply, uint256 ts);
struct LockedBalance {
uint256 amount;
uint256 end;
}
struct Withdrawn {
uint256 amount;
uint256 penalty;
}
struct Point {
int128 bias;
int128 slope;
uint256 ts;
uint256 blk;
}
function totalSupply() external view returns (uint256);
function locked(address _user) external view returns (LockedBalance memory);
function modify_lock(
uint256 _amount,
uint256 _unlock_time,
address _user
)
external
returns (LockedBalance memory);
function withdraw() external returns (Withdrawn memory);
function point_history(address user, uint256 epoch) external view returns (Point memory);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.18;
import { IVotingYFI } from "./deps/yearn/veYFI/IVotingYFI.sol";
interface IYearnStakingDelegate {
// Struct definitions
struct RewardSplit {
uint64 treasury;
uint64 coveYfi;
uint64 user;
uint64 lock;
}
struct ExitRewardSplit {
uint128 treasury;
uint128 coveYfi;
}
struct BoostRewardSplit {
uint128 treasury;
uint128 coveYfi;
}
function deposit(address gauge, uint256 amount) external;
function withdraw(address gauge, uint256 amount) external;
function withdraw(address gauge, uint256 amount, address receiver) external;
function lockYfi(uint256 amount) external returns (IVotingYFI.LockedBalance memory);
function harvest(address vault) external returns (uint256);
function setCoveYfiRewardForwarder(address forwarder) external;
function setGaugeRewardSplit(
address gauge,
uint64 treasuryPct,
uint64 coveYfiPct,
uint64 userPct,
uint64 veYfiPct
)
external;
function setBoostRewardSplit(uint128 treasuryPct, uint128 coveYfiPct) external;
function setExitRewardSplit(uint128 treasuryPct, uint128 coveYfiPct) external;
function setSwapAndLock(address swapAndLock) external;
function balanceOf(address user, address gauge) external view returns (uint256);
function totalDeposited(address gauge) external view returns (uint256);
function depositLimit(address gauge) external view returns (uint256);
function availableDepositLimit(address gauge) external view returns (uint256);
function gaugeStakingRewards(address gauge) external view returns (address);
function gaugeRewardReceivers(address gauge) external view returns (address);
function getGaugeRewardSplit(address gauge) external view returns (RewardSplit memory);
function getBoostRewardSplit() external view returns (BoostRewardSplit memory);
function getExitRewardSplit() external view returns (ExitRewardSplit memory);
function treasury() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
interface IYfiRewardPool {
event CheckpointToken(uint256 time, uint256 tokens);
function claim() external returns (uint256);
function checkpoint_token() external;
function checkpoint_total_supply() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @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) {
// (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.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 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);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @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) {
// (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.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 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);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
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 {
/**
* @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);
bool private _paused;
/**
* @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 {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @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());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @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;
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
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// 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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Errors } from "src/libraries/Errors.sol";
/**
* @title Rescuable
* @notice Allows the inheriting contract to rescue ERC20 tokens that are sent to it by mistake.
*/
contract Rescuable {
// Libraries
using SafeERC20 for IERC20;
/**
* @dev Rescue any ERC20 tokens that are stuck in this contract.
* The inheriting contract that calls this function should specify required access controls
* @param token address of the ERC20 token to rescue. Use zero address for ETH
* @param to address to send the tokens to
* @param balance amount of tokens to rescue. Use zero to rescue all
*/
function _rescue(IERC20 token, address to, uint256 balance) internal {
if (address(token) == address(0)) {
// for ether
uint256 totalBalance = address(this).balance;
balance = balance != 0 ? Math.min(totalBalance, balance) : totalBalance;
if (balance != 0) {
// slither-disable-next-line arbitrary-send
// slither-disable-next-line low-level-calls
(bool success,) = to.call{ value: balance }("");
if (!success) revert Errors.EthTransferFailed();
return;
}
revert Errors.ZeroEthTransfer();
} else {
// for any other erc20
uint256 totalBalance = token.balanceOf(address(this));
balance = balance != 0 ? Math.min(totalBalance, balance) : totalBalance;
if (balance != 0) {
token.safeTransfer(to, balance);
return;
}
revert Errors.ZeroTokenTransfer();
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
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 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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, 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);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @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.isContract(address(token));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMathUpgradeable {
/**
* @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);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { AccessControlEnumerable } from "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Errors } from "src/libraries/Errors.sol";
import { IStakingDelegateRewards } from "src/interfaces/IStakingDelegateRewards.sol";
import { IYearnStakingDelegate } from "src/interfaces/IYearnStakingDelegate.sol";
/**
* @title Staking Delegate Rewards
* @notice Contract for managing staking rewards with functionality to update balances, notify new rewards, and recover
* tokens.
* @dev Inherits from IStakingDelegateRewards and AccessControlEnumerable.
*/
contract StakingDelegateRewards is IStakingDelegateRewards, AccessControlEnumerable {
// Libraries
using SafeERC20 for IERC20;
// Constants
/// @dev Default duration of rewards period in seconds (7 days).
uint256 private constant _DEFAULT_DURATION = 7 days;
/// @dev Role identifier used for protecting functions with timelock access.
bytes32 public constant TIMELOCK_ROLE = keccak256("TIMELOCK_ROLE");
// slither-disable-start naming-convention
/// @dev Address of the token used for rewards, immutable.
address private immutable _REWARDS_TOKEN;
/// @dev Address of the staking delegate, immutable.
address private immutable _STAKING_DELEGATE;
// slither-disable-end naming-convention
// State variables
/// @dev Mapping of staking tokens to the period end timestamp.
mapping(address => uint256) public periodFinish;
/// @dev Mapping of staking tokens to their respective reward rate.
mapping(address => uint256) public rewardRate;
/// @dev Mapping of staking tokens to their rewards duration.
mapping(address => uint256) public rewardsDuration;
/// @dev Mapping of staking tokens to the last update time for rewards.
mapping(address => uint256) public lastUpdateTime;
/// @dev Mapping of staking tokens to the accumulated reward per token.
mapping(address => uint256) public rewardPerTokenStored;
/// @dev Mapping of staking tokens to the leftover rewards.
mapping(address => uint256) public leftOver;
/// @dev Mapping of staking tokens and users to the paid-out reward per token.
mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
/// @dev Mapping of staking tokens and users to their respective rewards.
mapping(address => mapping(address => uint256)) public rewards;
/// @dev Mapping of staking tokens to their reward distributors.
mapping(address => address) public rewardDistributors;
/// @dev Mapping of users to their designated reward receivers.
mapping(address => address) public rewardReceiver;
// Events
/**
* @notice Emitted when rewards are added for a staking token.
* @param stakingToken The staking token for which rewards are added.
* @param rewardAmount The amount of rewards added.
* @param rewardRate The rate at which rewards will be distributed.
* @param start The start time of the reward period.
* @param end The end time of the reward period.
*/
event RewardAdded(
address indexed stakingToken, uint256 rewardAmount, uint256 rewardRate, uint256 start, uint256 end
);
/**
* @notice Emitted when a staking token is added to the rewards program.
* @param stakingToken The staking token that was added.
* @param rewardDistributioner The address authorized to distribute rewards for the staking token.
*/
event StakingTokenAdded(address indexed stakingToken, address rewardDistributioner);
/**
* @notice Emitted when a user's balance is updated for a staking token.
* @param user The user whose balance was updated.
* @param stakingToken The staking token for which the balance was updated.
*/
event UserBalanceUpdated(address indexed user, address indexed stakingToken);
/**
* @notice Emitted when rewards are paid out to a user for a staking token.
* @param user The user who received the rewards.
* @param stakingToken The staking token for which the rewards were paid.
* @param reward The amount of rewards paid.
* @param receiver The address that received the rewards.
*/
event RewardPaid(address indexed user, address indexed stakingToken, uint256 reward, address receiver);
/**
* @notice Emitted when the rewards duration is updated for a staking token.
* @param stakingToken The staking token for which the duration was updated.
* @param newDuration The new duration for rewards.
*/
event RewardsDurationUpdated(address indexed stakingToken, uint256 newDuration);
/**
* @notice Emitted when tokens are recovered from the contract.
* @param token The address of the token that was recovered.
* @param amount The amount of the token that was recovered.
*/
event Recovered(address token, uint256 amount);
/**
* @notice Emitted when a user sets a reward receiver address.
* @param user The user who set the reward receiver.
* @param receiver The address set as the reward receiver.
*/
event RewardReceiverSet(address indexed user, address receiver);
/**
* @notice Constructor that sets the rewards token and staking delegate addresses.
* @param rewardsToken_ The ERC20 token to be used as the rewards token.
* @param stakingDelegate_ The address of the staking delegate contract.
*/
// slither-disable-next-line locked-ether
constructor(address rewardsToken_, address stakingDelegate_, address admin, address timeLock) payable {
// Checks
// Check for zero addresses
if (rewardsToken_ == address(0) || stakingDelegate_ == address(0)) {
revert Errors.ZeroAddress();
}
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(TIMELOCK_ROLE, timeLock); // This role must be revoked after granting it to the timelock
_setRoleAdmin(TIMELOCK_ROLE, TIMELOCK_ROLE); // Only those with the timelock role can grant the timelock role
_REWARDS_TOKEN = rewardsToken_;
_STAKING_DELEGATE = stakingDelegate_;
}
/**
* @notice Claims reward for a given staking token.
* @param stakingToken The address of the staking token.
*/
function getReward(address stakingToken) external {
_getReward(msg.sender, stakingToken);
}
/**
* @notice Claims reward for a given user and staking token.
* @param user The address of the user to claim rewards for.
* @param stakingToken The address of the staking token.
*/
function getReward(address user, address stakingToken) external {
_getReward(user, stakingToken);
}
/**
* @notice Sets the reward receiver who will receive your rewards instead.
* @dev This can be set to the zero address to receive rewards directly.
* @param receiver The address of the reward receiver.
*/
function setRewardReceiver(address receiver) external {
rewardReceiver[msg.sender] = receiver;
emit RewardReceiverSet(msg.sender, receiver);
}
/**
* @notice Notifies a new reward amount for a given staking token.
* @param stakingToken The address of the staking token to notify the reward for.
* @param reward The amount of the new reward.
*/
function notifyRewardAmount(address stakingToken, uint256 reward) external {
if (msg.sender != rewardDistributors[stakingToken]) {
revert Errors.OnlyRewardDistributorCanNotifyRewardAmount();
}
_updateReward(address(0), stakingToken);
uint256 periodFinish_ = periodFinish[stakingToken];
// slither-disable-next-line similar-names
uint256 rewardDuration_ = rewardsDuration[stakingToken];
uint256 leftOverRewards = leftOver[stakingToken];
// slither-disable-next-line timestamp
if (block.timestamp < periodFinish_) {
uint256 remainingTime = periodFinish_ - block.timestamp;
leftOverRewards = leftOverRewards + (remainingTime * rewardRate[stakingToken]);
}
uint256 newRewardAmount = reward + leftOverRewards;
uint256 newRewardRate = newRewardAmount / rewardDuration_;
// slither-disable-next-line incorrect-equality
if (newRewardRate == 0) {
revert Errors.RewardRateTooLow();
}
uint256 newPeriodFinish = block.timestamp + rewardDuration_;
emit RewardAdded(stakingToken, reward, newRewardRate, block.timestamp, newPeriodFinish);
rewardRate[stakingToken] = newRewardRate;
lastUpdateTime[stakingToken] = block.timestamp;
periodFinish[stakingToken] = newPeriodFinish;
// slither-disable-next-line weak-prng
leftOver[stakingToken] = newRewardAmount % rewardDuration_;
IERC20(_REWARDS_TOKEN).safeTransferFrom(msg.sender, address(this), reward);
}
/**
* @notice Updates the balance of a user for a given staking token.
* @param user The address of the user to update the balance for.
* @param stakingToken The address of the staking token.
* @param currentUserBalance The current balance of staking token of the user.
* @param currentTotalDeposited The current total deposited amount of the staking token.
*/
function updateUserBalance(
address user,
address stakingToken,
uint256 currentUserBalance,
uint256 currentTotalDeposited
)
external
{
if (msg.sender != _STAKING_DELEGATE) {
revert Errors.OnlyStakingDelegateCanUpdateUserBalance();
}
_updateReward(user, stakingToken, currentUserBalance, currentTotalDeposited);
emit UserBalanceUpdated(user, stakingToken);
}
/**
* @notice Adds a new staking token to the contract.
* @param stakingToken The address of the staking token to add.
* @param rewardDistributioner The address allowed to notify new rewards for the staking token.
*/
function addStakingToken(address stakingToken, address rewardDistributioner) external {
if (msg.sender != _STAKING_DELEGATE) {
revert Errors.OnlyStakingDelegateCanAddStakingToken();
}
if (rewardDistributors[stakingToken] != address(0)) {
revert Errors.StakingTokenAlreadyAdded();
}
rewardDistributors[stakingToken] = rewardDistributioner;
rewardsDuration[stakingToken] = _DEFAULT_DURATION;
emit StakingTokenAdded(stakingToken, rewardDistributioner);
emit RewardsDurationUpdated(stakingToken, _DEFAULT_DURATION);
}
/**
* @notice Sets the duration of the rewards period for a given staking token.
* @param stakingToken The address of the staking token to set the rewards duration for.
* @param rewardsDuration_ The new duration of the rewards period.
*/
function setRewardsDuration(address stakingToken, uint256 rewardsDuration_) external onlyRole(TIMELOCK_ROLE) {
if (rewardsDuration_ == 0) {
revert Errors.RewardDurationCannotBeZero();
}
if (rewardsDuration[stakingToken] == 0) {
revert Errors.StakingTokenNotAdded();
}
// slither-disable-next-line timestamp
if (block.timestamp <= periodFinish[stakingToken]) {
revert Errors.PreviousRewardsPeriodNotCompleted();
}
rewardsDuration[stakingToken] = rewardsDuration_;
emit RewardsDurationUpdated(stakingToken, rewardsDuration_);
}
/**
* @notice Allows recovery of ERC20 tokens other than the staking and rewards tokens.
* @dev Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
* @param tokenAddress The address of the token to recover.
* @param to The address to send the recovered tokens to.
* @param tokenAmount The amount of tokens to recover.
*/
function recoverERC20(
address tokenAddress,
address to,
uint256 tokenAmount
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
if (tokenAddress == _REWARDS_TOKEN || rewardDistributors[tokenAddress] != address(0)) {
revert Errors.RescueNotAllowed();
}
emit Recovered(tokenAddress, tokenAmount);
IERC20(tokenAddress).safeTransfer(to, tokenAmount);
}
/**
* @notice Calculates the total reward for a given duration for a staking token.
* @param stakingToken The address of the staking token.
* @return The total reward for the given duration.
*/
function getRewardForDuration(address stakingToken) external view returns (uint256) {
return rewardRate[stakingToken] * rewardsDuration[stakingToken];
}
/**
* @notice Returns the address of the rewards token.
* @return The address of the rewards token.
*/
function rewardToken() external view returns (address) {
return _REWARDS_TOKEN;
}
/**
* @notice Returns the address of the staking delegate.
* @return The address of the staking delegate.
*/
function stakingDelegate() external view returns (address) {
return _STAKING_DELEGATE;
}
/**
* @notice Calculates the last time a reward was applicable for the given staking token.
* @param stakingToken The address of the staking token.
* @return The last applicable timestamp for rewards.
*/
function lastTimeRewardApplicable(address stakingToken) public view returns (uint256) {
uint256 finish = periodFinish[stakingToken];
// slither-disable-next-line timestamp
return block.timestamp < finish ? block.timestamp : finish;
}
/**
* @notice Calculates the accumulated reward per token stored.
* @param stakingToken The address of the staking token.
* @return The accumulated reward per token.
*/
function rewardPerToken(address stakingToken) external view returns (uint256) {
return _rewardPerToken(stakingToken, IYearnStakingDelegate(_STAKING_DELEGATE).totalDeposited(stakingToken));
}
function _rewardPerToken(address stakingToken, uint256 currentTotalDeposited) internal view returns (uint256) {
if (currentTotalDeposited == 0) {
return rewardPerTokenStored[stakingToken];
}
return rewardPerTokenStored[stakingToken]
+ (lastTimeRewardApplicable(stakingToken) - lastUpdateTime[stakingToken]) * rewardRate[stakingToken] * 1e18
/ currentTotalDeposited;
}
/**
* @notice Calculates the amount of reward earned by an account for a given staking token.
* @param account The address of the user's account.
* @param stakingToken The address of the staking token.
* @return The amount of reward earned.
*/
function earned(address account, address stakingToken) external view returns (uint256) {
return _earned(
account,
stakingToken,
IYearnStakingDelegate(_STAKING_DELEGATE).balanceOf(account, stakingToken),
_rewardPerToken(stakingToken, IYearnStakingDelegate(_STAKING_DELEGATE).totalDeposited(stakingToken))
);
}
function _earned(
address account,
address stakingToken,
uint256 userBalance,
uint256 rewardPerToken_
)
internal
view
returns (uint256)
{
return rewards[account][stakingToken]
+ (userBalance * (rewardPerToken_ - userRewardPerTokenPaid[account][stakingToken]) / 1e18);
}
/**
* @notice Updates the reward state for a given user and staking token. If there are any rewards to be paid out,
* they are sent to the receiver that was set by the user. (Defaults to the user's address if not set)
* @param user The address of the user to update rewards for.
* @param stakingToken The address of the staking token.
*/
function _getReward(address user, address stakingToken) internal {
_updateReward(user, stakingToken);
uint256 reward = rewards[user][stakingToken];
if (reward > 0) {
rewards[user][stakingToken] = 0;
address receiver = rewardReceiver[user];
if (receiver == address(0)) {
receiver = user;
}
emit RewardPaid(user, stakingToken, reward, receiver);
IERC20(_REWARDS_TOKEN).safeTransfer(receiver, reward);
}
}
function _updateReward(address account, address stakingToken) internal {
_updateReward(
account,
stakingToken,
IYearnStakingDelegate(_STAKING_DELEGATE).balanceOf(account, stakingToken),
IYearnStakingDelegate(_STAKING_DELEGATE).totalDeposited(stakingToken)
);
}
/**
* @dev Updates reward state for a given user and staking token.
* @param account The address of the user to update rewards for.
* @param stakingToken The address of the staking token.
*/
function _updateReward(
address account,
address stakingToken,
uint256 currentUserBalance,
uint256 currentTotalDeposited
)
internal
{
uint256 rewardPerToken_ = _rewardPerToken(stakingToken, currentTotalDeposited);
rewardPerTokenStored[stakingToken] = rewardPerToken_;
lastUpdateTime[stakingToken] = lastTimeRewardApplicable(stakingToken);
if (account != address(0)) {
rewards[account][stakingToken] = _earned(account, stakingToken, currentUserBalance, rewardPerToken_);
userRewardPerTokenPaid[account][stakingToken] = rewardPerToken_;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
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 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 toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(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) {
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[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
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 keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.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 toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.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, MathUpgradeable.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) {
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[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
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 keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IVotingYFI } from "src/interfaces/deps/yearn/veYFI/IVotingYFI.sol";
import { IDYfiRewardPool } from "src/interfaces/deps/yearn/veYFI/IDYfiRewardPool.sol";
import { IYfiRewardPool } from "src/interfaces/deps/yearn/veYFI/IYfiRewardPool.sol";
import { ISnapshotDelegateRegistry } from "src/interfaces/deps/snapshot/ISnapshotDelegateRegistry.sol";
import { IGauge } from "src/interfaces/deps/yearn/veYFI/IGauge.sol";
import { AccessControlEnumerable } from "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import { Errors } from "src/libraries/Errors.sol";
import { Rescuable } from "src/Rescuable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { Pausable } from "@openzeppelin/contracts/security/Pausable.sol";
import { ClonesWithImmutableArgs } from "lib/clones-with-immutable-args/src/ClonesWithImmutableArgs.sol";
import { GaugeRewardReceiver } from "src/GaugeRewardReceiver.sol";
import { StakingDelegateRewards } from "src/StakingDelegateRewards.sol";
import { IYearnStakingDelegate } from "src/interfaces/IYearnStakingDelegate.sol";
/**
* @title YearnStakingDelegate
* @notice Contract for staking yearn gauge tokens, managing rewards, and delegating voting power.
* @dev Inherits from IYearnStakingDelegate, AccessControlEnumerable, ReentrancyGuard, Rescuable, and Pausable.
*/
contract YearnStakingDelegate is
IYearnStakingDelegate,
AccessControlEnumerable,
ReentrancyGuard,
Rescuable,
Pausable
{
// Libraries
using SafeERC20 for IERC20;
using ClonesWithImmutableArgs for address;
// Constants
/// @dev Role identifier for pausers, capable of pausing contract functions.
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/// @dev Role identifier for timelock, capable of performing time-sensitive administrative functions.
bytes32 public constant TIMELOCK_ROLE = keccak256("TIMELOCK_ROLE");
/// @dev Role identifier for depositors, capable of depositing gauge tokens.
bytes32 public constant DEPOSITOR_ROLE = keccak256("DEPOSITOR_ROLE");
// slither-disable-start naming-convention
/// @dev Address of the Yearn Finance YFI reward pool.
address private constant _YFI_REWARD_POOL = 0xb287a1964AEE422911c7b8409f5E5A273c1412fA;
/// @dev Address of the Yearn Finance D_YFI reward pool.
address private constant _DYFI_REWARD_POOL = 0x2391Fc8f5E417526338F5aa3968b1851C16D894E;
/// @dev Address of the Yearn Finance YFI token.
address private constant _YFI = 0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e;
/// @dev Address of the Yearn Finance D_YFI token.
address private constant _D_YFI = 0x41252E8691e964f7DE35156B68493bAb6797a275;
/// @dev Address of the Yearn Finance veYFI token.
address private constant _VE_YFI = 0x90c1f9220d90d3966FbeE24045EDd73E1d588aD5;
/// @dev Address of the Snapshot delegate registry.
address private constant _SNAPSHOT_DELEGATE_REGISTRY = 0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446;
/// @dev Maximum percentage of the treasury in basis points.
uint256 private constant _MAX_TREASURY_PCT = 0.2e18;
// Immutables
/// @dev Address of the GaugeRewardReceiver implementation, set at contract deployment and immutable thereafter.
address private immutable _GAUGE_REWARD_RECEIVER_IMPL;
// slither-disable-end naming-convention
// Mappings
/// @notice Mapping of gauge addresses to their corresponding staking rewards contract addresses.
mapping(address => address) public gaugeStakingRewards;
/// @notice Mapping of gauge addresses to their corresponding GaugeRewardReceiver contract addresses.
mapping(address => address) public gaugeRewardReceivers;
/// @notice Mapping of user addresses to a nested mapping of token addresses to the user's balance of that token.
mapping(address => mapping(address => uint256)) public balanceOf;
/// @notice Mapping of gauge token address to the total amount deposited in this contract.
mapping(address => uint256) public totalDeposited;
/// @notice Mapping of gauge token addresses to their corresponding deposit limits. Note that this is the ideal
/// limit, which should be enforced by the depositing contracts
mapping(address => uint256) public depositLimit;
/// @notice Mapping of target addresses to a boolean indicating whether the target is blocked.
mapping(address => bool) public blockedTargets;
/// @dev Mapping of vault addresses to their corresponding RewardSplit configuration.
mapping(address => RewardSplit) private _gaugeRewardSplit;
// Variables
/// @dev Address of the treasury where funds are managed.
address private _treasury;
/// @dev Flag indicating whether to lock rewards perpetually.
bool private _shouldPerpetuallyLock;
/// @dev Address of the contract that swaps and locks tokens.
address private _swapAndLock;
/// @dev Address of the contract that forwards YFI rewards to CoveYFI.
address private _coveYfiRewardForwarder;
/// @dev Configuration for how rewards are split in the boost phase.
BoostRewardSplit private _boostRewardSplit;
/// @dev Configuration for how rewards are split upon exit.
ExitRewardSplit private _exitRewardSplit;
/**
* @notice Emitted when YFI tokens are locked.
* @param sender The address of the sender who locked YFI tokens.
* @param amount The amount of YFI tokens locked.
*/
event LockYfi(address indexed sender, uint256 amount);
/**
* @notice Emitted when gauge rewards are set.
* @param gauge The address of the gauge for which rewards are set.
* @param stakingRewardsContract The address of the staking rewards contract.
* @param receiver The address of the rewards receiver.
*/
event GaugeRewardsSet(address indexed gauge, address stakingRewardsContract, address receiver);
/**
* @notice Emitted when the perpetual lock setting is updated.
* @param shouldLock The status of the perpetual lock setting.
*/
event PerpetualLockSet(bool shouldLock);
/**
* @notice Emitted when the reward split configuration for a gauge is set.
* @param gauge The address of the gauge for which the reward split is set.
* @param split The reward split configuration.
*/
event GaugeRewardSplitSet(address indexed gauge, RewardSplit split);
/**
* @notice Emitted when the boost reward split configuration is set.
* @param treasuryPct The percentage of the boost reward allocated to the treasury.
* @param coveYfiPct The percentage of the boost reward allocated to CoveYFI.
*/
event BoostRewardSplitSet(uint128 treasuryPct, uint128 coveYfiPct);
/**
* @notice Emitted when the exit reward split configuration is set.
* @param treasuryPct The percentage of the exit reward allocated to the treasury.
* @param coveYfiPct The percentage of the exit reward allocated to CoveYFI.
*/
event ExitRewardSplitSet(uint128 treasuryPct, uint128 coveYfiPct);
/**
* @notice Emitted when a deposit limit is set.
* @param gaugeToken The address of the gauge token for which the deposit limit is set.
* @param limit The deposit limit.
*/
event DepositLimitSet(address indexed gaugeToken, uint256 limit);
/**
* @notice Emitted when the swap and lock contract address is set.
* @param swapAndLockContract The address of the swap and lock contract.
*/
event SwapAndLockSet(address swapAndLockContract);
/**
* @notice Emitted when the treasury address is updated.
* @param newTreasury The new address of the treasury.
*/
event TreasurySet(address newTreasury);
/**
* @notice Emitted when the CoveYFI reward forwarder address is set.
* @param forwarder The address of the CoveYFI reward forwarder.
*/
event CoveYfiRewardForwarderSet(address forwarder);
/**
* @notice Emitted when a gauge token is deposited
* @param sender The address of the sender who made the deposit.
* @param gauge The address of the gauge token deposited.
* @param amount The amount of tokens deposited.
* @param newTotalDeposited The new total amount of the gauge tokens deposited across all users.
*/
event Deposit(address indexed sender, address indexed gauge, uint256 amount, uint256 newTotalDeposited);
/**
* @notice Emitted when a gauge token is withdrawn
* @param sender The address of the sender who made the withdrawal.
* @param gauge The address of the gauge token withdrawn.
* @param amount The amount of tokens withdrawn.
* @param newTotalDeposited The new total amount of the gauge tokens deposited across all users.
*/
event Withdraw(address indexed sender, address indexed gauge, uint256 amount, uint256 newTotalDeposited);
/**
* @notice Emitted when the checkpointing of a user's balance fails
* @param stakingDelegateRewards The address of the StakingDelegateRewards contract.
* @param user The address of the user whose balance failed to checkpoint.
* @param gauge The address of the gauge token.
* @param currentUserBalance The current balance of gauge tokens deposited by the user.
* @param currentTotalDeposited The current total amount of the gauge tokens deposited across all users.
*/
event StakingDelegateRewardsFaulty(
address stakingDelegateRewards,
address user,
address gauge,
uint256 currentUserBalance,
uint256 currentTotalDeposited
);
/**
* @dev Initializes the contract by setting up roles and initializing state variables.
* @param gaugeRewardReceiverImpl Address of the GaugeRewardReceiver implementation.
* @param treasury_ Address of the treasury.
* @param admin Address of the admin.
* @param pauser Address of the pauser.
* @param timelock Address of the timelock.
*/
// slither-disable-next-line locked-ether
constructor(
address gaugeRewardReceiverImpl,
address treasury_,
address admin,
address pauser,
address timelock
)
payable
{
// Checks
// Check for zero addresses
if (
gaugeRewardReceiverImpl == address(0) || treasury_ == address(0) || admin == address(0)
|| pauser == address(0) || timelock == address(0)
) {
revert Errors.ZeroAddress();
}
// Effects
// Set storage variables
_setTreasury(treasury_);
_setPerpetualLock(true);
_setBoostRewardSplit(0, 1e18); // 100% to CoveYFI by default
_setExitRewardSplit(0, 1e18); // 100% to CoveYFI by default
_GAUGE_REWARD_RECEIVER_IMPL = gaugeRewardReceiverImpl;
blockedTargets[_YFI] = true;
blockedTargets[_D_YFI] = true;
blockedTargets[_VE_YFI] = true;
blockedTargets[_YFI_REWARD_POOL] = true;
blockedTargets[_DYFI_REWARD_POOL] = true;
blockedTargets[_SNAPSHOT_DELEGATE_REGISTRY] = true;
blockedTargets[_GAUGE_REWARD_RECEIVER_IMPL] = true;
_setRoleAdmin(TIMELOCK_ROLE, TIMELOCK_ROLE);
_setRoleAdmin(DEPOSITOR_ROLE, TIMELOCK_ROLE);
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(TIMELOCK_ROLE, timelock);
_grantRole(PAUSER_ROLE, pauser);
// Interactions
// Max approve YFI to veYFI so we can lock it later
IERC20(_YFI).forceApprove(_VE_YFI, type(uint256).max);
}
/**
* @notice Deposits a specified amount of gauge tokens into this staking delegate.
* @dev Deposits can be paused in case of emergencies by the admin or pauser roles.
* @param gauge The address of the gauge token to deposit.
* @param amount The amount of tokens to deposit.
*/
function deposit(address gauge, uint256 amount) external onlyRole(DEPOSITOR_ROLE) whenNotPaused {
// Checks
if (amount == 0) {
revert Errors.ZeroAmount();
}
address stakingDelegateReward = gaugeStakingRewards[gauge];
if (stakingDelegateReward == address(0)) {
revert Errors.GaugeRewardsNotYetAdded();
}
// Effects
uint256 currentTotalDeposited = totalDeposited[gauge];
uint256 currentUserBalance = balanceOf[msg.sender][gauge];
uint256 newTotalDeposited = currentTotalDeposited + amount;
balanceOf[msg.sender][gauge] = currentUserBalance + amount;
totalDeposited[gauge] = newTotalDeposited;
// Interactions
emit Deposit(msg.sender, gauge, amount, newTotalDeposited);
_checkpointUserBalance(stakingDelegateReward, gauge, msg.sender, currentUserBalance, currentTotalDeposited);
IERC20(gauge).safeTransferFrom(msg.sender, address(this), amount);
}
/**
* @notice Withdraws a specified amount of gauge tokens from this staking delegate.
* @param gauge The address of the gauge token to withdraw.
* @param amount The amount of tokens to withdraw.
*/
function withdraw(address gauge, uint256 amount, address receiver) external {
_withdraw(gauge, amount, receiver);
}
/**
* @notice Withdraws a specified amount of gauge tokens from this staking delegate.
* @param gauge The address of the gauge token to withdraw.
* @param amount The amount of tokens to withdraw.
*/
function withdraw(address gauge, uint256 amount) external {
_withdraw(gauge, amount, msg.sender);
}
function _withdraw(address gauge, uint256 amount, address receiver) internal {
// Checks
if (amount == 0) {
revert Errors.ZeroAmount();
}
// Effects
uint256 currentUserBalance = balanceOf[msg.sender][gauge];
uint256 currentTotalDeposited = totalDeposited[gauge];
uint256 newTotalDeposited = currentTotalDeposited - amount;
balanceOf[msg.sender][gauge] = currentUserBalance - amount;
totalDeposited[gauge] = newTotalDeposited;
// Interactions
emit Withdraw(msg.sender, gauge, amount, newTotalDeposited);
_checkpointUserBalance(gaugeStakingRewards[gauge], gauge, msg.sender, currentUserBalance, currentTotalDeposited);
IERC20(gauge).safeTransfer(receiver, amount);
}
/**
* @notice Harvests rewards from a gauge and distributes them.
* @param gauge Address of the gauge to harvest from.
* @return The amount of rewards harvested.
*/
function harvest(address gauge) external returns (uint256) {
// Checks
address swapAndLockContract = _swapAndLock;
if (swapAndLockContract == address(0)) {
revert Errors.SwapAndLockNotSet();
}
address gaugeRewardReceiver = gaugeRewardReceivers[gauge];
if (gaugeRewardReceiver == address(0)) {
revert Errors.GaugeRewardsNotYetAdded();
}
address rewardForwarder = _coveYfiRewardForwarder;
if (rewardForwarder == address(0)) {
revert Errors.CoveYfiRewardForwarderNotSet();
}
// Interactions
return GaugeRewardReceiver(gaugeRewardReceiver).harvest(
swapAndLockContract, _treasury, rewardForwarder, _gaugeRewardSplit[gauge]
);
}
/**
* @notice Claim dYFI rewards from the reward pool and transfer them to the CoveYFI Reward Forwarder
*/
function claimBoostRewards() external {
// Checks
address rewardForwarder = _coveYfiRewardForwarder;
if (rewardForwarder == address(0)) {
revert Errors.CoveYfiRewardForwarderNotSet();
}
// Interactions
// Ignore the returned amount and use the balance instead to ensure we capture
// any rewards claimed for this contract by other addresses
// https://etherscan.io/address/0x2391Fc8f5E417526338F5aa3968b1851C16D894E#code
// slither-disable-next-line unused-return
IDYfiRewardPool(_DYFI_REWARD_POOL).claim();
uint256 balance = IERC20(_D_YFI).balanceOf(address(this));
uint256 coveYfiAmount = (balance * _boostRewardSplit.coveYfi) / 1e18;
IERC20(_D_YFI).safeTransfer(rewardForwarder, coveYfiAmount);
IERC20(_D_YFI).safeTransfer(_treasury, balance - coveYfiAmount);
}
/**
* @notice Claim YFI rewards from the reward pool and transfer them to the CoveYFI Reward Forwarder
*/
function claimExitRewards() external {
// Checks
address rewardForwarder = _coveYfiRewardForwarder;
if (rewardForwarder == address(0)) {
revert Errors.CoveYfiRewardForwarderNotSet();
}
// Interactions
// Ignore the returned amount and use the balance instead to ensure we capture
// any rewards claimed for this contract by other addresses
// https://etherscan.io/address/0xb287a1964AEE422911c7b8409f5E5A273c1412fA#code
// slither-disable-next-line unused-return
IYfiRewardPool(_YFI_REWARD_POOL).claim();
uint256 balance = IERC20(_YFI).balanceOf(address(this));
uint256 coveYfiAmount = (balance * _exitRewardSplit.coveYfi) / 1e18;
IERC20(_YFI).safeTransfer(rewardForwarder, coveYfiAmount);
IERC20(_YFI).safeTransfer(_treasury, balance - coveYfiAmount);
}
/**
* @notice Locks YFI tokens in the veYFI contract.
* @dev Locking YFI can be paused in case of emergencies by the admin or pauser roles.
* @param amount Amount of YFI tokens to lock.
* @return The locked balance information.
*/
function lockYfi(uint256 amount) external whenNotPaused returns (IVotingYFI.LockedBalance memory) {
// Checks
if (amount == 0) {
revert Errors.ZeroAmount();
}
if (!_shouldPerpetuallyLock) {
revert Errors.PerpetualLockDisabled();
}
// Interactions
emit LockYfi(msg.sender, amount);
IERC20(_YFI).safeTransferFrom(msg.sender, address(this), amount);
return IVotingYFI(_VE_YFI).modify_lock(amount, block.timestamp + 4 * 365 days + 4 weeks, address(this));
}
/**
* @notice Sets the address for the CoveYFI Reward Forwarder.
* @dev Can only be called by an address with the TIMELOCK_ROLE. Emits CoveYfiRewardForwarderSet event.
* @param forwarder The address of the new CoveYFI Reward Forwarder.
*/
function setCoveYfiRewardForwarder(address forwarder) external onlyRole(TIMELOCK_ROLE) {
// Checks
if (forwarder == address(0)) {
revert Errors.ZeroAddress();
}
// Effects
_setCoveYfiRewardForwarder(forwarder);
}
/**
* @notice Set treasury address. This address will receive a portion of the rewards
* @param treasury_ address to receive rewards
*/
function setTreasury(address treasury_) external onlyRole(TIMELOCK_ROLE) {
// Checks
if (treasury_ == address(0)) {
revert Errors.ZeroAddress();
}
// Effects
_setTreasury(treasury_);
}
/**
* @notice Sets the address for the SwapAndLock contract.
* @param newSwapAndLock Address of the SwapAndLock contract.
*/
function setSwapAndLock(address newSwapAndLock) external onlyRole(TIMELOCK_ROLE) {
// Checks
if (newSwapAndLock == address(0)) {
revert Errors.ZeroAddress();
}
_swapAndLock = newSwapAndLock;
emit SwapAndLockSet(newSwapAndLock);
}
/**
* @notice Set the reward split percentages
* @param gauge address of the gauge token
* @param treasuryPct percentage of rewards to treasury
* @param coveYfiPct percentage of rewards to coveYFI Reward Forwarder
* @param userPct percentage of rewards to user
* @param veYfiPct percentage of rewards to veYFI
* @dev Sum of percentages must equal to 1e18
*/
function setGaugeRewardSplit(
address gauge,
uint64 treasuryPct,
uint64 coveYfiPct,
uint64 userPct,
uint64 veYfiPct
)
external
onlyRole(TIMELOCK_ROLE)
{
_setGaugeRewardSplit(gauge, treasuryPct, coveYfiPct, userPct, veYfiPct);
}
/**
* @notice Set the reward split percentages for dYFI boost rewards
* @dev Sum of percentages must equal to 1e18
* @param treasuryPct percentage of rewards to treasury
* @param coveYfiPct percentage of rewards to CoveYFI Reward Forwarder
*/
function setBoostRewardSplit(uint128 treasuryPct, uint128 coveYfiPct) external onlyRole(TIMELOCK_ROLE) {
_setBoostRewardSplit(treasuryPct, coveYfiPct);
}
/**
* @notice Set the reward split percentages for YFI exit rewards
* @dev Sum of percentages must equal to 1e18
* @param treasuryPct percentage of rewards to treasury
* @param coveYfiPct percentage of rewards to CoveYFI Reward Forwarder
*/
function setExitRewardSplit(uint128 treasuryPct, uint128 coveYfiPct) external onlyRole(TIMELOCK_ROLE) {
_setExitRewardSplit(treasuryPct, coveYfiPct);
}
/**
* @notice Set the deposit limit for a gauge token. This is the ideal limit, which should be enforced by the
* depositing contracts.
* @param gaugeToken address of the gauge token
* @param limit maximum amount of tokens that can be deposited
*/
function setDepositLimit(address gaugeToken, uint256 limit) external onlyRole(TIMELOCK_ROLE) {
// Effects
emit DepositLimitSet(gaugeToken, limit);
depositLimit[gaugeToken] = limit;
}
/**
* @notice Delegates voting power to a given address
* @param id name of the space in snapshot to apply delegation. For yearn it is "veyfi.eth"
* @param delegate address to delegate voting power to
*/
function setSnapshotDelegate(bytes32 id, address delegate) external onlyRole(TIMELOCK_ROLE) {
// Checks
if (delegate == address(0)) {
revert Errors.ZeroAddress();
}
// Interactions
ISnapshotDelegateRegistry(_SNAPSHOT_DELEGATE_REGISTRY).setDelegate(id, delegate);
}
/**
* @notice Adds gauge rewards configuration.
* @param gauge Address of the gauge.
* @param stakingDelegateRewards Address of the StakingDelegateRewards contract.
*/
function addGaugeRewards(
address gauge,
address stakingDelegateRewards
)
external
nonReentrant
onlyRole(DEFAULT_ADMIN_ROLE)
{
// Checks
if (gauge == address(0) || stakingDelegateRewards == address(0)) {
revert Errors.ZeroAddress();
}
if (gaugeStakingRewards[gauge] != address(0)) {
revert Errors.GaugeRewardsAlreadyAdded();
}
// Effects
// 0% to treasury, 0% to coveYfi, 100% to user, 0% to SwapAndLock for increasing veYFI lock
_setGaugeRewardSplit(gauge, 0, 0, 1e18, 0);
// Effects & Interactions
_setGaugeRewards(gauge, stakingDelegateRewards);
}
/**
* @notice Updates gauge rewards configuration.
* @param gauge Address of the gauge.
* @param stakingDelegateRewards Address of the new StakingDelegateRewards contract.
*/
function updateGaugeRewards(
address gauge,
address stakingDelegateRewards
)
external
nonReentrant
onlyRole(TIMELOCK_ROLE)
{
// Checks
if (gauge == address(0) || stakingDelegateRewards == address(0)) {
revert Errors.ZeroAddress();
}
address previousStakingDelegateRewards = gaugeStakingRewards[gauge];
if (previousStakingDelegateRewards == address(0)) {
revert Errors.GaugeRewardsNotYetAdded();
}
if (previousStakingDelegateRewards == stakingDelegateRewards) {
revert Errors.GaugeRewardsAlreadyAdded();
}
// Effects & Interactions
_setGaugeRewards(gauge, stakingDelegateRewards);
}
/**
* @notice Set perpetual lock status
* @param lock if true, lock YFI for 4 years after each harvest
*/
function setPerpetualLock(bool lock) external onlyRole(TIMELOCK_ROLE) {
_setPerpetualLock(lock);
}
/**
* @notice early unlock veYFI and send YFI to treasury
*/
function earlyUnlock() external onlyRole(TIMELOCK_ROLE) {
// Checks
if (_shouldPerpetuallyLock) {
revert Errors.PerpetualLockEnabled();
}
// Interactions
IVotingYFI.Withdrawn memory withdrawn = IVotingYFI(_VE_YFI).withdraw();
IERC20(_YFI).safeTransfer(_treasury, withdrawn.amount);
}
/**
* @dev Pauses the contract. Only callable by PAUSER_ROLE or DEFAULT_ADMIN_ROLE.
*/
function pause() external {
if (!(hasRole(PAUSER_ROLE, msg.sender) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender))) {
revert Errors.Unauthorized();
}
_pause();
}
/**
* @dev Unpauses the contract. Only callable by DEFAULT_ADMIN_ROLE.
*/
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
/**
* @notice Execute arbitrary calls from the staking delegate. This function is callable
* by the admin role for future proofing. Target must not be YFI, dYFI, veYFI, or a known
* gauge token.
* @param target contract to call
* @param data calldata to execute the call with
* @param value call value
* @return result of the call
*/
function execute(
address target,
bytes calldata data,
uint256 value
)
external
payable
onlyRole(TIMELOCK_ROLE)
returns (bytes memory)
{
// Checks
if (blockedTargets[target]) {
revert Errors.ExecutionNotAllowed();
}
// Interactions
// slither-disable-start arbitrary-send-eth
// slither-disable-start low-level-calls
// solhint-disable-next-line avoid-low-level-calls
// nosemgrep: solidity.security.arbitrary-low-level-call.arbitrary-low-level-call
(bool success, bytes memory result) = target.call{ value: value }(data);
// slither-disable-end arbitrary-send-eth
// slither-disable-end low-level-calls
if (!success) {
revert Errors.ExecutionFailed();
}
return result;
}
/**
* @notice Get the available deposit limit for a gauge token
* @param gaugeToken The address of the gauge token
* @return Available deposit limit
*/
function availableDepositLimit(address gaugeToken) external view returns (uint256) {
uint256 currentTotalDeposited = totalDeposited[gaugeToken];
uint256 currentDepositLimit = depositLimit[gaugeToken];
if (currentTotalDeposited >= currentDepositLimit) {
return 0;
}
// Return the difference between the max total assets and the current total assets, an underflow is not possible
// due to the above check
unchecked {
return currentDepositLimit - currentTotalDeposited;
}
}
/**
* @notice Get the dYFI boost reward split
* @return BoostRewardSplit struct containing the treasury and coveYFI split.
*/
function getBoostRewardSplit() external view returns (BoostRewardSplit memory) {
return _boostRewardSplit;
}
/**
* @notice Get the YFI exit reward split
* @return ExitRewardSplit struct containing the treasury and coveYFI split.
*/
function getExitRewardSplit() external view returns (ExitRewardSplit memory) {
return _exitRewardSplit;
}
/**
* @notice Get the dYFI reward split for a gauge
* @param gauge Address of the gauge
* @return RewardSplit struct containing the treasury, coveYFI, user, and lock splits for the gauge
*/
function getGaugeRewardSplit(address gauge) external view returns (RewardSplit memory) {
return _gaugeRewardSplit[gauge];
}
/**
* @notice Get the address of the treasury
* @return The address of the treasury
*/
function treasury() external view returns (address) {
return _treasury;
}
/**
* @notice Get the address of the stored CoveYFI Reward Forwarder
* @return The address of the CoveYFI Reward Forwarder
*/
function coveYfiRewardForwarder() external view returns (address) {
return _coveYfiRewardForwarder;
}
/**
* @notice Get the address of the SwapAndLock contract
* @return The address of the SwapAndLock contract
*/
function swapAndLock() external view returns (address) {
return _swapAndLock;
}
/**
* @notice Get the perpetual lock status
* @return True if perpetual lock is enabled
*/
function shouldPerpetuallyLock() external view returns (bool) {
return _shouldPerpetuallyLock;
}
/**
* @notice Get the address of the YFI token
* @return The address of the YFI token
*/
function yfi() external pure returns (address) {
return _YFI;
}
/**
* @notice Get the address of the dYFI token
* @return The address of the dYFI token
*/
function dYfi() external pure returns (address) {
return _D_YFI;
}
/**
* @notice Get the address of the veYFI token
* @return The address of the veYFI token
*/
function veYfi() external pure returns (address) {
return _VE_YFI;
}
/**
* @dev Internal function to set the treasury address.
* @param treasury_ The address of the new treasury.
*/
function _setTreasury(address treasury_) internal {
_treasury = treasury_;
emit TreasurySet(treasury_);
}
/**
* @dev Internal function to set the CoveYFI Reward Forwarder address.
* @param forwarder The address of the CoveYFI Reward Forwarder.
*/
function _setCoveYfiRewardForwarder(address forwarder) internal {
_coveYfiRewardForwarder = forwarder;
emit CoveYfiRewardForwarderSet(forwarder);
}
/**
* @dev Internal function to set gauge rewards and reward receiver.
* @param gauge Address of the gauge.
* @param stakingDelegateRewards Address of the StakingDelegateRewards contract.
*/
function _setGaugeRewards(address gauge, address stakingDelegateRewards) internal {
gaugeStakingRewards[gauge] = stakingDelegateRewards;
blockedTargets[gauge] = true;
blockedTargets[stakingDelegateRewards] = true;
address receiver =
_GAUGE_REWARD_RECEIVER_IMPL.clone(abi.encodePacked(address(this), gauge, _D_YFI, stakingDelegateRewards));
gaugeRewardReceivers[gauge] = receiver;
blockedTargets[receiver] = true;
// Interactions
emit GaugeRewardsSet(gauge, stakingDelegateRewards, receiver);
GaugeRewardReceiver(receiver).initialize(msg.sender);
IGauge(gauge).setRecipient(receiver);
StakingDelegateRewards(stakingDelegateRewards).addStakingToken(gauge, receiver);
}
/**
* @dev Internal function to set the perpetual lock status.
* @param lock True for max lock.
*/
function _setPerpetualLock(bool lock) internal {
_shouldPerpetuallyLock = lock;
emit PerpetualLockSet(lock);
}
/**
* @dev Internal function to set the reward split for a gauge.
* @param gauge Address of the gauge.
* @param treasuryPct Percentage of rewards to the treasury.
* @param userPct Percentage of rewards to the user.
* @param lockPct Percentage of rewards to lock in veYFI.
*/
function _setGaugeRewardSplit(
address gauge,
uint64 treasuryPct,
uint64 coveYfiPct,
uint64 userPct,
uint64 lockPct
)
internal
{
if (uint256(treasuryPct) + coveYfiPct + userPct + lockPct != 1e18) {
revert Errors.InvalidRewardSplit();
}
if (treasuryPct > _MAX_TREASURY_PCT) {
revert Errors.TreasuryPctTooHigh();
}
RewardSplit memory newRewardSplit =
RewardSplit({ treasury: treasuryPct, coveYfi: coveYfiPct, user: userPct, lock: lockPct });
_gaugeRewardSplit[gauge] = newRewardSplit;
emit GaugeRewardSplitSet(gauge, newRewardSplit);
}
/**
* @dev Internal function to set the reward split for the dYFI boost rewards
* @param treasuryPct Percentage of rewards to the treasury.
* @param coveYfiPct Percentage of rewards to the CoveYFI Reward Forwarder.
*/
function _setBoostRewardSplit(uint128 treasuryPct, uint128 coveYfiPct) internal {
if (uint256(treasuryPct) + coveYfiPct != 1e18) {
revert Errors.InvalidRewardSplit();
}
if (treasuryPct > _MAX_TREASURY_PCT) {
revert Errors.TreasuryPctTooHigh();
}
_boostRewardSplit = BoostRewardSplit({ treasury: treasuryPct, coveYfi: coveYfiPct });
emit BoostRewardSplitSet(treasuryPct, coveYfiPct);
}
/**
* @dev Internal function to set the reward split for the YFI exit rewards (when veYFI holders early unlock their
* YFI, a portion of their YFI is distributed to other veYFI holders).
* @param treasuryPct Percentage of rewards to the treasury.
* @param coveYfiPct Percentage of rewards to the CoveYFI Reward Forwarder.
*/
function _setExitRewardSplit(uint128 treasuryPct, uint128 coveYfiPct) internal {
if (uint256(treasuryPct) + coveYfiPct != 1e18) {
revert Errors.InvalidRewardSplit();
}
if (treasuryPct > _MAX_TREASURY_PCT) {
revert Errors.TreasuryPctTooHigh();
}
_exitRewardSplit = ExitRewardSplit({ treasury: treasuryPct, coveYfi: coveYfiPct });
emit ExitRewardSplitSet(treasuryPct, coveYfiPct);
}
/**
* @dev Internal function to checkpoint a user's balance for a gauge.
* @param stakingDelegateReward Address of the StakingDelegateRewards contract.
* @param gauge Address of the gauge.
* @param user Address of the user.
* @param userBalance New balance of the user for the gauge.
*/
function _checkpointUserBalance(
address stakingDelegateReward,
address gauge,
address user,
uint256 userBalance,
uint256 currentTotalDeposited
)
internal
{
// In case of error, we don't want to block the entire tx so we try-catch
bytes memory data =
abi.encodeCall(StakingDelegateRewards.updateUserBalance, (user, gauge, userBalance, currentTotalDeposited));
uint256 gasBefore = gasleft();
// slither-disable-next-line missing-zero-check,return-bomb,low-level-calls
(bool success,) = address(stakingDelegateReward).call{ gas: gasBefore }(data);
// Protect against griefing via specifying low gas to trigger a revert in the callee
// https://ronan.eth.limo/blog/ethereum-gas-dangers/
// https://www.rareskills.io/post/eip-150-and-the-63-64-rule-for-gas
if (gasleft() <= gasBefore / 63) {
revert Errors.InsufficientGas();
}
if (!success) {
// slither-disable-next-line reentrancy-events
emit StakingDelegateRewardsFaulty(stakingDelegateReward, user, gauge, userBalance, currentTotalDeposited);
}
}
}
{
"compilationTarget": {
"src/YearnStakingDelegate.sol": "YearnStakingDelegate"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@crytic/properties/=lib/properties/",
":@openzeppelin-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
":@openzeppelin/=lib/openzeppelin-contracts/",
":Yearn-ERC4626-Router/=lib/Yearn-ERC4626-Router/src/",
":ds-test/=lib/forge-std/lib/ds-test/src/",
":forge-deploy/=lib/forge-deploy/contracts/",
":forge-std/=lib/forge-std/src/",
":permit2/=lib/permit2/src/",
":script/=script/",
":solmate/=lib/permit2/lib/solmate/src/",
":src/=src/",
":test/=test/",
":tokenized-strategy/=lib/tokenized-strategy/src/",
":yearn-vaults-v3/=lib/yearn-vaults-v3/contracts/"
]
}
[{"inputs":[{"internalType":"address","name":"gaugeRewardReceiverImpl","type":"address"},{"internalType":"address","name":"treasury_","type":"address"},{"internalType":"address","name":"admin","type":"address"},{"internalType":"address","name":"pauser","type":"address"},{"internalType":"address","name":"timelock","type":"address"}],"stateMutability":"payable","type":"constructor"},{"inputs":[],"name":"CoveYfiRewardForwarderNotSet","type":"error"},{"inputs":[],"name":"CreateFail","type":"error"},{"inputs":[],"name":"ExecutionFailed","type":"error"},{"inputs":[],"name":"ExecutionNotAllowed","type":"error"},{"inputs":[],"name":"GaugeRewardsAlreadyAdded","type":"error"},{"inputs":[],"name":"GaugeRewardsNotYetAdded","type":"error"},{"inputs":[],"name":"InsufficientGas","type":"error"},{"inputs":[],"name":"InvalidRewardSplit","type":"error"},{"inputs":[],"name":"PerpetualLockDisabled","type":"error"},{"inputs":[],"name":"PerpetualLockEnabled","type":"error"},{"inputs":[],"name":"SwapAndLockNotSet","type":"error"},{"inputs":[],"name":"TreasuryPctTooHigh","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[],"name":"ZeroAmount","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint128","name":"treasuryPct","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"coveYfiPct","type":"uint128"}],"name":"BoostRewardSplitSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"forwarder","type":"address"}],"name":"CoveYfiRewardForwarderSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"gauge","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTotalDeposited","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"gaugeToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"limit","type":"uint256"}],"name":"DepositLimitSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint128","name":"treasuryPct","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"coveYfiPct","type":"uint128"}],"name":"ExitRewardSplitSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"gauge","type":"address"},{"components":[{"internalType":"uint64","name":"treasury","type":"uint64"},{"internalType":"uint64","name":"coveYfi","type":"uint64"},{"internalType":"uint64","name":"user","type":"uint64"},{"internalType":"uint64","name":"lock","type":"uint64"}],"indexed":false,"internalType":"struct IYearnStakingDelegate.RewardSplit","name":"split","type":"tuple"}],"name":"GaugeRewardSplitSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"gauge","type":"address"},{"indexed":false,"internalType":"address","name":"stakingRewardsContract","type":"address"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"}],"name":"GaugeRewardsSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"LockYfi","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"shouldLock","type":"bool"}],"name":"PerpetualLockSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"stakingDelegateRewards","type":"address"},{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"address","name":"gauge","type":"address"},{"indexed":false,"internalType":"uint256","name":"currentUserBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"currentTotalDeposited","type":"uint256"}],"name":"StakingDelegateRewardsFaulty","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"swapAndLockContract","type":"address"}],"name":"SwapAndLockSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newTreasury","type":"address"}],"name":"TreasurySet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"gauge","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTotalDeposited","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEPOSITOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PAUSER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TIMELOCK_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"gauge","type":"address"},{"internalType":"address","name":"stakingDelegateRewards","type":"address"}],"name":"addGaugeRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"gaugeToken","type":"address"}],"name":"availableDepositLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"blockedTargets","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"claimBoostRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimExitRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"coveYfiRewardForwarder","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dYfi","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"gauge","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"depositLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"earlyUnlock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"execute","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"gaugeRewardReceivers","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"gaugeStakingRewards","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getBoostRewardSplit","outputs":[{"components":[{"internalType":"uint128","name":"treasury","type":"uint128"},{"internalType":"uint128","name":"coveYfi","type":"uint128"}],"internalType":"struct IYearnStakingDelegate.BoostRewardSplit","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getExitRewardSplit","outputs":[{"components":[{"internalType":"uint128","name":"treasury","type":"uint128"},{"internalType":"uint128","name":"coveYfi","type":"uint128"}],"internalType":"struct IYearnStakingDelegate.ExitRewardSplit","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"gauge","type":"address"}],"name":"getGaugeRewardSplit","outputs":[{"components":[{"internalType":"uint64","name":"treasury","type":"uint64"},{"internalType":"uint64","name":"coveYfi","type":"uint64"},{"internalType":"uint64","name":"user","type":"uint64"},{"internalType":"uint64","name":"lock","type":"uint64"}],"internalType":"struct IYearnStakingDelegate.RewardSplit","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"gauge","type":"address"}],"name":"harvest","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"lockYfi","outputs":[{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"}],"internalType":"struct IVotingYFI.LockedBalance","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"treasuryPct","type":"uint128"},{"internalType":"uint128","name":"coveYfiPct","type":"uint128"}],"name":"setBoostRewardSplit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"forwarder","type":"address"}],"name":"setCoveYfiRewardForwarder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"gaugeToken","type":"address"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"setDepositLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"treasuryPct","type":"uint128"},{"internalType":"uint128","name":"coveYfiPct","type":"uint128"}],"name":"setExitRewardSplit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"gauge","type":"address"},{"internalType":"uint64","name":"treasuryPct","type":"uint64"},{"internalType":"uint64","name":"coveYfiPct","type":"uint64"},{"internalType":"uint64","name":"userPct","type":"uint64"},{"internalType":"uint64","name":"veYfiPct","type":"uint64"}],"name":"setGaugeRewardSplit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"lock","type":"bool"}],"name":"setPerpetualLock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"id","type":"bytes32"},{"internalType":"address","name":"delegate","type":"address"}],"name":"setSnapshotDelegate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newSwapAndLock","type":"address"}],"name":"setSwapAndLock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"treasury_","type":"address"}],"name":"setTreasury","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"shouldPerpetuallyLock","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"swapAndLock","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"totalDeposited","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"treasury","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"gauge","type":"address"},{"internalType":"address","name":"stakingDelegateRewards","type":"address"}],"name":"updateGaugeRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"veYfi","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"gauge","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"gauge","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"yfi","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"pure","type":"function"}]