ETH Price: $2,533.34 (-1.32%)

Transaction Decoder

Block:
20258752 at Jul-08-2024 02:16:35 AM +UTC
Transaction Fee:
0.000122321415518092 ETH $0.31
Gas Used:
41,069 Gas / 2.978436668 Gwei

Emitted Events:

865 TransparentUpgradeableProxy.0xbfe611b001dfcd411432f7bf0d79b82b4b2ee81511edac123a3403c357fb972a( 0xbfe611b001dfcd411432f7bf0d79b82b4b2ee81511edac123a3403c357fb972a, 0x0000000000000000000000000c1f4fd031d780965e8cd8195c0af21ec8c0c026, 0000000000000000000000000000000000000000000000000083d823be3d095f )

Account State Difference:

  Address   Before After State Difference Code
(MEV Builder: 0x0Aa...667)
2.568654468767079813 Eth
Nonce: 17473
2.531421277375339674 Eth
Nonce: 17474
0.037233191391740139
0xb3D9cf8E...E295B8f39
(Swell Network: Deposit Manager)
54.678555826459543761 Eth54.715666696435765808 Eth0.037110869976222047

Execution Trace

ETH 0.037110869976222047 0x0c1f4fd031d780965e8cd8195c0af21ec8c0c026.00000000( )
  • ETH 0.037110869976222047 TransparentUpgradeableProxy.CALL( )
    • ETH 0.037110869976222047 DepositManager.DELEGATECALL( )
      File 1 of 2: TransparentUpgradeableProxy
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
      import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";
      import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
      import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
      import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";
      // Kept for backwards compatibility with older versions of Hardhat and Truffle plugins.
      contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy {
          constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {}
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      import "./IBeacon.sol";
      import "../Proxy.sol";
      import "../ERC1967/ERC1967Upgrade.sol";
      /**
       * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
       *
       * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
       * conflict with the storage layout of the implementation behind the proxy.
       *
       * _Available since v3.4._
       */
      contract BeaconProxy is Proxy, ERC1967Upgrade {
          /**
           * @dev Initializes the proxy with `beacon`.
           *
           * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
           * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
           * constructor.
           *
           * Requirements:
           *
           * - `beacon` must be a contract with the interface {IBeacon}.
           */
          constructor(address beacon, bytes memory data) payable {
              assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1));
              _upgradeBeaconToAndCall(beacon, data, false);
          }
          /**
           * @dev Returns the current beacon address.
           */
          function _beacon() internal view virtual returns (address) {
              return _getBeacon();
          }
          /**
           * @dev Returns the current implementation address of the associated beacon.
           */
          function _implementation() internal view virtual override returns (address) {
              return IBeacon(_getBeacon()).implementation();
          }
          /**
           * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
           *
           * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
           *
           * Requirements:
           *
           * - `beacon` must be a contract.
           * - The implementation returned by `beacon` must be a contract.
           */
          function _setBeacon(address beacon, bytes memory data) internal virtual {
              _upgradeBeaconToAndCall(beacon, data, false);
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      import "./IBeacon.sol";
      import "../../access/Ownable.sol";
      import "../../utils/Address.sol";
      /**
       * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
       * implementation contract, which is where they will delegate all function calls.
       *
       * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
       */
      contract UpgradeableBeacon is IBeacon, Ownable {
          address private _implementation;
          /**
           * @dev Emitted when the implementation returned by the beacon is changed.
           */
          event Upgraded(address indexed implementation);
          /**
           * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
           * beacon.
           */
          constructor(address implementation_) {
              _setImplementation(implementation_);
          }
          /**
           * @dev Returns the current implementation address.
           */
          function implementation() public view virtual override returns (address) {
              return _implementation;
          }
          /**
           * @dev Upgrades the beacon to a new implementation.
           *
           * Emits an {Upgraded} event.
           *
           * Requirements:
           *
           * - msg.sender must be the owner of the contract.
           * - `newImplementation` must be a contract.
           */
          function upgradeTo(address newImplementation) public virtual onlyOwner {
              _setImplementation(newImplementation);
              emit Upgraded(newImplementation);
          }
          /**
           * @dev Sets the implementation contract address for this beacon
           *
           * Requirements:
           *
           * - `newImplementation` must be a contract.
           */
          function _setImplementation(address newImplementation) private {
              require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract");
              _implementation = newImplementation;
          }
      }
      // SPDX-License-Identifier: MIT
      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
      pragma solidity ^0.8.0;
      import "../ERC1967/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
      pragma solidity ^0.8.0;
      import "./TransparentUpgradeableProxy.sol";
      import "../../access/Ownable.sol";
      /**
       * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
       * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
       */
      contract ProxyAdmin is Ownable {
          /**
           * @dev Returns the current implementation of `proxy`.
           *
           * Requirements:
           *
           * - This contract must be the admin of `proxy`.
           */
          function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
              // We need to manually run the static call since the getter cannot be flagged as view
              // bytes4(keccak256("implementation()")) == 0x5c60da1b
              (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
              require(success);
              return abi.decode(returndata, (address));
          }
          /**
           * @dev Returns the current admin of `proxy`.
           *
           * Requirements:
           *
           * - This contract must be the admin of `proxy`.
           */
          function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
              // We need to manually run the static call since the getter cannot be flagged as view
              // bytes4(keccak256("admin()")) == 0xf851a440
              (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
              require(success);
              return abi.decode(returndata, (address));
          }
          /**
           * @dev Changes the admin of `proxy` to `newAdmin`.
           *
           * Requirements:
           *
           * - This contract must be the current admin of `proxy`.
           */
          function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
              proxy.changeAdmin(newAdmin);
          }
          /**
           * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
           *
           * Requirements:
           *
           * - This contract must be the admin of `proxy`.
           */
          function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
              proxy.upgradeTo(implementation);
          }
          /**
           * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
           * {TransparentUpgradeableProxy-upgradeToAndCall}.
           *
           * Requirements:
           *
           * - This contract must be the admin of `proxy`.
           */
          function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
              proxy.upgradeToAndCall{value: msg.value}(implementation, data);
          }
      }
      // SPDX-License-Identifier: MIT
      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
      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 {
              // solhint-disable-next-line no-inline-assembly
              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
      pragma solidity ^0.8.2;
      import "../beacon/IBeacon.sol";
      import "../../utils/Address.sol";
      import "../../utils/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 {
              _setImplementation(newImplementation);
              emit Upgraded(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
                  _setImplementation(newImplementation);
                  emit Upgraded(newImplementation);
              }
          }
          /**
           * @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);
              }
          }
          /**
           * @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;
          }
      }
      // SPDX-License-Identifier: MIT
      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;
              // solhint-disable-next-line no-inline-assembly
              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");
              // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
              (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");
              // solhint-disable-next-line avoid-low-level-calls
              (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");
              // solhint-disable-next-line avoid-low-level-calls
              (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");
              // solhint-disable-next-line avoid-low-level-calls
              (bool success, bytes memory returndata) = target.delegatecall(data);
              return _verifyCallResult(success, returndata, errorMessage);
          }
          function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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
                      // solhint-disable-next-line no-inline-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
      }
      // SPDX-License-Identifier: MIT
      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
              }
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      import "../utils/Context.sol";
      /**
       * @dev Contract module which provides a basic access control mechanism, where
       * there is an account (an owner) that can be granted exclusive access to
       * specific functions.
       *
       * By default, the owner account will be the one that deploys the contract. This
       * can later be changed with {transferOwnership}.
       *
       * This module is used through inheritance. It will make available the modifier
       * `onlyOwner`, which can be applied to your functions to restrict their use to
       * the owner.
       */
      abstract contract Ownable is Context {
          address private _owner;
          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          /**
           * @dev Initializes the contract setting the deployer as the initial owner.
           */
          constructor () {
              address msgSender = _msgSender();
              _owner = msgSender;
              emit OwnershipTransferred(address(0), msgSender);
          }
          /**
           * @dev Returns the address of the current owner.
           */
          function owner() public view virtual returns (address) {
              return _owner;
          }
          /**
           * @dev Throws if called by any account other than the owner.
           */
          modifier onlyOwner() {
              require(owner() == _msgSender(), "Ownable: caller is not the owner");
              _;
          }
          /**
           * @dev Leaves the contract without owner. It will not be possible to call
           * `onlyOwner` functions anymore. Can only be called by the current owner.
           *
           * NOTE: Renouncing ownership will leave the contract without an owner,
           * thereby removing any functionality that is only available to the owner.
           */
          function renounceOwnership() public virtual onlyOwner {
              emit OwnershipTransferred(_owner, address(0));
              _owner = address(0);
          }
          /**
           * @dev Transfers ownership of the contract to a new account (`newOwner`).
           * Can only be called by the current owner.
           */
          function transferOwnership(address newOwner) public virtual onlyOwner {
              require(newOwner != address(0), "Ownable: new owner is the zero address");
              emit OwnershipTransferred(_owner, newOwner);
              _owner = newOwner;
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      /*
       * @dev Provides information about the current execution context, including the
       * sender of the transaction and its data. While these are generally available
       * via msg.sender and msg.data, they should not be accessed in such a direct
       * manner, since when dealing with meta-transactions the account sending and
       * paying for execution may not be the actual sender (as far as an application
       * is concerned).
       *
       * This contract is only required for intermediate, library-like contracts.
       */
      abstract contract Context {
          function _msgSender() internal view virtual returns (address) {
              return msg.sender;
          }
          function _msgData() internal view virtual returns (bytes calldata) {
              this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
              return msg.data;
          }
      }
      

      File 2 of 2: DepositManager
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
      pragma solidity ^0.8.0;
      import "./IAccessControlUpgradeable.sol";
      /**
       * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
       */
      interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
          /**
           * @dev Returns one of the accounts that have `role`. `index` must be a
           * value between 0 and {getRoleMemberCount}, non-inclusive.
           *
           * Role bearers are not sorted in any particular way, and their ordering may
           * change at any point.
           *
           * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
           * you perform all queries on the same block. See the following
           * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
           * for more information.
           */
          function getRoleMember(bytes32 role, uint256 index) external view returns (address);
          /**
           * @dev Returns the number of accounts that have `role`. Can be used
           * together with {getRoleMember} to enumerate all bearers of a role.
           */
          function getRoleMemberCount(bytes32 role) external view returns (uint256);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev External interface of AccessControl declared to support ERC165 detection.
       */
      interface IAccessControlUpgradeable {
          /**
           * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
           *
           * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
           * {RoleAdminChanged} not being emitted signaling this.
           *
           * _Available since v3.1._
           */
          event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
          /**
           * @dev Emitted when `account` is granted `role`.
           *
           * `sender` is the account that originated the contract call, an admin role
           * bearer except when using {AccessControl-_setupRole}.
           */
          event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
          /**
           * @dev Emitted when `account` is revoked `role`.
           *
           * `sender` is the account that originated the contract call:
           *   - if using `revokeRole`, it is the admin role bearer
           *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
           */
          event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
          /**
           * @dev Returns `true` if `account` has been granted `role`.
           */
          function hasRole(bytes32 role, address account) external view returns (bool);
          /**
           * @dev Returns the admin role that controls `role`. See {grantRole} and
           * {revokeRole}.
           *
           * To change a role's admin, use {AccessControl-_setRoleAdmin}.
           */
          function getRoleAdmin(bytes32 role) external view returns (bytes32);
          /**
           * @dev Grants `role` to `account`.
           *
           * If `account` had not been already granted `role`, emits a {RoleGranted}
           * event.
           *
           * Requirements:
           *
           * - the caller must have ``role``'s admin role.
           */
          function grantRole(bytes32 role, address account) external;
          /**
           * @dev Revokes `role` from `account`.
           *
           * If `account` had been granted `role`, emits a {RoleRevoked} event.
           *
           * Requirements:
           *
           * - the caller must have ``role``'s admin role.
           */
          function revokeRole(bytes32 role, address account) external;
          /**
           * @dev Revokes `role` from the calling account.
           *
           * Roles are often managed via {grantRole} and {revokeRole}: this function's
           * purpose is to provide a mechanism for accounts to lose their privileges
           * if they are compromised (such as when a trusted device is misplaced).
           *
           * If the calling account had been granted `role`, emits a {RoleRevoked}
           * event.
           *
           * Requirements:
           *
           * - the caller must be `account`.
           */
          function renounceRole(bytes32 role, address account) external;
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
      pragma solidity ^0.8.2;
      import "../../utils/AddressUpgradeable.sol";
      /**
       * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
       * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
       * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
       * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
       *
       * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
       * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
       * case an upgrade adds a module that needs to be initialized.
       *
       * For example:
       *
       * [.hljs-theme-light.nopadding]
       * ```
       * contract MyToken is ERC20Upgradeable {
       *     function initialize() initializer public {
       *         __ERC20_init("MyToken", "MTK");
       *     }
       * }
       * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
       *     function initializeV2() reinitializer(2) public {
       *         __ERC20Permit_init("MyToken");
       *     }
       * }
       * ```
       *
       * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
       * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
       *
       * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
       * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
       *
       * [CAUTION]
       * ====
       * Avoid leaving a contract uninitialized.
       *
       * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
       * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
       * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
       *
       * [.hljs-theme-light.nopadding]
       * ```
       * /// @custom:oz-upgrades-unsafe-allow constructor
       * constructor() {
       *     _disableInitializers();
       * }
       * ```
       * ====
       */
      abstract contract Initializable {
          /**
           * @dev Indicates that the contract has been initialized.
           * @custom:oz-retyped-from bool
           */
          uint8 private _initialized;
          /**
           * @dev Indicates that the contract is in the process of being initialized.
           */
          bool private _initializing;
          /**
           * @dev Triggered when the contract has been initialized or reinitialized.
           */
          event Initialized(uint8 version);
          /**
           * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
           * `onlyInitializing` functions can be used to initialize parent contracts.
           *
           * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
           * constructor.
           *
           * Emits an {Initialized} event.
           */
          modifier initializer() {
              bool isTopLevelCall = !_initializing;
              require(
                  (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                  "Initializable: contract is already initialized"
              );
              _initialized = 1;
              if (isTopLevelCall) {
                  _initializing = true;
              }
              _;
              if (isTopLevelCall) {
                  _initializing = false;
                  emit Initialized(1);
              }
          }
          /**
           * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
           * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
           * used to initialize parent contracts.
           *
           * A reinitializer may be used after the original initialization step. This is essential to configure modules that
           * are added through upgrades and that require initialization.
           *
           * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
           * cannot be nested. If one is invoked in the context of another, execution will revert.
           *
           * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
           * a contract, executing them in the right order is up to the developer or operator.
           *
           * WARNING: setting the version to 255 will prevent any future reinitialization.
           *
           * Emits an {Initialized} event.
           */
          modifier reinitializer(uint8 version) {
              require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
              _initialized = version;
              _initializing = true;
              _;
              _initializing = false;
              emit Initialized(version);
          }
          /**
           * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
           * {initializer} and {reinitializer} modifiers, directly or indirectly.
           */
          modifier onlyInitializing() {
              require(_initializing, "Initializable: contract is not initializing");
              _;
          }
          /**
           * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
           * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
           * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
           * through proxies.
           *
           * Emits an {Initialized} event the first time it is successfully executed.
           */
          function _disableInitializers() internal virtual {
              require(!_initializing, "Initializable: contract is initializing");
              if (_initialized < type(uint8).max) {
                  _initialized = type(uint8).max;
                  emit Initialized(type(uint8).max);
              }
          }
          /**
           * @dev Returns the highest version that has been initialized. See {reinitializer}.
           */
          function _getInitializedVersion() internal view returns (uint8) {
              return _initialized;
          }
          /**
           * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
           */
          function _isInitializing() internal view returns (bool) {
              return _initializing;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 standard as defined in the EIP.
       */
      interface IERC20Upgradeable {
          /**
           * @dev Emitted when `value` tokens are moved from one account (`from`) to
           * another (`to`).
           *
           * Note that `value` may be zero.
           */
          event Transfer(address indexed from, address indexed to, uint256 value);
          /**
           * @dev Emitted when the allowance of a `spender` for an `owner` is set by
           * a call to {approve}. `value` is the new allowance.
           */
          event Approval(address indexed owner, address indexed spender, uint256 value);
          /**
           * @dev Returns the amount of tokens in existence.
           */
          function totalSupply() external view returns (uint256);
          /**
           * @dev Returns the amount of tokens owned by `account`.
           */
          function balanceOf(address account) external view returns (uint256);
          /**
           * @dev Moves `amount` tokens from the caller's account to `to`.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transfer(address to, uint256 amount) external returns (bool);
          /**
           * @dev Returns the remaining number of tokens that `spender` will be
           * allowed to spend on behalf of `owner` through {transferFrom}. This is
           * zero by default.
           *
           * This value changes when {approve} or {transferFrom} are called.
           */
          function allowance(address owner, address spender) external view returns (uint256);
          /**
           * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * IMPORTANT: Beware that changing an allowance with this method brings the risk
           * that someone may use both the old and the new allowance by unfortunate
           * transaction ordering. One possible solution to mitigate this race
           * condition is to first reduce the spender's allowance to 0 and set the
           * desired value afterwards:
           * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
           *
           * Emits an {Approval} event.
           */
          function approve(address spender, uint256 amount) external returns (bool);
          /**
           * @dev Moves `amount` tokens from `from` to `to` using the
           * allowance mechanism. `amount` is then deducted from the caller's
           * allowance.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(
              address from,
              address to,
              uint256 amount
          ) external returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)
      pragma solidity ^0.8.0;
      import "../../utils/introspection/IERC165Upgradeable.sol";
      /**
       * @dev Required interface of an ERC721 compliant contract.
       */
      interface IERC721Upgradeable is IERC165Upgradeable {
          /**
           * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
           */
          event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
          /**
           * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
           */
          event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
          /**
           * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
           */
          event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
          /**
           * @dev Returns the number of tokens in ``owner``'s account.
           */
          function balanceOf(address owner) external view returns (uint256 balance);
          /**
           * @dev Returns the owner of the `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function ownerOf(uint256 tokenId) external view returns (address owner);
          /**
           * @dev Safely transfers `tokenId` token from `from` to `to`.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must exist and be owned by `from`.
           * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
           * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
           *
           * Emits a {Transfer} event.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId,
              bytes calldata data
          ) external;
          /**
           * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
           * are aware of the ERC721 protocol to prevent tokens from being forever locked.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must exist and be owned by `from`.
           * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
           * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
           *
           * Emits a {Transfer} event.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external;
          /**
           * @dev Transfers `tokenId` token from `from` to `to`.
           *
           * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
           * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
           * understand this adds an external call which potentially creates a reentrancy vulnerability.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must be owned by `from`.
           * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external;
          /**
           * @dev Gives permission to `to` to transfer `tokenId` token to another account.
           * The approval is cleared when the token is transferred.
           *
           * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
           *
           * Requirements:
           *
           * - The caller must own the token or be an approved operator.
           * - `tokenId` must exist.
           *
           * Emits an {Approval} event.
           */
          function approve(address to, uint256 tokenId) external;
          /**
           * @dev Approve or remove `operator` as an operator for the caller.
           * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
           *
           * Requirements:
           *
           * - The `operator` cannot be the caller.
           *
           * Emits an {ApprovalForAll} event.
           */
          function setApprovalForAll(address operator, bool _approved) external;
          /**
           * @dev Returns the account approved for `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function getApproved(uint256 tokenId) external view returns (address operator);
          /**
           * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
           *
           * See {setApprovalForAll}
           */
          function isApprovedForAll(address owner, address operator) external view returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.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 functionCallWithValue(target, data, 0, "Address: low-level call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
           * `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but also transferring `value` wei to `target`.
           *
           * Requirements:
           *
           * - the calling contract must have an ETH balance of at least `value`.
           * - the called Solidity function must be `payable`.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
          }
          /**
           * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
           * with `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value,
              string memory errorMessage
          ) internal returns (bytes memory) {
              require(address(this).balance >= value, "Address: insufficient balance for call");
              (bool success, bytes memory returndata) = target.call{value: value}(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
              return functionStaticCall(target, data, "Address: low-level static call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              (bool success, bytes memory returndata) = target.staticcall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
           * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
           *
           * _Available since v4.8._
           */
          function verifyCallResultFromTarget(
              address target,
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              if (success) {
                  if (returndata.length == 0) {
                      // only check isContract if the call was successful and the return data is empty
                      // otherwise we already know that it was a contract
                      require(isContract(target), "Address: call to non-contract");
                  }
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          /**
           * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
           * revert reason or using the provided one.
           *
           * _Available since v4.3._
           */
          function verifyCallResult(
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal pure returns (bytes memory) {
              if (success) {
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          function _revert(bytes memory returndata, string memory errorMessage) private pure {
              // Look for revert reason and bubble it up if present
              if (returndata.length > 0) {
                  // The easiest way to bubble the revert reason is using memory via assembly
                  /// @solidity memory-safe-assembly
                  assembly {
                      let returndata_size := mload(returndata)
                      revert(add(32, returndata), returndata_size)
                  }
              } else {
                  revert(errorMessage);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts 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 (token/ERC20/extensions/draft-IERC20Permit.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
       * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
       *
       * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
       * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
       * need to send a transaction, and thus is not required to hold Ether at all.
       */
      interface IERC20Permit {
          /**
           * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
           * given ``owner``'s signed approval.
           *
           * IMPORTANT: The same issues {IERC20-approve} has related to transaction
           * ordering also apply here.
           *
           * Emits an {Approval} event.
           *
           * Requirements:
           *
           * - `spender` cannot be the zero address.
           * - `deadline` must be a timestamp in the future.
           * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
           * over the EIP712-formatted function arguments.
           * - the signature must use ``owner``'s current nonce (see {nonces}).
           *
           * For more information on the signature format, see the
           * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
           * section].
           */
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) external;
          /**
           * @dev Returns the current nonce for `owner`. This value must be
           * included whenever a signature is generated for {permit}.
           *
           * Every successful call to {permit} increases ``owner``'s nonce by one. This
           * prevents a signature from being used multiple times.
           */
          function nonces(address owner) external view returns (uint256);
          /**
           * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
           */
          // solhint-disable-next-line func-name-mixedcase
          function DOMAIN_SEPARATOR() external view returns (bytes32);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 standard as defined in the EIP.
       */
      interface IERC20 {
          /**
           * @dev Emitted when `value` tokens are moved from one account (`from`) to
           * another (`to`).
           *
           * Note that `value` may be zero.
           */
          event Transfer(address indexed from, address indexed to, uint256 value);
          /**
           * @dev Emitted when the allowance of a `spender` for an `owner` is set by
           * a call to {approve}. `value` is the new allowance.
           */
          event Approval(address indexed owner, address indexed spender, uint256 value);
          /**
           * @dev Returns the amount of tokens in existence.
           */
          function totalSupply() external view returns (uint256);
          /**
           * @dev Returns the amount of tokens owned by `account`.
           */
          function balanceOf(address account) external view returns (uint256);
          /**
           * @dev Moves `amount` tokens from the caller's account to `to`.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transfer(address to, uint256 amount) external returns (bool);
          /**
           * @dev Returns the remaining number of tokens that `spender` will be
           * allowed to spend on behalf of `owner` through {transferFrom}. This is
           * zero by default.
           *
           * This value changes when {approve} or {transferFrom} are called.
           */
          function allowance(address owner, address spender) external view returns (uint256);
          /**
           * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * IMPORTANT: Beware that changing an allowance with this method brings the risk
           * that someone may use both the old and the new allowance by unfortunate
           * transaction ordering. One possible solution to mitigate this race
           * condition is to first reduce the spender's allowance to 0 and set the
           * desired value afterwards:
           * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
           *
           * Emits an {Approval} event.
           */
          function approve(address spender, uint256 amount) external returns (bool);
          /**
           * @dev Moves `amount` tokens from `from` to `to` using the
           * allowance mechanism. `amount` is then deducted from the caller's
           * allowance.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(
              address from,
              address to,
              uint256 amount
          ) external returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
      pragma solidity ^0.8.0;
      import "../IERC20.sol";
      import "../extensions/draft-IERC20Permit.sol";
      import "../../../utils/Address.sol";
      /**
       * @title SafeERC20
       * @dev Wrappers around ERC20 operations that throw on failure (when the token
       * contract returns false). Tokens that return no value (and instead revert or
       * throw on failure) are also supported, non-reverting calls are assumed to be
       * successful.
       * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
       * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
       */
      library SafeERC20 {
          using Address for address;
          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));
              }
          }
          function safePermit(
              IERC20Permit token,
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) internal {
              uint256 nonceBefore = token.nonces(owner);
              token.permit(owner, spender, value, deadline, v, r, s);
              uint256 nonceAfter = token.nonces(owner);
              require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
          }
          /**
           * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
           * on the return value: the return value is optional (but if data is returned, it must not be false).
           * @param token The token targeted by the call.
           * @param data The call data (encoded using abi.encode or one of its variants).
           */
          function _callOptionalReturn(IERC20 token, bytes memory data) private {
              // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
              // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
              // the target address contains contract code and also asserts for success in the low-level call.
              bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
              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 (last updated v4.8.0) (utils/Address.sol)
      pragma solidity ^0.8.1;
      /**
       * @dev Collection of functions related to the address type
       */
      library Address {
          /**
           * @dev Returns true if `account` is a contract.
           *
           * [IMPORTANT]
           * ====
           * It is unsafe to assume that an address for which this function returns
           * false is an externally-owned account (EOA) and not a contract.
           *
           * Among others, `isContract` will return false for the following
           * types of addresses:
           *
           *  - an externally-owned account
           *  - a contract in construction
           *  - an address where a contract will be created
           *  - an address where a contract lived, but was destroyed
           * ====
           *
           * [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 functionCallWithValue(target, data, 0, "Address: low-level call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
           * `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but also transferring `value` wei to `target`.
           *
           * Requirements:
           *
           * - the calling contract must have an ETH balance of at least `value`.
           * - the called Solidity function must be `payable`.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
          }
          /**
           * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
           * with `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value,
              string memory errorMessage
          ) internal returns (bytes memory) {
              require(address(this).balance >= value, "Address: insufficient balance for call");
              (bool success, bytes memory returndata) = target.call{value: value}(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
              return functionStaticCall(target, data, "Address: low-level static call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              (bool success, bytes memory returndata) = target.staticcall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionDelegateCall(target, data, "Address: low-level delegate call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              (bool success, bytes memory returndata) = target.delegatecall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
           * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
           *
           * _Available since v4.8._
           */
          function verifyCallResultFromTarget(
              address target,
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              if (success) {
                  if (returndata.length == 0) {
                      // only check isContract if the call was successful and the return data is empty
                      // otherwise we already know that it was a contract
                      require(isContract(target), "Address: call to non-contract");
                  }
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          /**
           * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
           * revert reason or using the provided one.
           *
           * _Available since v4.3._
           */
          function verifyCallResult(
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal pure returns (bytes memory) {
              if (success) {
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          function _revert(bytes memory returndata, string memory errorMessage) private pure {
              // Look for revert reason and bubble it up if present
              if (returndata.length > 0) {
                  // The easiest way to bubble the revert reason is using memory via assembly
                  /// @solidity memory-safe-assembly
                  assembly {
                      let returndata_size := mload(returndata)
                      revert(add(32, returndata), returndata_size)
                  }
              } else {
                  revert(errorMessage);
              }
          }
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.16;
      import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
      import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
      import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
      import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
      import {IAccessControlManager} from "../interfaces/IAccessControlManager.sol";
      import {IDepositManager} from "../interfaces/IDepositManager.sol";
      import {INodeOperatorRegistry} from "../interfaces/INodeOperatorRegistry.sol";
      import {SwellLib} from "../libraries/SwellLib.sol";
      import {DepositDataRoot} from "../libraries/DepositDataRoot.sol";
      import {IDepositContract} from "../vendors/IDepositContract.sol";
      /**
       * @title DepositManager
       * @author https://github.com/max-taylor
       * @notice This contract will hold the ETH while awaiting new validator setup. This contract will also be used as the withdrawal_credentials when setting up new validators, so that any exited validator ETH and rewards will be sent here.
       */
      contract DepositManager is IDepositManager, Initializable {
        using SafeERC20 for IERC20;
        IAccessControlManager public AccessControlManager;
        IDepositContract public DepositContract;
        /// @custom:oz-upgrades-unsafe-allow constructor
        constructor() {
          _disableInitializers();
        }
        modifier checkRole(bytes32 role) {
          AccessControlManager.checkRole(role, msg.sender);
          _;
        }
        /**
         * @dev Modifier to check for empty addresses
         * @param _address The address to check
         */
        modifier checkZeroAddress(address _address) {
          SwellLib._checkZeroAddress(_address);
          _;
        }
        fallback() external {
          revert SwellLib.InvalidMethodCall();
        }
        receive() external payable {
          emit ETHReceived(msg.sender, msg.value);
        }
        function initialize(
          IAccessControlManager _accessControlManager
        ) external initializer checkZeroAddress(address(_accessControlManager)) {
          DepositContract = IDepositContract(
            // Hardcoded address for the ETH2 deposit contract
            // Mainnet - 0x00000000219ab540356cBB839Cbe05303d7705Fa
            // Goerli - 0xff50ed3d0ec03aC01D4C79aAd74928BFF48a7b2b
            0x00000000219ab540356cBB839Cbe05303d7705Fa
          );
          AccessControlManager = _accessControlManager;
        }
        // ************************************
        // ***** External methods ******
        function withdrawERC20(
          IERC20 _token
        ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
          uint256 contractBalance = _token.balanceOf(address(this));
          if (contractBalance == 0) {
            revert SwellLib.NoTokensToWithdraw();
          }
          _token.safeTransfer(msg.sender, contractBalance);
        }
        function setupValidators(
          bytes[] calldata _pubKeys,
          bytes32 _depositDataRoot
        ) external override checkRole(SwellLib.BOT) {
          if (_pubKeys.length == 0) {
            revert NoPubKeysProvided();
          }
          if (AccessControlManager.botMethodsPaused()) {
            revert SwellLib.BotMethodsPaused();
          }
          // Protect against this method being front-ran by an operator
          if (_depositDataRoot != DepositContract.get_deposit_root()) {
            revert InvalidDepositDataRoot();
          }
          uint256 exitingETH = AccessControlManager.swEXIT().exitingETH();
          // Validator setup in the deposit contract requires 32 ETH
          uint256 depositAmount = 32 ether;
          if (address(this).balance < _pubKeys.length * depositAmount + exitingETH) {
            revert InsufficientETHBalance();
          }
          // Validates all the provided pubKeys have been registered by the Node operator registry and are pending validator keys, also return the signatures for each
          INodeOperatorRegistry.ValidatorDetails[]
            memory validatorDetails = AccessControlManager
              .NodeOperatorRegistry()
              .usePubKeysForValidatorSetup(_pubKeys);
          // Cache the withdrawal credentials
          bytes memory withdrawalCredentials = getWithdrawalCredentials();
          uint256 validatorDetailsLength = validatorDetails.length;
          for (uint256 i; i < validatorDetailsLength; ) {
            bytes32 depositDataRoot = DepositDataRoot.formatDepositDataRoot(
              validatorDetails[i].pubKey,
              withdrawalCredentials,
              validatorDetails[i].signature,
              depositAmount
            );
            DepositContract.deposit{value: depositAmount}(
              validatorDetails[i].pubKey,
              withdrawalCredentials,
              validatorDetails[i].signature,
              depositDataRoot
            );
            unchecked {
              ++i;
            }
          }
          emit ValidatorsSetup(_pubKeys);
        }
        function transferETHForWithdrawRequests(uint256 _amount) external override {
          if (msg.sender != address(AccessControlManager.swEXIT())) {
            revert OnlySwEXITCanWithdrawETH();
          }
          AddressUpgradeable.sendValue(payable(msg.sender), _amount);
          emit EthSent(msg.sender, _amount);
        }
        function getWithdrawalCredentials()
          public
          view
          override
          returns (bytes memory withdrawalCredentials)
        {
          // Create the bytes array which will contain the withdrawal credentials, this must be a dynamic bytes array of 32 length in order to work with the deposit contract
          withdrawalCredentials = new bytes(32);
          // Store the ETH1 withdrawal prefix, see IDepositManager.sol for more details
          withdrawalCredentials[0] = 0x01;
          assembly {
            // Add 44 bytes to the withdrawalCredentials memory address; 32 bytes to skip over the length storage slot and another 12 (the prefix + 11 empty bytes)
            // The remaining 20 bytes are to store the address of the contract. To enable this we must bit shift left the address() variable by 96 bits (12 bytes), so that instead of address() taking up the last 20 bytes it will instead take up the first 20 so that it can be copied into the remaining 20 bytes in the withdrawalCredentials
            mstore(add(withdrawalCredentials, 44), shl(96, address()))
          }
        }
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.16;
      import {IAccessControlEnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol";
      import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
      import {IDepositManager} from "./IDepositManager.sol";
      import {IswETH} from "./IswETH.sol";
      import {IswEXIT} from "./IswEXIT.sol";
      import {INodeOperatorRegistry} from "./INodeOperatorRegistry.sol";
      /**
        @title IAccessControlManager
        @author https://github.com/max-taylor 
        @dev The interface for the Access Control Manager, which manages roles and permissions for contracts within the Swell ecosystem
      */
      interface IAccessControlManager is IAccessControlEnumerableUpgradeable {
        // ***** Structs ******
        /**
          @dev Parameters for initializing the contract.
          @param admin The admin address
          @param swellTreasury The swell treasury address
        */
        struct InitializeParams {
          address admin;
          address swellTreasury;
        }
        // ***** Errors ******
        /**
          @dev Error thrown when attempting to pause an already-paused boolean
        */
        error AlreadyPaused();
        /**
          @dev Error thrown when attempting to unpause an already-unpaused boolean
        */
        error AlreadyUnpaused();
        // ***** Events ******
        /**
          @dev Emitted when a new DepositManager contract address is set.
          @param newAddress The new DepositManager contract address.
          @param oldAddress The old DepositManager contract address.
        */
        event UpdatedDepositManager(address newAddress, address oldAddress);
        /**
          @dev Emitted when a new NodeOperatorRegistry contract address is set.
          @param newAddress The new NodeOperatorRegistry contract address.
          @param oldAddress The old NodeOperatorRegistry contract address.
        */
        event UpdatedNodeOperatorRegistry(address newAddress, address oldAddress);
        /**
          @dev Emitted when a new SwellTreasury contract address is set.
          @param newAddress The new SwellTreasury contract address.
          @param oldAddress The old SwellTreasury contract address.
        */
        event UpdatedSwellTreasury(address newAddress, address oldAddress);
        /**
          @dev Emitted when a new SwETH contract address is set.
          @param newAddress The new SwETH contract address.
          @param oldAddress The old SwETH contract address.
        */
        event UpdatedSwETH(address newAddress, address oldAddress);
        /**
          @dev Emitted when a new swEXIT contract address is set.
          @param newAddress The new swEXIT contract address.
          @param oldAddress The old swEXIT contract address.
        */
        event UpdatedSwEXIT(address newAddress, address oldAddress);
        /**
          @dev Emitted when core methods functionality is paused or unpaused.
          @param newPausedStatus The new paused status.
        */
        event CoreMethodsPause(bool newPausedStatus);
        /**
          @dev Emitted when bot methods functionality is paused or unpaused.
          @param newPausedStatus The new paused status.
        */
        event BotMethodsPause(bool newPausedStatus);
        /**
          @dev Emitted when operator methods functionality is paused or unpaused.
          @param newPausedStatus The new paused status.
        */
        event OperatorMethodsPause(bool newPausedStatus);
        /**
          @dev Emitted when withdrawals functionality is paused or unpaused.
          @param newPausedStatus The new paused status.
        */
        event WithdrawalsPause(bool newPausedStatus);
        /**
          @dev Emitted when all functionality is paused.
        */
        event Lockdown();
        // ************************************
        // ***** External Methods ******
        /**
         * @dev Pass-through method to call the _checkRole method on the inherited access control contract. This method is to be used by external contracts that are using this centralised access control manager, this ensures that if the check fails it reverts with the correct access control error message
         * @param role The role to check
         * @param account The account to check for
         */
        function checkRole(bytes32 role, address account) external view;
        // ***** Setters ******
        /**
         * @notice Sets the `swETH` address to `_swETH`.
         * @dev This function is only callable by the `PLATFORM_ADMIN` role.
         * @param _swETH The address of the `swETH` contract.
         */
        function setSwETH(IswETH _swETH) external;
        /**
         * @notice Sets the `swEXIT` address to `_swEXIT`.
         * @dev This function is only callable by the `PLATFORM_ADMIN` role.
         * @param _swEXIT The address of the `swEXIT` contract.
         */
        function setSwEXIT(IswEXIT _swEXIT) external;
        /**
         * @notice Sets the `DepositManager` address to `_depositManager`.
         * @dev This function is only callable by the `PLATFORM_ADMIN` role.
         * @param _depositManager The address of the `DepositManager` contract.
         */
        function setDepositManager(IDepositManager _depositManager) external;
        /**
         * @notice Sets the `NodeOperatorRegistry` address to `_NodeOperatorRegistry`.
         * @dev This function is only callable by the `PLATFORM_ADMIN` role.
         * @param _NodeOperatorRegistry The address of the `NodeOperatorRegistry` contract.
         */
        function setNodeOperatorRegistry(
          INodeOperatorRegistry _NodeOperatorRegistry
        ) external;
        /**
         * @notice Sets the `SwellTreasury` address to `_swellTreasury`.
         * @dev This function is only callable by the `PLATFORM_ADMIN` role.
         * @param _swellTreasury The new address of the `SwellTreasury` contract.
         */
        function setSwellTreasury(address _swellTreasury) external;
        // ***** Getters ******
        /**
          @dev Returns the PLATFORM_ADMIN role.
          @return The bytes32 representation of the PLATFORM_ADMIN role.
        */
        function PLATFORM_ADMIN() external pure returns (bytes32);
        /**
          @dev Returns the Swell ETH contract.
          @return The Swell ETH contract.
        */
        function swETH() external view returns (IswETH);
        /**
         * @dev Returns the swEXIT contract.
         * @return The swEXIT contract.
         */
        function swEXIT() external view returns (IswEXIT);
        /**
          @dev Returns the address of the Swell Treasury contract.
          @return The address of the Swell Treasury contract.
        */
        function SwellTreasury() external view returns (address);
        /**
          @dev Returns the Deposit Manager contract.
          @return The Deposit Manager contract.
        */
        function DepositManager() external view returns (IDepositManager);
        /**
          @dev Returns the Node Operator Registry contract.
          @return The Node Operator Registry contract.
        */
        function NodeOperatorRegistry() external view returns (INodeOperatorRegistry);
        /**
          @dev Returns true if core methods are currently paused.
          @return Whether core methods are paused.
        */
        function coreMethodsPaused() external view returns (bool);
        /**
          @dev Returns true if bot methods are currently paused.
          @return Whether bot methods are paused.
        */
        function botMethodsPaused() external view returns (bool);
        /**
          @dev Returns true if operator methods are currently paused.
          @return Whether operator methods are paused.
        */
        function operatorMethodsPaused() external view returns (bool);
        /**
          @dev Returns true if withdrawals are currently paused.
          @dev ! Note that this is completely unused in the current implementation and is a placeholder that will be used once the withdrawals are implemented.
          @return Whether withdrawals are paused.
        */
        function withdrawalsPaused() external view returns (bool);
        // ***** Pausable methods ******
        /**
          @dev Pauses the core methods of the Swell ecosystem, only callable by the PAUSER role
        */
        function pauseCoreMethods() external;
        /**
          @dev Unpauses the core methods of the Swell ecosystem, only callable by the UNPAUSER role
        */
        function unpauseCoreMethods() external;
        /**
          @dev Pauses the bot specific methods, only callable by the PAUSER role
        */
        function pauseBotMethods() external;
        /**
          @dev Unpauses the bot specific methods, only callable by the UNPAUSER role
        */
        function unpauseBotMethods() external;
        /**
          @dev Pauses the operator methods in the NO registry contract, only callable by the PAUSER role
        */
        function pauseOperatorMethods() external;
        /**
          @dev Unpauses the operator methods in the NO registry contract, only callable by the UNPAUSER role
        */
        function unpauseOperatorMethods() external;
        /**
          @dev Pauses the withdrawals of the Swell ecosystem, only callable by the PAUSER role
        */
        function pauseWithdrawals() external;
        /**
          @dev Unpauses the withdrawals of the Swell ecosystem, only callable by the UNPAUSER role
        */
        function unpauseWithdrawals() external;
        /**
          @dev Pause all the methods in one go, only callable by the PAUSER role.
        */
        function lockdown() external;
        /**
         * @dev This method withdraws contract's _token balance to a platform admin
         * @param _token The ERC20 token to withdraw from the contract
         */
        function withdrawERC20(IERC20 _token) external;
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.16;
      import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
      /**
       * @title IDepositManager
       * @author https://github.com/max-taylor
       * @notice The interface for the deposit manager contract
       */
      interface IDepositManager {
        // ***** Errors ******
        /**
         * @dev Error thrown when the depositDataRoot parameter in the setupValidators contract doesn't match the onchain deposit data root from the deposit contract
         */
        error InvalidDepositDataRoot();
        /**
         * @dev Error thrown when setting up new validators and the contract doesn't hold enough ETH to be able to set them up.
         */
        error InsufficientETHBalance();
        /**
         * @dev Error thrown when the transferETHForWithdrawRequests method is called from an account other than swEXIT
         */
        error OnlySwEXITCanWithdrawETH();
        /**
         * @dev Error thrown when no public keys are provided to setupValidators
         */
        error NoPubKeysProvided();
        // ***** Events ******
        /**
         * Emitted when new validators are setup
         * @param pubKeys The pubKeys that have been used for validator setup
         */
        event ValidatorsSetup(bytes[] pubKeys);
        /**
         * @dev Event is fired when some contracts receive ETH
         * @param from The account that sent the ETH
         * @param amount The amount of ETH received
         */
        event ETHReceived(address indexed from, uint256 amount);
        /**
         * @dev Event is fired when the DepositManager sends ETH, this will currently only happen when swEXIT calls transferETHForWithdrawRequests to get ETH for fulfill withdraw requests
         * @param to The account that is receiving the ETH
         * @param amount The amount of ETH sent
         */
        event EthSent(address indexed to, uint256 amount);
        // ************************************
        // ***** External methods ******
        /**
         * @dev This method is called by swEXIT when it needs ETH to fulfill withdraw requests
         * @param _amount The amount of ETH to transfer to swEXIT
         */
        function transferETHForWithdrawRequests(uint256 _amount) external;
        /**
         * @dev This method withdraws contract's _token balance to a platform admin
         * @param _token The ERC20 token to withdraw from the contract
         */
        function withdrawERC20(IERC20 _token) external;
        /**
         * @dev Formats ETH1 the withdrawal credentials according to the following standard: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/validator.md#eth1_address_withdrawal_prefix
         * @dev It doesn't outline the withdrawal prefixes, they can be found here: https://eth2book.info/altair/part3/config/constants#withdrawal-prefixes
         * @dev As the DepositManager on the execution layer is going to be the withdrawal contract, we will be doing ETH1 withdrawals. The standard for this is a 32 byte response where; the first byte stores the withdrawal prefix (0x01), the following 11 bytes are empty and the last 20 bytes are the address
         */
        function getWithdrawalCredentials()
          external
          view
          returns (bytes memory withdrawalCredentials);
        /**
         * @dev This method allows setting up of new validators in the beacon deposit contract, it ensures the provided pubKeys are unused in the NO registry
         * @notice An off-chain service provides front-running protection by validating each pubKey ensuring that it hasn't been used for a validator setup. This service snapshots the depositDataRoot of the deposit contract, then this value is re-read from the deposit contract within setupValdiators() and ensures that they match, this consistency provides the front-running protection. Read more here: https://research.lido.fi/t/mitigations-for-deposit-front-running-vulnerability/1239
         * @param _pubKeys The pubKeys to setup
         * @param _depositDataRoot The deposit contracts deposit root which MUST match the current beacon deposit contract deposit data root otherwise the contract will revert due to the risk of the front-running vulnerability.
         */
        function setupValidators(
          bytes[] calldata _pubKeys,
          bytes32 _depositDataRoot
        ) external;
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.16;
      import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
      import {IAccessControlManager} from "../interfaces/IAccessControlManager.sol";
      import {IPoRAddresses} from "../vendors/IPoRAddresses.sol";
      /**
       * @title INodeOperatorRegistry
       * @author https://github.com/max-taylor
       * @notice Interface for the Node Operator Registry contract.
       */
      interface INodeOperatorRegistry is IPoRAddresses {
        /**
         * @dev  Struct containing the required details to setup a validator on the beacon chain
         * @param pubKey Public key of the validator
         * @param signature The signature of the validator
         */
        struct ValidatorDetails {
          bytes pubKey;
          bytes signature;
        }
        /**
         * @dev  Struct containing operator details
         * @param enabled Flag indicating if the operator is enabled or disabled
         * @param rewardAddress Address to sending repricing rewards to
         * @param controllingAddress The address that can control the operator account
         * @param name The name of the operator
         * @param activeValidators The amount of active validators for the operator
         */
        struct Operator {
          bool enabled;
          address rewardAddress;
          address controllingAddress;
          string name;
          uint128 activeValidators;
        }
        // ***** Events *****
        /**
         * @dev  Emitted when a new operator is added.
         * @param operatorAddress  The address of the newly added operator.
         * @param rewardAddress    The address associated with the reward for the operator.
         */
        event OperatorAdded(address operatorAddress, address rewardAddress);
        /**
         * @dev  Emitted when an operator is enabled.
         * @param operator  The address of the operator that was enabled.
         */
        event OperatorEnabled(address indexed operator);
        /**
         * @dev  Emitted when an operator is disabled.
         * @param operator  The address of the operator that was disabled.
         */
        event OperatorDisabled(address indexed operator);
        /**
         * @dev  Emitted when the validator details for an operator are added.
         * @param operator  The address of the operator for which the validator details were added.
         * @param pubKeys   An array of `ValidatorDetails` for the operator.
         */
        event OperatorAddedValidatorDetails(
          address indexed operator,
          ValidatorDetails[] pubKeys
        );
        /**
         * @dev  Emitted when active public keys are deleted.
         * @param pubKeys  An array of public keys that were deleted.
         */
        event ActivePubKeysDeleted(bytes[] pubKeys);
        /**
         * @dev  Emitted when pending public keys are deleted.
         * @param pubKeys  An array of public keys that were deleted.
         */
        event PendingPubKeysDeleted(bytes[] pubKeys);
        /**
         * @dev  Emitted when public keys are used for validator setup.
         * @param pubKeys  An array of public keys that were used for validator setup.
         */
        event PubKeysUsedForValidatorSetup(bytes[] pubKeys);
        /**
         * @dev  Emitted when the controlling address for an operator is updated.
         * @param oldControllingAddress  The old controlling address for the operator.
         * @param newControllingAddress  The new controlling address for the operator.
         */
        event OperatorControllingAddressUpdated(
          address indexed oldControllingAddress,
          address indexed newControllingAddress
        );
        /**
         * @dev  Emitted when the reward address for an operator is updated.
         * @param operator  The address of the operator for which the reward address was updated.
         * @param newRewardAddress  The new reward address for the operator.
         * @param oldRewardAddress  The old reward address for the operator.
         */
        event OperatorRewardAddressUpdated(
          address indexed operator,
          address indexed newRewardAddress,
          address indexed oldRewardAddress
        );
        /**
         * @dev  Emitted when the name for an operator is updated.
         * @param operator  The address of the operator for which the name was updated.
         * @param newName  The new name for the operator.
         * @param oldName  The old name for the operator.
         */
        event OperatorNameUpdated(
          address indexed operator,
          string newName,
          string oldName
        );
        // ***** Errors *****
        /**
         * @dev Thrown when an operator is not found.
         * @param operator  The address of the operator that was not found.
         */
        error NoOperatorFound(address operator);
        /**
         * @dev Thrown when an operator already exists.
         * @param operator The address of the operator that already exists.
         */
        error OperatorAlreadyExists(address operator);
        /**
         * @dev Thrown when an operator is already enabled.
         */
        error OperatorAlreadyEnabled();
        /**
         * @dev Thrown when an operator is already disabled.
         */
        error OperatorAlreadyDisabled();
        /**
         * @dev Thrown when an array length of zero is invalid.
         */
        error InvalidArrayLengthOfZero();
        /**
         * @dev Thrown when an operator is adding new validator details and this causes the total amount of operator's validator details to exceed uint128
         */
        error AmountOfValidatorDetailsExceedsLimit();
        /**
         * @dev Thrown during setup of new validators, when comparing the next operator's public key to the provided public key they should match. This ensures consistency in the tracking of the active and pending validator details.
         * @param foundPubKey The operator's next available public key
         * @param providedPubKey The public key that was passed in as an argument
         */
        error NextOperatorPubKeyMismatch(bytes foundPubKey, bytes providedPubKey);
        /**
         * @dev Thrown during the setup of new validators and when the operator that has no pending details left to use
         */
        error OperatorOutOfPendingKeys();
        /**
         * @dev Thrown when the given pubKey hasn't been added to the registry and cannot be found
         * @param pubKey  The public key that was not found.
         */
        error NoPubKeyFound(bytes pubKey);
        /**
         * @dev Thrown when an operator tries to use the node operator registry whilst they are disabled
         */
        error CannotUseDisabledOperator();
        /**
         * @dev Thrown when a duplicate public key is added.
         * @param existingKey  The public key that already exists.
         */
        error CannotAddDuplicatePubKey(bytes existingKey);
        /**
         * @dev Thrown when the given pubKey doesn't exist in the pending validator details sets
         * @param pubKey  The missing pubKey
         */
        error MissingPendingValidatorDetails(bytes pubKey);
        /**
         * @dev Thrown when the pubKey doesn't exist in the active validator details set
         * @param pubKey  The missing pubKey
         */
        error MissingActiveValidatorDetails(bytes pubKey);
        /**
         * @dev Throw when the msg.sender isn't the Deposit Manager contract
         */
        error InvalidPubKeySetupCaller();
        /**
         * @dev Thrown when an operator is trying to add validator details and a provided pubKey isn't the correct length
         */
        error InvalidPubKeyLength();
        /**
         * @dev Thrown when an operator is trying to add validator details and a provided signature isn't the correct length
         */
        error InvalidSignatureLength();
        /**
         * @dev Thrown when calling the delete active validators method from an address that doens't have the PLATFORM_ADMIN or DELETE_ACTIVE_VALIDATORS role
         */
        error InvalidCallerToDeleteActiveValidators();
        /**
         * @dev Thrown when trying to update the controlling address for an operator and the new controlling address is the same as the current controlling address
         */
        error CannotSetOperatorControllingAddressToSameAddress();
        /**
         * @dev Thrown when trying to update the controlling address for an operator and the new controlling address is already assigned to another operator
         */
        error CannotUpdateOperatorControllingAddressToAlreadyAssignedAddress();
        // ************************************
        // ***** External  methods ******
        /**
         * @dev This method withdraws contract's _token balance to a PLATFORM_ADMIN
         * @param _token The ERC20 token to withdraw from the contract
         */
        function withdrawERC20(IERC20 _token) external;
        /**
         * @dev  Gets the next available validator details, ordered by operators with the least amount of active validators. There may be less available validators then the provided _numNewValidators amount, in that case the function will return an array of length equal to _numNewValidators but all indexes after the second return value; foundValidators, will be 0x0 values
         * @param _numNewValidators The number of new validators to get details for.
         * @return An array of ValidatorDetails and the length of the array of non-zero validator details
         * @notice This method tries to return enough validator details to equal the provided _numNewValidators, but if there aren't enough validator details to find, it will simply return what it found, and the caller will need to check for empty values.
         */
        function getNextValidatorDetails(
          uint256 _numNewValidators
        ) external view returns (ValidatorDetails[] memory, uint256 foundValidators);
        /**
         * @dev  Allows the DepositManager to move provided _pubKeys from the pending validator details arrays into the active validator details array. It also returns the validator details, so that the DepositManager can pass the signature along to the ETH2 deposit contract.
         * @param _pubKeys Array of public keys to use for validator setup.
         * @return validatorDetails The associated validator details for the given public keys
         * @notice This method will be called when the DepositManager is setting up new validators.
         */
        function usePubKeysForValidatorSetup(
          bytes[] calldata _pubKeys
        ) external returns (ValidatorDetails[] memory validatorDetails);
        // ** Operator management methods **
        /**
         * @dev  Adds new validator details to the registry.
        /**
         * @dev  Callable by node operator's to add their validator details to the setup queue
         * @param _validatorDetails Array of ValidatorDetails to add.
        */
        function addNewValidatorDetails(
          ValidatorDetails[] calldata _validatorDetails
        ) external;
        // ** PLATFORM_ADMIN management methods **
        /**
         * @dev  Adds a new operator to the registry.
         * @param _name Name of the operator.
         * @param _operatorAddress Address of the operator.
         * @param _rewardAddress Address of the reward recipient for this operator.
         * @notice Throws if an operator already exists with the given _operatorAddress
         */
        function addOperator(
          string calldata _name,
          address _operatorAddress,
          address _rewardAddress
        ) external;
        /**
         * @dev  Enables an operator in the registry.
         * @param _operatorAddress Address of the operator to enable.
         * @notice Throws NoOperatorFound if the operator address is not found in the registry
         */
        function enableOperator(address _operatorAddress) external;
        /**
         * @dev  Disables an operator in the registry.
         * @param _operatorAddress Address of the operator to disable.
         * @notice Throws NoOperatorFound if the operator address is not found in the registry
         */
        function disableOperator(address _operatorAddress) external;
        /**
         * @dev  Updates the controlling address of an operator in the registry.
         * @param _operatorAddress Current address of the operator.
         * @param _newOperatorAddress New address of the operator.
         * @notice Throws NoOperatorFound if the operator address is not found in the registry
         */
        function updateOperatorControllingAddress(
          address _operatorAddress,
          address _newOperatorAddress
        ) external;
        /**
         * @dev  Updates the reward address of an operator in the registry.
         * @param _operatorAddress Address of the operator to update.
         * @param _newRewardAddress New reward address for the operator.
         * @notice Throws NoOperatorFound if the operator address is not found in the registry
         */
        function updateOperatorRewardAddress(
          address _operatorAddress,
          address _newRewardAddress
        ) external;
        /**
         * @dev  Updates the name of an operator in the registry
         * @param _operatorAddress The address of the operator to update
         * @param _name The new name for the operator
         * @notice Throws NoOperatorFound if the operator address is not found in the registry
         */
        function updateOperatorName(
          address _operatorAddress,
          string calldata _name
        ) external;
        /**
         * @dev  Allows the PLATFORM_ADMIN to delete validators that are pending. This is likely to be called via an admin if a public key fails the front-running checks
         * @notice Throws InvalidArrayLengthOfZero if the length of _pubKeys is 0
         * @notice Throws NoPubKeyFound if any of the provided pubKeys is not found in the pending validators set
         * @param _pubKeys The public keys of the pending validators to delete
         */
        function deletePendingValidators(bytes[] calldata _pubKeys) external;
        /**
         * @dev  Allows the PLATFORM_ADMIN to delete validator public keys that have been used to setup a validator and that validator has now exited
         * @notice Throws NoPubKeyFound if any of the provided pubKeys is not found in the active validators set
         * @notice Throws InvalidArrayLengthOfZero if the length of _pubKeys is 0
         * @param _pubKeys The public keys of the active validators to delete
         */
        function deleteActiveValidators(bytes[] calldata _pubKeys) external;
        /**
         * @dev  Returns the address of the AccessControlManager contract
         */
        function AccessControlManager() external returns (IAccessControlManager);
        /**
         * @dev  Returns the operator details for a given operator address
         * @notice Throws NoOperatorFound if the operator address is not found in the registry
         * @param _operatorAddress The address of the operator to retrieve
         * @return operator The operator details, including name, reward address, and enabled status
         * @return totalValidatorDetails The total amount of validator details for an operator
         * @return operatorId The operator's Id
         */
        function getOperator(
          address _operatorAddress
        )
          external
          view
          returns (
            Operator memory operator,
            uint128 totalValidatorDetails,
            uint128 operatorId
          );
        /**
         * @dev  Returns the pending validator details for a given operator address
         * @notice Throws NoOperatorFound if the operator address is not found in the registry
         * @param _operatorAddress The address of the operator to retrieve pending validator details for
         * @return validatorDetails The pending validator details for the given operator
         */
        function getOperatorsPendingValidatorDetails(
          address _operatorAddress
        ) external returns (ValidatorDetails[] memory);
        /**
         * @dev  Returns the active validator details for a given operator address
         * @notice Throws NoOperatorFound if the operator address is not found in the registry
         * @param _operatorAddress The address of the operator to retrieve active validator details for
         * @return validatorDetails The active validator details for the given operator
         */
        function getOperatorsActiveValidatorDetails(
          address _operatorAddress
        ) external returns (ValidatorDetails[] memory validatorDetails);
        /**
         * @dev  Returns the reward details for a given operator Id, this method is used in the swETH contract when paying swETH rewards
         * @param _operatorId The operator Id to get the reward details for
         * @return rewardAddress The reward address of the operator
         * @return activeValidators The amount of active validators for the operator
         */
        function getRewardDetailsForOperatorId(
          uint128 _operatorId
        ) external returns (address rewardAddress, uint128 activeValidators);
        /**
         * @dev  Returns the number of operators in the registry
         */
        function numOperators() external returns (uint128);
        /**
         * @dev  Returns the amount of pending validator keys in the registry
         */
        function numPendingValidators() external returns (uint256);
        /**
         * @dev  Returns the operator ID for a given operator address
         * @notice Throws NoOperatorFound if the operator address is not found in the registry
         * @param _operator The address of the operator to retrieve the operator ID for
         * @return _operatorId The operator ID for the given operator
         */
        function getOperatorIdForAddress(
          address _operator
        ) external returns (uint128 _operatorId);
        /**
         * @dev Returns the `operatorId` associated with the given `pubKey`.
         * @param pubKey  The public key to lookup the `operatorId` for.
         * @notice Returns 0 if no operatorId controls the pubKey
         */
        function getOperatorIdForPubKey(
          bytes calldata pubKey
        ) external returns (uint128);
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.16;
      import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
      import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
      /**
       * @title SwETH Interface
       * @author https://github.com/max-taylor
       * @dev This interface provides the methods to interact with the SwETH contract.
       */
      interface IswETH is IERC20Upgradeable {
        // ***** Errors ******
        /**
         * @dev Error thrown when attempting to reprice with zero SwETH supply.
         */
        error CannotRepriceWithZeroSwETHSupply();
        /**
         * @dev Error thrown when passing a preRewardETHReserves value equal to 0 into the repricing function
         */
        error InvalidPreRewardETHReserves();
        /**
         * @dev Error thrown when updating the reward percentage for either the NOs or the swell treasury and the update will cause the NO percentage + swell treasury percentage to exceed 100%.
         */
        error RewardPercentageTotalOverflow();
        /**
         * @dev Thrown when calling the reprice function and not enough time has elapsed between the previous repriace and the current reprice.
         * @param remainingTime Remaining time until reprice can be called
         */
        error NotEnoughTimeElapsedForReprice(uint256 remainingTime);
        /**
         * @dev Thrown when repricing the rate and the difference in reserves values is greater than expected
         * @param repriceDiff The difference between the previous swETH rate and what would be the updated rate
         * @param maximumRepriceDiff The maximum allowed difference in swETH rate
         */
        error RepriceDifferenceTooLarge(
          uint256 repriceDiff,
          uint256 maximumRepriceDiff
        );
        /**
         * @dev Thrown during repricing when the difference in swETH supplied to repricing compared to the actual supply is too great
         * @param repriceswETHDiff The difference between the swETH supplied to repricing and actual supply
         * @param maximumswETHRepriceDiff The maximum allowed difference in swETH supply
         */
        error RepriceswETHDifferenceTooLarge(
          uint256 repriceswETHDiff,
          uint256 maximumswETHRepriceDiff
        );
        /**
         * @dev Throw when the caller tries to burn 0 swETH
         */
        error CannotBurnZeroSwETH();
        // ***** Events *****
        /**
         * @dev Event emitted when a user withdraws ETH for swETH
         * @param to Address of the recipient.
         * @param swETHBurned Amount of SwETH burned in the transaction.
         * @param ethReturned Amount of ETH returned in the transaction.
         */
        event ETHWithdrawn(
          address indexed to,
          uint256 swETHBurned,
          uint256 ethReturned
        );
        /**
         * @dev Event emitted when the swell treasury reward percentage is updated.
         * @dev Only callable by the platform admin
         * @param oldPercentage The previous swell treasury reward percentage.
         * @param newPercentage The new swell treasury reward percentage.
         */
        event SwellTreasuryRewardPercentageUpdate(
          uint256 oldPercentage,
          uint256 newPercentage
        );
        /**
         * @dev Event emitted when the node operator reward percentage is updated.
         * @dev Only callable by the platform admin
         * @param oldPercentage The previous node operator reward percentage.
         * @param newPercentage The new node operator reward percentage.
         */
        event NodeOperatorRewardPercentageUpdate(
          uint256 oldPercentage,
          uint256 newPercentage
        );
        /**
         * @dev Event emitted when the swETH - ETH rate is updated
         * @param newEthReserves The new ETH reserves for the swell protocol
         * @param newSwETHToETHRate The new SwETH to ETH rate.
         * @param nodeOperatorRewards The rewards for the node operator's.
         * @param swellTreasuryRewards The rewards for the swell treasury.
         * @param totalETHDeposited Current total ETH staked at time of reprice.
         */
        event Reprice(
          uint256 newEthReserves,
          uint256 newSwETHToETHRate,
          uint256 nodeOperatorRewards,
          uint256 swellTreasuryRewards,
          uint256 totalETHDeposited
        );
        /**
         * @dev Event is fired when some contracts receive ETH
         * @param from The account that sent the ETH
         * @param swETHMinted The amount of swETH minted to the caller
         * @param amount The amount of ETH received
         * @param referral The referrer's address
         */
        event ETHDepositReceived(
          address indexed from,
          uint256 amount,
          uint256 swETHMinted,
          uint256 newTotalETHDeposited,
          address indexed referral
        );
        /**
         * @dev Event emitted on a successful call to setMinimumRepriceTime
         * @param _oldMinimumRepriceTime The old reprice time
         * @param _newMinimumRepriceTime The new updated reprice time
         */
        event MinimumRepriceTimeUpdated(
          uint256 _oldMinimumRepriceTime,
          uint256 _newMinimumRepriceTime
        );
        /**
         * @dev Event emitted on a successful call to setMaximumRepriceswETHDifferencePercentage
         * @param _oldMaximumRepriceswETHDifferencePercentage The old maximum swETH supply difference
         * @param _newMaximumRepriceswETHDifferencePercentage The new updated swETH supply difference
         */
        event MaximumRepriceswETHDifferencePercentageUpdated(
          uint256 _oldMaximumRepriceswETHDifferencePercentage,
          uint256 _newMaximumRepriceswETHDifferencePercentage
        );
        /**
         * @dev Event emitted on a successful call to setMaximumRepriceDifferencePercentage
         * @param _oldMaximumRepriceDifferencePercentage The old maximum reprice difference
         * @param _newMaximumRepriceDifferencePercentage The new updated maximum reprice difference
         */
        event MaximumRepriceDifferencePercentageUpdated(
          uint256 _oldMaximumRepriceDifferencePercentage,
          uint256 _newMaximumRepriceDifferencePercentage
        );
        // ************************************
        // ***** External Methods ******
        /**
         * @dev This method withdraws contract's _token balance to a platform admin
         * @param _token The ERC20 token to withdraw from the contract
         */
        function withdrawERC20(IERC20 _token) external;
        /**
         * @dev Returns the ETH reserves that were provided in the most recent call to the reprice function
         * @return The last recorded ETH reserves
         */
        function lastRepriceETHReserves() external view returns (uint256);
        /**
         * @dev Returns the last time the reprice method was called in UNIX
         * @return The UNIX timestamp of the last time reprice was called
         */
        function lastRepriceUNIX() external view returns (uint256);
        /**
         * @dev Returns the total ETH that has been deposited over the protocols lifespan
         * @return The current total amount of ETH that has been deposited
         */
        function totalETHDeposited() external view returns (uint256);
        /**
         * @dev Returns the current swell treasury reward percentage.
         * @return The current swell treasury reward percentage.
         */
        function swellTreasuryRewardPercentage() external view returns (uint256);
        /**
         * @dev Returns the current node operator reward percentage.
         * @return The current node operator reward percentage.
         */
        function nodeOperatorRewardPercentage() external view returns (uint256);
        /**
         * @dev Returns the current SwETH to ETH rate, returns 1:1 if no reprice has occurred otherwise it returns the swETHToETHRateFixed rate.
         * @return The current SwETH to ETH rate.
         */
        function swETHToETHRate() external view returns (uint256);
        /**
         * @dev Returns the current ETH to SwETH rate.
         * @return The current ETH to SwETH rate.
         */
        function ethToSwETHRate() external view returns (uint256);
        /**
         * @dev Returns the minimum reprice time
         * @return The minimum reprice time
         */
        function minimumRepriceTime() external view returns (uint256);
        /**
         * @dev Returns the maximum percentage difference with 1e18 precision
         * @return The maximum percentage difference
         */
        function maximumRepriceDifferencePercentage() external view returns (uint256);
        /**
         * @dev Returns the maximum percentage difference with 1e18 precision
         * @return The maximum percentage difference in suppled and actual swETH supply
         */
        function maximumRepriceswETHDifferencePercentage()
          external
          view
          returns (uint256);
        /**
         * @dev Sets the new swell treasury reward percentage.
         * @notice Only a platform admin can call this function.
         * @param _newSwellTreasuryRewardPercentage The new swell treasury reward percentage to set.
         */
        function setSwellTreasuryRewardPercentage(
          uint256 _newSwellTreasuryRewardPercentage
        ) external;
        /**
         * @dev Sets the new node operator reward percentage.
         * @notice Only a platform admin can call this function.
         * @param _newNodeOperatorRewardPercentage The new node operator reward percentage to set.
         */
        function setNodeOperatorRewardPercentage(
          uint256 _newNodeOperatorRewardPercentage
        ) external;
        /**
         * @dev Sets the minimum permitted time between successful repricing calls using the block timestamp.
         * @notice Only a platform admin can call this function.
         * @param _minimumRepriceTime The new minimum time between successful repricing calls
         */
        function setMinimumRepriceTime(uint256 _minimumRepriceTime) external;
        /**
         * @dev Sets the maximum percentage allowable difference in swETH supplied to repricing compared to current swETH supply.
         * @notice Only a platform admin can call this function.
         * @param _maximumRepriceswETHDifferencePercentage The new maximum percentage swETH supply difference allowed.
         */
        function setMaximumRepriceswETHDifferencePercentage(
          uint256 _maximumRepriceswETHDifferencePercentage
        ) external;
        /**
         * @dev Sets the maximum percentage allowable difference in swETH to ETH price changes for a repricing call.
         * @notice Only a platform admin can call this function.
         * @param _maximumRepriceDifferencePercentage The new maximum percentage difference in repricing rate.
         */
        function setMaximumRepriceDifferencePercentage(
          uint256 _maximumRepriceDifferencePercentage
        ) external;
        /**
         * @dev Deposits ETH into the contract
         * @notice The amount of ETH deposited will be converted to SwETH at the current SwETH to ETH rate
         */
        function deposit() external payable;
        /**
         * @dev Deposits ETH into the contract
         * @param referral The referrer's address
         * @notice The amount of ETH deposited will be converted to SwETH at the current SwETH to ETH rate
         */
        function depositWithReferral(address referral) external payable;
        /**
         * @dev Burns the requested amount of swETH, it does not return any ETH to the caller
         * @param amount The amount of swETH to burn
         */
        function burn(uint256 amount) external;
        /**
         * @dev This method reprices the swETH -> ETH rate, this will be called via an offchain service on a regular interval, likely ~1 day. The swETH total supply is passed as an argument to avoid a potential race conditions between the off-chain reserve calculations and the on-chain repricing
         * @dev This method also mints a percentage of swETH as rewards to be claimed by NO's and the swell treasury. The formula for determining the amount of swETH to mint is the following: swETHToMint = (swETHSupply * newETHRewards * feeRate) / (preRewardETHReserves - newETHRewards * feeRate + newETHRewards)
         * @dev The formula is quite complicated because it needs to factor in the updated exchange rate whilst it calculates the amount of swETH rewards to mint. This ensures the rewards aren't double-minted and are backed by ETH.
         * @param _preRewardETHReserves The PoR value exclusive of the new ETH rewards earned
         * @param _newETHRewards The total amount of new ETH earnt over the period.
         * @param _swETHTotalSupply The total swETH supply at the time of off-chain reprice calculation
         */
        function reprice(
          uint256 _preRewardETHReserves,
          uint256 _newETHRewards,
          uint256 _swETHTotalSupply
        ) external;
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.16;
      import {IERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
      import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
      /**
       * @title SwEXIT Interface
       * @author https://github.com/max-taylor
       * @dev This interface provides the methods to interact with the SwEXIT contract.
       */
      interface IswEXIT is IERC721Upgradeable {
        /**
         * @dev Struct representing a withdrawal request.
         * @param timestamp The timestamp of the withdrawal request.
         * @param amount The amount of SwETH that was requested to be withdrawn.
         * @param lastTokenIdProcessed The last token ID processed when the withdraw request was created, required later on when fetching the rates.
         * @param rateWhenCreated The rate when the withdrawal request was created.
         */
        struct WithdrawRequest {
          uint256 amount;
          uint256 lastTokenIdProcessed;
          uint256 rateWhenCreated;
        }
        /**
         * @dev Thrown when the withdrawal request is too large
         * @param amount The withdrawal request amount.
         * @param limit The withdrawal request limit.
         */
        error WithdrawRequestTooLarge(uint256 amount, uint256 limit);
        /**
         * @dev Thrown when the withdrawal request amount is less than the minimum.
         * @param amount The withdrawal request amount.
         * @param minimum The withdrawal request minimum.
         */
        error WithdrawRequestTooSmall(uint256 amount, uint256 minimum);
        /**
         * @dev Thrown when trying to claim withdrawals for a token that doesn't exist
         */
        error WithdrawalRequestDoesNotExist();
        /**
         * @dev Thrown when trying to claim withdrawals and the requested token has not been processed.
         */
        error WithdrawalRequestNotProcessed();
        /**
         * @dev Thrown when processing withdrawals and the provided _lastRequestIdToProcess hasn't been minted
         */
        error CannotProcessWithdrawalsForNonExistentToken();
        /**
         * @dev Thrown when processing withdrawals and the provided _lastRequestIdToProcess is less than the previous token ID processed
         */
        error LastTokenIdToProcessMustBeGreaterOrEqualThanPrevious();
        /**
         * @dev Thrown when calling a withdrawal method and the withdrawals are paused.
         */
        error WithdrawalsPaused();
        /**
         * @dev Thrown when trying to update the withdrawal request minimum to be less than the withdrawal request maximum.
         */
        error WithdrawRequestMinimumMustBeLessOrEqualToMaximum();
        /**
         * @dev Thrown when trying to update the withdrawal request maximum to be less than the withdrawal request minimum.
         */
        error WithdrawRequestMaximumMustBeGreaterOrEqualToMinimum();
        /**
         * @dev Thrown when anyone except the owner tries to finalize a withdrawal request
         */
        error WithdrawalRequestFinalizationOnlyAllowedForNFTOwner();
        /**
         * @dev Emitted when the base URI is updated.
         * @param oldBaseURI The old base URI.
         * @param newBaseURI The new base URI.
         */
        event BaseURIUpdated(string oldBaseURI, string newBaseURI);
        /**
         * @dev Emitted when a withdrawal request is created.
         * @param tokenId The token ID of the withdrawal request.
         * @param amount The amount of SwETH to withdraw.
         * @param timestamp The timestamp of the withdrawal request.
         * @param lastTokenIdProcessed The last token ID processed, required later on when fetching the rates.
         * @param rateWhenCreated The rate when the withdrawal request was created.
         * @param owner The owner of the withdrawal request.
         */
        event WithdrawRequestCreated(
          uint256 tokenId,
          uint256 amount,
          uint256 timestamp,
          uint256 indexed lastTokenIdProcessed,
          uint256 rateWhenCreated,
          address indexed owner
        );
        /**
         * @dev Emitted when a withdrawal request is claimed.
         * @param owner The owner of the withdrawal request.
         * @param tokenId The token ID of the withdrawal request.
         * @param exitClaimedETH The amount of ETH the owner received.
         */
        event WithdrawalClaimed(
          address indexed owner,
          uint256 tokenId,
          uint256 exitClaimedETH
        );
        /**
         * @dev Emitted when withdrawals are processed.
         * @param fromTokenId The first token ID to process.
         * @param toTokenId The last token ID to process.
         * @param processedRate The rate that the withdrawal requests were processed at, not the finalised rate when claiming just the processed rate
         * @param processedExitingETH The amount of exiting ETH accumulated when processing withdrawals.
         * @param processedExitedETH The amount of exited ETH accumulated when processing withdrawals.
         */
        event WithdrawalsProcessed(
          uint256 fromTokenId,
          uint256 toTokenId,
          uint256 processedRate,
          uint256 processedExitingETH,
          uint256 processedExitedETH
        );
        /**
         * @dev Emitted when the withdrawal request limit is updated.
         * @param oldLimit The old withdrawal request limit.
         * @param newLimit The new withdrawal request limit.
         */
        event WithdrawalRequestMaximumUpdated(uint256 oldLimit, uint256 newLimit);
        /**
         * @dev Emitted when the withdrawal request minimum is updated.
         * @param oldMinimum The old withdrawal request minimum.
         * @param newMinimum The new withdrawal request minimum.
         */
        event WithdrawalRequestMinimumUpdated(uint256 oldMinimum, uint256 newMinimum);
        /**
         * @dev Emitted when ETH is received.
         * @param sender The sender of the ETH.
         * @param amount The amount of ETH received.
         */
        event ETHReceived(address indexed sender, uint256 amount);
        /**
         * @dev Returns the base URI.
         */
        function baseURI() external view returns (string memory);
        /**
         * @dev This method withdraws contract's _token balance to a platform admin
         * @param _token The ERC20 token to withdraw from the contract
         */
        function withdrawERC20(IERC20 _token) external;
        /**
         * @dev Returns the withdrawal request maximum size.
         * @return The withdrawal request maximum size.
         */
        function withdrawRequestMaximum() external view returns (uint256);
        /**
         * @dev Returns the withdrawal request minimum.
         * @return The withdrawal request minimum.
         */
        function withdrawRequestMinimum() external view returns (uint256);
        /**
         * @dev Returns the amount of exiting ETH, which is has not yet been processed for withdrawals.
         * @dev This value is increased by new withdrawal requests and decreased when withdrawals are processed.
         * @dev The amount is given by (amount * rate when requested), where amount is the amount of withdrawn swETH.
         * @return The current amount of exiting ETH.
         */
        function exitingETH() external view returns (uint256);
        /**
         * @dev Returns the total amount of exited ETH to date. Exited ETH is ETH that was processed in a withdrawal request.
         * @dev When ETH is processed in a withdrawal request, the amount of exited ETH is given by (amount * finalRate), where finalRate is the lesser of the rate when requested and the processed rate, and amount is the amount of withdrawn swETH.
         * @return The exited ETH.
         */
        function totalETHExited() external view returns (uint256);
        /**
         * @dev Allows the platform admin to update the base URI.
         * @param _baseURI The new base URI.
         */
        function setBaseURI(string memory _baseURI) external;
        /**
         * @dev Allows the platform admin to update the withdrawal request maximum.
         * @param _withdrawRequestMaximum The new withdrawal request maximum.
         */
        function setWithdrawRequestMaximum(uint256 _withdrawRequestMaximum) external;
        /**
         * @dev Allows the platform admin to update the withdrawal request minimum.
         * @param _withdrawRequestMinimum The new withdrawal request minimum.
         */
        function setWithdrawRequestMinimum(uint256 _withdrawRequestMinimum) external;
        /**
         * @dev Processes withdrawals for a given range of token IDs.
         * @param _lastTokenIdToProcess The last token Id to process.
         */
        function processWithdrawals(uint256 _lastTokenIdToProcess) external;
        /**
         * @dev Creates a new withdrawal request.
         * @param amount The amount of SwETH to withdraw.
         */
        function createWithdrawRequest(uint256 amount) external;
        /**
         * @dev Finalizes a withdrawal request, sending the ETH to the owner of the request. This is callable by anyone.
         * @param tokenId The token ID of the withdrawal request to claim.
         */
        function finalizeWithdrawal(uint256 tokenId) external;
        /**
         * @dev Checks if the provided token ID has been processed and returns the rate it was processed at. NOTE: This isn't the final rate that the user will receive, it's just the rate that the withdrawal request was processed at.
         * @param tokenId The token ID to check.
         * @return isProcessed A boolean indicating whether or not the token ID has been processed.
         * @return processedRate The processed rate for the given token ID.
         */
        function getProcessedRateForTokenId(
          uint256 tokenId
        ) external view returns (bool isProcessed, uint256 processedRate);
        /**
         * @dev Returns the last token ID that was processed.
         * @return The last token ID processed.
         */
        function getLastTokenIdProcessed() external view returns (uint256);
        /**
         * @dev Returns the last token ID that was created.
         * @return The last token ID created.
         */
        function getLastTokenIdCreated() external view returns (uint256);
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.16;
      import {BytesLib} from "solidity-bytes-utils/contracts/BytesLib.sol";
      /**
       * @title DepositDataRoot
       * @author https://github.com/max-taylor
       * @notice This library helps to format the deposit data root for new validator setup
       */
      library DepositDataRoot {
        using BytesLib for bytes;
        /**
         * @dev This method converts a uint64 value into a LE bytes array, this is required for compatibility with the beacon deposit contract
         * @dev Code was taken from: https://github.com/ethereum/consensus-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol#L165
         * @param value The value to convert to the LE bytes array
         */
        function _toLittleEndian64(
          uint64 value
        ) internal pure returns (bytes memory ret) {
          ret = new bytes(8);
          bytes8 bytesValue = bytes8(value);
          // Byte swap each item so it's LE not BE
          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 This method formats the deposit data root for setting up a new validator in the deposit contract. Logic was token from the deposit contract: https://github.com/ethereum/consensus-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol#L128
         * @param _pubKey The pubKey to use in the deposit data root
         * @param _withdrawalCredentials The withdrawal credentials
         * @param _signature The signature
         * @param _amount The amount, will always be 32 ETH
         */
        function formatDepositDataRoot(
          bytes memory _pubKey,
          bytes memory _withdrawalCredentials,
          bytes memory _signature,
          uint256 _amount
        ) internal pure returns (bytes32 node) {
          uint256 deposit_amount = _amount / 1 gwei;
          bytes memory amount = _toLittleEndian64(uint64(deposit_amount));
          bytes32 pubKeyRoot = sha256(abi.encodePacked(_pubKey, bytes16(0)));
          bytes32 signature_root = sha256(
            abi.encodePacked(
              sha256(abi.encodePacked(_signature.slice(0, 64))),
              sha256(abi.encodePacked(_signature.slice(64, 32), bytes32(0)))
            )
          );
          node = sha256(
            abi.encodePacked(
              sha256(abi.encodePacked(pubKeyRoot, _withdrawalCredentials)),
              sha256(abi.encodePacked(amount, bytes24(0), signature_root))
            )
          );
        }
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.16;
      /**
       * @title SwellLib
       * @author https://github.com/max-taylor
       * @notice This library contains roles, errors, events and functions that are widely used throughout the protocol
       */
      library SwellLib {
        // ***** Roles *****
        /**
         * @dev The platform admin role
         */
        bytes32 public constant PLATFORM_ADMIN = keccak256("PLATFORM_ADMIN");
        /**
         * @dev The bot role
         */
        bytes32 public constant BOT = keccak256("BOT");
        /**
         * @dev The role used for the swETH.reprice method
         */
        bytes32 public constant REPRICER = keccak256("REPRICER");
        /**
         * @dev Used for checking all the pausing methods
         */
        bytes32 public constant PAUSER = keccak256("PAUSER");
        /**
         * @dev Used for checking all the unpausing methods
         */
        bytes32 public constant UNPAUSER = keccak256("UNPAUSER");
        /**
         * @dev Role used specifically in the deleteActiveValidators method
         */
        bytes32 public constant DELETE_ACTIVE_VALIDATORS =
          keccak256("DELETE_ACTIVE_VALIDATORS");
        /**
         * @dev Role used specifically in the processWithdrawals method
         */
        bytes32 public constant PROCESS_WITHDRAWALS =
          keccak256("PROCESS_WITHDRAWALS");
        // ***** Errors *****
        /**
         * @dev Thrown when _checkZeroAddress is called with the zero address
         */
        error CannotBeZeroAddress();
        /**
         * @dev Thrown in some contracts when the contract call is received by the fallback method
         */
        error InvalidMethodCall();
        /**
         * @dev Thrown in some contracts when ETH is sent directly to the contract
         */
        error InvalidETHDeposit();
        /**
         * @dev Thrown when interacting with a method on the protocol that is disabled via the coreMethodsPaused bool
         */
        error CoreMethodsPaused();
        /**
         * @dev Thrown when interacting with a method on the protocol that is disabled via the botMethodsPaused bool
         */
        error BotMethodsPaused();
        /**
         * @dev Thrown when interacting with a method on the protocol that is disabled via the operatorMethodsPaused bool
         */
        error OperatorMethodsPaused();
        /**
         * @dev Thrown when interacting with a method on the protocol that is disabled via the withdrawalsPaused bool
         */
        error WithdrawalsPaused();
        /**
         * @dev Thrown when calling the withdrawERC20 method and the contracts balance is 0
         */
        error NoTokensToWithdraw();
        /**
         * @dev Thrown when attempting to deposit with referrer the same all calling address
         */
        error CannotReferSelf();
        // ************************************
        // ***** Internal Methods *****
        /**
         * @dev This helper is used throughout the protocol to guard against zero addresses being passed as parameters
         * @param _address The address to check if it is the zero address
         */
        function _checkZeroAddress(address _address) internal pure {
          if (_address == address(0)) {
            revert CannotBeZeroAddress();
          }
        }
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.16;
      /**
       * @title IDepositcontract
       * @notice This is the Ethereum 2.0 deposit contract interface.
       * @dev Implementation can be found here: https://github.com/ethereum/consensus-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol
       */
      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);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity 0.8.16;
      /**
       * @title Chainlink Proof-of-Reserve address list interface.
       * @notice This interface enables Chainlink nodes to get the list addresses to be used in a PoR feed. A single
       * contract that implements this interface can only store an address list for a single PoR feed.
       * @dev All functions in this interface are expected to be called off-chain, so gas usage is not a big concern.
       * This makes it possible to store addresses in optimized data types and convert them to human-readable strings
       * in `getPoRAddressList()`.
       */
      interface IPoRAddresses {
        /**
         * @notice Get total number of addresses in the list.
         * @return The array length
         */
        function getPoRAddressListLength() external view returns (uint256);
        /**
         * @notice Get a batch of human-readable addresses from the address list.
         * @dev Due to limitations of gas usage in off-chain calls, we need to support fetching the addresses in batches.
         * EVM addresses need to be converted to human-readable strings. The address strings need to be in the same format
         * that would be used when querying the balance of that address.
         * @param startIndex The index of the first address in the batch.
         * @param endIndex The index of the last address in the batch. If `endIndex > getPoRAddressListLength()-1`,
         * endIndex need to default to `getPoRAddressListLength()-1`. If `endIndex < startIndex`, the result would be an
         * empty array.
         * @return Array of addresses as strings.
         */
        function getPoRAddressList(
          uint256 startIndex,
          uint256 endIndex
        ) external view returns (string[] memory);
      }
      // 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;
          }
      }