Created
May 7, 2024 17:08
-
-
Save jordaniza/6fdce883e89f05fb0757d5dcdb9605bb to your computer and use it in GitHub Desktop.
Flattened version of DAO.sol using yarn hardhat flatten
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sources flattened with hardhat v2.22.3 https://hardhat.org | |
// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT | |
// File @openzeppelin/contracts-upgradeable/interfaces/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified | |
* proxy whose upgrades are fully controlled by the current implementation. | |
*/ | |
interface IERC1822ProxiableUpgradeable { | |
/** | |
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation | |
* address. | |
* | |
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks | |
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this | |
* function revert if invoked through a proxy. | |
*/ | |
function proxiableUUID() external view returns (bytes32); | |
} | |
// File @openzeppelin/contracts-upgradeable/interfaces/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC. | |
* | |
* _Available since v4.8.3._ | |
*/ | |
interface IERC1967Upgradeable { | |
/** | |
* @dev Emitted when the implementation is upgraded. | |
*/ | |
event Upgraded(address indexed implementation); | |
/** | |
* @dev Emitted when the admin account has changed. | |
*/ | |
event AdminChanged(address previousAdmin, address newAdmin); | |
/** | |
* @dev Emitted when the beacon is changed. | |
*/ | |
event BeaconUpgraded(address indexed beacon); | |
} | |
// File @openzeppelin/contracts-upgradeable/proxy/beacon/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev This is the interface that {BeaconProxy} expects of its beacon. | |
*/ | |
interface IBeaconUpgradeable { | |
/** | |
* @dev Must return an address that can be used as a delegate call target. | |
* | |
* {BeaconProxy} will check that this address is a contract. | |
*/ | |
function implementation() external view returns (address); | |
} | |
// File @openzeppelin/contracts-upgradeable/utils/[email protected] | |
// Original license: 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); | |
} | |
} | |
} | |
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) | |
pragma solidity ^0.8.2; | |
/** | |
* @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; | |
} | |
} | |
// File @openzeppelin/contracts-upgradeable/utils/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol) | |
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js. | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Library for reading and writing primitive types to specific storage slots. | |
* | |
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. | |
* This library helps with reading and writing to such slots without the need for inline assembly. | |
* | |
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write. | |
* | |
* Example usage to set ERC1967 implementation slot: | |
* ```solidity | |
* contract ERC1967 { | |
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; | |
* | |
* function _getImplementation() internal view returns (address) { | |
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; | |
* } | |
* | |
* function _setImplementation(address newImplementation) internal { | |
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); | |
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; | |
* } | |
* } | |
* ``` | |
* | |
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._ | |
* _Available since v4.9 for `string`, `bytes`._ | |
*/ | |
library StorageSlotUpgradeable { | |
struct AddressSlot { | |
address value; | |
} | |
struct BooleanSlot { | |
bool value; | |
} | |
struct Bytes32Slot { | |
bytes32 value; | |
} | |
struct Uint256Slot { | |
uint256 value; | |
} | |
struct StringSlot { | |
string value; | |
} | |
struct BytesSlot { | |
bytes value; | |
} | |
/** | |
* @dev Returns an `AddressSlot` with member `value` located at `slot`. | |
*/ | |
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `BooleanSlot` with member `value` located at `slot`. | |
*/ | |
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`. | |
*/ | |
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `Uint256Slot` with member `value` located at `slot`. | |
*/ | |
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `StringSlot` with member `value` located at `slot`. | |
*/ | |
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `StringSlot` representation of the string storage pointer `store`. | |
*/ | |
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := store.slot | |
} | |
} | |
/** | |
* @dev Returns an `BytesSlot` with member `value` located at `slot`. | |
*/ | |
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. | |
*/ | |
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := store.slot | |
} | |
} | |
} | |
// File @openzeppelin/contracts-upgradeable/proxy/ERC1967/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol) | |
pragma solidity ^0.8.2; | |
/** | |
* @dev This abstract contract provides getters and event emitting update functions for | |
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. | |
* | |
* _Available since v4.1._ | |
*/ | |
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable { | |
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 | |
bytes32 private constant _ROLLBACK_SLOT = | |
0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; | |
/** | |
* @dev Storage slot with the address of the current implementation. | |
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is | |
* validated in the constructor. | |
*/ | |
bytes32 internal constant _IMPLEMENTATION_SLOT = | |
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; | |
function __ERC1967Upgrade_init() internal onlyInitializing {} | |
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {} | |
/** | |
* @dev Returns the current implementation address. | |
*/ | |
function _getImplementation() internal view returns (address) { | |
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; | |
} | |
/** | |
* @dev Stores a new address in the EIP1967 implementation slot. | |
*/ | |
function _setImplementation(address newImplementation) private { | |
require( | |
AddressUpgradeable.isContract(newImplementation), | |
"ERC1967: new implementation is not a contract" | |
); | |
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; | |
} | |
/** | |
* @dev Perform implementation upgrade | |
* | |
* Emits an {Upgraded} event. | |
*/ | |
function _upgradeTo(address newImplementation) internal { | |
_setImplementation(newImplementation); | |
emit Upgraded(newImplementation); | |
} | |
/** | |
* @dev Perform implementation upgrade with additional setup call. | |
* | |
* Emits an {Upgraded} event. | |
*/ | |
function _upgradeToAndCall( | |
address newImplementation, | |
bytes memory data, | |
bool forceCall | |
) internal { | |
_upgradeTo(newImplementation); | |
if (data.length > 0 || forceCall) { | |
AddressUpgradeable.functionDelegateCall(newImplementation, data); | |
} | |
} | |
/** | |
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. | |
* | |
* Emits an {Upgraded} event. | |
*/ | |
function _upgradeToAndCallUUPS( | |
address newImplementation, | |
bytes memory data, | |
bool forceCall | |
) internal { | |
// Upgrades from old implementations will perform a rollback test. This test requires the new | |
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing | |
// this special case will break upgrade paths from old UUPS implementation to new ones. | |
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { | |
_setImplementation(newImplementation); | |
} else { | |
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns ( | |
bytes32 slot | |
) { | |
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); | |
} catch { | |
revert("ERC1967Upgrade: new implementation is not UUPS"); | |
} | |
_upgradeToAndCall(newImplementation, data, forceCall); | |
} | |
} | |
/** | |
* @dev Storage slot with the admin of the contract. | |
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is | |
* validated in the constructor. | |
*/ | |
bytes32 internal constant _ADMIN_SLOT = | |
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; | |
/** | |
* @dev Returns the current admin. | |
*/ | |
function _getAdmin() internal view returns (address) { | |
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; | |
} | |
/** | |
* @dev Stores a new address in the EIP1967 admin slot. | |
*/ | |
function _setAdmin(address newAdmin) private { | |
require(newAdmin != address(0), "ERC1967: new admin is the zero address"); | |
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; | |
} | |
/** | |
* @dev Changes the admin of the proxy. | |
* | |
* Emits an {AdminChanged} event. | |
*/ | |
function _changeAdmin(address newAdmin) internal { | |
emit AdminChanged(_getAdmin(), newAdmin); | |
_setAdmin(newAdmin); | |
} | |
/** | |
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. | |
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. | |
*/ | |
bytes32 internal constant _BEACON_SLOT = | |
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; | |
/** | |
* @dev Returns the current beacon. | |
*/ | |
function _getBeacon() internal view returns (address) { | |
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; | |
} | |
/** | |
* @dev Stores a new beacon in the EIP1967 beacon slot. | |
*/ | |
function _setBeacon(address newBeacon) private { | |
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); | |
require( | |
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), | |
"ERC1967: beacon implementation is not a contract" | |
); | |
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; | |
} | |
/** | |
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does | |
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). | |
* | |
* Emits a {BeaconUpgraded} event. | |
*/ | |
function _upgradeBeaconToAndCall( | |
address newBeacon, | |
bytes memory data, | |
bool forceCall | |
) internal { | |
_setBeacon(newBeacon); | |
emit BeaconUpgraded(newBeacon); | |
if (data.length > 0 || forceCall) { | |
AddressUpgradeable.functionDelegateCall( | |
IBeaconUpgradeable(newBeacon).implementation(), | |
data | |
); | |
} | |
} | |
/** | |
* @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; | |
} | |
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an | |
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. | |
* | |
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is | |
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing | |
* `UUPSUpgradeable` with a custom implementation of upgrades. | |
* | |
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. | |
* | |
* _Available since v4.1._ | |
*/ | |
abstract contract UUPSUpgradeable is | |
Initializable, | |
IERC1822ProxiableUpgradeable, | |
ERC1967UpgradeUpgradeable | |
{ | |
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment | |
address private immutable __self = address(this); | |
/** | |
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is | |
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case | |
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a | |
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to | |
* fail. | |
*/ | |
modifier onlyProxy() { | |
require(address(this) != __self, "Function must be called through delegatecall"); | |
require(_getImplementation() == __self, "Function must be called through active proxy"); | |
_; | |
} | |
/** | |
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be | |
* callable on the implementing contract but not through proxies. | |
*/ | |
modifier notDelegated() { | |
require( | |
address(this) == __self, | |
"UUPSUpgradeable: must not be called through delegatecall" | |
); | |
_; | |
} | |
function __UUPSUpgradeable_init() internal onlyInitializing {} | |
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {} | |
/** | |
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the | |
* implementation. It is used to validate the implementation's compatibility when performing an upgrade. | |
* | |
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks | |
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this | |
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. | |
*/ | |
function proxiableUUID() external view virtual override notDelegated returns (bytes32) { | |
return _IMPLEMENTATION_SLOT; | |
} | |
/** | |
* @dev Upgrade the implementation of the proxy to `newImplementation`. | |
* | |
* Calls {_authorizeUpgrade}. | |
* | |
* Emits an {Upgraded} event. | |
* | |
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall | |
*/ | |
function upgradeTo(address newImplementation) public virtual onlyProxy { | |
_authorizeUpgrade(newImplementation); | |
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false); | |
} | |
/** | |
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call | |
* encoded in `data`. | |
* | |
* Calls {_authorizeUpgrade}. | |
* | |
* Emits an {Upgraded} event. | |
* | |
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall | |
*/ | |
function upgradeToAndCall( | |
address newImplementation, | |
bytes memory data | |
) public payable virtual onlyProxy { | |
_authorizeUpgrade(newImplementation); | |
_upgradeToAndCallUUPS(newImplementation, data, true); | |
} | |
/** | |
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by | |
* {upgradeTo} and {upgradeToAndCall}. | |
* | |
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. | |
* | |
* ```solidity | |
* function _authorizeUpgrade(address) internal override onlyOwner {} | |
* ``` | |
*/ | |
function _authorizeUpgrade(address newImplementation) internal virtual; | |
/** | |
* @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; | |
} | |
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] | |
// Original license: 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); | |
} | |
// File @openzeppelin/contracts-upgradeable/token/ERC1155/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev _Available since v3.1._ | |
*/ | |
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { | |
/** | |
* @dev Handles the receipt of a single ERC1155 token type. This function is | |
* called at the end of a `safeTransferFrom` after the balance has been updated. | |
* | |
* NOTE: To accept the transfer, this must return | |
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` | |
* (i.e. 0xf23a6e61, or its own function selector). | |
* | |
* @param operator The address which initiated the transfer (i.e. msg.sender) | |
* @param from The address which previously owned the token | |
* @param id The ID of the token being transferred | |
* @param value The amount of tokens being transferred | |
* @param data Additional data with no specified format | |
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed | |
*/ | |
function onERC1155Received( | |
address operator, | |
address from, | |
uint256 id, | |
uint256 value, | |
bytes calldata data | |
) external returns (bytes4); | |
/** | |
* @dev Handles the receipt of a multiple ERC1155 token types. This function | |
* is called at the end of a `safeBatchTransferFrom` after the balances have | |
* been updated. | |
* | |
* NOTE: To accept the transfer(s), this must return | |
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` | |
* (i.e. 0xbc197c81, or its own function selector). | |
* | |
* @param operator The address which initiated the batch transfer (i.e. msg.sender) | |
* @param from The address which previously owned the token | |
* @param ids An array containing ids of each token being transferred (order and length must match values array) | |
* @param values An array containing amounts of each token being transferred (order and length must match ids array) | |
* @param data Additional data with no specified format | |
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed | |
*/ | |
function onERC1155BatchReceived( | |
address operator, | |
address from, | |
uint256[] calldata ids, | |
uint256[] calldata values, | |
bytes calldata data | |
) external returns (bytes4); | |
} | |
// File @openzeppelin/contracts-upgradeable/token/ERC1155/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/IERC1155.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Required interface of an ERC1155 compliant contract, as defined in the | |
* https://eips.ethereum.org/EIPS/eip-1155[EIP]. | |
* | |
* _Available since v3.1._ | |
*/ | |
interface IERC1155Upgradeable is IERC165Upgradeable { | |
/** | |
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. | |
*/ | |
event TransferSingle( | |
address indexed operator, | |
address indexed from, | |
address indexed to, | |
uint256 id, | |
uint256 value | |
); | |
/** | |
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all | |
* transfers. | |
*/ | |
event TransferBatch( | |
address indexed operator, | |
address indexed from, | |
address indexed to, | |
uint256[] ids, | |
uint256[] values | |
); | |
/** | |
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to | |
* `approved`. | |
*/ | |
event ApprovalForAll(address indexed account, address indexed operator, bool approved); | |
/** | |
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. | |
* | |
* If an {URI} event was emitted for `id`, the standard | |
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value | |
* returned by {IERC1155MetadataURI-uri}. | |
*/ | |
event URI(string value, uint256 indexed id); | |
/** | |
* @dev Returns the amount of tokens of token type `id` owned by `account`. | |
* | |
* Requirements: | |
* | |
* - `account` cannot be the zero address. | |
*/ | |
function balanceOf(address account, uint256 id) external view returns (uint256); | |
/** | |
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. | |
* | |
* Requirements: | |
* | |
* - `accounts` and `ids` must have the same length. | |
*/ | |
function balanceOfBatch( | |
address[] calldata accounts, | |
uint256[] calldata ids | |
) external view returns (uint256[] memory); | |
/** | |
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, | |
* | |
* Emits an {ApprovalForAll} event. | |
* | |
* Requirements: | |
* | |
* - `operator` cannot be the caller. | |
*/ | |
function setApprovalForAll(address operator, bool approved) external; | |
/** | |
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens. | |
* | |
* See {setApprovalForAll}. | |
*/ | |
function isApprovedForAll(address account, address operator) external view returns (bool); | |
/** | |
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`. | |
* | |
* Emits a {TransferSingle} event. | |
* | |
* Requirements: | |
* | |
* - `to` cannot be the zero address. | |
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}. | |
* - `from` must have a balance of tokens of type `id` of at least `amount`. | |
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the | |
* acceptance magic value. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 id, | |
uint256 amount, | |
bytes calldata data | |
) external; | |
/** | |
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. | |
* | |
* Emits a {TransferBatch} event. | |
* | |
* Requirements: | |
* | |
* - `ids` and `amounts` must have the same length. | |
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the | |
* acceptance magic value. | |
*/ | |
function safeBatchTransferFrom( | |
address from, | |
address to, | |
uint256[] calldata ids, | |
uint256[] calldata amounts, | |
bytes calldata data | |
) external; | |
} | |
// File @openzeppelin/contracts-upgradeable/token/ERC20/extensions/[email protected] | |
// Original license: 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 IERC20PermitUpgradeable { | |
/** | |
* @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); | |
} | |
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] | |
// Original license: 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 IERC20Upgradeable { | |
/** | |
* @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); | |
} | |
// File @openzeppelin/contracts-upgradeable/token/ERC20/utils/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @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 SafeERC20Upgradeable { | |
using AddressUpgradeable 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(IERC20Upgradeable 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( | |
IERC20Upgradeable 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(IERC20Upgradeable 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( | |
IERC20Upgradeable 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( | |
IERC20Upgradeable 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(IERC20Upgradeable 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( | |
IERC20PermitUpgradeable 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(IERC20Upgradeable 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( | |
IERC20Upgradeable 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))) && | |
AddressUpgradeable.isContract(address(token)); | |
} | |
} | |
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @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; | |
} | |
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Storage.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Storage based implementation of the {IERC165} interface. | |
* | |
* Contracts may inherit from this and call {_registerInterface} to declare | |
* their support of an interface. | |
*/ | |
abstract contract ERC165StorageUpgradeable is Initializable, ERC165Upgradeable { | |
/** | |
* @dev Mapping of interface ids to whether or not it's supported. | |
*/ | |
mapping(bytes4 => bool) private _supportedInterfaces; | |
function __ERC165Storage_init() internal onlyInitializing {} | |
function __ERC165Storage_init_unchained() internal onlyInitializing {} | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { | |
return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId]; | |
} | |
/** | |
* @dev Registers the contract as an implementer of the interface defined by | |
* `interfaceId`. Support of the actual ERC165 interface is automatic and | |
* registering its interface id is not required. | |
* | |
* See {IERC165-supportsInterface}. | |
* | |
* Requirements: | |
* | |
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). | |
*/ | |
function _registerInterface(bytes4 interfaceId) internal virtual { | |
require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); | |
_supportedInterfaces[interfaceId] = true; | |
} | |
/** | |
* @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; | |
} | |
// File @openzeppelin/contracts/utils/[email protected] | |
// Original license: 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; | |
} | |
} | |
// File @openzeppelin/contracts/access/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Contract module which provides a basic access control mechanism, where | |
* there is an account (an owner) that can be granted exclusive access to | |
* specific functions. | |
* | |
* By default, the owner account will be the one that deploys the contract. This | |
* can later be changed with {transferOwnership}. | |
* | |
* This module is used through inheritance. It will make available the modifier | |
* `onlyOwner`, which can be applied to your functions to restrict their use to | |
* the owner. | |
*/ | |
abstract contract Ownable is Context { | |
address private _owner; | |
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); | |
/** | |
* @dev Initializes the contract setting the deployer as the initial owner. | |
*/ | |
constructor() { | |
_transferOwnership(_msgSender()); | |
} | |
/** | |
* @dev Throws if called by any account other than the owner. | |
*/ | |
modifier onlyOwner() { | |
_checkOwner(); | |
_; | |
} | |
/** | |
* @dev Returns the address of the current owner. | |
*/ | |
function owner() public view virtual returns (address) { | |
return _owner; | |
} | |
/** | |
* @dev Throws if the sender is not the owner. | |
*/ | |
function _checkOwner() internal view virtual { | |
require(owner() == _msgSender(), "Ownable: caller is not the owner"); | |
} | |
/** | |
* @dev Leaves the contract without owner. It will not be possible to call | |
* `onlyOwner` functions. Can only be called by the current owner. | |
* | |
* NOTE: Renouncing ownership will leave the contract without an owner, | |
* thereby disabling any functionality that is only available to the owner. | |
*/ | |
function renounceOwnership() public virtual onlyOwner { | |
_transferOwnership(address(0)); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
* Can only be called by the current owner. | |
*/ | |
function transferOwnership(address newOwner) public virtual onlyOwner { | |
require(newOwner != address(0), "Ownable: new owner is the zero address"); | |
_transferOwnership(newOwner); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
* Internal function without access restriction. | |
*/ | |
function _transferOwnership(address newOwner) internal virtual { | |
address oldOwner = _owner; | |
_owner = newOwner; | |
emit OwnershipTransferred(oldOwner, newOwner); | |
} | |
} | |
// File @openzeppelin/contracts/proxy/beacon/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev This is the interface that {BeaconProxy} expects of its beacon. | |
*/ | |
interface IBeacon { | |
/** | |
* @dev Must return an address that can be used as a delegate call target. | |
* | |
* {BeaconProxy} will check that this address is a contract. | |
*/ | |
function implementation() external view returns (address); | |
} | |
// File @openzeppelin/contracts/interfaces/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified | |
* proxy whose upgrades are fully controlled by the current implementation. | |
*/ | |
interface IERC1822Proxiable { | |
/** | |
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation | |
* address. | |
* | |
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks | |
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this | |
* function revert if invoked through a proxy. | |
*/ | |
function proxiableUUID() external view returns (bytes32); | |
} | |
// File @openzeppelin/contracts/interfaces/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC. | |
* | |
* _Available since v4.8.3._ | |
*/ | |
interface IERC1967 { | |
/** | |
* @dev Emitted when the implementation is upgraded. | |
*/ | |
event Upgraded(address indexed implementation); | |
/** | |
* @dev Emitted when the admin account has changed. | |
*/ | |
event AdminChanged(address previousAdmin, address newAdmin); | |
/** | |
* @dev Emitted when the beacon is changed. | |
*/ | |
event BeaconUpgraded(address indexed beacon); | |
} | |
// File @openzeppelin/contracts/utils/[email protected] | |
// Original license: 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); | |
} | |
} | |
} | |
// File @openzeppelin/contracts/utils/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol) | |
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js. | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Library for reading and writing primitive types to specific storage slots. | |
* | |
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. | |
* This library helps with reading and writing to such slots without the need for inline assembly. | |
* | |
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write. | |
* | |
* Example usage to set ERC1967 implementation slot: | |
* ```solidity | |
* contract ERC1967 { | |
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; | |
* | |
* function _getImplementation() internal view returns (address) { | |
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; | |
* } | |
* | |
* function _setImplementation(address newImplementation) internal { | |
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); | |
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; | |
* } | |
* } | |
* ``` | |
* | |
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._ | |
* _Available since v4.9 for `string`, `bytes`._ | |
*/ | |
library StorageSlot { | |
struct AddressSlot { | |
address value; | |
} | |
struct BooleanSlot { | |
bool value; | |
} | |
struct Bytes32Slot { | |
bytes32 value; | |
} | |
struct Uint256Slot { | |
uint256 value; | |
} | |
struct StringSlot { | |
string value; | |
} | |
struct BytesSlot { | |
bytes value; | |
} | |
/** | |
* @dev Returns an `AddressSlot` with member `value` located at `slot`. | |
*/ | |
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `BooleanSlot` with member `value` located at `slot`. | |
*/ | |
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`. | |
*/ | |
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `Uint256Slot` with member `value` located at `slot`. | |
*/ | |
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `StringSlot` with member `value` located at `slot`. | |
*/ | |
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `StringSlot` representation of the string storage pointer `store`. | |
*/ | |
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := store.slot | |
} | |
} | |
/** | |
* @dev Returns an `BytesSlot` with member `value` located at `slot`. | |
*/ | |
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := slot | |
} | |
} | |
/** | |
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. | |
*/ | |
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { | |
/// @solidity memory-safe-assembly | |
assembly { | |
r.slot := store.slot | |
} | |
} | |
} | |
// File @openzeppelin/contracts/proxy/ERC1967/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol) | |
pragma solidity ^0.8.2; | |
/** | |
* @dev This abstract contract provides getters and event emitting update functions for | |
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. | |
* | |
* _Available since v4.1._ | |
*/ | |
abstract contract ERC1967Upgrade is IERC1967 { | |
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 | |
bytes32 private constant _ROLLBACK_SLOT = | |
0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; | |
/** | |
* @dev Storage slot with the address of the current implementation. | |
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is | |
* validated in the constructor. | |
*/ | |
bytes32 internal constant _IMPLEMENTATION_SLOT = | |
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; | |
/** | |
* @dev Returns the current implementation address. | |
*/ | |
function _getImplementation() internal view returns (address) { | |
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; | |
} | |
/** | |
* @dev Stores a new address in the EIP1967 implementation slot. | |
*/ | |
function _setImplementation(address newImplementation) private { | |
require( | |
Address.isContract(newImplementation), | |
"ERC1967: new implementation is not a contract" | |
); | |
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; | |
} | |
/** | |
* @dev Perform implementation upgrade | |
* | |
* Emits an {Upgraded} event. | |
*/ | |
function _upgradeTo(address newImplementation) internal { | |
_setImplementation(newImplementation); | |
emit Upgraded(newImplementation); | |
} | |
/** | |
* @dev Perform implementation upgrade with additional setup call. | |
* | |
* Emits an {Upgraded} event. | |
*/ | |
function _upgradeToAndCall( | |
address newImplementation, | |
bytes memory data, | |
bool forceCall | |
) internal { | |
_upgradeTo(newImplementation); | |
if (data.length > 0 || forceCall) { | |
Address.functionDelegateCall(newImplementation, data); | |
} | |
} | |
/** | |
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. | |
* | |
* Emits an {Upgraded} event. | |
*/ | |
function _upgradeToAndCallUUPS( | |
address newImplementation, | |
bytes memory data, | |
bool forceCall | |
) internal { | |
// Upgrades from old implementations will perform a rollback test. This test requires the new | |
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing | |
// this special case will break upgrade paths from old UUPS implementation to new ones. | |
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { | |
_setImplementation(newImplementation); | |
} else { | |
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { | |
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); | |
} catch { | |
revert("ERC1967Upgrade: new implementation is not UUPS"); | |
} | |
_upgradeToAndCall(newImplementation, data, forceCall); | |
} | |
} | |
/** | |
* @dev Storage slot with the admin of the contract. | |
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is | |
* validated in the constructor. | |
*/ | |
bytes32 internal constant _ADMIN_SLOT = | |
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; | |
/** | |
* @dev Returns the current admin. | |
*/ | |
function _getAdmin() internal view returns (address) { | |
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; | |
} | |
/** | |
* @dev Stores a new address in the EIP1967 admin slot. | |
*/ | |
function _setAdmin(address newAdmin) private { | |
require(newAdmin != address(0), "ERC1967: new admin is the zero address"); | |
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; | |
} | |
/** | |
* @dev Changes the admin of the proxy. | |
* | |
* Emits an {AdminChanged} event. | |
*/ | |
function _changeAdmin(address newAdmin) internal { | |
emit AdminChanged(_getAdmin(), newAdmin); | |
_setAdmin(newAdmin); | |
} | |
/** | |
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. | |
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. | |
*/ | |
bytes32 internal constant _BEACON_SLOT = | |
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; | |
/** | |
* @dev Returns the current beacon. | |
*/ | |
function _getBeacon() internal view returns (address) { | |
return StorageSlot.getAddressSlot(_BEACON_SLOT).value; | |
} | |
/** | |
* @dev Stores a new beacon in the EIP1967 beacon slot. | |
*/ | |
function _setBeacon(address newBeacon) private { | |
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); | |
require( | |
Address.isContract(IBeacon(newBeacon).implementation()), | |
"ERC1967: beacon implementation is not a contract" | |
); | |
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; | |
} | |
/** | |
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does | |
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). | |
* | |
* Emits a {BeaconUpgraded} event. | |
*/ | |
function _upgradeBeaconToAndCall( | |
address newBeacon, | |
bytes memory data, | |
bool forceCall | |
) internal { | |
_setBeacon(newBeacon); | |
emit BeaconUpgraded(newBeacon); | |
if (data.length > 0 || forceCall) { | |
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); | |
} | |
} | |
} | |
// File @openzeppelin/contracts/proxy/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM | |
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to | |
* be specified by overriding the virtual {_implementation} function. | |
* | |
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a | |
* different contract through the {_delegate} function. | |
* | |
* The success and return data of the delegated call will be returned back to the caller of the proxy. | |
*/ | |
abstract contract Proxy { | |
/** | |
* @dev Delegates the current call to `implementation`. | |
* | |
* This function does not return to its internal call site, it will return directly to the external caller. | |
*/ | |
function _delegate(address implementation) internal virtual { | |
assembly { | |
// Copy msg.data. We take full control of memory in this inline assembly | |
// block because it will not return to Solidity code. We overwrite the | |
// Solidity scratch pad at memory position 0. | |
calldatacopy(0, 0, calldatasize()) | |
// Call the implementation. | |
// out and outsize are 0 because we don't know the size yet. | |
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) | |
// Copy the returned data. | |
returndatacopy(0, 0, returndatasize()) | |
switch result | |
// delegatecall returns 0 on error. | |
case 0 { | |
revert(0, returndatasize()) | |
} | |
default { | |
return(0, returndatasize()) | |
} | |
} | |
} | |
/** | |
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback function | |
* and {_fallback} should delegate. | |
*/ | |
function _implementation() internal view virtual returns (address); | |
/** | |
* @dev Delegates the current call to the address returned by `_implementation()`. | |
* | |
* This function does not return to its internal call site, it will return directly to the external caller. | |
*/ | |
function _fallback() internal virtual { | |
_beforeFallback(); | |
_delegate(_implementation()); | |
} | |
/** | |
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other | |
* function in the contract matches the call data. | |
*/ | |
fallback() external payable virtual { | |
_fallback(); | |
} | |
/** | |
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data | |
* is empty. | |
*/ | |
receive() external payable virtual { | |
_fallback(); | |
} | |
/** | |
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` | |
* call, or as part of the Solidity `fallback` or `receive` functions. | |
* | |
* If overridden should call `super._beforeFallback()`. | |
*/ | |
function _beforeFallback() internal virtual {} | |
} | |
// File @openzeppelin/contracts/proxy/beacon/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}. | |
* | |
* The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't | |
* conflict with the storage layout of the implementation behind the proxy. | |
* | |
* _Available since v3.4._ | |
*/ | |
contract BeaconProxy is Proxy, ERC1967Upgrade { | |
/** | |
* @dev Initializes the proxy with `beacon`. | |
* | |
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This | |
* will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity | |
* constructor. | |
* | |
* Requirements: | |
* | |
* - `beacon` must be a contract with the interface {IBeacon}. | |
*/ | |
constructor(address beacon, bytes memory data) payable { | |
_upgradeBeaconToAndCall(beacon, data, false); | |
} | |
/** | |
* @dev Returns the current beacon address. | |
*/ | |
function _beacon() internal view virtual returns (address) { | |
return _getBeacon(); | |
} | |
/** | |
* @dev Returns the current implementation address of the associated beacon. | |
*/ | |
function _implementation() internal view virtual override returns (address) { | |
return IBeacon(_getBeacon()).implementation(); | |
} | |
/** | |
* @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. | |
* | |
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. | |
* | |
* Requirements: | |
* | |
* - `beacon` must be a contract. | |
* - The implementation returned by `beacon` must be a contract. | |
*/ | |
function _setBeacon(address beacon, bytes memory data) internal virtual { | |
_upgradeBeaconToAndCall(beacon, data, false); | |
} | |
} | |
// File @openzeppelin/contracts/proxy/beacon/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their | |
* implementation contract, which is where they will delegate all function calls. | |
* | |
* An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. | |
*/ | |
contract UpgradeableBeacon is IBeacon, Ownable { | |
address private _implementation; | |
/** | |
* @dev Emitted when the implementation returned by the beacon is changed. | |
*/ | |
event Upgraded(address indexed implementation); | |
/** | |
* @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the | |
* beacon. | |
*/ | |
constructor(address implementation_) { | |
_setImplementation(implementation_); | |
} | |
/** | |
* @dev Returns the current implementation address. | |
*/ | |
function implementation() public view virtual override returns (address) { | |
return _implementation; | |
} | |
/** | |
* @dev Upgrades the beacon to a new implementation. | |
* | |
* Emits an {Upgraded} event. | |
* | |
* Requirements: | |
* | |
* - msg.sender must be the owner of the contract. | |
* - `newImplementation` must be a contract. | |
*/ | |
function upgradeTo(address newImplementation) public virtual onlyOwner { | |
_setImplementation(newImplementation); | |
emit Upgraded(newImplementation); | |
} | |
/** | |
* @dev Sets the implementation contract address for this beacon | |
* | |
* Requirements: | |
* | |
* - `newImplementation` must be a contract. | |
*/ | |
function _setImplementation(address newImplementation) private { | |
require( | |
Address.isContract(newImplementation), | |
"UpgradeableBeacon: implementation is not a contract" | |
); | |
_implementation = newImplementation; | |
} | |
} | |
// File @openzeppelin/contracts/proxy/ERC1967/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an | |
* implementation address that can be changed. This address is stored in storage in the location specified by | |
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the | |
* implementation behind the proxy. | |
*/ | |
contract ERC1967Proxy is Proxy, ERC1967Upgrade { | |
/** | |
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. | |
* | |
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded | |
* function call, and allows initializing the storage of the proxy like a Solidity constructor. | |
*/ | |
constructor(address _logic, bytes memory _data) payable { | |
_upgradeToAndCall(_logic, _data, false); | |
} | |
/** | |
* @dev Returns the current implementation address. | |
*/ | |
function _implementation() internal view virtual override returns (address impl) { | |
return ERC1967Upgrade._getImplementation(); | |
} | |
} | |
// File @openzeppelin/contracts/proxy/transparent/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/transparent/TransparentUpgradeableProxy.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy} | |
* does not implement this interface directly, and some of its functions are implemented by an internal dispatch | |
* mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not | |
* include them in the ABI so this interface must be used to interact with it. | |
*/ | |
interface ITransparentUpgradeableProxy is IERC1967 { | |
function admin() external view returns (address); | |
function implementation() external view returns (address); | |
function changeAdmin(address) external; | |
function upgradeTo(address) external; | |
function upgradeToAndCall(address, bytes memory) external payable; | |
} | |
/** | |
* @dev This contract implements a proxy that is upgradeable by an admin. | |
* | |
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector | |
* clashing], which can potentially be used in an attack, this contract uses the | |
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two | |
* things that go hand in hand: | |
* | |
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if | |
* that call matches one of the admin functions exposed by the proxy itself. | |
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the | |
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says | |
* "admin cannot fallback to proxy target". | |
* | |
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing | |
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due | |
* to sudden errors when trying to call a function from the proxy implementation. | |
* | |
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, | |
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. | |
* | |
* NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not | |
* inherit from that interface, and instead the admin functions are implicitly implemented using a custom dispatch | |
* mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to | |
* fully implement transparency without decoding reverts caused by selector clashes between the proxy and the | |
* implementation. | |
* | |
* WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the compiler | |
* will not check that there are no selector conflicts, due to the note above. A selector clash between any new function | |
* and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This could | |
* render the admin operations inaccessible, which could prevent upgradeability. Transparency may also be compromised. | |
*/ | |
contract TransparentUpgradeableProxy is ERC1967Proxy { | |
/** | |
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and | |
* optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. | |
*/ | |
constructor( | |
address _logic, | |
address admin_, | |
bytes memory _data | |
) payable ERC1967Proxy(_logic, _data) { | |
_changeAdmin(admin_); | |
} | |
/** | |
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. | |
* | |
* CAUTION: This modifier is deprecated, as it could cause issues if the modified function has arguments, and the | |
* implementation provides a function with the same selector. | |
*/ | |
modifier ifAdmin() { | |
if (msg.sender == _getAdmin()) { | |
_; | |
} else { | |
_fallback(); | |
} | |
} | |
/** | |
* @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior | |
*/ | |
function _fallback() internal virtual override { | |
if (msg.sender == _getAdmin()) { | |
bytes memory ret; | |
bytes4 selector = msg.sig; | |
if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) { | |
ret = _dispatchUpgradeTo(); | |
} else if (selector == ITransparentUpgradeableProxy.upgradeToAndCall.selector) { | |
ret = _dispatchUpgradeToAndCall(); | |
} else if (selector == ITransparentUpgradeableProxy.changeAdmin.selector) { | |
ret = _dispatchChangeAdmin(); | |
} else if (selector == ITransparentUpgradeableProxy.admin.selector) { | |
ret = _dispatchAdmin(); | |
} else if (selector == ITransparentUpgradeableProxy.implementation.selector) { | |
ret = _dispatchImplementation(); | |
} else { | |
revert("TransparentUpgradeableProxy: admin cannot fallback to proxy target"); | |
} | |
assembly { | |
return(add(ret, 0x20), mload(ret)) | |
} | |
} else { | |
super._fallback(); | |
} | |
} | |
/** | |
* @dev Returns the current admin. | |
* | |
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the | |
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. | |
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` | |
*/ | |
function _dispatchAdmin() private returns (bytes memory) { | |
_requireZeroValue(); | |
address admin = _getAdmin(); | |
return abi.encode(admin); | |
} | |
/** | |
* @dev Returns the current implementation. | |
* | |
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the | |
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. | |
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` | |
*/ | |
function _dispatchImplementation() private returns (bytes memory) { | |
_requireZeroValue(); | |
address implementation = _implementation(); | |
return abi.encode(implementation); | |
} | |
/** | |
* @dev Changes the admin of the proxy. | |
* | |
* Emits an {AdminChanged} event. | |
*/ | |
function _dispatchChangeAdmin() private returns (bytes memory) { | |
_requireZeroValue(); | |
address newAdmin = abi.decode(msg.data[4:], (address)); | |
_changeAdmin(newAdmin); | |
return ""; | |
} | |
/** | |
* @dev Upgrade the implementation of the proxy. | |
*/ | |
function _dispatchUpgradeTo() private returns (bytes memory) { | |
_requireZeroValue(); | |
address newImplementation = abi.decode(msg.data[4:], (address)); | |
_upgradeToAndCall(newImplementation, bytes(""), false); | |
return ""; | |
} | |
/** | |
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified | |
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the | |
* proxied contract. | |
*/ | |
function _dispatchUpgradeToAndCall() private returns (bytes memory) { | |
(address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes)); | |
_upgradeToAndCall(newImplementation, data, true); | |
return ""; | |
} | |
/** | |
* @dev Returns the current admin. | |
* | |
* CAUTION: This function is deprecated. Use {ERC1967Upgrade-_getAdmin} instead. | |
*/ | |
function _admin() internal view virtual returns (address) { | |
return _getAdmin(); | |
} | |
/** | |
* @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to | |
* emulate some proxy functions being non-payable while still allowing value to pass through. | |
*/ | |
function _requireZeroValue() private { | |
require(msg.value == 0); | |
} | |
} | |
// File @openzeppelin/contracts/proxy/transparent/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.8.3) (proxy/transparent/ProxyAdmin.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an | |
* explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. | |
*/ | |
contract ProxyAdmin is Ownable { | |
/** | |
* @dev Returns the current implementation of `proxy`. | |
* | |
* Requirements: | |
* | |
* - This contract must be the admin of `proxy`. | |
*/ | |
function getProxyImplementation( | |
ITransparentUpgradeableProxy proxy | |
) public view virtual returns (address) { | |
// We need to manually run the static call since the getter cannot be flagged as view | |
// bytes4(keccak256("implementation()")) == 0x5c60da1b | |
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); | |
require(success); | |
return abi.decode(returndata, (address)); | |
} | |
/** | |
* @dev Returns the current admin of `proxy`. | |
* | |
* Requirements: | |
* | |
* - This contract must be the admin of `proxy`. | |
*/ | |
function getProxyAdmin( | |
ITransparentUpgradeableProxy proxy | |
) public view virtual returns (address) { | |
// We need to manually run the static call since the getter cannot be flagged as view | |
// bytes4(keccak256("admin()")) == 0xf851a440 | |
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); | |
require(success); | |
return abi.decode(returndata, (address)); | |
} | |
/** | |
* @dev Changes the admin of `proxy` to `newAdmin`. | |
* | |
* Requirements: | |
* | |
* - This contract must be the current admin of `proxy`. | |
*/ | |
function changeProxyAdmin( | |
ITransparentUpgradeableProxy proxy, | |
address newAdmin | |
) public virtual onlyOwner { | |
proxy.changeAdmin(newAdmin); | |
} | |
/** | |
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. | |
* | |
* Requirements: | |
* | |
* - This contract must be the admin of `proxy`. | |
*/ | |
function upgrade( | |
ITransparentUpgradeableProxy proxy, | |
address implementation | |
) public virtual onlyOwner { | |
proxy.upgradeTo(implementation); | |
} | |
/** | |
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See | |
* {TransparentUpgradeableProxy-upgradeToAndCall}. | |
* | |
* Requirements: | |
* | |
* - This contract must be the admin of `proxy`. | |
*/ | |
function upgradeAndCall( | |
ITransparentUpgradeableProxy proxy, | |
address implementation, | |
bytes memory data | |
) public payable virtual onlyOwner { | |
proxy.upgradeToAndCall{value: msg.value}(implementation, data); | |
} | |
} | |
// File @openzeppelin/contracts/utils/introspection/[email protected] | |
// Original license: 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); | |
} | |
// File @openzeppelin/contracts/utils/introspection/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @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; | |
} | |
} | |
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @title ERC721 token receiver interface | |
* @dev Interface for any contract that wants to support safeTransfers | |
* from ERC721 asset contracts. | |
*/ | |
interface IERC721ReceiverUpgradeable { | |
/** | |
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} | |
* by `operator` from `from`, this function is called. | |
* | |
* It must return its Solidity selector to confirm the token transfer. | |
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. | |
* | |
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. | |
*/ | |
function onERC721Received( | |
address operator, | |
address from, | |
uint256 tokenId, | |
bytes calldata data | |
) external returns (bytes4); | |
} | |
// File @openzeppelin/contracts/interfaces/[email protected] | |
// Original license: SPDX_License_Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Interface of the ERC1271 standard signature validation method for | |
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. | |
* | |
* _Available since v4.1._ | |
*/ | |
interface IERC1271 { | |
/** | |
* @dev Should return whether the signature provided is valid for the provided data | |
* @param hash Hash of the data to be signed | |
* @param signature Signature byte array associated with _data | |
*/ | |
function isValidSignature( | |
bytes32 hash, | |
bytes memory signature | |
) external view returns (bytes4 magicValue); | |
} | |
// File src/core/dao/IDAO.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity ^0.8.8; | |
/// @title IDAO | |
/// @author Aragon Association - 2022-2023 | |
/// @notice The interface required for DAOs within the Aragon App DAO framework. | |
interface IDAO { | |
/// @notice The action struct to be consumed by the DAO's `execute` function resulting in an external call. | |
/// @param to The address to call. | |
/// @param value The native token value to be sent with the call. | |
/// @param data The bytes-encoded function selector and calldata for the call. | |
struct Action { | |
address to; | |
uint256 value; | |
bytes data; | |
} | |
/// @notice Checks if an address has permission on a contract via a permission identifier and considers if `ANY_ADDRESS` was used in the granting process. | |
/// @param _where The address of the contract. | |
/// @param _who The address of a EOA or contract to give the permissions. | |
/// @param _permissionId The permission identifier. | |
/// @param _data The optional data passed to the `PermissionCondition` registered. | |
/// @return Returns true if the address has permission, false if not. | |
function hasPermission( | |
address _where, | |
address _who, | |
bytes32 _permissionId, | |
bytes memory _data | |
) external view returns (bool); | |
/// @notice Updates the DAO metadata (e.g., an IPFS hash). | |
/// @param _metadata The IPFS hash of the new metadata object. | |
function setMetadata(bytes calldata _metadata) external; | |
/// @notice Emitted when the DAO metadata is updated. | |
/// @param metadata The IPFS hash of the new metadata object. | |
event MetadataSet(bytes metadata); | |
/// @notice Executes a list of actions. If a zero allow-failure map is provided, a failing action reverts the entire execution. If a non-zero allow-failure map is provided, allowed actions can fail without the entire call being reverted. | |
/// @param _callId The ID of the call. The definition of the value of `callId` is up to the calling contract and can be used, e.g., as a nonce. | |
/// @param _actions The array of actions. | |
/// @param _allowFailureMap A bitmap allowing execution to succeed, even if individual actions might revert. If the bit at index `i` is 1, the execution succeeds even if the `i`th action reverts. A failure map value of 0 requires every action to not revert. | |
/// @return The array of results obtained from the executed actions in `bytes`. | |
/// @return The resulting failure map containing the actions have actually failed. | |
function execute( | |
bytes32 _callId, | |
Action[] memory _actions, | |
uint256 _allowFailureMap | |
) external returns (bytes[] memory, uint256); | |
/// @notice Emitted when a proposal is executed. | |
/// @param actor The address of the caller. | |
/// @param callId The ID of the call. | |
/// @param actions The array of actions executed. | |
/// @param allowFailureMap The allow failure map encoding which actions are allowed to fail. | |
/// @param failureMap The failure map encoding which actions have failed. | |
/// @param execResults The array with the results of the executed actions. | |
/// @dev The value of `callId` is defined by the component/contract calling the execute function. A `Plugin` implementation can use it, for example, as a nonce. | |
event Executed( | |
address indexed actor, | |
bytes32 callId, | |
Action[] actions, | |
uint256 allowFailureMap, | |
uint256 failureMap, | |
bytes[] execResults | |
); | |
/// @notice Emitted when a standard callback is registered. | |
/// @param interfaceId The ID of the interface. | |
/// @param callbackSelector The selector of the callback function. | |
/// @param magicNumber The magic number to be registered for the callback function selector. | |
event StandardCallbackRegistered( | |
bytes4 interfaceId, | |
bytes4 callbackSelector, | |
bytes4 magicNumber | |
); | |
/// @notice Deposits (native) tokens to the DAO contract with a reference string. | |
/// @param _token The address of the token or address(0) in case of the native token. | |
/// @param _amount The amount of tokens to deposit. | |
/// @param _reference The reference describing the deposit reason. | |
function deposit(address _token, uint256 _amount, string calldata _reference) external payable; | |
/// @notice Emitted when a token deposit has been made to the DAO. | |
/// @param sender The address of the sender. | |
/// @param token The address of the deposited token. | |
/// @param amount The amount of tokens deposited. | |
/// @param _reference The reference describing the deposit reason. | |
event Deposited( | |
address indexed sender, | |
address indexed token, | |
uint256 amount, | |
string _reference | |
); | |
/// @notice Emitted when a native token deposit has been made to the DAO. | |
/// @dev This event is intended to be emitted in the `receive` function and is therefore bound by the gas limitations for `send`/`transfer` calls introduced by [ERC-2929](https://eips.ethereum.org/EIPS/eip-2929). | |
/// @param sender The address of the sender. | |
/// @param amount The amount of native tokens deposited. | |
event NativeTokenDeposited(address sender, uint256 amount); | |
/// @notice Setter for the trusted forwarder verifying the meta transaction. | |
/// @param _trustedForwarder The trusted forwarder address. | |
function setTrustedForwarder(address _trustedForwarder) external; | |
/// @notice Getter for the trusted forwarder verifying the meta transaction. | |
/// @return The trusted forwarder address. | |
function getTrustedForwarder() external view returns (address); | |
/// @notice Emitted when a new TrustedForwarder is set on the DAO. | |
/// @param forwarder the new forwarder address. | |
event TrustedForwarderSet(address forwarder); | |
/// @notice Setter for the [ERC-1271](https://eips.ethereum.org/EIPS/eip-1271) signature validator contract. | |
/// @param _signatureValidator The address of the signature validator. | |
function setSignatureValidator(address _signatureValidator) external; | |
/// @notice Emitted when the signature validator address is updated. | |
/// @param signatureValidator The address of the signature validator. | |
event SignatureValidatorSet(address signatureValidator); | |
/// @notice Checks whether a signature is valid for the provided hash by forwarding the call to the set [ERC-1271](https://eips.ethereum.org/EIPS/eip-1271) signature validator contract. | |
/// @param _hash The hash of the data to be signed. | |
/// @param _signature The signature byte array associated with `_hash`. | |
/// @return Returns the `bytes4` magic value `0x1626ba7e` if the signature is valid. | |
function isValidSignature(bytes32 _hash, bytes memory _signature) external returns (bytes4); | |
/// @notice Registers an ERC standard having a callback by registering its [ERC-165](https://eips.ethereum.org/EIPS/eip-165) interface ID and callback function signature. | |
/// @param _interfaceId The ID of the interface. | |
/// @param _callbackSelector The selector of the callback function. | |
/// @param _magicNumber The magic number to be registered for the function signature. | |
function registerStandardCallback( | |
bytes4 _interfaceId, | |
bytes4 _callbackSelector, | |
bytes4 _magicNumber | |
) external; | |
} | |
// File src/core/dao/IEIP4824.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity 0.8.17; | |
/// @title EIP-4824 Common Interfaces for DAOs | |
/// @dev See https://eips.ethereum.org/EIPS/eip-4824 | |
/// @author Aragon Association - 2021-2023 | |
interface IEIP4824 { | |
/// @notice A distinct Uniform Resource Identifier (URI) pointing to a JSON object following the "EIP-4824 DAO JSON-LD Schema". This JSON file splits into four URIs: membersURI, proposalsURI, activityLogURI, and governanceURI. The membersURI should point to a JSON file that conforms to the "EIP-4824 Members JSON-LD Schema". The proposalsURI should point to a JSON file that conforms to the "EIP-4824 Proposals JSON-LD Schema". The activityLogURI should point to a JSON file that conforms to the "EIP-4824 Activity Log JSON-LD Schema". The governanceURI should point to a flatfile, normatively a .md file. Each of the JSON files named above can be statically hosted or dynamically-generated. | |
/// @return _daoURI The DAO URI. | |
function daoURI() external view returns (string memory _daoURI); | |
} | |
// File src/core/permission/IPermissionCondition.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity ^0.8.8; | |
/// @title IPermissionCondition | |
/// @author Aragon Association - 2021-2023 | |
/// @notice An interface to be implemented to support custom permission logic. | |
/// @dev To attach a condition to a permission, the `grantWithCondition` function must be used and refer to the implementing contract's address with the `condition` argument. | |
interface IPermissionCondition { | |
/// @notice Checks if a call is permitted. | |
/// @param _where The address of the target contract. | |
/// @param _who The address (EOA or contract) for which the permissions are checked. | |
/// @param _permissionId The permission identifier. | |
/// @param _data Optional data passed to the `PermissionCondition` implementation. | |
/// @return isPermitted Returns true if the call is permitted. | |
function isGranted( | |
address _where, | |
address _who, | |
bytes32 _permissionId, | |
bytes calldata _data | |
) external view returns (bool isPermitted); | |
} | |
// File src/core/permission/PermissionCondition.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity ^0.8.8; | |
/// @title PermissionCondition | |
/// @author Aragon Association - 2023 | |
/// @notice An abstract contract for non-upgradeable contracts instantiated via the `new` keyword to inherit from to support customary permissions depending on arbitrary on-chain state. | |
abstract contract PermissionCondition is ERC165, IPermissionCondition { | |
/// @notice Checks if an interface is supported by this or its parent contract. | |
/// @param _interfaceId The ID of the interface. | |
/// @return Returns `true` if the interface is supported. | |
function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) { | |
return | |
_interfaceId == type(IPermissionCondition).interfaceId || | |
super.supportsInterface(_interfaceId); | |
} | |
} | |
// File src/core/permission/PermissionLib.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity ^0.8.8; | |
/// @title PermissionLib | |
/// @author Aragon Association - 2021-2023 | |
/// @notice A library containing objects for permission processing. | |
library PermissionLib { | |
/// @notice A constant expressing that no condition is applied to a permission. | |
address public constant NO_CONDITION = address(0); | |
/// @notice The types of permission operations available in the `PermissionManager`. | |
/// @param Grant The grant operation setting a permission without a condition. | |
/// @param Revoke The revoke operation removing a permission (that was granted with or without a condition). | |
/// @param GrantWithCondition The grant operation setting a permission with a condition. | |
enum Operation { | |
Grant, | |
Revoke, | |
GrantWithCondition | |
} | |
/// @notice A struct containing the information for a permission to be applied on a single target contract without a condition. | |
/// @param operation The permission operation type. | |
/// @param who The address (EOA or contract) receiving the permission. | |
/// @param permissionId The permission identifier. | |
struct SingleTargetPermission { | |
Operation operation; | |
address who; | |
bytes32 permissionId; | |
} | |
/// @notice A struct containing the information for a permission to be applied on multiple target contracts, optionally, with a condition. | |
/// @param operation The permission operation type. | |
/// @param where The address of the target contract for which `who` receives permission. | |
/// @param who The address (EOA or contract) receiving the permission. | |
/// @param condition The `PermissionCondition` that will be asked for authorization on calls connected to the specified permission identifier. | |
/// @param permissionId The permission identifier. | |
struct MultiTargetPermission { | |
Operation operation; | |
address where; | |
address who; | |
address condition; | |
bytes32 permissionId; | |
} | |
} | |
// File src/core/permission/PermissionManager.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity ^0.8.8; | |
/// @title PermissionManager | |
/// @author Aragon Association - 2021-2023 | |
/// @notice The abstract permission manager used in a DAO, its associated plugins, and other framework-related components. | |
abstract contract PermissionManager is Initializable { | |
using AddressUpgradeable for address; | |
/// @notice The ID of the permission required to call the `grant`, `grantWithCondition`, `revoke`, and `bulk` function. | |
bytes32 public constant ROOT_PERMISSION_ID = keccak256("ROOT_PERMISSION"); | |
/// @notice A special address encoding permissions that are valid for any address `who` or `where`. | |
address internal constant ANY_ADDR = address(type(uint160).max); | |
/// @notice A special address encoding if a permissions is not set and therefore not allowed. | |
address internal constant UNSET_FLAG = address(0); | |
/// @notice A special address encoding if a permission is allowed. | |
address internal constant ALLOW_FLAG = address(2); | |
/// @notice A mapping storing permissions as hashes (i.e., `permissionHash(where, who, permissionId)`) and their status encoded by an address (unset, allowed, or redirecting to a `PermissionCondition`). | |
mapping(bytes32 => address) internal permissionsHashed; | |
/// @notice Thrown if a call is unauthorized. | |
/// @param where The context in which the authorization reverted. | |
/// @param who The address (EOA or contract) missing the permission. | |
/// @param permissionId The permission identifier. | |
error Unauthorized(address where, address who, bytes32 permissionId); | |
/// @notice Thrown if a permission has been already granted with a different condition. | |
/// @dev This makes sure that condition on the same permission can not be overwriten by a different condition. | |
/// @param where The address of the target contract to grant `_who` permission to. | |
/// @param who The address (EOA or contract) to which the permission has already been granted. | |
/// @param permissionId The permission identifier. | |
/// @param currentCondition The current condition set for permissionId. | |
/// @param newCondition The new condition it tries to set for permissionId. | |
error PermissionAlreadyGrantedForDifferentCondition( | |
address where, | |
address who, | |
bytes32 permissionId, | |
address currentCondition, | |
address newCondition | |
); | |
/// @notice Thrown if a condition address is not a contract. | |
/// @param condition The address that is not a contract. | |
error ConditionNotAContract(IPermissionCondition condition); | |
/// @notice Thrown if a condition contract does not support the `IPermissionCondition` interface. | |
/// @param condition The address that is not a contract. | |
error ConditionInterfacNotSupported(IPermissionCondition condition); | |
/// @notice Thrown for `ROOT_PERMISSION_ID` or `EXECUTE_PERMISSION_ID` permission grants where `who` or `where` is `ANY_ADDR`. | |
error PermissionsForAnyAddressDisallowed(); | |
/// @notice Thrown for permission grants where `who` and `where` are both `ANY_ADDR`. | |
error AnyAddressDisallowedForWhoAndWhere(); | |
/// @notice Thrown if `Operation.GrantWithCondition` is requested as an operation but the method does not support it. | |
error GrantWithConditionNotSupported(); | |
/// @notice Emitted when a permission `permission` is granted in the context `here` to the address `_who` for the contract `_where`. | |
/// @param permissionId The permission identifier. | |
/// @param here The address of the context in which the permission is granted. | |
/// @param where The address of the target contract for which `_who` receives permission. | |
/// @param who The address (EOA or contract) receiving the permission. | |
/// @param condition The address `ALLOW_FLAG` for regular permissions or, alternatively, the `IPermissionCondition` contract implementation to be used. | |
event Granted( | |
bytes32 indexed permissionId, | |
address indexed here, | |
address where, | |
address indexed who, | |
address condition | |
); | |
/// @notice Emitted when a permission `permission` is revoked in the context `here` from the address `_who` for the contract `_where`. | |
/// @param permissionId The permission identifier. | |
/// @param here The address of the context in which the permission is revoked. | |
/// @param where The address of the target contract for which `_who` loses permission. | |
/// @param who The address (EOA or contract) losing the permission. | |
event Revoked( | |
bytes32 indexed permissionId, | |
address indexed here, | |
address where, | |
address indexed who | |
); | |
/// @notice A modifier to make functions on inheriting contracts authorized. Permissions to call the function are checked through this permission manager. | |
/// @param _permissionId The permission identifier required to call the method this modifier is applied to. | |
modifier auth(bytes32 _permissionId) { | |
_auth(_permissionId); | |
_; | |
} | |
/// @notice Initialization method to set the initial owner of the permission manager. | |
/// @dev The initial owner is granted the `ROOT_PERMISSION_ID` permission. | |
/// @param _initialOwner The initial owner of the permission manager. | |
function __PermissionManager_init(address _initialOwner) internal onlyInitializing { | |
_initializePermissionManager(_initialOwner); | |
} | |
/// @notice Grants permission to an address to call methods in a contract guarded by an auth modifier with the specified permission identifier. | |
/// @dev Requires the `ROOT_PERMISSION_ID` permission. | |
/// @param _where The address of the target contract for which `_who` receives permission. | |
/// @param _who The address (EOA or contract) receiving the permission. | |
/// @param _permissionId The permission identifier. | |
/// @dev Note, that granting permissions with `_who` or `_where` equal to `ANY_ADDR` does not replace other permissions with specific `_who` and `_where` addresses that exist in parallel. | |
function grant( | |
address _where, | |
address _who, | |
bytes32 _permissionId | |
) external virtual auth(ROOT_PERMISSION_ID) { | |
_grant(_where, _who, _permissionId); | |
} | |
/// @notice Grants permission to an address to call methods in a target contract guarded by an auth modifier with the specified permission identifier if the referenced condition permits it. | |
/// @dev Requires the `ROOT_PERMISSION_ID` permission | |
/// @param _where The address of the target contract for which `_who` receives permission. | |
/// @param _who The address (EOA or contract) receiving the permission. | |
/// @param _permissionId The permission identifier. | |
/// @param _condition The `PermissionCondition` that will be asked for authorization on calls connected to the specified permission identifier. | |
/// @dev Note, that granting permissions with `_who` or `_where` equal to `ANY_ADDR` does not replace other permissions with specific `_who` and `_where` addresses that exist in parallel. | |
function grantWithCondition( | |
address _where, | |
address _who, | |
bytes32 _permissionId, | |
IPermissionCondition _condition | |
) external virtual auth(ROOT_PERMISSION_ID) { | |
_grantWithCondition(_where, _who, _permissionId, _condition); | |
} | |
/// @notice Revokes permission from an address to call methods in a target contract guarded by an auth modifier with the specified permission identifier. | |
/// @dev Requires the `ROOT_PERMISSION_ID` permission. | |
/// @param _where The address of the target contract for which `_who` loses permission. | |
/// @param _who The address (EOA or contract) losing the permission. | |
/// @param _permissionId The permission identifier. | |
/// @dev Note, that revoking permissions with `_who` or `_where` equal to `ANY_ADDR` does not revoke other permissions with specific `_who` and `_where` addresses that exist in parallel. | |
function revoke( | |
address _where, | |
address _who, | |
bytes32 _permissionId | |
) external virtual auth(ROOT_PERMISSION_ID) { | |
_revoke(_where, _who, _permissionId); | |
} | |
/// @notice Applies an array of permission operations on a single target contracts `_where`. | |
/// @param _where The address of the single target contract. | |
/// @param items The array of single-targeted permission operations to apply. | |
function applySingleTargetPermissions( | |
address _where, | |
PermissionLib.SingleTargetPermission[] calldata items | |
) external virtual auth(ROOT_PERMISSION_ID) { | |
for (uint256 i; i < items.length; ) { | |
PermissionLib.SingleTargetPermission memory item = items[i]; | |
if (item.operation == PermissionLib.Operation.Grant) { | |
_grant(_where, item.who, item.permissionId); | |
} else if (item.operation == PermissionLib.Operation.Revoke) { | |
_revoke(_where, item.who, item.permissionId); | |
} else if (item.operation == PermissionLib.Operation.GrantWithCondition) { | |
revert GrantWithConditionNotSupported(); | |
} | |
unchecked { | |
++i; | |
} | |
} | |
} | |
/// @notice Applies an array of permission operations on multiple target contracts `items[i].where`. | |
/// @param _items The array of multi-targeted permission operations to apply. | |
function applyMultiTargetPermissions( | |
PermissionLib.MultiTargetPermission[] calldata _items | |
) external virtual auth(ROOT_PERMISSION_ID) { | |
for (uint256 i; i < _items.length; ) { | |
PermissionLib.MultiTargetPermission memory item = _items[i]; | |
if (item.operation == PermissionLib.Operation.Grant) { | |
_grant(item.where, item.who, item.permissionId); | |
} else if (item.operation == PermissionLib.Operation.Revoke) { | |
_revoke(item.where, item.who, item.permissionId); | |
} else if (item.operation == PermissionLib.Operation.GrantWithCondition) { | |
_grantWithCondition( | |
item.where, | |
item.who, | |
item.permissionId, | |
IPermissionCondition(item.condition) | |
); | |
} | |
unchecked { | |
++i; | |
} | |
} | |
} | |
/// @notice Checks if an address has permission on a contract via a permission identifier and considers if `ANY_ADDRESS` was used in the granting process. | |
/// @param _where The address of the target contract for which `_who` receives permission. | |
/// @param _who The address (EOA or contract) for which the permission is checked. | |
/// @param _permissionId The permission identifier. | |
/// @param _data The optional data passed to the `PermissionCondition` registered. | |
/// @return Returns true if `_who` has the permissions on the target contract via the specified permission identifier. | |
function isGranted( | |
address _where, | |
address _who, | |
bytes32 _permissionId, | |
bytes memory _data | |
) public view virtual returns (bool) { | |
return | |
_isGranted(_where, _who, _permissionId, _data) || // check if `_who` has permission for `_permissionId` on `_where` | |
_isGranted(_where, ANY_ADDR, _permissionId, _data) || // check if anyone has permission for `_permissionId` on `_where` | |
_isGranted(ANY_ADDR, _who, _permissionId, _data); // check if `_who` has permission for `_permissionI` on any contract | |
} | |
/// @notice Grants the `ROOT_PERMISSION_ID` permission to the initial owner during initialization of the permission manager. | |
/// @param _initialOwner The initial owner of the permission manager. | |
function _initializePermissionManager(address _initialOwner) internal { | |
_grant(address(this), _initialOwner, ROOT_PERMISSION_ID); | |
} | |
/// @notice This method is used in the external `grant` method of the permission manager. | |
/// @param _where The address of the target contract for which `_who` receives permission. | |
/// @param _who The address (EOA or contract) owning the permission. | |
/// @param _permissionId The permission identifier. | |
/// @dev Note, that granting permissions with `_who` or `_where` equal to `ANY_ADDR` does not replace other permissions with specific `_who` and `_where` addresses that exist in parallel. | |
function _grant(address _where, address _who, bytes32 _permissionId) internal virtual { | |
if (_where == ANY_ADDR || _who == ANY_ADDR) { | |
revert PermissionsForAnyAddressDisallowed(); | |
} | |
bytes32 permHash = permissionHash(_where, _who, _permissionId); | |
address currentFlag = permissionsHashed[permHash]; | |
// Means permHash is not currently set. | |
if (currentFlag == UNSET_FLAG) { | |
permissionsHashed[permHash] = ALLOW_FLAG; | |
emit Granted(_permissionId, msg.sender, _where, _who, ALLOW_FLAG); | |
} | |
} | |
/// @notice This method is used in the external `grantWithCondition` method of the permission manager. | |
/// @param _where The address of the target contract for which `_who` receives permission. | |
/// @param _who The address (EOA or contract) owning the permission. | |
/// @param _permissionId The permission identifier. | |
/// @param _condition An address either resolving to a `PermissionCondition` contract address or being the `ALLOW_FLAG` address (`address(2)`). | |
/// @dev Note, that granting permissions with `_who` or `_where` equal to `ANY_ADDR` does not replace other permissions with specific `_who` and `_where` addresses that exist in parallel. | |
function _grantWithCondition( | |
address _where, | |
address _who, | |
bytes32 _permissionId, | |
IPermissionCondition _condition | |
) internal virtual { | |
address conditionAddr = address(_condition); | |
if (!conditionAddr.isContract()) { | |
revert ConditionNotAContract(_condition); | |
} | |
if ( | |
!PermissionCondition(conditionAddr).supportsInterface( | |
type(IPermissionCondition).interfaceId | |
) | |
) { | |
revert ConditionInterfacNotSupported(_condition); | |
} | |
if (_where == ANY_ADDR && _who == ANY_ADDR) { | |
revert AnyAddressDisallowedForWhoAndWhere(); | |
} | |
if (_where == ANY_ADDR || _who == ANY_ADDR) { | |
if ( | |
_permissionId == ROOT_PERMISSION_ID || | |
isPermissionRestrictedForAnyAddr(_permissionId) | |
) { | |
revert PermissionsForAnyAddressDisallowed(); | |
} | |
} | |
bytes32 permHash = permissionHash(_where, _who, _permissionId); | |
address currentCondition = permissionsHashed[permHash]; | |
// Means permHash is not currently set. | |
if (currentCondition == UNSET_FLAG) { | |
permissionsHashed[permHash] = conditionAddr; | |
emit Granted(_permissionId, msg.sender, _where, _who, conditionAddr); | |
} else if (currentCondition != conditionAddr) { | |
// Revert if `permHash` is already granted, but uses a different condition. | |
// If we don't revert, we either should: | |
// - allow overriding the condition on the same permission | |
// which could be confusing whoever granted the same permission first | |
// - or do nothing and succeed silently which could be confusing for the caller. | |
revert PermissionAlreadyGrantedForDifferentCondition({ | |
where: _where, | |
who: _who, | |
permissionId: _permissionId, | |
currentCondition: currentCondition, | |
newCondition: conditionAddr | |
}); | |
} | |
} | |
/// @notice This method is used in the public `revoke` method of the permission manager. | |
/// @param _where The address of the target contract for which `_who` receives permission. | |
/// @param _who The address (EOA or contract) owning the permission. | |
/// @param _permissionId The permission identifier. | |
/// @dev Note, that revoking permissions with `_who` or `_where` equal to `ANY_ADDR` does not revoke other permissions with specific `_who` and `_where` addresses that might have been granted in parallel. | |
function _revoke(address _where, address _who, bytes32 _permissionId) internal virtual { | |
bytes32 permHash = permissionHash(_where, _who, _permissionId); | |
if (permissionsHashed[permHash] != UNSET_FLAG) { | |
permissionsHashed[permHash] = UNSET_FLAG; | |
emit Revoked(_permissionId, msg.sender, _where, _who); | |
} | |
} | |
/// @notice Checks if a caller is granted permissions on a target contract via a permission identifier and redirects the approval to a `PermissionCondition` if this was specified in the setup. | |
/// @param _where The address of the target contract for which `_who` receives permission. | |
/// @param _who The address (EOA or contract) owning the permission. | |
/// @param _permissionId The permission identifier. | |
/// @param _data The optional data passed to the `PermissionCondition` registered. | |
/// @return Returns true if `_who` has the permissions on the contract via the specified permissionId identifier. | |
function _isGranted( | |
address _where, | |
address _who, | |
bytes32 _permissionId, | |
bytes memory _data | |
) internal view virtual returns (bool) { | |
address accessFlagOrCondition = permissionsHashed[ | |
permissionHash(_where, _who, _permissionId) | |
]; | |
if (accessFlagOrCondition == UNSET_FLAG) return false; | |
if (accessFlagOrCondition == ALLOW_FLAG) return true; | |
// Since it's not a flag, assume it's a PermissionCondition and try-catch to skip failures | |
try | |
IPermissionCondition(accessFlagOrCondition).isGranted( | |
_where, | |
_who, | |
_permissionId, | |
_data | |
) | |
returns (bool allowed) { | |
if (allowed) return true; | |
} catch {} | |
return false; | |
} | |
/// @notice A private function to be used to check permissions on the permission manager contract (`address(this)`) itself. | |
/// @param _permissionId The permission identifier required to call the method this modifier is applied to. | |
function _auth(bytes32 _permissionId) internal view virtual { | |
if (!isGranted(address(this), msg.sender, _permissionId, msg.data)) { | |
revert Unauthorized({ | |
where: address(this), | |
who: msg.sender, | |
permissionId: _permissionId | |
}); | |
} | |
} | |
/// @notice Generates the hash for the `permissionsHashed` mapping obtained from the word "PERMISSION", the contract address, the address owning the permission, and the permission identifier. | |
/// @param _where The address of the target contract for which `_who` receives permission. | |
/// @param _who The address (EOA or contract) owning the permission. | |
/// @param _permissionId The permission identifier. | |
/// @return The permission hash. | |
function permissionHash( | |
address _where, | |
address _who, | |
bytes32 _permissionId | |
) internal pure virtual returns (bytes32) { | |
return keccak256(abi.encodePacked("PERMISSION", _who, _where, _permissionId)); | |
} | |
/// @notice Decides if the granting permissionId is restricted when `_who == ANY_ADDR` or `_where == ANY_ADDR`. | |
/// @param _permissionId The permission identifier. | |
/// @return Whether or not the permission is restricted. | |
/// @dev By default, every permission is unrestricted and it is the derived contract's responsibility to override it. Note, that the `ROOT_PERMISSION_ID` is included and not required to be set it again. | |
function isPermissionRestrictedForAnyAddr( | |
bytes32 _permissionId | |
) internal view virtual returns (bool) { | |
(_permissionId); // silence the warning. | |
return false; | |
} | |
/// @notice 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 [OpenZeppelin's guide about storage gaps](https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps)). | |
uint256[49] private __gap; | |
} | |
// File src/core/utils/BitMap.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity 0.8.17; | |
/// @param bitmap The `uint256` representation of bits. | |
/// @param index The index number to check whether 1 or 0 is set. | |
/// @return Returns `true` if the bit is set at `index` on `bitmap`. | |
function hasBit(uint256 bitmap, uint8 index) pure returns (bool) { | |
uint256 bitValue = bitmap & (1 << index); | |
return bitValue > 0; | |
} | |
/// @param bitmap The `uint256` representation of bits. | |
/// @param index The index number to set the bit. | |
/// @return Returns a new number in which the bit is set at `index`. | |
function flipBit(uint256 bitmap, uint8 index) pure returns (uint256) { | |
return bitmap ^ (1 << index); | |
} | |
// File src/core/utils/CallbackHandler.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity 0.8.17; | |
/// @title CallbackHandler | |
/// @author Aragon Association - 2022-2023 | |
/// @notice This contract handles callbacks by registering a magic number together with the callback function's selector. It provides the `_handleCallback` function that inheriting contracts have to call inside their `fallback()` function (`_handleCallback(msg.callbackSelector, msg.data)`). This allows to adaptively register ERC standards (e.g., [ERC-721](https://eips.ethereum.org/EIPS/eip-721), [ERC-1115](https://eips.ethereum.org/EIPS/eip-1155), or future versions of [ERC-165](https://eips.ethereum.org/EIPS/eip-165)) and returning the required magic numbers for the associated callback functions for the inheriting contract so that it doesn't need to be upgraded. | |
/// @dev This callback handling functionality is intented to be used by executor contracts (i.e., `DAO.sol`). | |
abstract contract CallbackHandler { | |
/// @notice A mapping between callback function selectors and magic return numbers. | |
mapping(bytes4 => bytes4) internal callbackMagicNumbers; | |
/// @notice The magic number refering to unregistered callbacks. | |
bytes4 internal constant UNREGISTERED_CALLBACK = bytes4(0); | |
/// @notice Thrown if the callback function is not registered. | |
/// @param callbackSelector The selector of the callback function. | |
/// @param magicNumber The magic number to be registered for the callback function selector. | |
error UnkownCallback(bytes4 callbackSelector, bytes4 magicNumber); | |
/// @notice Emitted when `_handleCallback` is called. | |
/// @param sender Who called the callback. | |
/// @param sig The function signature. | |
/// @param data The calldata. | |
event CallbackReceived(address sender, bytes4 indexed sig, bytes data); | |
/// @notice Handles callbacks to adaptively support ERC standards. | |
/// @dev This function is supposed to be called via `_handleCallback(msg.sig, msg.data)` in the `fallback()` function of the inheriting contract. | |
/// @param _callbackSelector The function selector of the callback function. | |
/// @param _data The calldata. | |
/// @return The magic number registered for the function selector triggering the fallback. | |
function _handleCallback( | |
bytes4 _callbackSelector, | |
bytes memory _data | |
) internal virtual returns (bytes4) { | |
bytes4 magicNumber = callbackMagicNumbers[_callbackSelector]; | |
if (magicNumber == UNREGISTERED_CALLBACK) { | |
revert UnkownCallback({callbackSelector: _callbackSelector, magicNumber: magicNumber}); | |
} | |
emit CallbackReceived({sender: msg.sender, sig: _callbackSelector, data: _data}); | |
return magicNumber; | |
} | |
/// @notice Registers a magic number for a callback function selector. | |
/// @param _callbackSelector The selector of the callback function. | |
/// @param _magicNumber The magic number to be registered for the callback function selector. | |
function _registerCallback(bytes4 _callbackSelector, bytes4 _magicNumber) internal virtual { | |
callbackMagicNumbers[_callbackSelector] = _magicNumber; | |
} | |
/// @notice 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 [OpenZeppelin's guide about storage gaps](https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps)). | |
uint256[49] private __gap; | |
} | |
// File src/utils/protocol/IProtocolVersion.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity ^0.8.8; | |
/// @title IProtocolVersion | |
/// @author Aragon Association - 2022-2023 | |
/// @notice An interface defining the semantic OSx protocol version. | |
interface IProtocolVersion { | |
/// @notice Returns the protocol version at which the current contract was built. Use it to check for future upgrades that might be applicable. | |
/// @return _version Returns the semantic OSx protocol version. | |
function protocolVersion() external view returns (uint8[3] memory _version); | |
} | |
// File src/utils/protocol/ProtocolVersion.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity 0.8.17; | |
/// @title ProtocolVersion | |
/// @author Aragon Association - 2023 | |
/// @notice An abstract, stateless, non-upgradeable contract serves as a base for other contracts requiring awareness of the OSx protocol version. | |
/// @dev Do not add any new variables to this contract that would shift down storage in the inheritance chain. | |
abstract contract ProtocolVersion is IProtocolVersion { | |
// IMPORTANT: Do not add any storage variable, see the above notice. | |
/// @inheritdoc IProtocolVersion | |
function protocolVersion() public pure returns (uint8[3] memory) { | |
return [1, 3, 0]; | |
} | |
} | |
// File src/core/dao/DAO.sol | |
// Original license: SPDX_License_Identifier: AGPL-3.0-or-later | |
pragma solidity 0.8.17; | |
/// @title DAO | |
/// @author Aragon Association - 2021-2023 | |
/// @notice This contract is the entry point to the Aragon DAO framework and provides our users a simple and easy to use public interface. | |
/// @dev Public API of the Aragon DAO framework. | |
contract DAO is | |
IEIP4824, | |
Initializable, | |
IERC1271, | |
ERC165StorageUpgradeable, | |
IDAO, | |
UUPSUpgradeable, | |
ProtocolVersion, | |
PermissionManager, | |
CallbackHandler | |
{ | |
using SafeERC20Upgradeable for IERC20Upgradeable; | |
using AddressUpgradeable for address; | |
/// @notice The ID of the permission required to call the `execute` function. | |
bytes32 public constant EXECUTE_PERMISSION_ID = keccak256("EXECUTE_PERMISSION"); | |
/// @notice The ID of the permission required to call the `_authorizeUpgrade` function. | |
bytes32 public constant UPGRADE_DAO_PERMISSION_ID = keccak256("UPGRADE_DAO_PERMISSION"); | |
/// @notice The ID of the permission required to call the `setMetadata` function. | |
bytes32 public constant SET_METADATA_PERMISSION_ID = keccak256("SET_METADATA_PERMISSION"); | |
/// @notice The ID of the permission required to call the `setTrustedForwarder` function. | |
bytes32 public constant SET_TRUSTED_FORWARDER_PERMISSION_ID = | |
keccak256("SET_TRUSTED_FORWARDER_PERMISSION"); | |
/// @notice The ID of the permission required to call the `setSignatureValidator` function. | |
bytes32 public constant SET_SIGNATURE_VALIDATOR_PERMISSION_ID = | |
keccak256("SET_SIGNATURE_VALIDATOR_PERMISSION"); | |
/// @notice The ID of the permission required to call the `registerStandardCallback` function. | |
bytes32 public constant REGISTER_STANDARD_CALLBACK_PERMISSION_ID = | |
keccak256("REGISTER_STANDARD_CALLBACK_PERMISSION"); | |
/// @notice The internal constant storing the maximal action array length. | |
uint256 internal constant MAX_ACTIONS = 256; | |
/// @notice The first out of two values to which the `_reentrancyStatus` state variable (used by the `nonReentrant` modifier) can be set inidicating that a function was not entered. | |
uint256 private constant _NOT_ENTERED = 1; | |
/// @notice The second out of two values to which the `_reentrancyStatus` state variable (used by the `nonReentrant` modifier) can be set inidicating that a function was entered. | |
uint256 private constant _ENTERED = 2; | |
/// @notice The [ERC-1271](https://eips.ethereum.org/EIPS/eip-1271) signature validator contract. | |
/// @dev Added in v1.0.0. | |
IERC1271 public signatureValidator; | |
/// @notice The address of the trusted forwarder verifying meta transactions. | |
/// @dev Added in v1.0.0. | |
address private trustedForwarder; | |
/// @notice The [EIP-4824](https://eips.ethereum.org/EIPS/eip-4824) DAO URI. | |
/// @dev Added in v1.0.0. | |
string private _daoURI; | |
/// @notice The state variable for the reentrancy guard of the `execute` function. | |
/// @dev Added in v1.3.0. The variable can be of value `_NOT_ENTERED = 1` or `_ENTERED = 2` in usage and is initialized with `_NOT_ENTERED`. | |
uint256 private _reentrancyStatus; | |
/// @notice Thrown if a call is reentrant. | |
error ReentrantCall(); | |
/// @notice Thrown if the action array length is larger than `MAX_ACTIONS`. | |
error TooManyActions(); | |
/// @notice Thrown if action execution has failed. | |
/// @param index The index of the action in the action array that failed. | |
error ActionFailed(uint256 index); | |
/// @notice Thrown if an action has insufficent gas left. | |
error InsufficientGas(); | |
/// @notice Thrown if the deposit amount is zero. | |
error ZeroAmount(); | |
/// @notice Thrown if there is a mismatch between the expected and actually deposited amount of native tokens. | |
/// @param expected The expected native token amount. | |
/// @param actual The actual native token amount deposited. | |
error NativeTokenDepositAmountMismatch(uint256 expected, uint256 actual); | |
/// @notice Thrown if an upgrade is not supported from a specific protocol version . | |
error ProtocolVersionUpgradeNotSupported(uint8[3] protocolVersion); | |
/// @notice Emitted when a new DAO URI is set. | |
/// @param daoURI The new URI. | |
event NewURI(string daoURI); | |
/// @notice A modifier to protect a function from calling itself, directly or indirectly (reentrancy). | |
/// @dev Currently, this modifier is only applied to the `execute()` function. If this is used multiple times, private `_beforeNonReentrant()` and `_afterNonReentrant()` functions should be created to prevent code duplication. | |
modifier nonReentrant() { | |
if (_reentrancyStatus == _ENTERED) { | |
revert ReentrantCall(); | |
} | |
_reentrancyStatus = _ENTERED; | |
_; | |
_reentrancyStatus = _NOT_ENTERED; | |
} | |
/// @notice Disables the initializers on the implementation contract to prevent it from being left uninitialized. | |
constructor() { | |
_disableInitializers(); | |
} | |
/// @notice Initializes the DAO by | |
/// - setting the reentrancy status variable to `_NOT_ENTERED` | |
/// - registering the [ERC-165](https://eips.ethereum.org/EIPS/eip-165) interface ID | |
/// - setting the trusted forwarder for meta transactions | |
/// - giving the `ROOT_PERMISSION_ID` permission to the initial owner (that should be revoked and transferred to the DAO after setup). | |
/// @dev This method is required to support [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822). | |
/// @param _metadata IPFS hash that points to all the metadata (logo, description, tags, etc.) of a DAO. | |
/// @param _initialOwner The initial owner of the DAO having the `ROOT_PERMISSION_ID` permission. | |
/// @param _trustedForwarder The trusted forwarder responsible for verifying meta transactions. | |
/// @param daoURI_ The DAO URI required to support [ERC-4824](https://eips.ethereum.org/EIPS/eip-4824). | |
function initialize( | |
bytes calldata _metadata, | |
address _initialOwner, | |
address _trustedForwarder, | |
string calldata daoURI_ | |
) external reinitializer(2) { | |
_reentrancyStatus = _NOT_ENTERED; // added in v1.3.0 | |
_registerInterface(type(IDAO).interfaceId); | |
_registerInterface(type(IERC1271).interfaceId); | |
_registerInterface(type(IEIP4824).interfaceId); | |
_registerInterface(type(IProtocolVersion).interfaceId); // added in v1.3.0 | |
_registerTokenInterfaces(); | |
_setMetadata(_metadata); | |
_setTrustedForwarder(_trustedForwarder); | |
_setDaoURI(daoURI_); | |
__PermissionManager_init(_initialOwner); | |
} | |
/// @notice Initializes the DAO after an upgrade from a previous protocol version. | |
/// @param _previousProtocolVersion The semantic protocol version number of the previous DAO implementation contract this upgrade is transitioning from. | |
/// @param _initData The initialization data to be passed to via `upgradeToAndCall` (see [ERC-1967](https://docs.openzeppelin.com/contracts/4.x/api/proxy#ERC1967Upgrade)). | |
function initializeFrom( | |
uint8[3] calldata _previousProtocolVersion, | |
bytes calldata _initData | |
) external reinitializer(2) { | |
_initData; // Silences the unused function parameter warning. | |
// Check that the contract is not upgrading from a different major release. | |
if (_previousProtocolVersion[0] != 1) { | |
revert ProtocolVersionUpgradeNotSupported(_previousProtocolVersion); | |
} | |
// Initialize `_reentrancyStatus` that was added in v1.3.0. | |
// Register Interface `ProtocolVersion` that was added in v1.3.0. | |
if (_previousProtocolVersion[1] <= 2) { | |
_reentrancyStatus = _NOT_ENTERED; | |
_registerInterface(type(IProtocolVersion).interfaceId); | |
} | |
} | |
/// @inheritdoc PermissionManager | |
function isPermissionRestrictedForAnyAddr( | |
bytes32 _permissionId | |
) internal pure override returns (bool) { | |
return | |
_permissionId == EXECUTE_PERMISSION_ID || | |
_permissionId == UPGRADE_DAO_PERMISSION_ID || | |
_permissionId == SET_METADATA_PERMISSION_ID || | |
_permissionId == SET_TRUSTED_FORWARDER_PERMISSION_ID || | |
_permissionId == SET_SIGNATURE_VALIDATOR_PERMISSION_ID || | |
_permissionId == REGISTER_STANDARD_CALLBACK_PERMISSION_ID; | |
} | |
/// @notice Internal method authorizing the upgrade of the contract via the [upgradeability mechanism for UUPS proxies](https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable) (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)). | |
/// @dev The caller must have the `UPGRADE_DAO_PERMISSION_ID` permission. | |
function _authorizeUpgrade(address) internal virtual override auth(UPGRADE_DAO_PERMISSION_ID) {} | |
/// @inheritdoc IDAO | |
function setTrustedForwarder( | |
address _newTrustedForwarder | |
) external override auth(SET_TRUSTED_FORWARDER_PERMISSION_ID) { | |
_setTrustedForwarder(_newTrustedForwarder); | |
} | |
/// @inheritdoc IDAO | |
function getTrustedForwarder() external view virtual override returns (address) { | |
return trustedForwarder; | |
} | |
/// @inheritdoc IDAO | |
function hasPermission( | |
address _where, | |
address _who, | |
bytes32 _permissionId, | |
bytes memory _data | |
) external view override returns (bool) { | |
return isGranted(_where, _who, _permissionId, _data); | |
} | |
/// @inheritdoc IDAO | |
function setMetadata( | |
bytes calldata _metadata | |
) external override auth(SET_METADATA_PERMISSION_ID) { | |
_setMetadata(_metadata); | |
} | |
/// @inheritdoc IDAO | |
function execute( | |
bytes32 _callId, | |
Action[] calldata _actions, | |
uint256 _allowFailureMap | |
) | |
external | |
override | |
nonReentrant | |
auth(EXECUTE_PERMISSION_ID) | |
returns (bytes[] memory execResults, uint256 failureMap) | |
{ | |
// Check that the action array length is within bounds. | |
if (_actions.length > MAX_ACTIONS) { | |
revert TooManyActions(); | |
} | |
execResults = new bytes[](_actions.length); | |
uint256 gasBefore; | |
uint256 gasAfter; | |
for (uint256 i = 0; i < _actions.length; ) { | |
gasBefore = gasleft(); | |
(bool success, bytes memory result) = _actions[i].to.call{value: _actions[i].value}( | |
_actions[i].data | |
); | |
gasAfter = gasleft(); | |
// Check if failure is allowed | |
if (!hasBit(_allowFailureMap, uint8(i))) { | |
// Check if the call failed. | |
if (!success) { | |
revert ActionFailed(i); | |
} | |
} else { | |
// Check if the call failed. | |
if (!success) { | |
// Make sure that the action call did not fail because 63/64 of `gasleft()` was insufficient to execute the external call `.to.call` (see [ERC-150](https://eips.ethereum.org/EIPS/eip-150)). | |
// In specific scenarios, i.e. proposal execution where the last action in the action array is allowed to fail, the account calling `execute` could force-fail this action by setting a gas limit | |
// where 63/64 is insufficient causing the `.to.call` to fail, but where the remaining 1/64 gas are sufficient to successfully finish the `execute` call. | |
if (gasAfter < gasBefore / 64) { | |
revert InsufficientGas(); | |
} | |
// Store that this action failed. | |
failureMap = flipBit(failureMap, uint8(i)); | |
} | |
} | |
execResults[i] = result; | |
unchecked { | |
++i; | |
} | |
} | |
emit Executed({ | |
actor: msg.sender, | |
callId: _callId, | |
actions: _actions, | |
allowFailureMap: _allowFailureMap, | |
failureMap: failureMap, | |
execResults: execResults | |
}); | |
} | |
/// @inheritdoc IDAO | |
function deposit( | |
address _token, | |
uint256 _amount, | |
string calldata _reference | |
) external payable override { | |
if (_amount == 0) revert ZeroAmount(); | |
if (_token == address(0)) { | |
if (msg.value != _amount) | |
revert NativeTokenDepositAmountMismatch({expected: _amount, actual: msg.value}); | |
} else { | |
if (msg.value != 0) | |
revert NativeTokenDepositAmountMismatch({expected: 0, actual: msg.value}); | |
IERC20Upgradeable(_token).safeTransferFrom(msg.sender, address(this), _amount); | |
} | |
emit Deposited(msg.sender, _token, _amount, _reference); | |
} | |
/// @inheritdoc IDAO | |
function setSignatureValidator( | |
address _signatureValidator | |
) external override auth(SET_SIGNATURE_VALIDATOR_PERMISSION_ID) { | |
signatureValidator = IERC1271(_signatureValidator); | |
emit SignatureValidatorSet({signatureValidator: _signatureValidator}); | |
} | |
/// @inheritdoc IDAO | |
function isValidSignature( | |
bytes32 _hash, | |
bytes memory _signature | |
) external view override(IDAO, IERC1271) returns (bytes4) { | |
if (address(signatureValidator) == address(0)) { | |
// Return the invalid magic number | |
return bytes4(0); | |
} | |
// Forward the call to the set signature validator contract | |
return signatureValidator.isValidSignature(_hash, _signature); | |
} | |
/// @notice Emits the `NativeTokenDeposited` event to track native token deposits that weren't made via the deposit method. | |
/// @dev This call is bound by the gas limitations for `send`/`transfer` calls introduced by [ERC-2929](https://eips.ethereum.org/EIPS/eip-2929). | |
/// Gas cost increases in future hard forks might break this function. As an alternative, [ERC-2930](https://eips.ethereum.org/EIPS/eip-2930)-type transactions using access lists can be employed. | |
receive() external payable { | |
emit NativeTokenDeposited(msg.sender, msg.value); | |
} | |
/// @notice Fallback to handle future versions of the [ERC-165](https://eips.ethereum.org/EIPS/eip-165) standard. | |
/// @param _input An alias being equivalent to `msg.data`. This feature of the fallback function was introduced with the [solidity compiler version 0.7.6](https://github.com/ethereum/solidity/releases/tag/v0.7.6) | |
/// @return The magic number registered for the function selector triggering the fallback. | |
fallback(bytes calldata _input) external returns (bytes memory) { | |
bytes4 magicNumber = _handleCallback(msg.sig, _input); | |
return abi.encode(magicNumber); | |
} | |
/// @notice Emits the MetadataSet event if new metadata is set. | |
/// @param _metadata Hash of the IPFS metadata object. | |
function _setMetadata(bytes calldata _metadata) internal { | |
emit MetadataSet(_metadata); | |
} | |
/// @notice Sets the trusted forwarder on the DAO and emits the associated event. | |
/// @param _trustedForwarder The trusted forwarder address. | |
function _setTrustedForwarder(address _trustedForwarder) internal { | |
trustedForwarder = _trustedForwarder; | |
emit TrustedForwarderSet(_trustedForwarder); | |
} | |
/// @notice Registers the [ERC-721](https://eips.ethereum.org/EIPS/eip-721) and [ERC-1155](https://eips.ethereum.org/EIPS/eip-1155) interfaces and callbacks. | |
function _registerTokenInterfaces() private { | |
_registerInterface(type(IERC721ReceiverUpgradeable).interfaceId); | |
_registerInterface(type(IERC1155ReceiverUpgradeable).interfaceId); | |
_registerCallback( | |
IERC721ReceiverUpgradeable.onERC721Received.selector, | |
IERC721ReceiverUpgradeable.onERC721Received.selector | |
); | |
_registerCallback( | |
IERC1155ReceiverUpgradeable.onERC1155Received.selector, | |
IERC1155ReceiverUpgradeable.onERC1155Received.selector | |
); | |
_registerCallback( | |
IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector, | |
IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector | |
); | |
} | |
/// @inheritdoc IDAO | |
function registerStandardCallback( | |
bytes4 _interfaceId, | |
bytes4 _callbackSelector, | |
bytes4 _magicNumber | |
) external override auth(REGISTER_STANDARD_CALLBACK_PERMISSION_ID) { | |
_registerInterface(_interfaceId); | |
_registerCallback(_callbackSelector, _magicNumber); | |
emit StandardCallbackRegistered(_interfaceId, _callbackSelector, _magicNumber); | |
} | |
/// @inheritdoc IEIP4824 | |
function daoURI() external view returns (string memory) { | |
return _daoURI; | |
} | |
/// @notice Updates the set DAO URI to a new value. | |
/// @param newDaoURI The new DAO URI to be set. | |
function setDaoURI(string calldata newDaoURI) external auth(SET_METADATA_PERMISSION_ID) { | |
_setDaoURI(newDaoURI); | |
} | |
/// @notice Sets the new [ERC-4824](https://eips.ethereum.org/EIPS/eip-4824) DAO URI and emits the associated event. | |
/// @param daoURI_ The new DAO URI. | |
function _setDaoURI(string calldata daoURI_) internal { | |
_daoURI = daoURI_; | |
emit NewURI(daoURI_); | |
} | |
/// @notice 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 [OpenZeppelin's guide about storage gaps](https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps)). | |
uint256[46] private __gap; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment