ETH Price: $2,501.09 (-0.81%)

Transaction Decoder

Block:
22524217 at May-20-2025 12:45:59 PM +UTC
Transaction Fee:
0.000055675378156026 ETH $0.14
Gas Used:
28,247 Gas / 1.971019158 Gwei

Account State Difference:

  Address   Before After State Difference Code
0x4beFa2aA...045269E9d
(Bedrock: Liquid Staking)
15.441845855952590152 Eth15.456143570129742641 Eth0.014297714177152489
(beaverbuild)
19.737040020109271597 Eth
Nonce: 2516527
19.722686630553963082 Eth
Nonce: 2516528
0.014353389555308515

Execution Trace

ETH 0.014297714177152489 TransparentUpgradeableProxy.CALL( )
  • ETH 0.014297714177152489 Staking.DELEGATECALL( )
    File 1 of 2: TransparentUpgradeableProxy
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol)
    pragma solidity ^0.8.0;
    import "ERC1967Proxy.sol";
    /**
     * @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.
     */
    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) {
            assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
            _changeAdmin(admin_);
        }
        /**
         * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
         */
        modifier ifAdmin() {
            if (msg.sender == _getAdmin()) {
                _;
            } else {
                _fallback();
            }
        }
        /**
         * @dev Returns the current admin.
         *
         * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
         *
         * 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 admin() external ifAdmin returns (address admin_) {
            admin_ = _getAdmin();
        }
        /**
         * @dev Returns the current implementation.
         *
         * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
         *
         * 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 implementation() external ifAdmin returns (address implementation_) {
            implementation_ = _implementation();
        }
        /**
         * @dev Changes the admin of the proxy.
         *
         * Emits an {AdminChanged} event.
         *
         * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
         */
        function changeAdmin(address newAdmin) external virtual ifAdmin {
            _changeAdmin(newAdmin);
        }
        /**
         * @dev Upgrade the implementation of the proxy.
         *
         * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
         */
        function upgradeTo(address newImplementation) external ifAdmin {
            _upgradeToAndCall(newImplementation, bytes(""), false);
        }
        /**
         * @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.
         *
         * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
         */
        function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
            _upgradeToAndCall(newImplementation, data, true);
        }
        /**
         * @dev Returns the current admin.
         */
        function _admin() internal view virtual returns (address) {
            return _getAdmin();
        }
        /**
         * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
         */
        function _beforeFallback() internal virtual override {
            require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
            super._beforeFallback();
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)
    pragma solidity ^0.8.0;
    import "Proxy.sol";
    import "ERC1967Upgrade.sol";
    /**
     * @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 initializating the storage of the proxy like a Solidity constructor.
         */
        constructor(address _logic, bytes memory _data) payable {
            assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
            _upgradeToAndCall(_logic, _data, false);
        }
        /**
         * @dev Returns the current implementation address.
         */
        function _implementation() internal view virtual override returns (address impl) {
            return ERC1967Upgrade._getImplementation();
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (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 internall 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 overriden 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 internall 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 overriden should call `super._beforeFallback()`.
         */
        function _beforeFallback() internal virtual {}
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
    pragma solidity ^0.8.2;
    import "IBeacon.sol";
    import "Address.sol";
    import "StorageSlot.sol";
    /**
     * @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._
     *
     * @custom:oz-upgrades-unsafe-allow delegatecall
     */
    abstract contract ERC1967Upgrade {
        // 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 Emitted when the implementation is upgraded.
         */
        event Upgraded(address indexed implementation);
        /**
         * @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 _upgradeToAndCallSecure(
            address newImplementation,
            bytes memory data,
            bool forceCall
        ) internal {
            address oldImplementation = _getImplementation();
            // Initial upgrade and setup call
            _setImplementation(newImplementation);
            if (data.length > 0 || forceCall) {
                Address.functionDelegateCall(newImplementation, data);
            }
            // Perform rollback test if not already in progress
            StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
            if (!rollbackTesting.value) {
                // Trigger rollback using upgradeTo from the new implementation
                rollbackTesting.value = true;
                Address.functionDelegateCall(
                    newImplementation,
                    abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
                );
                rollbackTesting.value = false;
                // Check rollback was effective
                require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
                // Finally reset to the new implementation and log the upgrade
                _upgradeTo(newImplementation);
            }
        }
        /**
         * @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 Emitted when the admin account has changed.
         */
        event AdminChanged(address previousAdmin, address newAdmin);
        /**
         * @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 Emitted when the beacon is upgraded.
         */
        event BeaconUpgraded(address indexed beacon);
        /**
         * @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);
            }
        }
    }
    // 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);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
    pragma solidity ^0.8.0;
    /**
     * @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
         * ====
         */
        function isContract(address account) internal view returns (bool) {
            // This method relies on extcodesize, which returns 0 for contracts in
            // construction, since the code is only stored at the end of the
            // constructor execution.
            uint256 size;
            assembly {
                size := extcodesize(account)
            }
            return size > 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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
            require(isContract(target), "Address: call to non-contract");
            (bool success, bytes memory returndata) = target.call{value: value}(data);
            return verifyCallResult(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) {
            require(isContract(target), "Address: static call to non-contract");
            (bool success, bytes memory returndata) = target.staticcall(data);
            return verifyCallResult(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) {
            require(isContract(target), "Address: delegate call to non-contract");
            (bool success, bytes memory returndata) = target.delegatecall(data);
            return verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
         * revert reason 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 {
                // 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
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
    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:
     * ```
     * 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`, and `uint256`._
     */
    library StorageSlot {
        struct AddressSlot {
            address value;
        }
        struct BooleanSlot {
            bool value;
        }
        struct Bytes32Slot {
            bytes32 value;
        }
        struct Uint256Slot {
            uint256 value;
        }
        /**
         * @dev Returns an `AddressSlot` with member `value` located at `slot`.
         */
        function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
            assembly {
                r.slot := slot
            }
        }
        /**
         * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
         */
        function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
            assembly {
                r.slot := slot
            }
        }
        /**
         * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
         */
        function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
            assembly {
                r.slot := slot
            }
        }
        /**
         * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
         */
        function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
            assembly {
                r.slot := slot
            }
        }
    }
    

    File 2 of 2: Staking
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.4;
    import "iface.sol";
    import "BytesLib.sol";
    import "SafeERC20.sol";
    import "Initializable.sol";
    import "AccessControlUpgradeable.sol";
    import "PausableUpgradeable.sol";
    import "ReentrancyGuardUpgradeable.sol";
    import "SafeCast.sol";
    /**
     * @title Bedrock Ethereum 2.0 Staking Contract
     *
     * Description:
     * 
     * ───╔═╦═╗─╔╗╔═╗──────╔╗──╔╗╔╗─╔╦╗╔╗─╔═╗─╔╗───────╔╦╗
     * ╔═╗║═╣═╬═╣╚╣═╣╔══╗╔╗╠╬═╗║╚╬╬╗╠╣╚╬╬═╣═╣╔╝╚╗╔═╦═╦╦╬╣╚╦╦╗
     * ║╬╚╬═╠═║╩╣╔╬═║╠══╣║╚╣║╬╚╣╬║║╚╣║╔╣║╩╬═║╚╗╔╝║╩╣╬║║║║╔╣║║
     * ╚══╩═╩═╩═╩═╩═╝╚══╝╚═╩╩══╩═╩╩═╩╩═╩╩═╩═╝─╚╝─╚═╩╗╠═╩╩═╬╗║
     * ─────────────────────────────────────────────╚╝────╚═╝
     * 
     * Term:
     *  ExchangeRatio:              Exchange Ratio of xETH to ETH, normally >= 1.0
     *  TotalXETH:                  Total Supply of xETH
     *  TotalStaked:                Total Ethers Staked to Validators
     *  TotalDebts:                 Total unpaid debts(generated from redeemFromValidators), 
     *                              awaiting to be paid by turn off validators to clean debts.
     *  TotalPending:               Pending Ethers(<32 Ethers), awaiting to be staked
     *  RewardDebts:                The amount re-staked into TotalPending
     *
     *  AccountedUserRevenue:       Overall Net revenue which belongs to all xETH holders(excluded re-staked amount)
     *  ReportedValidators:         Latest Reported Validator Count
     *  ReportedValidatorBalance:   Latest Reported Validator Overall Balance
     *  RecentReceived:             The Amount this contract receives recently.
     *  CurrentReserve:             Assets Under Management
     *
     * Lemma 1: (AUM)
     *
     *          CurrentReserve = TotalPending + TotalStaked + AccountedUserRevenue - TotalDebts - RewardDebts
     *
     * Lemma 2: (Exchange Ratio)
     *
     *          ExchangeRatio = CurrentReserve / TotalXETH
     *
     * Rule 1: (function mint) For every mint operation, the ethers pays debt in priority the reset will be put in TotalPending(deprecated),
     *          ethersToMint:               The amount user deposits
     *
     *          TotalPending = TotalPending + ethersToMint
     *          TotalXETH = TotalXETH + ethersToMint / ExchangeRatio
     *
     * Rule 2: (function mint) At any time TotalPending has more than 32 Ethers, It will be staked, TotalPending
     *          moves to TotalStaked and keeps TotalPending less than 32 Ether.
     *
     *          TotalPending = TotalPending - ⌊TotalPending/32ETH⌋ * 32ETH
     *          TotalStaked = TotalStaked + ⌊TotalPending/32ETH⌋ * 32ETH
     *
     * Rule 3: (function validatorStopped) Whenever a validator stopped, all value pays debts in priority, then:
     *          valueStopped:               The value sent-back via receive() funtion
     *          amountUnstaked:             The amount of unstaked node (base 32ethers)
     *          validatorStopped:           The count of validator stopped
     *          
     *          incrRewardDebt := valueStopped - amountUnstaked
     *          RewardDebts = RewardDebt + incrRewardDebt
     *          RecentReceived = RecentReceived + valueStopped
     *          TotalPending = TotalPending + Max(0, amountUnstaked - TotalDebts) + incrRewardDebt
     *          TotalStaked = TotalStaked - validatorStopped * 32 ETH
     *
     * Rule 4.1: (function pushBeacon) Oracle push balance, rebase if new validator is alive:
     *          aliveValidator:             The count of validators alive
     *          
     *          RewardBase = ReportedValidatorBalance + Max(0, aliveValidator - ReportedValidators) * 32 ETH
     *
     * Rule 4.2: (function pushBeacon) Oracle push balance, revenue calculation:
     *          aliveBalance:               The balance of current alive validators
     *
     *          r := aliveBalance + RecentReceived - RewardBase
     *          AccountedUserRevenue = AccountedUserRevenue + r * (1000 - managerFeeShare) / 1000
     *          RecentReceived = 0
     *          ReportedValidators = aliveValidator
     *          ReportedValidatorBalance = aliveBalance
     */
    contract Staking is Initializable, PausableUpgradeable, AccessControlUpgradeable, ReentrancyGuardUpgradeable {
        using SafeERC20 for IERC20;
        using Address for address payable;
        using Address for address;
        // stored credentials
        struct ValidatorCredential {
            bytes pubkey;
            bytes signature;
            bool stopped;
            bool restaking; // UPDATE(20240115) : flag the validator is using liquid staking address
            uint8 eigenpod; // UPDATE(20240402) : eigenpod id
        }
        // track ether debts to return to async caller
        struct Debt {
            address account;
            uint256 amount;
        }
        /**
            Incorrect storage preservation:
            |Implementation_v0   |Implementation_v1        |
            |--------------------|-------------------------|
            |address _owner      |address _lastContributor | <=== Storage collision!
            |mapping _balances   |address _owner           |
            |uint256 _supply     |mapping _balances        |
            |...                 |uint256 _supply          |
            |                    |...                      |
            Correct storage preservation:
            |Implementation_v0   |Implementation_v1        |
            |--------------------|-------------------------|
            |address _owner      |address _owner           |
            |mapping _balances   |mapping _balances        |
            |uint256 _supply     |uint256 _supply          |
            |...                 |address _lastContributor | <=== Storage extension.
            |                    |...                      |
        */
        // Always extend storage instead of modifying it
        // Variables in implementation v0 
        bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
        bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
        bytes32 public constant REGISTRY_ROLE = keccak256("REGISTRY_ROLE");
        bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
        uint256 public constant DEPOSIT_SIZE = 32 ether;
        uint256 public constant SAFE_PUSH_REWARDS = 30 ether;
        uint256 private constant MULTIPLIER = 1e18; 
        uint256 private constant DEPOSIT_AMOUNT_UNIT = 1000000000 wei;
        uint256 private constant SIGNATURE_LENGTH = 96;
        uint256 private constant PUBKEY_LENGTH = 48;
        address public ethDepositContract;      // ETH 2.0 Deposit contract
        address public xETHAddress;             // xETH token address
        address public redeemContract;          // redeeming contract for user to pull ethers
        uint256 public managerFeeShare;         // manager's fee in 1/1000
        bytes32 public withdrawalCredentials;   // WithdrawCredential for all validator
        // credentials, pushed by owner
        ValidatorCredential [] public validatorRegistry;
        mapping(bytes32 => uint256) private pubkeyIndices; // indices of validatorRegistry by pubkey hash, starts from 1
        // next validator id
        uint256 private nextValidatorId;
        // exchange ratio related variables
        // track user deposits & redeem (xETH mint & burn)
        uint256 private totalPending;           // track pending ethers awaiting to be staked to validators
        uint256 private totalStaked;            // track current staked ethers for validators, rounded to 32 ethers
        uint256 private totalDebts;             // track current unpaid debts
        // FIFO of debts from redeemFromValidators
        mapping(uint256=>Debt) private etherDebts;
        uint256 private firstDebt;
        uint256 private lastDebt;
        mapping(address=>uint256) private userDebts;    // debts from user's perspective
        // track revenue from validators to form exchange ratio
        uint256 private accountedUserRevenue;           // accounted shared user revenue
        uint256 private accountedManagerRevenue;        // accounted manager's revenue
        uint256 private rewardDebts;                    // check validatorStopped function
        // revenue related variables
        // track beacon validator & balance
        uint256 private reportedValidators;
        uint256 private reportedValidatorBalance;
        // balance tracking
        int256 private accountedBalance;                // tracked balance change in functions,
                                                        // NOTE(x): balance might be negative for not accounting validators's redeeming
        uint256 private maxToStop;                      // set max validators to stop (20240530)
        uint256 private recentReceived;                 // track recently received (un-accounted) value into this contract
        bytes32 private vectorClock;                    // a vector clock for detecting receive() & pushBeacon() causality violations
        uint256 private vectorClockTicks;               // record current vector clock step;
        // track stopped validators
        uint256 private stoppedValidators;              // track stopped validators count
        // phase switch from 0 to 1
        uint256 private __DEPRECATED_phase;
        // gas refunds
        uint256 [] private refunds;
        // PATCH VARIABLES(UPGRADES)
        uint256 private recentStopped;                  // track recent stopped validators(update: 20220927)
        /**
         * @dev empty reserved space for future adding of variables
         */
        uint256[31] private __gap;
        // KYC control
        mapping(address=>uint256) __DEPRECATED_quotaUsed;
        mapping(address=>bool) __DEPRECATED_whiteList;
        // auto-compounding
        bool private __DEPRECATED_autoCompoundEnabled;
        // DEPRECATED(20240130): eigenlayer's restaking withdrawal credential
        bytes32 private __DEPRECATED_restakingWithdrawalCredentials;
        address private __DEPRECATED_restakingAddress;
        // UPDATE(20240130): use variable instead of constant, require upgradeAndCall to set it's value
        address public restakingContract;
        // UPDATE(20240405): record latest unrealized profits
        uint256 private reportedUnrealizedProfits;
        /** 
         * ======================================================================================
         * 
         * SYSTEM SETTINGS, OPERATED VIA OWNER(DAO/TIMELOCK)
         * 
         * ======================================================================================
         */
        receive() external payable { }
        constructor() { _disableInitializers(); }
        /**
         * @dev pause the contract
         */
        function pause() public onlyRole(PAUSER_ROLE) {
            _pause();
        }
        /**
         * @dev unpause the contract
         */
        function unpause() public onlyRole(PAUSER_ROLE) {
            _unpause();
        }
        /**
         * @dev initialization address
         */
        /*
        function initialize() initializer public {
            __Pausable_init();
            __AccessControl_init();
            __ReentrancyGuard_init();
            _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
            _grantRole(ORACLE_ROLE, msg.sender);
            _grantRole(REGISTRY_ROLE, msg.sender);
            _grantRole(PAUSER_ROLE, msg.sender);
            _grantRole(MANAGER_ROLE, msg.sender);
            // init default values
            managerFeeShare = 5;
            firstDebt = 1;
            lastDebt = 0;
            phase = 0;
            _vectorClockTick();
            // initiate default withdrawal credential to the contract itself
            // uint8('0x1') + 11 bytes(0) + this.address
            bytes memory cred = abi.encodePacked(bytes1(0x01), new bytes(11), address(this));
            withdrawalCredentials = BytesLib.toBytes32(cred, 0);
        }
       */
       
        /**
         * UPDATE(20240130): to set a variable after upgrades
         * use upgradeAndCall to initializeV2
         */ 
        /*
        function initializeV2(address restakingContract_) reinitializer(2) public {
            restakingContract = restakingContract_;
        }
        */
        /**
         * @dev replace validators in batch
         */
        function replaceValidators(
            bytes [] calldata oldpubkeys, 
            bytes [] calldata pubkeys, 
            bytes [] calldata signatures, 
            bool restaking, 
            uint8 [] calldata podIds) external onlyRole(REGISTRY_ROLE) {
            _require(pubkeys.length == signatures.length, "SYS007");
            _require(oldpubkeys.length == pubkeys.length, "SYS007");
            _require(pubkeys.length == podIds.length, "SYS007");
            uint256 n = pubkeys.length;
            for(uint256 i=0;i<n;i++) {
                _require(oldpubkeys[i].length == PUBKEY_LENGTH, "SYS004");
                _require(pubkeys[i].length == PUBKEY_LENGTH, "SYS004");
                _require(signatures[i].length == SIGNATURE_LENGTH, "SYS003");
                // mark old pub key to false
                bytes32 oldPubKeyHash = keccak256(oldpubkeys[i]);
                _require(pubkeyIndices[oldPubKeyHash] > 0, "SYS006");
                uint256 index = pubkeyIndices[oldPubKeyHash] - 1;
                delete pubkeyIndices[oldPubKeyHash];
                // set new pubkey
                bytes32 pubkeyHash = keccak256(pubkeys[i]);
                ValidatorCredential storage validator = validatorRegistry[index];
                validator.pubkey = pubkeys[i];
                validator.signature = signatures[i];
                validator.restaking = restaking;
                validator.eigenpod = podIds[i];
                pubkeyIndices[pubkeyHash] = index+1;
            }
        }
        /**
         * @dev register a batch of validators
         */
        function registerValidators(bytes [] calldata pubkeys, bytes [] calldata signatures) external onlyRole(REGISTRY_ROLE) {
            _require(pubkeys.length == signatures.length, "SYS007");
            uint256 n = pubkeys.length;
            for(uint256 i=0;i<n;i++) {
                _require(pubkeys[i].length == PUBKEY_LENGTH, "SYS004");
                _require(signatures[i].length == SIGNATURE_LENGTH, "SYS003");
                bytes32 pubkeyHash = keccak256(pubkeys[i]);
                _require(pubkeyIndices[pubkeyHash] == 0, "SYS005");
                validatorRegistry.push(ValidatorCredential({pubkey:pubkeys[i], signature:signatures[i], stopped:false, restaking: false, eigenpod: 0}));
                pubkeyIndices[pubkeyHash] = validatorRegistry.length;
            }
        }
        /**
         * @dev register a batch of LRT validators
         * UPDATE(20240115): register a batch of validators for Liquid Restaking (EigenLayer)
         */
        function registerRestakingValidators(bytes [] calldata pubkeys, bytes [] calldata signatures) external onlyRole(REGISTRY_ROLE) {
            _require(pubkeys.length == signatures.length, "SYS007");
            uint256 n = pubkeys.length;
            for(uint256 i=0;i<n;i++) {
                _require(pubkeys[i].length == PUBKEY_LENGTH, "SYS004");
                _require(signatures[i].length == SIGNATURE_LENGTH, "SYS003");
                bytes32 pubkeyHash = keccak256(pubkeys[i]);
                _require(pubkeyIndices[pubkeyHash] == 0, "SYS005");
                validatorRegistry.push(ValidatorCredential({pubkey:pubkeys[i], signature:signatures[i], stopped:false, restaking: true, eigenpod: 0}));
                pubkeyIndices[pubkeyHash] = validatorRegistry.length;
            }
        }
        /**
         * @dev register a batch of LRT validators
         * UPDATE(20240402): register a batch of validators for Liquid Restaking (EigenLayer) with given eigenpod id
         */
        function registerRestakingValidators(
            bytes [] calldata pubkeys, 
            bytes [] calldata signatures, 
            uint8 [] calldata podIds) external onlyRole(REGISTRY_ROLE) {
            _require(pubkeys.length == signatures.length, "SYS007");
            _require(pubkeys.length == podIds.length, "SYS007");
            uint256 n = pubkeys.length;
            uint256 maxPods = IRestaking(restakingContract).getTotalPods();
            for(uint256 i=0;i<n;i++) {
                _require(pubkeys[i].length == PUBKEY_LENGTH, "SYS004");
                _require(signatures[i].length == SIGNATURE_LENGTH, "SYS003");
                _require(podIds[i] < maxPods, "SYS031");
                bytes32 pubkeyHash = keccak256(pubkeys[i]);
                _require(pubkeyIndices[pubkeyHash] == 0, "SYS005");
                validatorRegistry.push(ValidatorCredential({pubkey:pubkeys[i], signature:signatures[i], stopped:false, restaking: true, eigenpod: podIds[i]}));
                pubkeyIndices[pubkeyHash] = validatorRegistry.length;
            }
        }
        /**
         * @dev set manager's fee in 1/1000
         */
        function setManagerFeeShare(uint256 milli) external onlyRole(DEFAULT_ADMIN_ROLE)  {
            _require(milli >=0 && milli <=1000, "SYS008");
            managerFeeShare = milli;
            emit ManagerFeeSet(milli);
        }
        /**
         * @dev set eth deposit contract address
         */
        function setETHDepositContract(address _ethDepositContract) external onlyRole(DEFAULT_ADMIN_ROLE) {
            ethDepositContract = _ethDepositContract;
            emit DepositContractSet(_ethDepositContract);
        }
        /**
         * @dev set withdraw credential to receive revenue, usually this should be the contract itself.
         */
        function setWithdrawCredential(bytes32 withdrawalCredentials_) external onlyRole(DEFAULT_ADMIN_ROLE) {
            withdrawalCredentials = withdrawalCredentials_;
            emit WithdrawCredentialSet(withdrawalCredentials);
        } 
        
        /**
         * @dev stake into eth2 staking contract by calling this function
         */
        function stake() external { _stakeInternal(); }
        /**
         * @dev internal entry of stake() external 
         */
        function _stakeInternal() internal {
            // spin max nodes
            uint256 numValidators = totalPending / DEPOSIT_SIZE;
            uint256 maxValidators = (nextValidatorId + numValidators <= validatorRegistry.length)?
                                        numValidators:
                                        validatorRegistry.length - nextValidatorId;
            for (uint256 i = 0;i<maxValidators;i++) {
                _spinup();
            }
            if (maxValidators > 0) {
                emit ValidatorActivated(nextValidatorId);
            }
        }
        /**
         * @dev manager withdraw fees as uniETH
         */
        function withdrawManagerFee(address to) external onlyRole(MANAGER_ROLE) {
            IERC20(xETHAddress).safeTransfer(to, IERC20(xETHAddress).balanceOf(address(this)));
        }
        /**
         * @dev compound manager's revenue
         *  NOTE(20240406): this MUST be called in pushBeacon, to make sure debts are paied in priority, otherwise
         *      debts may be used to pay as the manager's revenue(that may take serveral months to come back).
         */
        function _compoundManagerRevenue() internal {
            uint256 freeEthers = address(this).balance - totalPending;
            uint256 amountEthers = freeEthers < accountedManagerRevenue ? freeEthers:accountedManagerRevenue;
            if (amountEthers > 0) {
                uint256 totalSupply = IERC20(xETHAddress).totalSupply();
                uint256 totalEthers = currentReserve();
                uint256 tokensToMint = totalSupply * amountEthers / totalEthers;
                // swapping
                // uint256 ratio = _exchangeRatioInternal();           // RATIO GUARD BEGIN
                IMintableContract(xETHAddress).mint(address(this), tokensToMint);
                totalPending += amountEthers;
                accountedManagerRevenue -= amountEthers;
                // assert(ratio == _exchangeRatioInternal());          // RATIO GUARD END
                emit ManagerRevenueCompounded(amountEthers);
            }
        }
        /**
         * @dev clear debts
         */
        function _clearDebts() internal {
            uint256 maxUsable = (address(this).balance - totalPending) / 32 ether * 32 ether;
            uint256 effectiveEthers = totalDebts < maxUsable? totalDebts:maxUsable;
            if (effectiveEthers > 0) {
                uint256 ratio = _exchangeRatioInternal();           // RATIO GUARD BEGIN
                uint256 paid = _payDebts(effectiveEthers);
                totalStaked -= paid;
                assert(ratio == _exchangeRatioInternal());          // RATIO GUARD END
            }
        }
        /**
         * @dev balance sync, also moves the vector clock if it has different value
         */
        function syncBalance() external { _syncBalance(); }
        
        /**
         * @dev balance sync, also moves the vector clock if it has different value
         */
        function _syncBalance() internal {
            // account restaking values
            IRestaking(restakingContract).update();
            assert(SafeCast.toInt256(address(this).balance) >= accountedBalance);
            uint256 diff = SafeCast.toUint256(SafeCast.toInt256(address(this).balance) - accountedBalance);
            if (diff > 0) {
                accountedBalance = SafeCast.toInt256(address(this).balance);
                recentReceived += diff;
                _vectorClockTick();
                emit BalanceSynced(diff);
            }
        }
        
        /**
         * @dev public invokable settlement to update exchangeRatio with default revenue limit.
         */
        function pushBeacon() external { _pushBeacon(vectorClock, SAFE_PUSH_REWARDS); }
        /**
         * @dev operators to settle revenue with custom revenue limit under abnormal conditions.
         */
        function pushBeacon(bytes32 clock, uint256 maxRewards) external onlyRole(ORACLE_ROLE) { _pushBeacon(clock, maxRewards); }
        function _pushBeacon(bytes32 clock, uint256 maxRewards) internal {
            _require(vectorClock == clock, "SYS012");
            // Collect new revenue if there is any.
            _syncBalance();
            
            // Check if new validators increased
            // and adjust rewardBase to include the new validators' value
            uint256 rewardBase = reportedValidatorBalance + reportedUnrealizedProfits;
            uint256 _aliveValidators = nextValidatorId - stoppedValidators;
            if (_aliveValidators + recentStopped > reportedValidators) {
                // newly launched validators
                uint256 newValidators = _aliveValidators + recentStopped - reportedValidators;
                rewardBase += newValidators * DEPOSIT_SIZE;
            }
            // Rewards calculation, this also considers recentReceived ethers from 
            // either stopped validators or withdrawed ethers as rewards.
            //
            // During two consecutive pushBeacon operation, the ethers will ONLY: 
            //  1. staked to new validators
            //  2. move from active validators to this contract
            // 
            // so, at any time, revenue generated if:
            //
            //  current active validator balance 
            //      + recent received from validators(since last pushBeacon) 
            //  >(GREATER THAN) reward base(last active validator balance + new nodes balance)
            uint256 _aliveBalance = _aliveValidators * DEPOSIT_SIZE;  // computed balance
            uint256 _unrealizedProfits = IRestaking(restakingContract).getPendingWithdrawalAmount();   // get unrealized profits
            _require(_aliveBalance + _unrealizedProfits + recentReceived >= rewardBase, "SYS015");
            uint256 rewards = _aliveBalance + _unrealizedProfits + recentReceived - rewardBase;
            _require(rewards <= maxRewards, "SYS016");
            _distributeRewards(rewards);
            // PRIORITY IN ETHER USAGE:
            // 1. to clear off debts
            // 2. to compound manager's revenue
            // 3. to auto-compound
            _clearDebts();
            _compoundManagerRevenue();
            _autocompound();
            // Update reportedValidators & reportedValidatorBalance
            // reset the recentReceived to 0
            reportedValidatorBalance = _aliveBalance; 
            reportedValidators = _aliveValidators;
            reportedUnrealizedProfits = _unrealizedProfits;
            recentReceived = 0;
            recentStopped = 0;
        }
        /**
         * @dev notify some validators stopped, and pay the debts
         */
        function validatorStopped(bytes [] calldata _stoppedPubKeys, bytes32 clock) external nonReentrant onlyRole(ORACLE_ROLE) {
            _require(vectorClock == clock, "SYS012");
            uint256 amountUnstaked = _stoppedPubKeys.length * DEPOSIT_SIZE;
            _require(_stoppedPubKeys.length > 0, "SYS017");
            _require(_stoppedPubKeys.length + stoppedValidators <= nextValidatorId, "SYS018");
            _require(maxToStop >= _stoppedPubKeys.length, "SYS019");
            // track stopped validators
            for (uint i=0;i<_stoppedPubKeys.length;i++) {
                bytes32 pubkeyHash = keccak256(_stoppedPubKeys[i]);
                _require(pubkeyIndices[pubkeyHash] > 0, "SYS006");
                uint256 index = pubkeyIndices[pubkeyHash] - 1;
                _require(!validatorRegistry[index].stopped, "SYS020");
                validatorRegistry[index].stopped = true;
            }
            stoppedValidators += _stoppedPubKeys.length;
            recentStopped += _stoppedPubKeys.length;
            maxToStop -= _stoppedPubKeys.length;
        
            // log
            emit ValidatorStopped(_stoppedPubKeys.length);
            // vector clock moves
            _vectorClockTick();
        }
        /**
         * ======================================================================================
         * 
         * VIEW FUNCTIONS
         * 
         * ======================================================================================
         */
        /**
         * @dev returns current reserve of ethers
         */
        function currentReserve() public view returns(uint256) {
            return totalPending + totalStaked + accountedUserRevenue - totalDebts - rewardDebts;
        }
        /*
         * @dev returns current vector clock
         */
        function getVectorClock() external view returns(bytes32) { return vectorClock; }
        /*
         * @dev returns current accounted balance
         */
        function getAccountedBalance() external view returns(int256) { return accountedBalance; }
        /**
         * @dev return total staked ethers
         */
        function getTotalStaked() external view returns (uint256) { return totalStaked; }
        /**
         * @dev return pending ethers
         */
        function getPendingEthers() external view returns (uint256) { return totalPending; }
        /**
         * @dev return reward debts(total compounded ethers)
         */
        function getRewardDebts() external view returns (uint256) { return rewardDebts; }
        /**
         * @dev return current debts
         */
        function getCurrentDebts() external view returns (uint256) { return totalDebts; }
        /**
         * @dev returns the accounted user revenue
         */
        function getAccountedUserRevenue() external view returns (uint256) { return accountedUserRevenue; }
        /**
         * @dev returns the accounted manager's revenue
         */
        function getAccountedManagerRevenue() external view returns (uint256) { return accountedManagerRevenue; }
        /*
         * @dev returns accumulated beacon validators
         */
        function getReportedValidators() external view returns (uint256) { return reportedValidators; }
        /*
         * @dev returns reported validator balance snapshot
         */
        function getReportedValidatorBalance() external view returns (uint256) { return reportedValidatorBalance; }
        /*
         * @dev returns maxToStop
         */
        function getMaxToStop() external view returns (uint256) { return maxToStop; }
        
        /*
         * @dev returns recent received value
         */
        function getRecentReceived() external view returns (uint256) { return recentReceived; }
        /*
         * @dev returns recent received value
         */
        function getRecentStopped() external view returns (uint256) { return recentStopped; }
        /**
         * @dev return debt for an account
         */
        function debtOf(address account) external view returns (uint256) {
            return userDebts[account];
        }
        /**
         * @dev return number of registered validator
         */
        function getRegisteredValidatorsCount() external view returns (uint256) {
            return validatorRegistry.length;
        }
        
        /**
         * @dev return a batch of validators credential
         */
        function getRegisteredValidators(uint256 idx_from, uint256 idx_to) external view returns (bytes [] memory pubkeys, bytes [] memory signatures, bool[] memory stopped) {
            pubkeys = new bytes[](idx_to - idx_from);
            signatures = new bytes[](idx_to - idx_from);
            stopped = new bool[](idx_to - idx_from);
            uint counter = 0;
            for (uint i = idx_from; i < idx_to;i++) {
                pubkeys[counter] = validatorRegistry[i].pubkey;
                signatures[counter] = validatorRegistry[i].signature;
                stopped[counter] = validatorRegistry[i].stopped;
                counter++;
            }
        }
        /**
         * @dev return a batch of validators information
         * UPDATE(20240119): V2 returns restaking info
         */
        function getRegisteredValidatorsV2(uint256 idx_from, uint256 idx_to) external view returns (
             bytes [] memory pubkeys,
             bytes [] memory signatures,
             bool [] memory stopped,
             bool [] memory restaking)
        {
            pubkeys = new bytes[](idx_to - idx_from);
            signatures = new bytes[](idx_to - idx_from);
            stopped = new bool[](idx_to - idx_from);
            restaking = new bool[](idx_to - idx_from);
            uint counter = 0;
            for (uint i = idx_from; i < idx_to;i++) {
                pubkeys[counter] = validatorRegistry[i].pubkey;
                signatures[counter] = validatorRegistry[i].signature;
                stopped[counter] = validatorRegistry[i].stopped;
                restaking[counter] = validatorRegistry[i].restaking;
                counter++;
            }
        }
        /**
         * @dev return next validator id
         */
        function getNextValidatorId() external view returns (uint256) { return nextValidatorId; }
        /**
         * @dev return exchange ratio for 1 uniETH to ETH, multiplied by 1e18
         */
        function exchangeRatio() external view returns (uint256) { return _exchangeRatioInternal(); }
        function _exchangeRatioInternal() internal view returns (uint256) {
            uint256 xETHAmount = IERC20(xETHAddress).totalSupply();
            if (xETHAmount == 0) {
                return 1 * MULTIPLIER;
            }
            uint256 ratio = currentReserve() * MULTIPLIER / xETHAmount;
            return ratio;
        }
        /**
         * @dev return debt of index
         */
        function checkDebt(uint256 index) external view returns (address account, uint256 amount) {
            Debt memory debt = etherDebts[index];
            return (debt.account, debt.amount);
        }
        /**
         * @dev return debt queue index
         */
        function getDebtQueue() external view returns (uint256 first, uint256 last) {
            return (firstDebt, lastDebt);
        }
        /**
         * @dev get stopped validators count
         */
        function getStoppedValidatorsCount() external view returns (uint256) { return stoppedValidators; }
        /**
         * ======================================================================================
         * 
         * EXTERNAL FUNCTIONS
         * 
         * ======================================================================================
         */
        /**
         * @dev mint xETH with ETH
         */
        function mint(uint256 minToMint, uint256 deadline) external payable nonReentrant whenNotPaused returns(uint256 minted) {
            _require(block.timestamp < deadline, "USR001");
            _require(msg.value > 0, "USR002");
            // track balance
            _balanceIncrease(msg.value);
            // mint xETH while keeping the exchange ratio invariant
            uint256 totalXETH = IERC20(xETHAddress).totalSupply();
            uint256 totalEthers = currentReserve();
            uint256 toMint = 1 * msg.value;  // default exchange ratio 1:1
            if (totalEthers > 0) { // avert division overflow
                toMint = totalXETH * msg.value / totalEthers;
            }
            _require(toMint >= minToMint, "USR004");
            // mint token while keeping exchange ratio invariant
            // uint256 ratio = _exchangeRatioInternal();           // RATIO GUARD BEGIN
            IMintableContract(xETHAddress).mint(msg.sender, toMint);
            totalPending += msg.value;
            // assert(ratio == _exchangeRatioInternal());          // RATIO GUARD END
            // try to initiate stake()
            _stakeInternal();
            return toMint;
        }
        /** 
         * @dev preview instant payment at CURRENT exchangeRatio
         */
        function previewInstantSwap(uint256 tokenAmount) external view returns(
            uint256 maxEthersToSwap,
            uint256 maxTokensToBurn
        ) {
            return _instantSwapRate(tokenAmount);
        }
        /** 
         * @dev instant payment as much as possbile from pending ethers at CURRENT exchangeRatio
         */
        function instantSwap(uint256 tokenAmount) external nonReentrant whenNotPaused {
            (uint256 maxEthersToSwap, uint256 maxTokensToBurn) = _instantSwapRate(tokenAmount);
            // _require(maxTokensToBurn > 0 && maxEthersToSwap > 0, "USR007");
            // uint256 ratio = _exchangeRatioInternal();               // RATIO GUARD BEGIN
            // transfer token from user and burn, substract ethers from pending ethers
            IMintableContract(xETHAddress).burnFrom(msg.sender, maxTokensToBurn);
            totalPending -= maxEthersToSwap;
            // assert(ratio == _exchangeRatioInternal());              // RATIO GUARD END
            // track balance change
            _balanceDecrease(maxEthersToSwap);
            // transfer ethers to users
            payable(msg.sender).sendValue(maxEthersToSwap);
        }
        /**
         * @dev internal function for the calculation of max allowed instant swap rate
         */
        function _instantSwapRate(uint256 tokenAmount) internal view returns (
            uint256 maxEthersToSwap,
            uint256 maxTokensToBurn
        ) {
            // find max instant swappable ethers
            uint256 totalSupply = IERC20(xETHAddress).totalSupply();
            uint256 r = currentReserve();
            uint256 expectedEthersToSwap =  tokenAmount * r / totalSupply;
            maxEthersToSwap = expectedEthersToSwap > totalPending ? totalPending:expectedEthersToSwap;
            // reverse calculation for how much token to burn.
            maxTokensToBurn = totalSupply * maxEthersToSwap / r;
        }
        /**
         * @dev redeem N * 32Ethers, which will turn off validadators,
         * note this function is asynchronous, the caller will only receive his ethers
         * after the validator has turned off.
         *
         * this function is dedicated for institutional operations.
         * 
         * redeem keeps the ratio invariant
         */
        function redeemFromValidators(uint256 ethersToRedeem, uint256 maxToBurn, uint256 deadline) external nonReentrant returns(uint256 burned) {
            _require(block.timestamp < deadline, "USR001");
            _require(ethersToRedeem % DEPOSIT_SIZE == 0, "USR005");
            _require(ethersToRedeem > 0, "USR005");
            uint256 totalXETH = IERC20(xETHAddress).totalSupply();
            uint256 xETHToBurn = totalXETH * ethersToRedeem / currentReserve();
            _require(xETHToBurn <= maxToBurn, "USR004");
            // NOTE: the following procdure must keep exchangeRatio invariant:
            // transfer xETH from sender & burn
            // uint256 ratio = _exchangeRatioInternal();           // RATIO GUARD BEGIN
            IMintableContract(xETHAddress).burnFrom(msg.sender, xETHToBurn);
            _enqueueDebt(msg.sender, ethersToRedeem);           // queue ether debts
            // assert(ratio == _exchangeRatioInternal());          // RATIO GUARD END
            maxToStop += ethersToRedeem / DEPOSIT_SIZE;
            // return burned 
            return xETHToBurn;
        }
        /** 
         * ======================================================================================
         * 
         * INTERNAL FUNCTIONS
         * 
         * ======================================================================================
         */
        function _balanceIncrease(uint256 amount) internal { accountedBalance += SafeCast.toInt256(amount); }
        function _balanceDecrease(uint256 amount) internal { accountedBalance -= SafeCast.toInt256(amount); }
        function _vectorClockTick() internal {
            vectorClockTicks++;
            vectorClock = keccak256(abi.encodePacked(vectorClock, block.timestamp, vectorClockTicks));
        }
        function _enqueueDebt(address account, uint256 amount) internal {
            // debt is paid in FIFO queue
            lastDebt += 1;
            etherDebts[lastDebt] = Debt({account:account, amount:amount});
            // track user debts
            userDebts[account] += amount;
            // track total debts
            totalDebts += amount;
            // log
            emit DebtQueued(account, amount);
        }
        function _dequeueDebt() internal returns (Debt memory debt) {
            _require(lastDebt >= firstDebt, "SYS022");  // non-empty queue
            debt = etherDebts[firstDebt];
            delete etherDebts[firstDebt];
            firstDebt += 1;
        }
        /**
         * @dev pay debts for a given amount
         */
        function _payDebts(uint256 total) internal returns(uint256 amountPaid) {
            // ethers to pay
            for (uint i=firstDebt;i<=lastDebt;i++) {
                if (total == 0) {
                    break;
                }
                Debt storage debt = etherDebts[i];
                // clean debts
                uint256 toPay = debt.amount <= total? debt.amount:total;
                debt.amount -= toPay;
                total -= toPay;
                userDebts[debt.account] -= toPay;
                amountPaid += toPay;
                // transfer money to debt contract
                IRedeem(redeemContract).pay{value:toPay}(debt.account);
                // dequeue if cleared 
                if (debt.amount == 0) {
                    _dequeueDebt();
                }
            }
            
            totalDebts -= amountPaid;
            
            // track balance
            _balanceDecrease(amountPaid);
        }
        /**
         * @dev distribute revenue
         */
        function _distributeRewards(uint256 rewards) internal {
            // rewards distribution
            uint256 fee = rewards * managerFeeShare / 1000;
            accountedManagerRevenue += fee;
            accountedUserRevenue += rewards - fee;
            emit RevenueAccounted(rewards);
        }
        /**
         * @dev auto compounding, after shanghai merge, called in pushBeacon
         *  NOTE(20240406): this MUST be called in pushBeacon, to make sure debts are paied in priority, otherwise
         *      debts may be used to pay as the users' revenue(that may take serveral months to come back).
         */
        function _autocompound() internal {
            uint256 maxCompound = accountedUserRevenue - rewardDebts;
            uint256 maxUsable = address(this).balance - totalPending;
            uint256 effectiveEthers = maxCompound < maxUsable? maxCompound:maxUsable;
            if (effectiveEthers > 0) {
                totalPending += effectiveEthers;
                rewardDebts += effectiveEthers;
                emit UserRevenueCompounded(effectiveEthers);
            }
        }
        /**
         * @dev spin up the node
         */
        function _spinup() internal {
             // load credential
            ValidatorCredential memory cred = validatorRegistry[nextValidatorId];
            
            // UPDATE(20240115):
            //  switch withdrawal credential based on it's registration
            if (!cred.restaking) {
                _stake(cred.pubkey, cred.signature, withdrawalCredentials);
            } else {
                address eigenPod = IRestaking(restakingContract).getPod(cred.eigenpod);
                bytes memory eigenPodCred = abi.encodePacked(bytes1(0x01), new bytes(11), eigenPod);
                bytes32 restakingWithdrawalCredentials = BytesLib.toBytes32(eigenPodCred, 0);
                _stake(cred.pubkey, cred.signature, restakingWithdrawalCredentials);
            }
            nextValidatorId++;        
            // track total staked & total pending ethers
            totalStaked += DEPOSIT_SIZE;
            totalPending -= DEPOSIT_SIZE;
        }
        /**
         * @dev Invokes a deposit call to the official Deposit contract
         *      UPDATE(20240115): add param withCred, instead of using contract variable
         */
        function _stake(bytes memory pubkey, bytes memory signature, bytes32 withCred) internal {
            _require(withCred != bytes32(0x0), "SYS024");
            uint256 value = DEPOSIT_SIZE;
            uint256 depositAmount = DEPOSIT_SIZE / DEPOSIT_AMOUNT_UNIT;
            assert(depositAmount * DEPOSIT_AMOUNT_UNIT == value);    // properly rounded
            // Compute deposit data root (`DepositData` hash tree root)
            // https://etherscan.io/address/0x00000000219ab540356cbb839cbe05303d7705fa#code
            bytes32 pubkey_root = sha256(abi.encodePacked(pubkey, bytes16(0)));
            bytes32 signature_root = sha256(abi.encodePacked(
                sha256(BytesLib.slice(signature, 0, 64)),
                sha256(abi.encodePacked(BytesLib.slice(signature, 64, SIGNATURE_LENGTH - 64), bytes32(0)))
            ));
            
            bytes memory amount = to_little_endian_64(uint64(depositAmount));
            bytes32 depositDataRoot = sha256(abi.encodePacked(
                sha256(abi.encodePacked(pubkey_root, withCred)),
                sha256(abi.encodePacked(amount, bytes24(0), signature_root))
            ));
            IDepositContract(ethDepositContract).deposit{value:DEPOSIT_SIZE} (
                pubkey, abi.encodePacked(withCred), signature, depositDataRoot);
            // track balance
            _balanceDecrease(DEPOSIT_SIZE);
        }
        /**
         * @dev to little endian
         * https://etherscan.io/address/0x00000000219ab540356cbb839cbe05303d7705fa#code
         */
        function to_little_endian_64(uint64 value) internal pure returns (bytes memory ret) {
            ret = new bytes(8);
            bytes8 bytesValue = bytes8(value);
            // Byteswapping during copying to bytes.
            ret[0] = bytesValue[7];
            ret[1] = bytesValue[6];
            ret[2] = bytesValue[5];
            ret[3] = bytesValue[4];
            ret[4] = bytesValue[3];
            ret[5] = bytesValue[2];
            ret[6] = bytesValue[1];
            ret[7] = bytesValue[0];
        }
        /**
         * @dev function version of _require, which could make the code size smaller
         */
        function _require(bool condition, string memory text) private pure {
            require(condition, text);
        }
        /**
         * ======================================================================================
         * 
         * CONTRCT EVENTS
         *
         * ======================================================================================
         */
        event ValidatorActivated(uint256 nextValidatorId);
        event ValidatorStopped(uint256 stoppedCount);
        event RevenueAccounted(uint256 amount);
        event ValidatorSlashedStopped(uint256 stoppedCount);
        event ManagerAccountSet(address account);
        event ManagerFeeSet(uint256 milli);
        event ManagerFeeWithdrawed(uint256 amount, address);
        event WithdrawCredentialSet(bytes32 withdrawCredential);
        event RestakingAddressSet(address addr);
        event DebtQueued(address creditor, uint256 amountEther);
        event DepositContractSet(address addr);
        event BalanceSynced(uint256 diff);
        event WhiteListToggle(address account, bool enabled);
        event ManagerRevenueCompounded(uint256 amount);
        event UserRevenueCompounded(uint256 amount);
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.4;
    import "IERC20.sol";
    interface IMintableContract is IERC20 {
        function mint(address account, uint256 amount) external;
        function burn(uint256 amount) external;
        function burnFrom(address account, uint256 amount) external;
    }
    // This interface is designed to be compatible with the Vyper version.
    /// @notice This is the Ethereum 2.0 deposit contract interface.
    /// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs
    interface IDepositContract {
        /// @notice A processed deposit event.
        event DepositEvent(
            bytes pubkey,
            bytes withdrawal_credentials,
            bytes amount,
            bytes signature,
            bytes index
        );
        /// @notice Submit a Phase 0 DepositData object.
        /// @param pubkey A BLS12-381 public key.
        /// @param withdrawal_credentials Commitment to a public key for withdrawals.
        /// @param signature A BLS12-381 signature.
        /// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object.
        /// Used as a protection against malformed input.
        function deposit(
            bytes calldata pubkey,
            bytes calldata withdrawal_credentials,
            bytes calldata signature,
            bytes32 deposit_data_root
        ) external payable;
        /// @notice Query the current deposit root hash.
        /// @return The deposit root hash.
        function get_deposit_root() external view returns (bytes32);
        /// @notice Query the current deposit count.
        /// @return The deposit count encoded as a little endian 64-bit number.
        function get_deposit_count() external view returns (bytes memory);
    }
    interface IRedeem {
        function pay(address account) external payable;
    }
    interface IRestaking {
        function update() external;
        function getPendingWithdrawalAmount() external view returns (uint256);
        function eigenPod() external view returns (address);
        function getPod(uint256 i) external view returns (address);
        function getTotalPods() external view returns (uint256);
    }
    interface IPodOwner {
        function transfer(address target, uint256 amount) external;
        function execute(address target, bytes memory data) external returns(bytes memory);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Interface of the ERC20 standard as defined in the EIP.
     */
    interface IERC20 {
        /**
         * @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 `recipient`.
         *
         * Returns a boolean value indicating whether the operation succeeded.
         *
         * Emits a {Transfer} event.
         */
        function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
            address recipient,
            uint256 amount
        ) external returns (bool);
        /**
         * @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);
    }
    // SPDX-License-Identifier: Unlicense
    /*
     * @title Solidity Bytes Arrays Utils
     * @author Gonçalo Sá <[email protected]>
     *
     * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
     *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
     */
    pragma solidity >=0.8.0 <0.9.0;
    library BytesLib {
        function concat(
            bytes memory _preBytes,
            bytes memory _postBytes
        )
            internal
            pure
            returns (bytes memory)
        {
            bytes memory tempBytes;
            assembly {
                // Get a location of some free memory and store it in tempBytes as
                // Solidity does for memory variables.
                tempBytes := mload(0x40)
                // Store the length of the first bytes array at the beginning of
                // the memory for tempBytes.
                let length := mload(_preBytes)
                mstore(tempBytes, length)
                // Maintain a memory counter for the current write location in the
                // temp bytes array by adding the 32 bytes for the array length to
                // the starting location.
                let mc := add(tempBytes, 0x20)
                // Stop copying when the memory counter reaches the length of the
                // first bytes array.
                let end := add(mc, length)
                for {
                    // Initialize a copy counter to the start of the _preBytes data,
                    // 32 bytes into its memory.
                    let cc := add(_preBytes, 0x20)
                } lt(mc, end) {
                    // Increase both counters by 32 bytes each iteration.
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    // Write the _preBytes data into the tempBytes memory 32 bytes
                    // at a time.
                    mstore(mc, mload(cc))
                }
                // Add the length of _postBytes to the current length of tempBytes
                // and store it as the new length in the first 32 bytes of the
                // tempBytes memory.
                length := mload(_postBytes)
                mstore(tempBytes, add(length, mload(tempBytes)))
                // Move the memory counter back from a multiple of 0x20 to the
                // actual end of the _preBytes data.
                mc := end
                // Stop copying when the memory counter reaches the new combined
                // length of the arrays.
                end := add(mc, length)
                for {
                    let cc := add(_postBytes, 0x20)
                } lt(mc, end) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    mstore(mc, mload(cc))
                }
                // Update the free-memory pointer by padding our last write location
                // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
                // next 32 byte block, then round down to the nearest multiple of
                // 32. If the sum of the length of the two arrays is zero then add
                // one before rounding down to leave a blank 32 bytes (the length block with 0).
                mstore(0x40, and(
                  add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                  not(31) // Round down to the nearest 32 bytes.
                ))
            }
            return tempBytes;
        }
        function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
            assembly {
                // Read the first 32 bytes of _preBytes storage, which is the length
                // of the array. (We don't need to use the offset into the slot
                // because arrays use the entire slot.)
                let fslot := sload(_preBytes.slot)
                // Arrays of 31 bytes or less have an even value in their slot,
                // while longer arrays have an odd value. The actual length is
                // the slot divided by two for odd values, and the lowest order
                // byte divided by two for even values.
                // If the slot is even, bitwise and the slot with 255 and divide by
                // two to get the length. If the slot is odd, bitwise and the slot
                // with -1 and divide by two.
                let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                let mlength := mload(_postBytes)
                let newlength := add(slength, mlength)
                // slength can contain both the length and contents of the array
                // if length < 32 bytes so let's prepare for that
                // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                switch add(lt(slength, 32), lt(newlength, 32))
                case 2 {
                    // Since the new array still fits in the slot, we just need to
                    // update the contents of the slot.
                    // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                    sstore(
                        _preBytes.slot,
                        // all the modifications to the slot are inside this
                        // next block
                        add(
                            // we can just add to the slot contents because the
                            // bytes we want to change are the LSBs
                            fslot,
                            add(
                                mul(
                                    div(
                                        // load the bytes from memory
                                        mload(add(_postBytes, 0x20)),
                                        // zero all bytes to the right
                                        exp(0x100, sub(32, mlength))
                                    ),
                                    // and now shift left the number of bytes to
                                    // leave space for the length in the slot
                                    exp(0x100, sub(32, newlength))
                                ),
                                // increase length by the double of the memory
                                // bytes length
                                mul(mlength, 2)
                            )
                        )
                    )
                }
                case 1 {
                    // The stored value fits in the slot, but the combined value
                    // will exceed it.
                    // get the keccak hash to get the contents of the array
                    mstore(0x0, _preBytes.slot)
                    let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                    // save new length
                    sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                    // The contents of the _postBytes array start 32 bytes into
                    // the structure. Our first read should obtain the `submod`
                    // bytes that can fit into the unused space in the last word
                    // of the stored array. To get this, we read 32 bytes starting
                    // from `submod`, so the data we read overlaps with the array
                    // contents by `submod` bytes. Masking the lowest-order
                    // `submod` bytes allows us to add that value directly to the
                    // stored value.
                    let submod := sub(32, slength)
                    let mc := add(_postBytes, submod)
                    let end := add(_postBytes, mlength)
                    let mask := sub(exp(0x100, submod), 1)
                    sstore(
                        sc,
                        add(
                            and(
                                fslot,
                                0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
                            ),
                            and(mload(mc), mask)
                        )
                    )
                    for {
                        mc := add(mc, 0x20)
                        sc := add(sc, 1)
                    } lt(mc, end) {
                        sc := add(sc, 1)
                        mc := add(mc, 0x20)
                    } {
                        sstore(sc, mload(mc))
                    }
                    mask := exp(0x100, sub(mc, end))
                    sstore(sc, mul(div(mload(mc), mask), mask))
                }
                default {
                    // get the keccak hash to get the contents of the array
                    mstore(0x0, _preBytes.slot)
                    // Start copying to the last used word of the stored array.
                    let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                    // save new length
                    sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                    // Copy over the first `submod` bytes of the new data as in
                    // case 1 above.
                    let slengthmod := mod(slength, 32)
                    let mlengthmod := mod(mlength, 32)
                    let submod := sub(32, slengthmod)
                    let mc := add(_postBytes, submod)
                    let end := add(_postBytes, mlength)
                    let mask := sub(exp(0x100, submod), 1)
                    sstore(sc, add(sload(sc), and(mload(mc), mask)))
                    for {
                        sc := add(sc, 1)
                        mc := add(mc, 0x20)
                    } lt(mc, end) {
                        sc := add(sc, 1)
                        mc := add(mc, 0x20)
                    } {
                        sstore(sc, mload(mc))
                    }
                    mask := exp(0x100, sub(mc, end))
                    sstore(sc, mul(div(mload(mc), mask), mask))
                }
            }
        }
        function slice(
            bytes memory _bytes,
            uint256 _start,
            uint256 _length
        )
            internal
            pure
            returns (bytes memory)
        {
            require(_length + 31 >= _length, "slice_overflow");
            require(_bytes.length >= _start + _length, "slice_outOfBounds");
            bytes memory tempBytes;
            assembly {
                switch iszero(_length)
                case 0 {
                    // Get a location of some free memory and store it in tempBytes as
                    // Solidity does for memory variables.
                    tempBytes := mload(0x40)
                    // The first word of the slice result is potentially a partial
                    // word read from the original array. To read it, we calculate
                    // the length of that partial word and start copying that many
                    // bytes into the array. The first word we copy will start with
                    // data we don't care about, but the last `lengthmod` bytes will
                    // land at the beginning of the contents of the new array. When
                    // we're done copying, we overwrite the full first word with
                    // the actual length of the slice.
                    let lengthmod := and(_length, 31)
                    // The multiplication in the next line is necessary
                    // because when slicing multiples of 32 bytes (lengthmod == 0)
                    // the following copy loop was copying the origin's length
                    // and then ending prematurely not copying everything it should.
                    let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                    let end := add(mc, _length)
                    for {
                        // The multiplication in the next line has the same exact purpose
                        // as the one above.
                        let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                    } lt(mc, end) {
                        mc := add(mc, 0x20)
                        cc := add(cc, 0x20)
                    } {
                        mstore(mc, mload(cc))
                    }
                    mstore(tempBytes, _length)
                    //update free-memory pointer
                    //allocating the array padded to 32 bytes like the compiler does now
                    mstore(0x40, and(add(mc, 31), not(31)))
                }
                //if we want a zero-length slice let's just return a zero-length array
                default {
                    tempBytes := mload(0x40)
                    //zero out the 32 bytes slice we are about to return
                    //we need to do it because Solidity does not garbage collect
                    mstore(tempBytes, 0)
                    mstore(0x40, add(tempBytes, 0x20))
                }
            }
            return tempBytes;
        }
        function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
            require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
            address tempAddress;
            assembly {
                tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
            }
            return tempAddress;
        }
        function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
            require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
            uint8 tempUint;
            assembly {
                tempUint := mload(add(add(_bytes, 0x1), _start))
            }
            return tempUint;
        }
        function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
            require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
            uint16 tempUint;
            assembly {
                tempUint := mload(add(add(_bytes, 0x2), _start))
            }
            return tempUint;
        }
        function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
            require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
            uint32 tempUint;
            assembly {
                tempUint := mload(add(add(_bytes, 0x4), _start))
            }
            return tempUint;
        }
        function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
            require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
            uint64 tempUint;
            assembly {
                tempUint := mload(add(add(_bytes, 0x8), _start))
            }
            return tempUint;
        }
        function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
            require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
            uint96 tempUint;
            assembly {
                tempUint := mload(add(add(_bytes, 0xc), _start))
            }
            return tempUint;
        }
        function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
            require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
            uint128 tempUint;
            assembly {
                tempUint := mload(add(add(_bytes, 0x10), _start))
            }
            return tempUint;
        }
        function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
            require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
            uint256 tempUint;
            assembly {
                tempUint := mload(add(add(_bytes, 0x20), _start))
            }
            return tempUint;
        }
        function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
            require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
            bytes32 tempBytes32;
            assembly {
                tempBytes32 := mload(add(add(_bytes, 0x20), _start))
            }
            return tempBytes32;
        }
        function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
            bool success = true;
            assembly {
                let length := mload(_preBytes)
                // if lengths don't match the arrays are not equal
                switch eq(length, mload(_postBytes))
                case 1 {
                    // cb is a circuit breaker in the for loop since there's
                    //  no said feature for inline assembly loops
                    // cb = 1 - don't breaker
                    // cb = 0 - break
                    let cb := 1
                    let mc := add(_preBytes, 0x20)
                    let end := add(mc, length)
                    for {
                        let cc := add(_postBytes, 0x20)
                    // the next line is the loop condition:
                    // while(uint256(mc < end) + cb == 2)
                    } eq(add(lt(mc, end), cb), 2) {
                        mc := add(mc, 0x20)
                        cc := add(cc, 0x20)
                    } {
                        // if any of these checks fails then arrays are not equal
                        if iszero(eq(mload(mc), mload(cc))) {
                            // unsuccess:
                            success := 0
                            cb := 0
                        }
                    }
                }
                default {
                    // unsuccess:
                    success := 0
                }
            }
            return success;
        }
        function equalStorage(
            bytes storage _preBytes,
            bytes memory _postBytes
        )
            internal
            view
            returns (bool)
        {
            bool success = true;
            assembly {
                // we know _preBytes_offset is 0
                let fslot := sload(_preBytes.slot)
                // Decode the length of the stored array like in concatStorage().
                let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                let mlength := mload(_postBytes)
                // if lengths don't match the arrays are not equal
                switch eq(slength, mlength)
                case 1 {
                    // slength can contain both the length and contents of the array
                    // if length < 32 bytes so let's prepare for that
                    // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                    if iszero(iszero(slength)) {
                        switch lt(slength, 32)
                        case 1 {
                            // blank the last byte which is the length
                            fslot := mul(div(fslot, 0x100), 0x100)
                            if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                                // unsuccess:
                                success := 0
                            }
                        }
                        default {
                            // cb is a circuit breaker in the for loop since there's
                            //  no said feature for inline assembly loops
                            // cb = 1 - don't breaker
                            // cb = 0 - break
                            let cb := 1
                            // get the keccak hash to get the contents of the array
                            mstore(0x0, _preBytes.slot)
                            let sc := keccak256(0x0, 0x20)
                            let mc := add(_postBytes, 0x20)
                            let end := add(mc, mlength)
                            // the next line is the loop condition:
                            // while(uint256(mc < end) + cb == 2)
                            for {} eq(add(lt(mc, end), cb), 2) {
                                sc := add(sc, 1)
                                mc := add(mc, 0x20)
                            } {
                                if iszero(eq(sload(sc), mload(mc))) {
                                    // unsuccess:
                                    success := 0
                                    cb := 0
                                }
                            }
                        }
                    }
                }
                default {
                    // unsuccess:
                    success := 0
                }
            }
            return success;
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
    pragma solidity ^0.8.0;
    import "IERC20.sol";
    import "Address.sol";
    /**
     * @title SafeERC20
     * @dev Wrappers around ERC20 operations that throw on failure (when the token
     * contract returns false). Tokens that return no value (and instead revert or
     * throw on failure) are also supported, non-reverting calls are assumed to be
     * successful.
     * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
     * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
     */
    library SafeERC20 {
        using Address for address;
        function safeTransfer(
            IERC20 token,
            address to,
            uint256 value
        ) internal {
            _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
        }
        function safeTransferFrom(
            IERC20 token,
            address from,
            address to,
            uint256 value
        ) internal {
            _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
        }
        /**
         * @dev Deprecated. This function has issues similar to the ones found in
         * {IERC20-approve}, and its usage is discouraged.
         *
         * Whenever possible, use {safeIncreaseAllowance} and
         * {safeDecreaseAllowance} instead.
         */
        function safeApprove(
            IERC20 token,
            address spender,
            uint256 value
        ) internal {
            // safeApprove should only be called when setting an initial allowance,
            // or when resetting it to zero. To increase and decrease it, use
            // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
            require(
                (value == 0) || (token.allowance(address(this), spender) == 0),
                "SafeERC20: approve from non-zero to non-zero allowance"
            );
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
        }
        function safeIncreaseAllowance(
            IERC20 token,
            address spender,
            uint256 value
        ) internal {
            uint256 newAllowance = token.allowance(address(this), spender) + value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
        function safeDecreaseAllowance(
            IERC20 token,
            address spender,
            uint256 value
        ) internal {
            unchecked {
                uint256 oldAllowance = token.allowance(address(this), spender);
                require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                uint256 newAllowance = oldAllowance - value;
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
            }
        }
        /**
         * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
         * on the return value: the return value is optional (but if data is returned, it must not be false).
         * @param token The token targeted by the call.
         * @param data The call data (encoded using abi.encode or one of its variants).
         */
        function _callOptionalReturn(IERC20 token, bytes memory data) private {
            // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
            // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
            // the target address contains contract code and also asserts for success in the low-level call.
            bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
            if (returndata.length > 0) {
                // Return data is optional
                require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
    pragma solidity ^0.8.0;
    /**
     * @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
         * ====
         */
        function isContract(address account) internal view returns (bool) {
            // This method relies on extcodesize, which returns 0 for contracts in
            // construction, since the code is only stored at the end of the
            // constructor execution.
            uint256 size;
            assembly {
                size := extcodesize(account)
            }
            return size > 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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
            require(isContract(target), "Address: call to non-contract");
            (bool success, bytes memory returndata) = target.call{value: value}(data);
            return verifyCallResult(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) {
            require(isContract(target), "Address: static call to non-contract");
            (bool success, bytes memory returndata) = target.staticcall(data);
            return verifyCallResult(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) {
            require(isContract(target), "Address: delegate call to non-contract");
            (bool success, bytes memory returndata) = target.delegatecall(data);
            return verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
         * revert reason 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 {
                // 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
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)
    pragma solidity ^0.8.2;
    import "AddressUpgradeable.sol";
    /**
     * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
     * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
     * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
     * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
     *
     * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
     * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
     * case an upgrade adds a module that needs to be initialized.
     *
     * For example:
     *
     * [.hljs-theme-light.nopadding]
     * ```
     * 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. Equivalent to `reinitializer(1)`.
         */
        modifier initializer() {
            bool isTopLevelCall = _setInitializedVersion(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.
         *
         * `initializer` is equivalent to `reinitializer(1)`, so 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.
         *
         * 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.
         */
        modifier reinitializer(uint8 version) {
            bool isTopLevelCall = _setInitializedVersion(version);
            if (isTopLevelCall) {
                _initializing = true;
            }
            _;
            if (isTopLevelCall) {
                _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.
         */
        function _disableInitializers() internal virtual {
            _setInitializedVersion(type(uint8).max);
        }
        function _setInitializedVersion(uint8 version) private returns (bool) {
            // If the contract is initializing we ignore whether _initialized is set in order to support multiple
            // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level
            // of initializers, because in other contexts the contract may have been reentered.
            if (_initializing) {
                require(
                    version == 1 && !AddressUpgradeable.isContract(address(this)),
                    "Initializable: contract is already initialized"
                );
                return false;
            } else {
                require(_initialized < version, "Initializable: contract is already initialized");
                _initialized = version;
                return true;
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.5.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
         * ====
         *
         * [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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
            require(isContract(target), "Address: call to non-contract");
            (bool success, bytes memory returndata) = target.call{value: value}(data);
            return verifyCallResult(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) {
            require(isContract(target), "Address: static call to non-contract");
            (bool success, bytes memory returndata) = target.staticcall(data);
            return verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
         * revert reason 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 {
                // 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
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.6.0) (access/AccessControl.sol)
    pragma solidity ^0.8.0;
    import "IAccessControlUpgradeable.sol";
    import "ContextUpgradeable.sol";
    import "StringsUpgradeable.sol";
    import "ERC165Upgradeable.sol";
    import "Initializable.sol";
    /**
     * @dev Contract module that allows children to implement role-based access
     * control mechanisms. This is a lightweight version that doesn't allow enumerating role
     * members except through off-chain means by accessing the contract event logs. Some
     * applications may benefit from on-chain enumerability, for those cases see
     * {AccessControlEnumerable}.
     *
     * Roles are referred to by their `bytes32` identifier. These should be exposed
     * in the external API and be unique. The best way to achieve this is by
     * using `public constant` hash digests:
     *
     * ```
     * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
     * ```
     *
     * Roles can be used to represent a set of permissions. To restrict access to a
     * function call, use {hasRole}:
     *
     * ```
     * function foo() public {
     *     require(hasRole(MY_ROLE, msg.sender));
     *     ...
     * }
     * ```
     *
     * Roles can be granted and revoked dynamically via the {grantRole} and
     * {revokeRole} functions. Each role has an associated admin role, and only
     * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
     *
     * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
     * that only accounts with this role will be able to grant or revoke other
     * roles. More complex role relationships can be created by using
     * {_setRoleAdmin}.
     *
     * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
     * grant and revoke this role. Extra precautions should be taken to secure
     * accounts that have been granted it.
     */
    abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
        function __AccessControl_init() internal onlyInitializing {
        }
        function __AccessControl_init_unchained() internal onlyInitializing {
        }
        struct RoleData {
            mapping(address => bool) members;
            bytes32 adminRole;
        }
        mapping(bytes32 => RoleData) private _roles;
        bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
        /**
         * @dev Modifier that checks that an account has a specific role. Reverts
         * with a standardized message including the required role.
         *
         * The format of the revert reason is given by the following regular expression:
         *
         *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
         *
         * _Available since v4.1._
         */
        modifier onlyRole(bytes32 role) {
            _checkRole(role);
            _;
        }
        /**
         * @dev See {IERC165-supportsInterface}.
         */
        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
            return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
        }
        /**
         * @dev Returns `true` if `account` has been granted `role`.
         */
        function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
            return _roles[role].members[account];
        }
        /**
         * @dev Revert with a standard message if `_msgSender()` is missing `role`.
         * Overriding this function changes the behavior of the {onlyRole} modifier.
         *
         * Format of the revert message is described in {_checkRole}.
         *
         * _Available since v4.6._
         */
        function _checkRole(bytes32 role) internal view virtual {
            _checkRole(role, _msgSender());
        }
        /**
         * @dev Revert with a standard message if `account` is missing `role`.
         *
         * The format of the revert reason is given by the following regular expression:
         *
         *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
         */
        function _checkRole(bytes32 role, address account) internal view virtual {
            if (!hasRole(role, account)) {
                revert(
                    string(
                        abi.encodePacked(
                            "AccessControl: account ",
                            StringsUpgradeable.toHexString(uint160(account), 20),
                            " is missing role ",
                            StringsUpgradeable.toHexString(uint256(role), 32)
                        )
                    )
                );
            }
        }
        /**
         * @dev Returns the admin role that controls `role`. See {grantRole} and
         * {revokeRole}.
         *
         * To change a role's admin, use {_setRoleAdmin}.
         */
        function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
            return _roles[role].adminRole;
        }
        /**
         * @dev Grants `role` to `account`.
         *
         * If `account` had not been already granted `role`, emits a {RoleGranted}
         * event.
         *
         * Requirements:
         *
         * - the caller must have ``role``'s admin role.
         */
        function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
            _grantRole(role, account);
        }
        /**
         * @dev Revokes `role` from `account`.
         *
         * If `account` had been granted `role`, emits a {RoleRevoked} event.
         *
         * Requirements:
         *
         * - the caller must have ``role``'s admin role.
         */
        function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
            _revokeRole(role, account);
        }
        /**
         * @dev Revokes `role` from the calling account.
         *
         * Roles are often managed via {grantRole} and {revokeRole}: this function's
         * purpose is to provide a mechanism for accounts to lose their privileges
         * if they are compromised (such as when a trusted device is misplaced).
         *
         * If the calling account had been revoked `role`, emits a {RoleRevoked}
         * event.
         *
         * Requirements:
         *
         * - the caller must be `account`.
         */
        function renounceRole(bytes32 role, address account) public virtual override {
            require(account == _msgSender(), "AccessControl: can only renounce roles for self");
            _revokeRole(role, account);
        }
        /**
         * @dev Grants `role` to `account`.
         *
         * If `account` had not been already granted `role`, emits a {RoleGranted}
         * event. Note that unlike {grantRole}, this function doesn't perform any
         * checks on the calling account.
         *
         * [WARNING]
         * ====
         * This function should only be called from the constructor when setting
         * up the initial roles for the system.
         *
         * Using this function in any other way is effectively circumventing the admin
         * system imposed by {AccessControl}.
         * ====
         *
         * NOTE: This function is deprecated in favor of {_grantRole}.
         */
        function _setupRole(bytes32 role, address account) internal virtual {
            _grantRole(role, account);
        }
        /**
         * @dev Sets `adminRole` as ``role``'s admin role.
         *
         * Emits a {RoleAdminChanged} event.
         */
        function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
            bytes32 previousAdminRole = getRoleAdmin(role);
            _roles[role].adminRole = adminRole;
            emit RoleAdminChanged(role, previousAdminRole, adminRole);
        }
        /**
         * @dev Grants `role` to `account`.
         *
         * Internal function without access restriction.
         */
        function _grantRole(bytes32 role, address account) internal virtual {
            if (!hasRole(role, account)) {
                _roles[role].members[account] = true;
                emit RoleGranted(role, account, _msgSender());
            }
        }
        /**
         * @dev Revokes `role` from `account`.
         *
         * Internal function without access restriction.
         */
        function _revokeRole(bytes32 role, address account) internal virtual {
            if (hasRole(role, account)) {
                _roles[role].members[account] = false;
                emit RoleRevoked(role, account, _msgSender());
            }
        }
        /**
         * @dev This empty reserved space is put in place to allow future versions to add new
         * variables without shifting down storage in the inheritance chain.
         * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
         */
        uint256[49] private __gap;
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev External interface of AccessControl declared to support ERC165 detection.
     */
    interface IAccessControlUpgradeable {
        /**
         * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
         *
         * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
         * {RoleAdminChanged} not being emitted signaling this.
         *
         * _Available since v3.1._
         */
        event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
        /**
         * @dev Emitted when `account` is granted `role`.
         *
         * `sender` is the account that originated the contract call, an admin role
         * bearer except when using {AccessControl-_setupRole}.
         */
        event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
        /**
         * @dev Emitted when `account` is revoked `role`.
         *
         * `sender` is the account that originated the contract call:
         *   - if using `revokeRole`, it is the admin role bearer
         *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
         */
        event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
        /**
         * @dev Returns `true` if `account` has been granted `role`.
         */
        function hasRole(bytes32 role, address account) external view returns (bool);
        /**
         * @dev Returns the admin role that controls `role`. See {grantRole} and
         * {revokeRole}.
         *
         * To change a role's admin, use {AccessControl-_setRoleAdmin}.
         */
        function getRoleAdmin(bytes32 role) external view returns (bytes32);
        /**
         * @dev Grants `role` to `account`.
         *
         * If `account` had not been already granted `role`, emits a {RoleGranted}
         * event.
         *
         * Requirements:
         *
         * - the caller must have ``role``'s admin role.
         */
        function grantRole(bytes32 role, address account) external;
        /**
         * @dev Revokes `role` from `account`.
         *
         * If `account` had been granted `role`, emits a {RoleRevoked} event.
         *
         * Requirements:
         *
         * - the caller must have ``role``'s admin role.
         */
        function revokeRole(bytes32 role, address account) external;
        /**
         * @dev Revokes `role` from the calling account.
         *
         * Roles are often managed via {grantRole} and {revokeRole}: this function's
         * purpose is to provide a mechanism for accounts to lose their privileges
         * if they are compromised (such as when a trusted device is misplaced).
         *
         * If the calling account had been granted `role`, emits a {RoleRevoked}
         * event.
         *
         * Requirements:
         *
         * - the caller must be `account`.
         */
        function renounceRole(bytes32 role, address account) external;
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
    pragma solidity ^0.8.0;
    import "Initializable.sol";
    /**
     * @dev Provides information about the current execution context, including the
     * sender of the transaction and its data. While these are generally available
     * via msg.sender and msg.data, they should not be accessed in such a direct
     * manner, since when dealing with meta-transactions the account sending and
     * paying for execution may not be the actual sender (as far as an application
     * is concerned).
     *
     * This contract is only required for intermediate, library-like contracts.
     */
    abstract contract ContextUpgradeable is Initializable {
        function __Context_init() internal onlyInitializing {
        }
        function __Context_init_unchained() internal onlyInitializing {
        }
        function _msgSender() internal view virtual returns (address) {
            return msg.sender;
        }
        function _msgData() internal view virtual returns (bytes calldata) {
            return msg.data;
        }
        /**
         * @dev This empty reserved space is put in place to allow future versions to add new
         * variables without shifting down storage in the inheritance chain.
         * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
         */
        uint256[50] private __gap;
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev String operations.
     */
    library StringsUpgradeable {
        bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
        /**
         * @dev Converts a `uint256` to its ASCII `string` decimal representation.
         */
        function toString(uint256 value) internal pure returns (string memory) {
            // Inspired by OraclizeAPI's implementation - MIT licence
            // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
            if (value == 0) {
                return "0";
            }
            uint256 temp = value;
            uint256 digits;
            while (temp != 0) {
                digits++;
                temp /= 10;
            }
            bytes memory buffer = new bytes(digits);
            while (value != 0) {
                digits -= 1;
                buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                value /= 10;
            }
            return string(buffer);
        }
        /**
         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
         */
        function toHexString(uint256 value) internal pure returns (string memory) {
            if (value == 0) {
                return "0x00";
            }
            uint256 temp = value;
            uint256 length = 0;
            while (temp != 0) {
                length++;
                temp >>= 8;
            }
            return toHexString(value, length);
        }
        /**
         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
         */
        function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
            bytes memory buffer = new bytes(2 * length + 2);
            buffer[0] = "0";
            buffer[1] = "x";
            for (uint256 i = 2 * length + 1; i > 1; --i) {
                buffer[i] = _HEX_SYMBOLS[value & 0xf];
                value >>= 4;
            }
            require(value == 0, "Strings: hex length insufficient");
            return string(buffer);
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
    pragma solidity ^0.8.0;
    import "IERC165Upgradeable.sol";
    import "Initializable.sol";
    /**
     * @dev Implementation of the {IERC165} interface.
     *
     * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
     * for the additional interface id that will be supported. For example:
     *
     * ```solidity
     * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
     *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
     * }
     * ```
     *
     * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
     */
    abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
        function __ERC165_init() internal onlyInitializing {
        }
        function __ERC165_init_unchained() internal onlyInitializing {
        }
        /**
         * @dev See {IERC165-supportsInterface}.
         */
        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
            return interfaceId == type(IERC165Upgradeable).interfaceId;
        }
        /**
         * @dev This empty reserved space is put in place to allow future versions to add new
         * variables without shifting down storage in the inheritance chain.
         * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
         */
        uint256[50] private __gap;
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Interface of the ERC165 standard, as defined in the
     * https://eips.ethereum.org/EIPS/eip-165[EIP].
     *
     * Implementers can declare support of contract interfaces, which can then be
     * queried by others ({ERC165Checker}).
     *
     * For an implementation, see {ERC165}.
     */
    interface IERC165Upgradeable {
        /**
         * @dev Returns true if this contract implements the interface defined by
         * `interfaceId`. See the corresponding
         * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
         * to learn more about how these ids are created.
         *
         * This function call must use less than 30 000 gas.
         */
        function supportsInterface(bytes4 interfaceId) external view returns (bool);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
    pragma solidity ^0.8.0;
    import "ContextUpgradeable.sol";
    import "Initializable.sol";
    /**
     * @dev Contract module which allows children to implement an emergency stop
     * mechanism that can be triggered by an authorized account.
     *
     * This module is used through inheritance. It will make available the
     * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
     * the functions of your contract. Note that they will not be pausable by
     * simply including this module, only once the modifiers are put in place.
     */
    abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
        /**
         * @dev Emitted when the pause is triggered by `account`.
         */
        event Paused(address account);
        /**
         * @dev Emitted when the pause is lifted by `account`.
         */
        event Unpaused(address account);
        bool private _paused;
        /**
         * @dev Initializes the contract in unpaused state.
         */
        function __Pausable_init() internal onlyInitializing {
            __Pausable_init_unchained();
        }
        function __Pausable_init_unchained() internal onlyInitializing {
            _paused = false;
        }
        /**
         * @dev Returns true if the contract is paused, and false otherwise.
         */
        function paused() public view virtual returns (bool) {
            return _paused;
        }
        /**
         * @dev Modifier to make a function callable only when the contract is not paused.
         *
         * Requirements:
         *
         * - The contract must not be paused.
         */
        modifier whenNotPaused() {
            require(!paused(), "Pausable: paused");
            _;
        }
        /**
         * @dev Modifier to make a function callable only when the contract is paused.
         *
         * Requirements:
         *
         * - The contract must be paused.
         */
        modifier whenPaused() {
            require(paused(), "Pausable: not paused");
            _;
        }
        /**
         * @dev Triggers stopped state.
         *
         * Requirements:
         *
         * - The contract must not be paused.
         */
        function _pause() internal virtual whenNotPaused {
            _paused = true;
            emit Paused(_msgSender());
        }
        /**
         * @dev Returns to normal state.
         *
         * Requirements:
         *
         * - The contract must be paused.
         */
        function _unpause() internal virtual whenPaused {
            _paused = false;
            emit Unpaused(_msgSender());
        }
        /**
         * @dev This empty reserved space is put in place to allow future versions to add new
         * variables without shifting down storage in the inheritance chain.
         * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
         */
        uint256[49] private __gap;
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
    pragma solidity ^0.8.0;
    import "Initializable.sol";
    /**
     * @dev Contract module that helps prevent reentrant calls to a function.
     *
     * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
     * available, which can be applied to functions to make sure there are no nested
     * (reentrant) calls to them.
     *
     * Note that because there is a single `nonReentrant` guard, functions marked as
     * `nonReentrant` may not call one another. This can be worked around by making
     * those functions `private`, and then adding `external` `nonReentrant` entry
     * points to them.
     *
     * TIP: If you would like to learn more about reentrancy and alternative ways
     * to protect against it, check out our blog post
     * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
     */
    abstract contract ReentrancyGuardUpgradeable is Initializable {
        // Booleans are more expensive than uint256 or any type that takes up a full
        // word because each write operation emits an extra SLOAD to first read the
        // slot's contents, replace the bits taken up by the boolean, and then write
        // back. This is the compiler's defense against contract upgrades and
        // pointer aliasing, and it cannot be disabled.
        // The values being non-zero value makes deployment a bit more expensive,
        // but in exchange the refund on every call to nonReentrant will be lower in
        // amount. Since refunds are capped to a percentage of the total
        // transaction's gas, it is best to keep them low in cases like this one, to
        // increase the likelihood of the full refund coming into effect.
        uint256 private constant _NOT_ENTERED = 1;
        uint256 private constant _ENTERED = 2;
        uint256 private _status;
        function __ReentrancyGuard_init() internal onlyInitializing {
            __ReentrancyGuard_init_unchained();
        }
        function __ReentrancyGuard_init_unchained() internal onlyInitializing {
            _status = _NOT_ENTERED;
        }
        /**
         * @dev Prevents a contract from calling itself, directly or indirectly.
         * Calling a `nonReentrant` function from another `nonReentrant`
         * function is not supported. It is possible to prevent this from happening
         * by making the `nonReentrant` function external, and making it call a
         * `private` function that does the actual work.
         */
        modifier nonReentrant() {
            // On the first call to nonReentrant, _notEntered will be true
            require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
            // Any calls to nonReentrant after this point will fail
            _status = _ENTERED;
            _;
            // By storing the original value once again, a refund is triggered (see
            // https://eips.ethereum.org/EIPS/eip-2200)
            _status = _NOT_ENTERED;
        }
        /**
         * @dev This empty reserved space is put in place to allow future versions to add new
         * variables without shifting down storage in the inheritance chain.
         * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
         */
        uint256[49] private __gap;
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
     * checks.
     *
     * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
     * easily result in undesired exploitation or bugs, since developers usually
     * assume that overflows raise errors. `SafeCast` restores this intuition by
     * reverting the transaction when such an operation overflows.
     *
     * Using this library instead of the unchecked operations eliminates an entire
     * class of bugs, so it's recommended to use it always.
     *
     * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
     * all math on `uint256` and `int256` and then downcasting.
     */
    library SafeCast {
        /**
         * @dev Returns the downcasted uint224 from uint256, reverting on
         * overflow (when the input is greater than largest uint224).
         *
         * Counterpart to Solidity's `uint224` operator.
         *
         * Requirements:
         *
         * - input must fit into 224 bits
         */
        function toUint224(uint256 value) internal pure returns (uint224) {
            require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
            return uint224(value);
        }
        /**
         * @dev Returns the downcasted uint128 from uint256, reverting on
         * overflow (when the input is greater than largest uint128).
         *
         * Counterpart to Solidity's `uint128` operator.
         *
         * Requirements:
         *
         * - input must fit into 128 bits
         */
        function toUint128(uint256 value) internal pure returns (uint128) {
            require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
            return uint128(value);
        }
        /**
         * @dev Returns the downcasted uint96 from uint256, reverting on
         * overflow (when the input is greater than largest uint96).
         *
         * Counterpart to Solidity's `uint96` operator.
         *
         * Requirements:
         *
         * - input must fit into 96 bits
         */
        function toUint96(uint256 value) internal pure returns (uint96) {
            require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
            return uint96(value);
        }
        /**
         * @dev Returns the downcasted uint64 from uint256, reverting on
         * overflow (when the input is greater than largest uint64).
         *
         * Counterpart to Solidity's `uint64` operator.
         *
         * Requirements:
         *
         * - input must fit into 64 bits
         */
        function toUint64(uint256 value) internal pure returns (uint64) {
            require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
            return uint64(value);
        }
        /**
         * @dev Returns the downcasted uint32 from uint256, reverting on
         * overflow (when the input is greater than largest uint32).
         *
         * Counterpart to Solidity's `uint32` operator.
         *
         * Requirements:
         *
         * - input must fit into 32 bits
         */
        function toUint32(uint256 value) internal pure returns (uint32) {
            require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
            return uint32(value);
        }
        /**
         * @dev Returns the downcasted uint16 from uint256, reverting on
         * overflow (when the input is greater than largest uint16).
         *
         * Counterpart to Solidity's `uint16` operator.
         *
         * Requirements:
         *
         * - input must fit into 16 bits
         */
        function toUint16(uint256 value) internal pure returns (uint16) {
            require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
            return uint16(value);
        }
        /**
         * @dev Returns the downcasted uint8 from uint256, reverting on
         * overflow (when the input is greater than largest uint8).
         *
         * Counterpart to Solidity's `uint8` operator.
         *
         * Requirements:
         *
         * - input must fit into 8 bits.
         */
        function toUint8(uint256 value) internal pure returns (uint8) {
            require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
            return uint8(value);
        }
        /**
         * @dev Converts a signed int256 into an unsigned uint256.
         *
         * Requirements:
         *
         * - input must be greater than or equal to 0.
         */
        function toUint256(int256 value) internal pure returns (uint256) {
            require(value >= 0, "SafeCast: value must be positive");
            return uint256(value);
        }
        /**
         * @dev Returns the downcasted int128 from int256, reverting on
         * overflow (when the input is less than smallest int128 or
         * greater than largest int128).
         *
         * Counterpart to Solidity's `int128` operator.
         *
         * Requirements:
         *
         * - input must fit into 128 bits
         *
         * _Available since v3.1._
         */
        function toInt128(int256 value) internal pure returns (int128) {
            require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
            return int128(value);
        }
        /**
         * @dev Returns the downcasted int64 from int256, reverting on
         * overflow (when the input is less than smallest int64 or
         * greater than largest int64).
         *
         * Counterpart to Solidity's `int64` operator.
         *
         * Requirements:
         *
         * - input must fit into 64 bits
         *
         * _Available since v3.1._
         */
        function toInt64(int256 value) internal pure returns (int64) {
            require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
            return int64(value);
        }
        /**
         * @dev Returns the downcasted int32 from int256, reverting on
         * overflow (when the input is less than smallest int32 or
         * greater than largest int32).
         *
         * Counterpart to Solidity's `int32` operator.
         *
         * Requirements:
         *
         * - input must fit into 32 bits
         *
         * _Available since v3.1._
         */
        function toInt32(int256 value) internal pure returns (int32) {
            require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
            return int32(value);
        }
        /**
         * @dev Returns the downcasted int16 from int256, reverting on
         * overflow (when the input is less than smallest int16 or
         * greater than largest int16).
         *
         * Counterpart to Solidity's `int16` operator.
         *
         * Requirements:
         *
         * - input must fit into 16 bits
         *
         * _Available since v3.1._
         */
        function toInt16(int256 value) internal pure returns (int16) {
            require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
            return int16(value);
        }
        /**
         * @dev Returns the downcasted int8 from int256, reverting on
         * overflow (when the input is less than smallest int8 or
         * greater than largest int8).
         *
         * Counterpart to Solidity's `int8` operator.
         *
         * Requirements:
         *
         * - input must fit into 8 bits.
         *
         * _Available since v3.1._
         */
        function toInt8(int256 value) internal pure returns (int8) {
            require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
            return int8(value);
        }
        /**
         * @dev Converts an unsigned uint256 into a signed int256.
         *
         * Requirements:
         *
         * - input must be less than or equal to maxInt256.
         */
        function toInt256(uint256 value) internal pure returns (int256) {
            // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
            require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
            return int256(value);
        }
    }