HYPE Price: $23.45 (+5.90%)
 

Overview

HYPE Balance

HyperEVM LogoHyperEVM LogoHyperEVM Logo0 HYPE

HYPE Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
RouterUpgradeable

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.28;

import { AdminAccessControlUpgradeable } from "@ambitfi/core-contracts/contracts/protocol/utils/Upgradeable.sol";
import { Upgradeable } from "@ambitfi/core-contracts/contracts/protocol/utils/Upgradeable.sol";
import { SweepableUpgradeable } from "@ambitfi/core-contracts/contracts/protocol/utils/SweepableUpgradeable.sol";
import { IAddressRegistry } from "@ambitfi/core-contracts/contracts/interfaces/IAddressRegistry.sol";
import { IVersionable } from "../../interfaces/IVersionable.sol";
import { Router } from "./Router.sol";

string constant VERSION = "1.1.0";

contract RouterUpgradeable is Upgradeable, SweepableUpgradeable, Router, IVersionable {
  /// @custom:oz-upgrades-unsafe-allow constructor
  constructor() {
    _disableInitializers();
  }

  function initialize(IAddressRegistry registry) public initializer {
    __RouterUpgradeable_init(registry);
  }

  // solhint-disable-next-line func-name-mixedcase
  function __RouterUpgradeable_init(IAddressRegistry registry) internal onlyInitializing {
    __UUPSUpgradeable_init_unchained();
    __AdminAccessControl_init_unchained(registry);
    __Upgradeable_init_unchained();
    __RouterUpgradeable_init_unchained();
  }

  // solhint-disable-next-line func-name-mixedcase, no-empty-blocks
  function __RouterUpgradeable_init_unchained() internal onlyInitializing {}

  receive() external payable {}

  /// @inheritdoc IVersionable
  function version() public pure returns (string memory) {
    return VERSION;
  }

  function addressRegistry() public view override(Router, AdminAccessControlUpgradeable) returns (IAddressRegistry) {
    return super.addressRegistry();
  }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

bytes32 constant AMBIT_ACCESS_CONTROL_LIST = 0x13a993c3bf3b4408a525cee20fb4780056c09c1378aeb33db21173b33d30bdd0; // ambit.acl
bytes32 constant AMBIT_TREASURY = 0xaef04b9e2c9ec721a01ca424bbc4285142e44828bb9153fda4eb5d820563cb16; // ambit.treasury
bytes32 constant AMBIT_GOVERNOR = 0xc178db1589a9b11430b9c9547236d8089bc566c2d91713297980e596baa4c0a0; // ambit.governor
bytes32 constant WETH = 0x0f8a193ff464434486c0daf7db2a895884365d2bc84ba47a68fcf89c1b14b5b8; // WETH

interface IAddressRegistry {
  event SetAddress(address indexed addr, bytes32 key);

  /**
   * @notice Sets an address for a given key.
   *
   * @param key The key that defines the address.
   * @param addr The address to assign to the given key.
   */
  function setAddress(bytes32 key, address addr) external;

  /**
   * @notice Returns an address that is defined by the given key.
   *
   * @param key The key that defines the address.
   *
   * @return The address that is defined by the given key.
   */
  function getAddress(bytes32 key) external view returns (address);

  /**
   * @notice Returns a list of addresses that are defined by the keys.
   *
   * @param keys The keys that defines the addresses.
   *
   * @return The addresses that are defined by the given keys.
   */
  function getAddresses(bytes32[] calldata keys) external view returns (address[] memory);
}

File 3 of 50 : IAccessControlList.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

bytes32 constant ADMIN_ROLE = 0xdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42; // ADMIN
bytes32 constant EMERGENCY_ADMIN_ROLE = 0x5c91514091af31f62f596a314af7d5be40146b2f2355969392f055e12e0982fb; // EMERGENCY_ADMIN

import { IRoleBasedAccessControl } from "./IRoleBasedAccessControl.sol";

// solhint-disable-next-line no-empty-blocks
interface IAccessControlList is IRoleBasedAccessControl {}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

interface IRoleBasedAccessControl {
  event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

  event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

  /**
   * @notice Returns a value indicating whether or not the account has the specified role.
   *
   * @param role The role to test for.
   * @param account The account to test for the role.
   *
   * @return Returns `true` if the account has the role, `false' if it doesnt.
   */
  function hasRole(bytes32 role, address account) external view returns (bool);

  /**
   * @notice Grants a role to the account.
   *
   * @param role The role to grant.
   * @param account The account to grant the role to.
   */
  function grantRole(bytes32 role, address account) external;

  /**
   * @notice Revokes a role from the account.
   *
   * @param role The role to revoke.
   * @param account The account to revoke the role from.
   */
  function revokeRole(bytes32 role, address account) external;

  /**
   * @notice Renounce a role from the calling account.
   *
   * @dev This can be used by the account itself to revoke roles that were assigned to it.
   *
   * @param role The role to revoke.
   * @param account The account to renounce the role from. This must be the callers account.
   */
  function renounceRole(bytes32 role, address account) external;

  /**
   * @notice Returns the list of members for a role.
   *
   * @param role The role to return the list of members for.
   *
   * @return The list of members that exists in the role.
   */
  function getRoleMembers(bytes32 role) external view returns (address[] memory);
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

interface ISweepable {
  event Sweep(address indexed caller, address indexed treasury, address indexed token, uint256 amount);

  event SweepETH(address indexed caller, address indexed treasury, uint256 amount);

  /**
   * @notice Sends a given amount of a token to the treasury.
   *
   * @param token The token to send to the treasury.
   * @param amount The amount to send to the treasury.
   */
  function sweep(IERC20 token, uint256 amount) external;

  /**
   * @notice Sweeps the given amount of ETH to the treasury.
   *
   * @param amount The amount to send to the treasury.
   */
  function sweepETH(uint256 amount) external;
}

File 6 of 50 : Errors.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

library Errors {
  error Authorization_NotAuthorized(address caller);
  error AccessControlList_MissingAdminRole(address account);
  error AccessControlList_CanNotRemoveRole(bytes32 role, address account);
  error RoleBasedAccessControl_MissingRole(bytes32 role, address account);
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { IAddressRegistry, AMBIT_ACCESS_CONTROL_LIST } from "../../interfaces/IAddressRegistry.sol";
import { IAccessControlList, ADMIN_ROLE, EMERGENCY_ADMIN_ROLE } from "../../interfaces/security/IAccessControlList.sol";
import { Errors } from "../../libraries/Errors.sol";

abstract contract AdminAccessControlUpgradeable is Initializable {
  /// @custom:storage-location erc7201:ambit.storage.AdminAccessControl
  struct AdminAccessControlStorage {
    IAddressRegistry registry;
  }

  // keccak256(abi.encode(uint256(keccak256("ambit.storage.AdminAccessControl")) - 1)) & ~bytes32(uint256(0xff))
  bytes32 private constant ADMIN_ACCESS_CONTROL_STORAGE_LOCATION =
    0x24da5178c808c813cf7ebebe5cb60eb708540ed968d5353d43b24720d9a86500;

  function getAdminAccessControlStorage() private pure returns (AdminAccessControlStorage storage $) {
    // solhint-disable-next-line no-inline-assembly
    assembly {
      $.slot := ADMIN_ACCESS_CONTROL_STORAGE_LOCATION
    }
  }

  // solhint-disable-next-line func-name-mixedcase
  function __AdminAccessControl_init(IAddressRegistry registry) internal onlyInitializing {
    __AdminAccessControl_init_unchained(registry);
  }

  // solhint-disable-next-line func-name-mixedcase
  function __AdminAccessControl_init_unchained(IAddressRegistry registry) internal onlyInitializing {
    AdminAccessControlStorage storage $ = getAdminAccessControlStorage();
    $.registry = registry;
  }

  modifier onlyAdmin() {
    checkRole(ADMIN_ROLE);
    _;
  }

  modifier onlyEmergencyAdmin() {
    checkRole(EMERGENCY_ADMIN_ROLE);
    _;
  }

  function checkAdminOrEmergencyAdmin() private view {
    bytes32[] memory roles = new bytes32[](2);
    roles[0] = ADMIN_ROLE;
    roles[1] = EMERGENCY_ADMIN_ROLE;
    checkRoles(roles);
  }

  modifier onlyAdminOrEmergencyAdmin() {
    checkAdminOrEmergencyAdmin();
    _;
  }

  function checkRole(bytes32 role) internal view {
    IAccessControlList acl = accessControlList();
    if (acl.hasRole(role, msg.sender) == false) {
      revert Errors.Authorization_NotAuthorized({ caller: msg.sender });
    }
  }

  function checkRoles(bytes32[] memory roles) internal view {
    IAccessControlList acl = accessControlList();
    for (uint256 i; i < roles.length; i++) {
      if (acl.hasRole(roles[i], msg.sender)) {
        return;
      }
    }
    revert Errors.Authorization_NotAuthorized({ caller: msg.sender });
  }

  function addressRegistry() public view virtual returns (IAddressRegistry) {
    AdminAccessControlStorage storage $ = getAdminAccessControlStorage();
    return IAddressRegistry($.registry);
  }

  function accessControlList() internal view returns (IAccessControlList) {
    return IAccessControlList(addressRegistry().getAddress(AMBIT_ACCESS_CONTROL_LIST));
  }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ISweepable } from "../../interfaces/utils/ISweepable.sol";

library SweepableLib {
  using SafeERC20 for IERC20;
  using Address for address payable;

  address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

  function sweep(address treasury, address[] memory tokens) internal {
    for (uint256 i = 0; i < tokens.length; i++) {
      if (tokens[i] == ETH) {
        uint256 amount = address(this).balance;
        if (amount > 0) {
          sweepETH(treasury, amount);
        }
      } else {
        uint256 amount = IERC20(tokens[i]).balanceOf(address(this));
        if (amount > 0) {
          sweep(treasury, IERC20(tokens[i]), amount);
        }
      }
    }
  }

  function sweep(address treasury, IERC20 token, uint256 amount) internal {
    token.safeTransfer(treasury, amount);

    emit ISweepable.Sweep(msg.sender, treasury, address(token), amount);
  }

  function sweepETH(address treasury, uint256 amount) internal {
    payable(treasury).sendValue(amount);

    emit ISweepable.SweepETH(msg.sender, treasury, amount);
  }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { AMBIT_TREASURY } from "../../interfaces/IAddressRegistry.sol";
import { ISweepable } from "../../interfaces/utils/ISweepable.sol";
import { AdminAccessControlUpgradeable } from "../security/AdminAccessControlUpgradeable.sol";
import { SweepableLib } from "./SweepableLib.sol";

abstract contract SweepableUpgradeable is AdminAccessControlUpgradeable, ISweepable {
  using SafeERC20 for IERC20;
  using Address for address payable;

  function sweep(address[] memory tokens) internal {
    address treasury = addressRegistry().getAddress(AMBIT_TREASURY);

    SweepableLib.sweep(treasury, tokens);
  }

  /// @inheritdoc ISweepable
  function sweep(IERC20 token, uint256 amount) external onlyAdmin {
    amount = Math.min(amount, token.balanceOf(address(this)));

    address treasury = addressRegistry().getAddress(AMBIT_TREASURY);

    SweepableLib.sweep(treasury, token, amount);
  }

  /// @inheritdoc ISweepable
  function sweepETH(uint256 amount) public onlyAdmin {
    amount = Math.min(amount, address(this).balance);

    address treasury = addressRegistry().getAddress(AMBIT_TREASURY);

    SweepableLib.sweepETH(treasury, amount);
  }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { AdminAccessControlUpgradeable } from "../security/AdminAccessControlUpgradeable.sol";

abstract contract Upgradeable is UUPSUpgradeable, AdminAccessControlUpgradeable {
  // solhint-disable-next-line func-name-mixedcase
  function __Upgradeable_init() internal onlyInitializing {
    __Upgradeable_init_unchained();
  }

  // solhint-disable-next-line func-name-mixedcase, no-empty-blocks
  function __Upgradeable_init_unchained() internal onlyInitializing {}

  // solhint-disable-next-line no-empty-blocks
  function _authorizeUpgrade(address) internal view override onlyAdmin {}
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;

import { TransientSlot } from "@openzeppelin/contracts/utils/TransientSlot.sol";

library ReentrancyGuardLib {
  using TransientSlot for *;

  error ReentrancyGuardFailed();

  // keccak256(abi.encode(uint256(keccak256("hyperdrive.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
  bytes32 private constant REENTRANCY_GUARD = 0xe26c696bf0e34aaf444e67b257b0ce1f00d161ab27c76bcd8c8582bed8ddd000;

  function enabled() internal view returns (bool) {
    return REENTRANCY_GUARD.asBoolean().tload();
  }

  /// @dev enable the reenterancy protection
  function enable() internal {
    require(enabled() == false, ReentrancyGuardFailed());

    REENTRANCY_GUARD.asBoolean().tstore(true);
  }

  /// @dev disables the reenterancy protection
  function disable() internal {
    require(enabled(), ReentrancyGuardFailed());

    REENTRANCY_GUARD.asBoolean().tstore(false);
  }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._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 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._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() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @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 {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

File 14 of 50 : draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

File 17 of 50 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

File 18 of 50 : IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

File 19 of 50 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @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.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.22;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @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 ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) 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
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

File 29 of 50 : Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

File 31 of 50 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

File 32 of 50 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @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 ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    using SafeCast for *;

    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;
    uint256 private constant SPECIAL_CHARS_LOOKUP =
        (1 << 0x08) | // backspace
            (1 << 0x09) | // tab
            (1 << 0x0a) | // newline
            (1 << 0x0c) | // form feed
            (1 << 0x0d) | // carriage return
            (1 << 0x22) | // double quote
            (1 << 0x5c); // backslash

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        uint256 result = 0;
        for (uint256 i = begin; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 9) return (false, 0);
            result *= 10;
            result += chr;
        }
        return (true, result);
    }

    /**
     * @dev Parse a decimal string and returns the value as a `int256`.
     *
     * Requirements:
     * - The string must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input) internal pure returns (int256) {
        return parseInt(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
        (bool success, int256 value) = tryParseInt(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
     * the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
    }

    uint256 private constant ABS_MIN_INT256 = 2 ** 255;

    /**
     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character or if the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, int256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseIntUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseIntUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, int256 value) {
        bytes memory buffer = bytes(input);

        // Check presence of a negative sign.
        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        bool positiveSign = sign == bytes1("+");
        bool negativeSign = sign == bytes1("-");
        uint256 offset = (positiveSign || negativeSign).toUint();

        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);

        if (absSuccess && absValue < ABS_MIN_INT256) {
            return (true, negativeSign ? -int256(absValue) : int256(absValue));
        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
            return (true, type(int256).min);
        } else return (false, 0);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input) internal pure returns (uint256) {
        return parseHexUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseHexUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
     * invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseHexUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseHexUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        // skip 0x prefix if present
        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 offset = hasPrefix.toUint() * 2;

        uint256 result = 0;
        for (uint256 i = begin + offset; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 15) return (false, 0);
            result *= 16;
            unchecked {
                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
                result += chr;
            }
        }
        return (true, result);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input) internal pure returns (address) {
        return parseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
        (bool success, address value) = tryParseAddress(input, begin, end);
        if (!success) revert StringsInvalidAddressFormat();
        return value;
    }

    /**
     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
     * formatted address. See {parseAddress-string} requirements.
     */
    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
        return tryParseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
     * formatted address. See {parseAddress-string-uint256-uint256} requirements.
     */
    function tryParseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, address value) {
        if (end > bytes(input).length || begin > end) return (false, address(0));

        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;

        // check that input is the correct length
        if (end - begin == expectedLength) {
            // length guarantees that this does not overflow, and value is at most type(uint160).max
            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
            return (s, address(uint160(v)));
        } else {
            return (false, address(0));
        }
    }

    function _tryParseChr(bytes1 chr) private pure returns (uint8) {
        uint8 value = uint8(chr);

        // Try to parse `chr`:
        // - Case 1: [0-9]
        // - Case 2: [a-f]
        // - Case 3: [A-F]
        // - otherwise not supported
        unchecked {
            if (value > 47 && value < 58) value -= 48;
            else if (value > 96 && value < 103) value -= 87;
            else if (value > 64 && value < 71) value -= 55;
            else return type(uint8).max;
        }

        return value;
    }

    /**
     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
     *
     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
     *
     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
     * characters that are not in this range, but other tooling may provide different results.
     */
    function escapeJSON(string memory input) internal pure returns (string memory) {
        bytes memory buffer = bytes(input);
        bytes memory output = new bytes(2 * buffer.length); // worst case scenario
        uint256 outputLength = 0;

        for (uint256 i; i < buffer.length; ++i) {
            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
                output[outputLength++] = "\\";
                if (char == 0x08) output[outputLength++] = "b";
                else if (char == 0x09) output[outputLength++] = "t";
                else if (char == 0x0a) output[outputLength++] = "n";
                else if (char == 0x0c) output[outputLength++] = "f";
                else if (char == 0x0d) output[outputLength++] = "r";
                else if (char == 0x5c) output[outputLength++] = "\\";
                else if (char == 0x22) {
                    // solhint-disable-next-line quotes
                    output[outputLength++] = '"';
                }
            } else {
                output[outputLength++] = char;
            }
        }
        // write the actual length and deallocate unused memory
        assembly ("memory-safe") {
            mstore(output, outputLength)
            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
        }

        return string(output);
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(buffer, add(0x20, offset)))
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

File 38 of 50 : IVersionable.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.28;

interface IVersionable {
  /// @notice Returns the contract version.
  function version() external view returns (string memory);
}

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.28;

interface IInterestRateModel {
  /**
   * @notice Calculate the interest rate for borrowing from the market.
   *
   * @param market The market to calculate the interest rate for.
   * @param totalAssets The current market assets.
   * @param totalLiabilities The current market liabilities.
   *
   * @return The interest rate for borrowing from the market as a WAD (18 decimal places).
   */
  function calculateRate(address market, uint256 totalAssets, uint256 totalLiabilities) external view returns (uint256);
}

File 40 of 50 : IMarket.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { BPS } from "../../libraries/MathLib.sol";
import { IInterestRateModel } from "./IInterestRateModel.sol";
import { IVersionable } from "../IVersionable.sol";

uint16 constant FIELDS_PRICE_ORACLE = 0x01;
uint16 constant FIELDS_MAX_SUPPLY = 0x02;
uint16 constant FIELDS_MAX_LTV = 0x04;
uint16 constant FIELDS_LIQUIDATION_LTV = 0x08;
uint16 constant FIELDS_LIQUIDATION_DISCOUNT = 0x10;

interface IMarket is IERC4626, IVersionable {
  error NoLiquidatorRole(address caller);
  error AssetNotFound(address token);
  error MaximumSupplyExceeded(uint256 maxSupply);
  error ExpectedAmountExceeded(uint256 expected, uint256 actual);
  error ZeroAmountNotAllowed();
  error InsufficentLiquidity(uint256 required, uint256 available);
  error UnhealthyAccount(address account);
  error ZeroAddressNotAllowed();
  error FlashLoanReceiverNotAllowed(address receiver);
  error FlashLoanReceiverFailed(address receiver);
  error FlashLoanAmountExceeded(uint256 available, uint256 wanted);
  error FlashLoanFailed(uint256 requested, uint256 received);
  error NotApprovedOperator(address owner, address caller);
  error NotAllowedOrigin(address account, address onBehalfOf);
  error AccountNotRepayable(address account, uint256 amount, uint256 shares);
  error AccountNotLiquidatable(address account);
  error LiquidationAmountExceedsLiabilities(uint256 liabilities, uint256 repaidAmount);

  event SetMaxSupply(uint256 maxSupply);

  event SetInterestRateModel(IInterestRateModel interestRateModel, address caller);

  event SetCollateralAsset(address indexed token, CollateralAsset asset, address caller, uint256 timestamp);

  event SetReserveFee(BPS bps);

  event SetBorrowingFee(BPS bps, uint256 maxAmount, address feeReceiver, address caller, uint256 timestamp);

  event SetHooks(IMarket.Hooks[] hooks, address caller, uint256 timestamp);

  event SetApprovedOperator(address indexed operator, bool approvedOrRevoked, address caller, uint256 timestamp);

  event SupplyCollateral(
    address indexed account,
    address indexed token,
    uint256 marketId,
    uint256 amount,
    address supplier,
    address caller,
    uint256 timestamp
  );

  event WithdrawCollateral(
    address indexed account,
    address indexed token,
    uint256 marketId,
    uint256 amount,
    address receiver,
    address caller,
    uint256 timestamp
  );

  event Deposit(
    address indexed account,
    address indexed asset,
    address indexed receiver,
    uint256 marketId,
    uint256 assets,
    uint256 shares,
    uint256 timestamp
  );

  event Withdraw(
    address indexed account,
    address indexed asset,
    address indexed receiver,
    address owner,
    uint256 marketId,
    uint256 assets,
    uint256 shares,
    uint256 timestamp
  );

  event Borrow(
    address indexed account,
    address indexed asset,
    address indexed receiver,
    uint256 marketId,
    uint256 amount,
    uint256 feeAmount,
    address feeReceiver,
    address caller,
    uint256 timestamp
  );

  event Repay(
    address indexed account,
    address indexed asset,
    address indexed repayer,
    uint256 marketId,
    uint256 amount,
    address caller,
    uint256 timestamp
  );

  event Liquidate(
    address indexed account,
    uint256 marketId,
    uint256 liabilities,
    uint256 repaidAmount,
    address[] tokens,
    uint256[] seizedAmounts,
    uint256 absorbed,
    uint256 socialized,
    uint256 toxic,
    address caller,
    uint256 timestamp
  );

  event Transfer(address indexed from, address indexed to, uint256 value, uint256 marketId, uint256 timestamp);

  event AccrueLiabilities(uint256 marketId, uint256 accrued, uint256 liabilities, uint256 timestamp);

  event ClaimReserves(
    uint256 marketId,
    address indexed toAddress,
    uint256 amount,
    address indexed caller,
    uint256 timestamp
  );

  event FlashLoan(address indexed initiator, uint256 marketId, uint256 amount, uint256 timestamp);

  event OperatorSet(address indexed controller, address indexed operator, bool approved);

  struct Hooks {
    address callback;
    uint16 options;
  }

  struct CollateralAsset {
    address token;
    address priceOracle;
    BPS maxLTV;
    BPS liquidationLTV;
    BPS liquidationDiscount;
    uint256 maxSupply;
  }

  struct Snapshot {
    uint32 timestamp;
    uint256 totalShares;
    uint256 totalAssets;
    uint256 totalReserveAssets;
    uint256 totalLiabilities;
    uint256 totalBalance;
    uint256 utilization;
    uint256 exchangeRate;
  }

  /**
   * @dev Approves or denies an approved operator.
   *
   * @param operator The address of the operator that can act on behalf of others.
   * @param approved True if the operator has been approved, false if it has been revoked.
   */
  function setApprovedOperator(address operator, bool approved) external;

  /**
   * @dev Returns true if the operator is approved to act on behalf of users, false if not.
   *
   * @param operator The address of the operator that can act on behalf of others.
   */
  function isApprovedOperator(address operator) external view returns (bool);

  /**
   * @dev Sets or removes an operator for the caller.
   *
   * @param operator The address of the operator.
   * @param approved The approval status.
   */
  function setOperator(address operator, bool approved) external;

  /**
   * @dev Returns `true` if the `operator` is approved as an operator for an `account`.
   *
   * @param account The address of the account.
   * @param operator The address of the operator.
   */
  function isOperator(address account, address operator) external view returns (bool);

  /**
   * @notice Adds or updates a collateral asset in the market.
   *
   * @param asset The asset to add.
   */
  function setCollateralAsset(IMarket.CollateralAsset memory asset) external;

  /**
   * @notice Returns a collateral asset by its token.
   *
   * @param token The token address of the collateral asset to return.
   * @param mask The mask to determine which fields are required.
   */
  function getCollateralAsset(address token, uint16 mask) external view returns (CollateralAsset memory);

  /**
   * @notice Returns all collateral assets in the market.
   *
   * @param mask The mask to determine which fields are required.
   */
  function getCollateralAssets(uint16 mask) external view returns (CollateralAsset[] memory);

  /**
   * @notice Returns the ID of the market.
   */
  function getMarketId() external view returns (uint256);

  /**
   * @notice Sets the interest rate model to apply to borrowing.
   *
   * @param interestRateModel The interest rate model to apply to borrowing.
   */
  function setInterestRateModel(IInterestRateModel interestRateModel) external;

  /**
   * @notice Gets the interest rate model that is to be applied to borrowing.
   *
   * @return The interest rate model to apply to borrowing.
   */
  function getInterestRateModel() external view returns (IInterestRateModel);

  /**
   * @notice Sets the supply cap for the market.
   */
  function setMaxSupply(uint256 maxSupply) external;

  /**
   * @notice Returns the supply cap for the market.
   */
  function getMaxSupply() external view returns (uint256);

  /**
   * @notice Sets the fee that is taken from the yield to be kept in the reserve.
   *
   * @param fee The fee parameters.
   */
  function setReserveFee(BPS fee) external;

  /**
   * @notice Gets the reserve fee.
   *
   * @return The reserve fee that is taken from the yield.
   */
  function getReserveFee() external view returns (BPS);

  /**
   * @notice Sets the borrowing fee.
   */
  function setBorrowingFee(BPS fee, uint256 feeMaxAmount, address feeReceiver) external;

  /**
   * @notice Gets the configured borrowing fee.
   */
  function getBorrowingFee() external view returns (BPS bps, uint256 maxAmount, address feeReceiver);

  /**
   * @notice Sets the hooks to run for the market.
   */
  function setHooks(IMarket.Hooks[] memory hooks) external;

  /**
   * @notice Returns the current list of hooks active for the market.
   */
  function getHooks() external view returns (IMarket.Hooks[] memory);

  /**
   * @notice Returns a preview of the current snapshot.
   */
  function previewSnapshot() external view returns (Snapshot memory snapshot);

  /**
   * @notice Supply collateral to the users position.
   *
   * @dev This can only be called by the owner or an authorized operator account.
   *
   * @param account The account to supply the collateral to.
   * @param token The token to supply.
   * @param amount The amount of assets to supply.
   * @param supplier The address to supply the assets from.
   */
  function supplyCollateral(address account, address token, uint256 amount, address supplier) external;

  /**
   * @notice Withdraw collateral from the users position.
   *
   * @dev This can only be called by the owner or an authorized operator account.
   *
   * @param account The account to withdraw the collateral to.
   * @param token The token to withdraw.
   * @param amount The amount of assets to withdraw.
   * @param receiver The account to receive the collateral once withdrawn.
   */
  function withdrawCollateral(address account, address token, uint256 amount, address receiver) external;

  /**
   * @notice Borrow an amount on behalf of another account.
   *
   * @dev This can only be called by the owner or an authorized operator account.
   *
   * @param account The account to borrow from.
   * @param amount The amount to borrow.
   * @param receiver The account that will receive the funds.
   */
  function borrow(address account, uint256 amount, address receiver) external;

  /**
   * @notice Repays an amount towards an accounts liabilities.
   *
   * @dev The repayer must be equal to the msg.sender unless the call is coming from
   * authorized operator.
   *
   * @dev The repayment amount can be more than the current liabilities which allows for the full position to be repaid.
   *
   * @param account The account to repay the debt for.
   * @param amount The amount to repay towards the current liabilities.
   * @param repayer The account that is repaying the liabilities.
   */
  function repay(address account, uint256 amount, address repayer) external;

  /**
   * @notice Returns a value indicating whether the account is healthy with the given level of debt.
   *
   * @param account The account to test whether it is healthy.
   * @param debt The level of debt to test whether the account would be healthy.
   */
  function isHealthy(address account, uint256 debt) external view returns (bool);

  /**
   * @notice Take a fee free flash loan from the market.
   */
  function flashLoan(uint256 amount, bytes calldata data) external returns (bytes memory);

  /**
   * @notice Collect the reserves from the contract to the treasury.
   */
  function claimReserves(uint256 amount) external;

  /**
   * @notice Returns The total collateral that has been supplied.
   */
  function getTotalCollateral(address[] memory tokens) external view returns (uint256[] memory supplied);

  /**
   * @notice Returns the list of collateral that has been supplied by the account.
   */
  function getUserCollateral(
    address account
  ) external view returns (address[] memory tokens, uint256[] memory supplied);

  /**
   * @notice Returns the list of collateral that has been supplied by the account.
   */
  function getUserCollateral(
    address account,
    address[] memory tokens
  ) external view returns (uint256[] memory supplied);

  /**
   * @notice Returns the outstanding liabilities for an account, including any interest that has accrued.
   *
   * @dev The liabilities is denominated in the base asset of the pool and this call must include
   * any interest that has accrued up until the current time in which this function is called.
   *
   * @param account The account to return the liabilities for.
   *
   * @return liabilities The total liabilities that the account has accrued.
   */
  function previewLiabilities(address account) external view returns (uint256 liabilities);

  /**
   * @notice Returns a value whether the account meets the criteria for liquidation.
   */
  function isLiquidatable(address account) external view returns (bool);

  /**
   * @notice Previews the liquidation to allows the results to be known a head of time.
   *
   * @param account The account to liquidate.
   * @param repayAmount The maximum amount to repay towards the outstanding debt.
   * @param tokens The list of tokens to seize.
   *
   * @return repaidAmount The actual amount that was repaid towards the debt.
   * @return seizedAmounts The amounts that would be seized from the collateral.
   */
  function previewLiquidate(
    address account,
    uint256 repayAmount,
    address[] memory tokens
  ) external view returns (uint256 repaidAmount, uint256[] memory seizedAmounts);

  /**
   * @notice Liquidate an accounts position.
   */
  function liquidate(
    address account,
    uint256 repayAmount,
    address[] memory tokens
  ) external returns (uint256 repaidAmount, uint256[] memory seizedAmounts);

  /**
   * @notice Previews the liquidation to allows the results to be known a head of time.
   *
   * @param account The account to liquidate.
   * @param tokens The list of tokens to seize.
   * @param seizeAmounts The amounts of collateral to seize.
   *
   * @return repaidAmount The actual amount that was repaid towards the debt.
   * @return seizedAmounts The amounts that would be seized from the collateral.
   */
  function previewLiquidate(
    address account,
    address[] memory tokens,
    uint256[] memory seizeAmounts
  ) external view returns (uint256 repaidAmount, uint256[] memory seizedAmounts);

  /**
   * @notice Liquidate an accounts position.
   */
  function liquidate(
    address account,
    address[] memory tokens,
    uint256[] memory seizeAmounts
  ) external returns (uint256 repaidAmount, uint256[] memory seizedAmounts);

  /**
   * @notice Liquidate an accounts position without any restrictions on the health of the account.
   *
   * @dev This will be a permissioned call.
   */
  function forceLiquidate(
    address account,
    uint256 repayAmount,
    address[] memory tokens,
    uint256[] memory seizeAmounts
  ) external;
}

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.24;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IWETH9 is IERC20 {
  event Deposit(address indexed dst, uint256 wad);

  event Withdrawal(address indexed src, uint256 wad);

  function deposit() external payable;

  function withdraw(uint256 wad) external;
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.28;

uint256 constant WRAP_ETH = 1;
uint256 constant UNWRAP_ETH = 2;
uint256 constant SUPPLY_COLLATERAL = 3;
uint256 constant WITHDRAW_COLLATERAL = 4;
uint256 constant BORROW = 5;
uint256 constant REPAY = 6;
uint256 constant FLASH_LOAN = 7;
uint256 constant ERC4626_DEPOSIT = 8;
uint256 constant ERC4626_MINT = 9;
uint256 constant ERC4626_WITHDRAW = 10;
uint256 constant ERC4626_REDEEM = 11;
uint256 constant ERC20_TRANSFER = 12;
uint256 constant ERC20_TRANSFER_FROM = 13;
uint256 constant ERC20_APPROVE = 14;
uint256 constant CALL = 15;
uint256 constant SWAP = 16;

interface IRouter {
  error UnknownMarket(uint256 marketId);
  error UntrustedCallback(address sender);
  error SlippageExceeded(uint256 expected, uint256 actual);
  error ActorNotAllowed(Actor actor);
  error ActorNotSpecified();
  error AccountNotSpecified();
  error InvalidAmount(uint256 expected, uint256 actual);
  error UntrustedCaller(address caller);
  error RegistryKeyNotFound(bytes32 key);

  enum Actor {
    Sender, // this could be the message sender or a delegated contract like a sub-account
    Router
  }

  struct Action {
    uint256 kind;
    bytes data;
  }

  struct WrapETHAction {
    uint256 amount;
    Actor receiver;
  }

  struct UnwrapETHAction {
    uint256 amount;
    Actor supplier;
    Actor receiver;
  }

  struct SupplyCollateralAction {
    uint256 marketId;
    address token;
    uint256 amount;
    Actor supplier;
  }

  struct WithdrawCollateralAction {
    uint256 marketId;
    address token;
    uint256 amount;
    Actor receiver;
  }

  struct BorrowAction {
    uint256 marketId;
    uint256 amount;
    Actor receiver;
  }

  struct RepayAction {
    uint256 marketId;
    uint256 amount;
    Actor repayer;
  }

  struct FlashLoanAction {
    uint256 marketId;
    uint256 amount;
    Action[] actions;
  }

  struct ERC20ApproveAction {
    address token;
    bytes32 spender; // the key of the address in the registry
    uint256 amount;
  }

  /// @dev transfers from the router to the sender
  struct ERC20TransferAction {
    address token;
    uint256 amount;
  }

  /// @dev transfers from the sender to the router
  struct ERC20TransferFromAction {
    address token;
    uint256 amount;
  }

  struct ERC4626DepositAction {
    address target;
    uint256 assets;
    uint256 minSharesOut;
    Actor supplier;
    Actor receiver;
  }

  struct ERC4626MintAction {
    address target;
    uint256 shares;
    uint256 maxAmountIn;
    Actor supplier;
    Actor receiver;
  }

  struct ERC4626WithdrawAction {
    address target;
    uint256 assets;
    uint256 maxSharesOut;
    Actor owner;
    Actor receiver;
  }

  struct ERC4626RedeemAction {
    address target;
    uint256 shares;
    uint256 minAmountOut;
    Actor owner;
    Actor receiver;
  }

  struct CallAction {
    bytes32 target; // the key of the address in the registry
    bytes data;
    uint256 value; // the native amount to pass to the call
  }

  /// @dev calls a swap router using a generic interface
  struct SwapAction {
    bytes32 router; // the key of the address in the registry
    bytes data;
    uint256 value; // the native amount to pass to the call
    address[] tokensIn;
    uint256[] amountsIn;
    address[] tokensOut;
    uint256[] amountsOutMinimum;
  }

  function execute(Action[] calldata actions) external payable returns (bytes[] memory output);
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";

/// @dev BPS is 4 decimal places and used for financial percentages
type BPS is uint16;
uint8 constant BPS_DECIMALS = 4;

library MathLib {
  using Math for uint256;

  /// @dev when comparing values of different precision we scale them all to an abnormally
  /// high amount then perform the calculations and descale back afterwards
  uint8 public constant SCALE = 27;

  uint256 public constant WAD = 1e18;

  function mul(BPS bps, uint256 amount) internal pure returns (uint256) {
    return amount.mulDiv(BPS.unwrap(bps), 10000);
  }

  function scale(uint256 amount, uint8 from) internal pure returns (uint256) {
    require(from <= SCALE); // solhint-disable-line reason-string
    return amount * 10 ** uint256(SCALE - from);
  }

  function descale(uint256 amount, uint8 to) internal pure returns (uint256) {
    require(to <= SCALE); // solhint-disable-line reason-string
    return amount / 10 ** uint256(SCALE - to);
  }

  function scale(uint256 amount, uint8 from, uint8 to) internal pure returns (uint256) {
    if (from < to) {
      return amount * 10 ** uint256(to - from);
    }
    if (from > to) {
      return amount / 10 ** uint256(from - to);
    }
    return amount;
  }

  function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
    return ((a * b) + 0.5e18) / WAD;
  }

  function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
    return ((a * WAD) + (b / 2)) / b;
  }

  /// @dev this performs a POW operation using the algorithim defined here;
  /// https://en.wikipedia.org/wiki/Exponentiation_by_squaring
  /// this has been adapted from the DSMath lib here;
  /// https://github.com/dapphub/ds-math/blob/master/src/math.sol
  function wadPow(uint256 x, uint256 n) internal pure returns (uint256) {
    require(x >= WAD, "value too big");

    uint256 z = n % 2 != 0 ? x : WAD;

    for (n >>= 1; n > 0; n >>= 1) {
      x = wadMul(x, x);

      if (n % 2 != 0) {
        z = wadMul(z, x);
      }
    }

    return z;
  }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { IAddressRegistry } from "@ambitfi/core-contracts/contracts/interfaces/IAddressRegistry.sol";
import { IWETH9 } from "../interfaces/markets/IWETH9.sol";
import { IMarket } from "../interfaces/markets/IMarket.sol";
import { IRouter } from "../interfaces/router/IRouter.sol";

bytes32 constant WETH = 0x0f8a193ff464434486c0daf7db2a895884365d2bc84ba47a68fcf89c1b14b5b8; // WETH

library RegistryLib {
  function lookup(IAddressRegistry self, string memory key) internal view returns (address) {
    return self.getAddress(keccak256(bytes(key)));
  }

  function lookupMarket(IAddressRegistry self, uint256 marketId) internal view returns (address) {
    return lookup(self, string.concat("hyperdrive.market.", Strings.toString(marketId)));
  }

  function getMarket(IAddressRegistry self, uint256 marketId) internal view returns (IMarket) {
    return IMarket(lookupMarket(self, marketId));
  }

  function getWETH(IAddressRegistry self) internal view returns (IWETH9) {
    return IWETH9(self.getAddress(WETH));
  }

  function getRouter(IAddressRegistry self) internal view returns (IRouter) {
    return IRouter(self.getAddress(keccak256("hyperdrive.router")));
  }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.28;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IRouter } from "../../interfaces/router/IRouter.sol";
import { RouterLib } from "./RouterLib.sol";

library ERC20RouterLib {
  using SafeERC20 for IERC20;

  function approve(
    function(bytes32) external view returns (address) lookup,
    IRouter.ERC20ApproveAction memory action
  ) internal returns (bytes memory output) {
    output = RouterLib.NOTHING;

    IERC20 token = IERC20(action.token);
    token.forceApprove(lookup(action.spender), action.amount);
  }

  function transfer(IRouter.ERC20TransferAction memory action) internal returns (bytes memory output) {
    output = RouterLib.NOTHING;

    IERC20 token = IERC20(action.token);

    // allow sweeping any remaining amount back to the caller
    uint256 amount = action.amount == type(uint256).max ? token.balanceOf(RouterLib.router()) : action.amount;

    if (amount > 0) {
      token.safeTransfer(RouterLib.sender(), amount);
    }
  }

  function transferFrom(IRouter.ERC20TransferFromAction memory action) internal returns (bytes memory output) {
    output = RouterLib.NOTHING;

    IERC20 token = IERC20(action.token);

    if (action.amount > 0) {
      token.safeTransferFrom(RouterLib.sender(), RouterLib.router(), action.amount);
    }
  }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.28;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IRouter } from "../../interfaces/router/IRouter.sol";
import { RouterLib } from "./RouterLib.sol";

library ERC4626RouterLib {
  using SafeERC20 for IERC20;
  using SafeERC20 for IERC4626;

  function deposit(IRouter.ERC4626DepositAction memory action) internal returns (bytes memory output) {
    IERC4626 vault = IERC4626(action.target);

    IERC20 token = IERC20(vault.asset());

    if (action.supplier == IRouter.Actor.Sender) {
      token.safeTransferFrom(RouterLib.actor(action.supplier), address(this), action.assets);
    }

    token.forceApprove(action.target, action.assets);

    uint256 shares = vault.deposit(action.assets, RouterLib.actor(action.receiver));
    require(shares >= action.minSharesOut, IRouter.SlippageExceeded(action.minSharesOut, shares));

    token.forceApprove(action.target, 0);

    output = abi.encode(shares);
  }

  function mint(IRouter.ERC4626MintAction memory action) internal returns (bytes memory output) {
    IERC4626 vault = IERC4626(action.target);

    IERC20 token = IERC20(vault.asset());

    if (action.supplier == IRouter.Actor.Sender) {
      token.safeTransferFrom(RouterLib.actor(action.supplier), address(this), action.maxAmountIn);
    }

    vault.forceApprove(action.target, action.maxAmountIn);

    uint256 amountIn = vault.mint(action.shares, RouterLib.actor(action.receiver));
    require(amountIn <= action.maxAmountIn, IRouter.SlippageExceeded(action.maxAmountIn, amountIn));

    vault.forceApprove(action.target, 0);

    // refund dust
    if (RouterLib.actor(action.supplier) != RouterLib.router() && amountIn < action.maxAmountIn) {
      token.safeTransfer(RouterLib.actor(action.supplier), action.maxAmountIn - amountIn);
    }

    output = abi.encode(amountIn);
  }

  function withdraw(IRouter.ERC4626WithdrawAction memory action) internal returns (bytes memory output) {
    IERC4626 vault = IERC4626(action.target);

    uint256 sharesOut = vault.withdraw(action.assets, RouterLib.actor(action.receiver), RouterLib.actor(action.owner));
    require(sharesOut <= action.maxSharesOut, IRouter.SlippageExceeded(action.maxSharesOut, sharesOut));

    output = abi.encode(sharesOut);
  }

  function redeem(IRouter.ERC4626RedeemAction memory action) internal returns (bytes memory output) {
    IERC4626 vault = IERC4626(action.target);

    uint256 amountOut = vault.redeem(action.shares, RouterLib.actor(action.receiver), RouterLib.actor(action.owner));
    require(amountOut >= action.minAmountOut, IRouter.SlippageExceeded(action.minAmountOut, amountOut));

    output = abi.encode(amountOut);
  }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.28;

import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IRouter } from "../../interfaces/router/IRouter.sol";
import { IWETH9 } from "../../interfaces/markets/IWETH9.sol";
import { IMarket } from "../../interfaces/markets/IMarket.sol";
import { Router } from "./Router.sol";
import { RouterLib } from "./RouterLib.sol";

library MarketRouterLib {
  using Address for address payable;
  using SafeERC20 for IERC20;
  using SafeERC20 for IERC4626;
  using SafeERC20 for IWETH9;

  function supplyCollateral(
    IMarket market,
    IRouter.SupplyCollateralAction memory action
  ) internal returns (bytes memory output) {
    output = RouterLib.NOTHING;

    require(address(market) != address(0), IRouter.UnknownMarket(action.marketId));

    if (action.supplier == IRouter.Actor.Router) {
      // when supplying from the router we can allow taking the maximum that is available
      // it is up to other integrators to ensure they dont leave dust on the contract
      action.amount = Math.min(IERC20(action.token).balanceOf(address(this)), action.amount);

      IERC20(action.token).forceApprove(address(market), action.amount);
    }

    market.supplyCollateral(RouterLib.account(), action.token, action.amount, RouterLib.actor(action.supplier));

    if (action.supplier == IRouter.Actor.Router) {
      IERC20(action.token).forceApprove(address(market), 0);
    }
  }

  function withdrawCollateral(
    IMarket market,
    IRouter.WithdrawCollateralAction memory action
  ) internal returns (bytes memory output) {
    output = RouterLib.NOTHING;

    require(address(market) != address(0), IRouter.UnknownMarket(action.marketId));

    market.withdrawCollateral(RouterLib.account(), action.token, action.amount, RouterLib.actor(action.receiver));
  }

  function borrow(IMarket market, IRouter.BorrowAction memory action) internal returns (bytes memory output) {
    output = RouterLib.NOTHING;

    require(address(market) != address(0), IRouter.UnknownMarket(action.marketId));

    market.borrow(RouterLib.account(), action.amount, RouterLib.actor(action.receiver));
  }

  function repay(IMarket market, IRouter.RepayAction memory action) internal returns (bytes memory output) {
    output = RouterLib.NOTHING;

    require(address(market) != address(0), IRouter.UnknownMarket(action.marketId));

    IERC20 token = IERC20(market.asset());

    if (action.repayer == IRouter.Actor.Router) {
      token.forceApprove(address(market), action.amount);
    }

    market.repay(RouterLib.account(), action.amount, RouterLib.actor(action.repayer));

    if (action.repayer == IRouter.Actor.Router) {
      token.forceApprove(address(market), 0);
    }
  }

  function flashLoan(IMarket market, IRouter.FlashLoanAction memory action) internal returns (bytes memory output) {
    require(address(market) != address(0), IRouter.UnknownMarket(action.marketId));

    output = market.flashLoan(action.amount, abi.encodeCall(Router.flashLoanCallback, (RouterLib.sender(), action)));
  }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.28;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuardLib } from "@ambitlabs/hyperdrive-periphery-contracts/contracts/ReentrancyGuardLib.sol";
import { IAddressRegistry } from "@ambitfi/core-contracts/contracts/interfaces/IAddressRegistry.sol";
import { IRouter } from "../../interfaces/router/IRouter.sol";
import { IMarket } from "../../interfaces/markets/IMarket.sol";
import { RegistryLib } from "../../libraries/RegistryLib.sol";
import { RouterLib } from "./RouterLib.sol";
import { MarketRouterLib } from "./MarketRouterLib.sol";
import { ERC20RouterLib } from "./ERC20RouterLib.sol";
import { ERC4626RouterLib } from "./ERC4626RouterLib.sol";
import { SwapLib } from "./SwapLib.sol";
import { WRAP_ETH, UNWRAP_ETH, SUPPLY_COLLATERAL, WITHDRAW_COLLATERAL, BORROW, REPAY, FLASH_LOAN, ERC4626_DEPOSIT, ERC4626_MINT, ERC4626_WITHDRAW, ERC4626_REDEEM, ERC20_APPROVE, ERC20_TRANSFER, ERC20_TRANSFER_FROM, CALL, SWAP } from "../../interfaces/router/IRouter.sol";

abstract contract Router is IRouter {
  using RegistryLib for IAddressRegistry;
  using SafeERC20 for IERC20;

  address private constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

  modifier nonReentrant() {
    ReentrancyGuardLib.enable();
    _;
    ReentrancyGuardLib.disable();
  }

  function addressRegistry() public view virtual returns (IAddressRegistry);

  function beforeExecute(Action[] memory actions) internal virtual returns (Action[] memory) {
    RouterLib.account(msg.sender);
    RouterLib.sender(msg.sender);
    return actions;
  }

  function afterExecute(Action[] memory) internal virtual {
    RouterLib.account(address(0));
    RouterLib.sender(address(0));
  }

  function execute(Action[] memory actions) external payable nonReentrant returns (bytes[] memory output) {
    actions = beforeExecute(actions);

    output = new bytes[](actions.length);

    for (uint256 i; i < actions.length; i++) {
      output[i] = dispatch(actions[i]);
    }

    afterExecute(actions);
  }

  function dispatch(Action memory action) internal virtual returns (bytes memory) {
    if (action.kind == WRAP_ETH) {
      return RouterLib.wrapETH(addressRegistry().getWETH(), abi.decode(action.data, (WrapETHAction)));
    }

    if (action.kind == UNWRAP_ETH) {
      return RouterLib.unwrapETH(addressRegistry().getWETH(), abi.decode(action.data, (UnwrapETHAction)));
    }

    if (action.kind == SUPPLY_COLLATERAL) {
      SupplyCollateralAction memory params = abi.decode(action.data, (SupplyCollateralAction));
      return MarketRouterLib.supplyCollateral(addressRegistry().getMarket(params.marketId), params);
    }

    if (action.kind == WITHDRAW_COLLATERAL) {
      WithdrawCollateralAction memory params = abi.decode(action.data, (WithdrawCollateralAction));
      return MarketRouterLib.withdrawCollateral(addressRegistry().getMarket(params.marketId), params);
    }

    if (action.kind == BORROW) {
      BorrowAction memory params = abi.decode(action.data, (BorrowAction));
      return MarketRouterLib.borrow(addressRegistry().getMarket(params.marketId), params);
    }

    if (action.kind == REPAY) {
      RepayAction memory params = abi.decode(action.data, (RepayAction));
      return MarketRouterLib.repay(addressRegistry().getMarket(params.marketId), params);
    }

    if (action.kind == FLASH_LOAN) {
      FlashLoanAction memory params = abi.decode(action.data, (FlashLoanAction));
      return MarketRouterLib.flashLoan(addressRegistry().getMarket(params.marketId), params);
    }

    if (action.kind == ERC20_TRANSFER) {
      return ERC20RouterLib.transfer(abi.decode(action.data, (ERC20TransferAction)));
    }

    if (action.kind == ERC20_TRANSFER_FROM) {
      return ERC20RouterLib.transferFrom(abi.decode(action.data, (ERC20TransferFromAction)));
    }

    if (action.kind == ERC20_APPROVE) {
      return ERC20RouterLib.approve(addressRegistry().getAddress, abi.decode(action.data, (ERC20ApproveAction)));
    }

    if (action.kind == ERC4626_DEPOSIT) {
      return ERC4626RouterLib.deposit(abi.decode(action.data, (ERC4626DepositAction)));
    }

    if (action.kind == ERC4626_MINT) {
      return ERC4626RouterLib.mint(abi.decode(action.data, (ERC4626MintAction)));
    }

    if (action.kind == ERC4626_WITHDRAW) {
      return ERC4626RouterLib.withdraw(abi.decode(action.data, (ERC4626WithdrawAction)));
    }

    if (action.kind == ERC4626_REDEEM) {
      return ERC4626RouterLib.redeem(abi.decode(action.data, (ERC4626RedeemAction)));
    }

    // if (action.kind == CALL) {
    //   return RouterLib.call(addressRegistry().getAddress, abi.decode(action.data, (CallAction)));
    // }

    // if (action.kind == SWAP) {
    //   return SwapLib.swap(addressRegistry().getAddress, abi.decode(action.data, (SwapAction)));
    // }

    return RouterLib.NOTHING;
  }

  function flashLoanCallback(address initiator, IRouter.FlashLoanAction memory action) external returns (bytes memory) {
    require(initiator != address(0) && initiator == RouterLib.sender(), UntrustedCaller(initiator));

    IMarket market = addressRegistry().getMarket(action.marketId);
    require(msg.sender == address(market), UntrustedCallback(msg.sender));

    bytes[] memory output = new bytes[](action.actions.length);

    for (uint256 i; i < action.actions.length; i++) {
      output[i] = dispatch(action.actions[i]);
    }

    // allow the flash loan to be repaid
    IERC20(market.asset()).forceApprove(address(market), action.amount);

    return abi.encode(output);
  }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.28;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { TransientSlot } from "@openzeppelin/contracts/utils/TransientSlot.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IWETH9 } from "../../interfaces/markets/IWETH9.sol";
import { IRouter } from "../../interfaces/router/IRouter.sol";

library RouterLib {
  using TransientSlot for *;
  using Address for address;
  using Address for address payable;
  using SafeERC20 for IWETH9;
  using SafeERC20 for IERC20;

  // keccak256(abi.encode(uint256(keccak256("hyperdrive.RouterSender")) - 1)) & ~bytes32(uint256(0xff))
  bytes32 private constant ROUTER_SENDER = 0x2bb2653324aca374dde55b9e445a0741fa5fbabd9d913cb269b1b38c5839df00;

  // keccak256(abi.encode(uint256(keccak256("hyperdrive.RouterAccount")) - 1)) & ~bytes32(uint256(0xff))
  bytes32 private constant ROUTER_ACCOUNT = 0x77d7587726ce27a2d1a6421e65daa8ab8481b71227099b995512d28afa6b8900;

  bytes internal constant NOTHING = abi.encode("");

  function account(address value) internal {
    ROUTER_ACCOUNT.asAddress().tstore(value);
  }

  function account() internal view returns (address value) {
    value = ROUTER_ACCOUNT.asAddress().tload();
    require(value != address(0), IRouter.AccountNotSpecified());
  }

  function sender(address value) internal {
    ROUTER_SENDER.asAddress().tstore(value);
  }

  function sender() internal view returns (address value) {
    value = ROUTER_SENDER.asAddress().tload();
    require(value != address(0), IRouter.ActorNotSpecified());
  }

  function actor(IRouter.Actor value) internal view returns (address) {
    if (value == IRouter.Actor.Sender) {
      return sender();
    }
    if (value == IRouter.Actor.Router) {
      return router();
    }
    revert IRouter.ActorNotAllowed(value);
  }

  function router() internal view returns (address) {
    return address(this);
  }

  function wrapETH(IWETH9 weth, IRouter.WrapETHAction memory action) internal returns (bytes memory output) {
    // NOTE: this conditional check means thats the wrapETH action can only be called once in the execution stack
    // and this is acceptable for now as it is expected that wrapping and unwrapping of the native token should
    // be handled on the outer edges of the list of actions
    require(msg.value == action.amount, IRouter.InvalidAmount(action.amount, msg.value));

    output = NOTHING;

    weth.deposit{ value: action.amount }();

    if (actor(action.receiver) != router()) {
      weth.safeTransfer(actor(action.receiver), action.amount);
    }
  }

  function unwrapETH(IWETH9 weth, IRouter.UnwrapETHAction memory action) internal returns (bytes memory output) {
    output = NOTHING;

    if (action.supplier != IRouter.Actor.Router) {
      weth.safeTransferFrom(actor(action.supplier), address(this), action.amount);
    }

    action.amount = Math.min(action.amount, weth.balanceOf(address(this)));

    weth.withdraw(action.amount);

    if (action.receiver != IRouter.Actor.Router) {
      payable(actor(action.receiver)).sendValue(action.amount);
    }
  }

  function call(
    function(bytes32) external view returns (address) lookup,
    IRouter.CallAction memory action
  ) internal returns (bytes memory output) {
    revert();
    // address target = lookup(action.target);
    // require(target != address(0), IRouter.RegistryKeyNotFound(action.target));

    // output = target.functionCallWithValue(action.data, action.value);
  }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.28;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IRouter } from "../../interfaces/router/IRouter.sol";

library SwapLib {
  using Address for address;
  using SafeERC20 for IERC20;

  function swap(
    function(bytes32) external view returns (address) lookup,
    IRouter.SwapAction memory action
  ) internal returns (bytes memory output) {
    revert();
    // address router = lookup(action.router);
    // require(router != address(0), IRouter.RegistryKeyNotFound(action.router));

    // uint256[] memory balances = new uint256[](action.tokensOut.length);

    // // store the current balances for the tokens that we need to assert the output amount for
    // for (uint256 i; i < action.tokensOut.length; i++) {
    //   balances[i] = IERC20(action.tokensOut[i]).balanceOf(address(this));
    // }

    // // set token approvals for the input tokens
    // for (uint256 i; i < action.tokensIn.length; i++) {
    //   IERC20(action.tokensIn[i]).forceApprove(router, action.amountsIn[i]);
    // }

    // output = router.functionCallWithValue(action.data, action.value);

    // // reset approvals
    // for (uint256 i; i < action.tokensIn.length; i++) {
    //   IERC20(action.tokensIn[i]).forceApprove(router, 0);
    // }

    // // assert the amounts out so we dont need to trust the router
    // for (uint256 i; i < action.tokensOut.length; i++) {
    //   uint256 amountOut = IERC20(action.tokensOut[i]).balanceOf(address(this)) - balances[i];
    //   require(amountOut >= action.amountsOutMinimum[i], "output amount failed");
    // }
  }
}

Settings
{
  "viaIR": true,
  "evmVersion": "cancun",
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccountNotSpecified","type":"error"},{"inputs":[{"internalType":"enum IRouter.Actor","name":"actor","type":"uint8"}],"name":"ActorNotAllowed","type":"error"},{"inputs":[],"name":"ActorNotSpecified","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"Authorization_NotAuthorized","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"InsufficientBalance","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"actual","type":"uint256"}],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"ReentrancyGuardFailed","type":"error"},{"inputs":[{"internalType":"bytes32","name":"key","type":"bytes32"}],"name":"RegistryKeyNotFound","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"actual","type":"uint256"}],"name":"SlippageExceeded","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"inputs":[{"internalType":"uint256","name":"marketId","type":"uint256"}],"name":"UnknownMarket","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"UntrustedCallback","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"UntrustedCaller","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"treasury","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Sweep","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"treasury","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"SweepETH","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"addressRegistry","outputs":[{"internalType":"contract IAddressRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"kind","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct IRouter.Action[]","name":"actions","type":"tuple[]"}],"name":"execute","outputs":[{"internalType":"bytes[]","name":"output","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"initiator","type":"address"},{"components":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"components":[{"internalType":"uint256","name":"kind","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct IRouter.Action[]","name":"actions","type":"tuple[]"}],"internalType":"struct IRouter.FlashLoanAction","name":"action","type":"tuple"}],"name":"flashLoanCallback","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IAddressRegistry","name":"registry","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"sweep","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"sweepETH","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"stateMutability":"payable","type":"receive"}]

60a080604052346100c257306080525f516020612e295f395f51905f525460ff8160401c166100b3576002600160401b03196001600160401b03821601610060575b604051612d6290816100c7823960805181818161090d015261099e0152f35b6001600160401b0319166001600160401b039081175f516020612e295f395f51905f525581527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a15f80610041565b63f92ee8a960e01b5f5260045ffd5b5f80fdfe6080604052600436101561001a575b3615610018575f80fd5b005b5f3560e01c80634f1ef2861461096157806352d1902d146108fb57806354fd4d50146108b45780636ea056a9146107315780638620be801461051f5780639830ff6a1461040f578063ad3cb1cc146103c8578063b58ce21d1461025d578063c4d66de8146100c45763f3ad65f40361000e57346100c0575f3660031901126100c0575f516020612cad5f395f51905f52546040516001600160a01b039091168152602090f35b5f80fd5b346100c05760203660031901126100c0576004356001600160a01b038116908190036100c0575f516020612ced5f395f51905f52549060ff8260401c1615916001600160401b03811680159081610255575b600114908161024b575b159081610242575b506102335767ffffffffffffffff1981166001175f516020612ced5f395f51905f525582610207575b5061015a612b49565b610162612b49565b61016a612b49565b6bffffffffffffffffffffffff60a01b5f516020612cad5f395f51905f525416175f516020612cad5f395f51905f52556101a2612b49565b6101aa612b49565b6101b057005b68ff0000000000000000195f516020612ced5f395f51905f5254165f516020612ced5f395f51905f52557fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2602060405160018152a1005b68ffffffffffffffffff191668010000000000000001175f516020612ced5f395f51905f525582610151565b63f92ee8a960e01b5f5260045ffd5b90501584610128565b303b159150610120565b849150610116565b60203660031901126100c0576004356001600160401b0381116100c057610288903690600401610c4b565b5f516020612d0d5f395f51905f525c6103b95760015f516020612d0d5f395f51905f525d337f77d7587726ce27a2d1a6421e65daa8ab8481b71227099b995512d28afa6b89005d337f2bb2653324aca374dde55b9e445a0741fa5fbabd9d913cb269b1b38c5839df005d6102fc8151610d7a565b905f5b815181101561033a578061031e61031860019385610dc3565b5161135e565b6103288286610dc3565b526103338185610dc3565b50016102ff565b825f7f77d7587726ce27a2d1a6421e65daa8ab8481b71227099b995512d28afa6b89005d5f7f2bb2653324aca374dde55b9e445a0741fa5fbabd9d913cb269b1b38c5839df005d5f516020612d0d5f395f51905f525c156103b9576103b5905f5f516020612d0d5f395f51905f525d60405191829182610d07565b0390f35b630800025b60e31b5f5260045ffd5b346100c0575f3660031901126100c0576103b56040516103e9604082610b8e565b60058152640352e302e360dc1b6020820152604051918291602083526020830190610c10565b346100c05760203660031901126100c05760043561042b610deb565b479081808210911802186024602060018060a01b035f516020612cad5f395f51905f525416604051928380926321f8a72160e01b82527faef04b9e2c9ec721a01ca424bbc4285142e44828bb9153fda4eb5d820563cb1660048301525afa908115610514575f916104da575b506001600160a01b0316906104ac8183612b02565b6040519081527f617a904b01259b64867cc3246576c5b0b4d723c337757ec09ae915f57633864a60203392a3005b90506020813d60201161050c575b816104f560209383610b8e565b810103126100c05761050690610d66565b82610497565b3d91506104e8565b6040513d5f823e3d90fd5b346100c05760403660031901126100c057610538610b2e565b6024356001600160401b0381116100c057606060031982360301126100c05760405161056381610b44565b816004013581526020810191602481013583526044810135906001600160401b0382116100c05760046105999236920101610c4b565b60408201908152926001600160a01b031680151580610718575b1561070657505f516020612cad5f395f51905f525490516001600160a01b03916105df91908316610f86565b168033036106f3576105f2835151610d7a565b915f5b8451805182101561062c579061061061031882600194610dc3565b61061a8287610dc3565b526106258186610dc3565b50016105f5565b50506040516338d52e0f60e01b81529350602084600481855afa938415610514575f946106a4575b6103b561068261069086610673898888519160018060a01b03166128e5565b60405192839160208301610d07565b03601f198101835282610b8e565b604051918291602083526020830190610c10565b9350916020843d6020116106eb575b816106c060209383610b8e565b810103126100c05761067361068293610690936106df6103b597610d66565b96509350919350610654565b3d91506106b3565b63a4fa10c160e01b5f523360045260245ffd5b63382fa62360e11b5f5260045260245ffd5b506001600160a01b03610729610f44565b1681146105b3565b346100c05760403660031901126100c0576004356001600160a01b038116908181036100c057602435610762610deb565b6040516370a0823160e01b815230600482015290602082602481875afa918215610514575f92610880575b508180821091180218906024602060018060a01b035f516020612cad5f395f51905f525416604051928380926321f8a72160e01b82527faef04b9e2c9ec721a01ca424bbc4285142e44828bb9153fda4eb5d820563cb1660048301525afa9081156105145783905f92610841575b508161080792936129a4565b6040519182526001600160a01b03169033907ffe6f9ffae65cf2c41cdbb3faf5a94e71eab2c2c62215df2efd79e12e451d0b6290602090a4005b9150506020813d602011610878575b8161085d60209383610b8e565b810103126100c0578261087261080792610d66565b916107fb565b3d9150610850565b9091506020813d6020116108ac575b8161089c60209383610b8e565b810103126100c05751908461078d565b3d915061088f565b346100c0575f3660031901126100c0576103b56040516108d5604082610b8e565b60058152640312e312e360dc1b6020820152604051918291602083526020830190610c10565b346100c0575f3660031901126100c0577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031630036109525760206040515f516020612ccd5f395f51905f528152f35b63703e46dd60e11b5f5260045ffd5b60403660031901126100c057610975610b2e565b6024356001600160401b0381116100c057610994903690600401610bca565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016308114908115610b0c575b50610952576109d6610deb565b6040516352d1902d60e01b81526001600160a01b0383169290602081600481875afa5f9181610ad8575b50610a185783634c9c8ce360e01b5f5260045260245ffd5b805f516020612ccd5f395f51905f52859203610ac65750813b15610ab4575f516020612ccd5f395f51905f5280546001600160a01b031916821790557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115610a9c575f8083602061001895519101845af4610a96612ad3565b91612c67565b505034610aa557005b63b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b632a87526960e21b5f5260045260245ffd5b9091506020813d602011610b04575b81610af460209383610b8e565b810103126100c057519085610a00565b3d9150610ae7565b5f516020612ccd5f395f51905f52546001600160a01b031614159050836109c9565b600435906001600160a01b03821682036100c057565b606081019081106001600160401b03821117610b5f57604052565b634e487b7160e01b5f52604160045260245ffd5b604081019081106001600160401b03821117610b5f57604052565b90601f801991011681019081106001600160401b03821117610b5f57604052565b6001600160401b038111610b5f57601f01601f191660200190565b81601f820112156100c057803590610be182610baf565b92610bef6040519485610b8e565b828452602083830101116100c057815f926020809301838601378301015290565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b6001600160401b038111610b5f5760051b60200190565b9080601f830112156100c057813591610c6383610c34565b92610c716040519485610b8e565b80845260208085019160051b830101918383116100c05760208101915b838310610c9d57505050505090565b82356001600160401b0381116100c0578201906040828703601f1901126100c05760405190610ccb82610b73565b602083013582526040830135916001600160401b0383116100c057610cf888602080969581960101610bca565b83820152815201920191610c8e565b602081016020825282518091526040820191602060408360051b8301019401925f915b838310610d3957505050505090565b9091929394602080610d57600193603f198682030187528951610c10565b97019301930191939290610d2a565b51906001600160a01b03821682036100c057565b90610d8482610c34565b610d916040519182610b8e565b8281528092610da2601f1991610c34565b01905f5b828110610db257505050565b806060602080938501015201610da6565b8051821015610dd75760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b5f516020612cad5f395f51905f52546040516321f8a72160e01b81527f13a993c3bf3b4408a525cee20fb4780056c09c1378aeb33db21173b33d30bdd0600482015290602090829060249082906001600160a01b03165afa908115610514575f91610f05575b50604051632474521560e21b81527fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42600482015233602482015290602090829060449082906001600160a01b03165afa908115610514575f91610eca575b5015610eb757565b6367841c7b60e11b5f523360045260245ffd5b90506020813d602011610efd575b81610ee560209383610b8e565b810103126100c0575180151581036100c0575f610eaf565b3d9150610ed8565b90506020813d602011610f3c575b81610f2060209383610b8e565b810103126100c0576020610f35604492610d66565b9150610e51565b3d9150610f13565b7f2bb2653324aca374dde55b9e445a0741fa5fbabd9d913cb269b1b38c5839df005c906001600160a01b03821615610f7857565b627d197d60e41b5f5260045ffd5b9080815f9272184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b811015611197575b50806d04ee2d6d415b85acef8100000000600a92101561117c575b662386f26fc10000811015611168575b6305f5e100811015611157575b612710811015611148575b606481101561113a575b1015611130575b6001820190600a602161102961101385610baf565b946110216040519687610b8e565b808652610baf565b602085019590601f19013687378401015b5f1901916f181899199a1a9b1b9c1cb0b131b232b360811b8282061a83530490811561106857600a9061103a565b50506020916110b0603260405180938682019571343cb832b9323934bb329736b0b935b2ba1760711b87525180918484015e81015f838201520301601f198101835282610b8e565b5190206040516321f8a72160e01b8152600481019190915291829060249082906001600160a01b03165afa908115610514575f916110f6575b506001600160a01b031690565b90506020813d602011611128575b8161111160209383610b8e565b810103126100c05761112290610d66565b5f6110e9565b3d9150611104565b9060010190610ffe565b606460029104930192610ff7565b61271060049104930192610fed565b6305f5e10060089104930192610fe2565b662386f26fc1000060109104930192610fd5565b6d04ee2d6d415b85acef810000000060209104930192610fc5565b6040935072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b90049050600a610faa565b91908260809103126100c057604051608081018181106001600160401b03821117610b5f5760405260608193805183526111f960208201610d66565b60208401526040810151604084015201519060028210156100c05760600152565b91908260609103126100c05760405161123281610b44565b60408193805183526020810151602084015201519060028210156100c05760400152565b81601f820112156100c05780519061126d82610baf565b9261127b6040519485610b8e565b828452602083830101116100c057815f9260208093018386015e8301015290565b91908260409103126100c0576040516112b481610b73565b60208082946112c281610d66565b84520151910152565b91908260a09103126100c05760405160a081018181106001600160401b03821117610b5f5760405280926112fe81610d66565b8252602081015160208301526040810151604083015260608101519060028210156100c057608091606084015201519060028210156100c05760800152565b6040516020808201525f60408201526040815261135b606082610b8e565b90565b80519060015f9214612701576002815114612524576003815114612325576004815114612239576005815114612142576006815114611f80576007815114611cb357600c815114611bee57600d815114611b8d57600e815114611a9a5760088151146118d457600981511461163d57600a81511461153b57600b8151146113e957505061135b61133d565b602001518051810160a082820312611537579060208061140b930191016112cb565b80516020820151608083015190916001600160a01b03169060028110156115235761143590612b74565b6060840151600281101561150f5791611491939186611455602095612b74565b604051635d043b2960e11b815260048101959095526001600160a01b039283166024860152909116604484015291938492839182906064820190565b03925af192831561150357926114cd575b508160406114b592015180821015612a5d565b6040519060208201526020815261135b604082610b8e565b9091506020813d6020116114fb575b816114e960209383610b8e565b810103126100c05751906114b56114a2565b3d91506114dc565b604051903d90823e3d90fd5b634e487b7160e01b86526021600452602486fd5b634e487b7160e01b85526021600452602485fd5b8280fd5b602001518051810160a082820312611537579060208061155d930191016112cb565b80516020820151608083015190916001600160a01b03169060028110156115235761158790612b74565b6060840151600281101561150f57916115e39391866115a7602095612b74565b604051632d182be560e21b815260048101959095526001600160a01b039283166024860152909116604484015291938492839182906064820190565b03925af19283156115035792611607575b508160406114b592015180821115612a5d565b9091506020813d602011611635575b8161162360209383610b8e565b810103126100c05751906114b56115f4565b3d9150611616565b602001518051810160a082820312611537579060208061165f930191016112cb565b9160018060a01b038351166040516338d52e0f60e01b8152602081600481855afa9081156118c957849161188b575b5060018060a01b031690606085018051600281101561150f5715611861575b85516040870180519093916116cc91906001600160a01b0316836128e5565b6020870151966080810151600281101561184d576117209697986116f1602092612b74565b6040516394bf804d60e01b815260048101929092526001600160a01b0316602482015296879081906044820190565b03818b865af195861561184257889661180a575b50906117599161174987865180821115612a5d565b516001600160a01b03169061282c565b805160028110156117f65761176d90612b74565b6001600160a01b0316301415806117ec575b6117a2575b5050509091506040519060208201526020815261135b604082610b8e565b51600281101561150f576117b590612b74565b9051918383039283116117d8576117ce939495506129a4565b81905f8080611784565b634e487b7160e01b86526011600452602486fd5b508151841061177f565b634e487b7160e01b87526021600452602487fd5b919095506020823d60201161183a575b8161182760209383610b8e565b810103126100c057905194611759611734565b3d915061181a565b6040513d8a823e3d90fd5b634e487b7160e01b88526021600452602488fd5b8051600281101561150f5761187861188691612b74565b604088015190309086612bc2565b6116ad565b90506020813d6020116118c1575b816118a660209383610b8e565b810103126118bd576118b790610d66565b5f61168e565b8380fd5b3d9150611899565b6040513d86823e3d90fd5b602001518051810160a08282031261153757906020806118f6930191016112cb565b9060018060a01b038251166040516338d52e0f60e01b8152602081600481855afa908115611a8f578391611a55575b5060018060a01b03169060608401805160028110156115235715611a17575b508351602085018051909161196391906001600160a01b0316856128e5565b51906080850151600281101561152357916020916119836119b894612b74565b604051636e553f6560e01b815260048101939093526001600160a01b0316602483015290928391908290879082906044820190565b03925af192831561150357926119e1575b50826117498360406114b59596015180821015612a5d565b91506020823d602011611a0f575b816119fc60209383610b8e565b810103126100c0576114b59151916119c9565b3d91506119ef565b516002811015611a4157611a2d611a3b91612b74565b602086015190309085612bc2565b5f611944565b634e487b7160e01b84526021600452602484fd5b90506020813d602011611a87575b81611a7060209383610b8e565b8101031261153757611a8190610d66565b5f611925565b3d9150611a63565b6040513d85823e3d90fd5b90602060018060a01b035f516020612cad5f395f51905f525416920151606081805181010312611b895760405192611ad184610b44565b611add60208301610d66565b84526060604083015192602086019384520151604085019081526020611b0161133d565b9560018060a01b0390511693516024604051809581936321f8a72160e01b835260048301525afa9182156118c9578492611b43575b5061135b935051916128e5565b915091926020823d602011611b81575b81611b6060209383610b8e565b81010312611b7e575090611b7761135b9392610d66565b905f611b36565b80fd5b3d9150611b53565b5080fd5b60200151908151820190604083830312611b7e575090602080611bb29301910161129c565b611bba61133d565b81516020909201805191926001600160a01b031691611bd857505090565b61135b91611be4610f44565b9151913091612bc2565b60200151805181016040828203126115375790602080611c109301910161129c565b611c1861133d565b91602060018060a01b038351169201515f1981145f14611cac57506040516370a0823160e01b8152306004820152602081602481865afa9182156115035791611c7a575b505b80611c6857505090565b61135b91611c74610f44565b906129a4565b90506020813d602011611ca4575b81611c9560209383610b8e565b810103126100c057515f611c5c565b3d9150611c88565b9050611c5e565b602001518051810160208101916020818303126118bd576020810151906001600160401b038211611eb95701916060838303126118bd5760405191611cf783610b44565b60208401518352604084015193602084019485526060810151906001600160401b038211611f7c5790602091010182601f82011215611f7857805191611d3c83610c34565b93611d4a6040519586610b8e565b83855260208086019460051b84010192818411611f745760208101945b848610611f0657505050505060408301918252505f516020612cad5f395f51905f525482516001600160a01b0391611da191908316610f86565b1691611db08151841515612a43565b835191611dbb610f44565b946040519563010c417d60e71b602088015260018060a01b031660248701526040604487015260c48601925160648701525160848601525190606060a4860152815180915260e4850190602060e48260051b88010193019187905b828210611eca5750505050918391611e3c8695611e66979503601f198101855284610b8e565b83604051809781958294635296a43160e01b84526004840152604060248401526044830190610c10565b03925af1918215611ebd578192611e7c57505090565b909291503d8084833e611e8f8183610b8e565b8101906020818303126118bd578051906001600160401b038211611eb95761135b93945001611256565b8480fd5b50604051903d90823e3d90fd5b90919293602080611ef860019360e3198c82030186526040838a518051845201519181858201520190610c10565b960192019201909291611e16565b85516001600160401b038111611f70578201604081860312611f705760405190611f2f82610b73565b602081015182526040810151906001600160401b038211611f6c5791611f5d86602080969481960101611256565b83820152815201950194611d67565b8c80fd5b8a80fd5b8880fd5b8580fd5b8680fd5b60200151805181016060828203126115375790602080611fa29301910161121a565b5f516020612cad5f395f51905f52548151611fc5916001600160a01b0316610f86565b91611fce61133d565b825190936001600160a01b03169190611fe990831515612a43565b6040516338d52e0f60e01b8152602081600481865afa9081156121375782916120fd575b5060018060a01b031692604081019081516002811015611a41576001146120e9575b6020612039612c06565b910151825160028110156115235761205090612b74565b91853b15611eb95760405163173aba7160e21b81526001600160a01b0391821660048201526024810192909252919091166044820152828160648183885af18015611a8f579083916120d4575b5050519060028210156120c057506001146120b757505090565b61135b9161282c565b634e487b7160e01b81526021600452602490fd5b816120de91610b8e565b611b8957815f61209d565b6120f8602082015185876128e5565b61202f565b90506020813d60201161212f575b8161211860209383610b8e565b81010312611b895761212990610d66565b5f61200d565b3d915061210b565b6040513d84823e3d90fd5b602001518051810160608282031261153757906020806121649301910161121a565b5f516020612cad5f395f51905f5254815191929161218a916001600160a01b0316610f86565b9161219361133d565b815190936001600160a01b0316906121ad90821515612a43565b6121b5612c06565b91604060208201519101516002811015611523576121d290612b74565b92823b15611eb957604051636c665a5560e01b81526001600160a01b0391821660048201526024810192909252909216604483015282908290818381606481015b03925af180156121375761222657505090565b612231828092610b8e565b611b7e575090565b6020015180518101608082820312611537579060208061225b930191016111bd565b5f516020612cad5f395f51905f52548151919291612281916001600160a01b0316610f86565b9161228a61133d565b815190936001600160a01b031691906122a590831515612a43565b6122ad612c06565b9160018060a01b0360208301511660606040840151930151600281101561150f576122d790612b74565b93823b15611f7857604051632d37a2ef60e11b81526001600160a01b039182166004820152918116602483015260448201939093529290911660648301528290829081838160848101612213565b60200151805181016080828203126115375790602080612347930191016111bd565b5f516020612cad5f395f51905f5254815161236a916001600160a01b0316610f86565b9161237361133d565b825190936001600160a01b0316919061238e90831515612a43565b60608301805160028110156125105760011461246e575b6123ad612c06565b6020850194604060018060a01b03875116910151918351600281101561150f576123d690612b74565b863b15611f785760405163582daa9760e11b81526001600160a01b03928316600482015292821660248401526044830193909352919091166064820152828160848183885af18015611a8f57908391612459575b5050519060028210156120c0575060011461244457505090565b905161135b91906001600160a01b031661282c565b8161246391610b8e565b611b8957815f61242a565b602084810180516040516370a0823160e01b81523060048201529290839060249082906001600160a01b03165afa9081156118c957859085926124d8575b6124d393506040880192835190818082109118021880935260018060a01b039051166128e5565b6123a5565b9150506020823d602011612508575b816124f460209383610b8e565b810103126100c057846124d39251916124ac565b3d91506124e7565b634e487b7160e01b83526021600452602483fd5b5f516020612cad5f395f51905f5254602090612548906001600160a01b03166129e0565b91015191606083805181010312611b7e576040519161256683610b44565b60208401518352604084015193600285101561153757602084019485526060015190600282101561153757604084019182526125a061133d565b9480516002811015611523575f19016126d1575b5083516040516370a0823160e01b81523060048201526001600160a01b039092169190602082602481865afa9182156126c6578592612692575b508180821091180218808552813b156118bd578391602483926040519485938492632e1a7d4d60e01b845260048401525af18015611a8f5790839161267d575b505080516002811015612510575f1901612649575b50505090565b519060028210156120c0575061267591906001600160a01b039061266c90612b74565b16905190612b02565b5f8080612643565b8161268791610b8e565b611b8957815f61262e565b9091506020813d6020116126be575b816126ae60209383610b8e565b810103126100c05751905f6125ee565b3d91506126a1565b6040513d87823e3d90fd5b516002811015611a41576126e76126fb91612b74565b85519030906001600160a01b038516612bc2565b5f6125b4565b90602061272360018060a01b035f516020612cad5f395f51905f5254166129e0565b920151906040828051810103126100c0576040519061274182610b73565b604060208401519384845201519260028410156100c05760208301938452803403612816575061276f61133d565b825190946001600160a01b03169390843b156100c0575f60049160405192838092630d0e30db60e41b8252895af1801561051457612801575b5080516002811015612510576127bd90612b74565b306001600160a01b03909116036127d6575b5050505090565b519060028210156120c05750906127f06127f89392612b74565b9051916129a4565b5f8080806127cf565b61280e9192505f90610b8e565b5f905f6127a8565b6307c83fcf60e41b5f526004523460245260445ffd5b6040519060205f8184019463095ea7b360e01b865260018060a01b03169485602486015281604486015260448552612865606486610b8e565b84519082855af15f513d826128c0575b50501561288157505050565b6128b96128be936040519063095ea7b360e01b602083015260248201525f6044820152604481526128b3606482610b8e565b82612a7b565b612a7b565b565b9091506128dd57506001600160a01b0381163b15155b5f80612875565b6001146128d6565b60405163095ea7b360e01b60208083019182526001600160a01b0385166024840152604480840196909652948252929390925f90612924606486610b8e565b84519082855af15f513d8261297f575b50501561294057505050565b60405163095ea7b360e01b60208201526001600160a01b0390931660248401525f60448085019190915283526128be926128b9906128b3606482610b8e565b90915061299c57506001600160a01b0381163b15155b5f80612934565b600114612995565b60405163a9059cbb60e01b60208201526001600160a01b039290921660248301526044808301939093529181526128be916128b9606483610b8e565b6040516321f8a72160e01b81527f0f8a193ff464434486c0daf7db2a895884365d2bc84ba47a68fcf89c1b14b5b8600482015290602090829060249082906001600160a01b03165afa908115610514575f916110f657506001600160a01b031690565b15612a4b5750565b6369616b8760e01b5f5260045260245ffd5b15612a66575050565b6371c4efed60e01b5f5260045260245260445ffd5b905f602091828151910182855af115610514575f513d612aca57506001600160a01b0381163b155b612aaa5750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b60011415612aa3565b3d15612afd573d90612ae482610baf565b91612af26040519384610b8e565b82523d5f602084013e565b606090565b814710612b32575f918291829182916001600160a01b03165af1612b24612ad3565b9015612b2d5750565b612c49565b504763cf47918160e01b5f5260045260245260445ffd5b60ff5f516020612ced5f395f51905f525460401c1615612b6557565b631afcd79f60e31b5f5260045ffd5b906002821015612bae578115612ba45760018214612b9f575063ee7bbe9d60e01b5f5260045260245ffd5b309150565b905061135b610f44565b634e487b7160e01b5f52602160045260245ffd5b6040516323b872dd60e01b60208201526001600160a01b0392831660248201529290911660448301526064808301939093529181526128be916128b9608483610b8e565b7f77d7587726ce27a2d1a6421e65daa8ab8481b71227099b995512d28afa6b89005c906001600160a01b03821615612c3a57565b634c0c913f60e01b5f5260045ffd5b805115612c5857805190602001fd5b63d6bda27560e01b5f5260045ffd5b90612c725750612c49565b81511580612ca3575b612c83575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b15612c7b56fe24da5178c808c813cf7ebebe5cb60eb708540ed968d5353d43b24720d9a86500360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbcf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00e26c696bf0e34aaf444e67b257b0ce1f00d161ab27c76bcd8c8582bed8ddd000a2646970667358221220d69c0c59caa8d5ae83a972c81076ff7a2cfc1f39fbc046f8899d0dd05469fd8664736f6c634300081c0033f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00

Deployed Bytecode

0x6080604052600436101561001a575b3615610018575f80fd5b005b5f3560e01c80634f1ef2861461096157806352d1902d146108fb57806354fd4d50146108b45780636ea056a9146107315780638620be801461051f5780639830ff6a1461040f578063ad3cb1cc146103c8578063b58ce21d1461025d578063c4d66de8146100c45763f3ad65f40361000e57346100c0575f3660031901126100c0575f516020612cad5f395f51905f52546040516001600160a01b039091168152602090f35b5f80fd5b346100c05760203660031901126100c0576004356001600160a01b038116908190036100c0575f516020612ced5f395f51905f52549060ff8260401c1615916001600160401b03811680159081610255575b600114908161024b575b159081610242575b506102335767ffffffffffffffff1981166001175f516020612ced5f395f51905f525582610207575b5061015a612b49565b610162612b49565b61016a612b49565b6bffffffffffffffffffffffff60a01b5f516020612cad5f395f51905f525416175f516020612cad5f395f51905f52556101a2612b49565b6101aa612b49565b6101b057005b68ff0000000000000000195f516020612ced5f395f51905f5254165f516020612ced5f395f51905f52557fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2602060405160018152a1005b68ffffffffffffffffff191668010000000000000001175f516020612ced5f395f51905f525582610151565b63f92ee8a960e01b5f5260045ffd5b90501584610128565b303b159150610120565b849150610116565b60203660031901126100c0576004356001600160401b0381116100c057610288903690600401610c4b565b5f516020612d0d5f395f51905f525c6103b95760015f516020612d0d5f395f51905f525d337f77d7587726ce27a2d1a6421e65daa8ab8481b71227099b995512d28afa6b89005d337f2bb2653324aca374dde55b9e445a0741fa5fbabd9d913cb269b1b38c5839df005d6102fc8151610d7a565b905f5b815181101561033a578061031e61031860019385610dc3565b5161135e565b6103288286610dc3565b526103338185610dc3565b50016102ff565b825f7f77d7587726ce27a2d1a6421e65daa8ab8481b71227099b995512d28afa6b89005d5f7f2bb2653324aca374dde55b9e445a0741fa5fbabd9d913cb269b1b38c5839df005d5f516020612d0d5f395f51905f525c156103b9576103b5905f5f516020612d0d5f395f51905f525d60405191829182610d07565b0390f35b630800025b60e31b5f5260045ffd5b346100c0575f3660031901126100c0576103b56040516103e9604082610b8e565b60058152640352e302e360dc1b6020820152604051918291602083526020830190610c10565b346100c05760203660031901126100c05760043561042b610deb565b479081808210911802186024602060018060a01b035f516020612cad5f395f51905f525416604051928380926321f8a72160e01b82527faef04b9e2c9ec721a01ca424bbc4285142e44828bb9153fda4eb5d820563cb1660048301525afa908115610514575f916104da575b506001600160a01b0316906104ac8183612b02565b6040519081527f617a904b01259b64867cc3246576c5b0b4d723c337757ec09ae915f57633864a60203392a3005b90506020813d60201161050c575b816104f560209383610b8e565b810103126100c05761050690610d66565b82610497565b3d91506104e8565b6040513d5f823e3d90fd5b346100c05760403660031901126100c057610538610b2e565b6024356001600160401b0381116100c057606060031982360301126100c05760405161056381610b44565b816004013581526020810191602481013583526044810135906001600160401b0382116100c05760046105999236920101610c4b565b60408201908152926001600160a01b031680151580610718575b1561070657505f516020612cad5f395f51905f525490516001600160a01b03916105df91908316610f86565b168033036106f3576105f2835151610d7a565b915f5b8451805182101561062c579061061061031882600194610dc3565b61061a8287610dc3565b526106258186610dc3565b50016105f5565b50506040516338d52e0f60e01b81529350602084600481855afa938415610514575f946106a4575b6103b561068261069086610673898888519160018060a01b03166128e5565b60405192839160208301610d07565b03601f198101835282610b8e565b604051918291602083526020830190610c10565b9350916020843d6020116106eb575b816106c060209383610b8e565b810103126100c05761067361068293610690936106df6103b597610d66565b96509350919350610654565b3d91506106b3565b63a4fa10c160e01b5f523360045260245ffd5b63382fa62360e11b5f5260045260245ffd5b506001600160a01b03610729610f44565b1681146105b3565b346100c05760403660031901126100c0576004356001600160a01b038116908181036100c057602435610762610deb565b6040516370a0823160e01b815230600482015290602082602481875afa918215610514575f92610880575b508180821091180218906024602060018060a01b035f516020612cad5f395f51905f525416604051928380926321f8a72160e01b82527faef04b9e2c9ec721a01ca424bbc4285142e44828bb9153fda4eb5d820563cb1660048301525afa9081156105145783905f92610841575b508161080792936129a4565b6040519182526001600160a01b03169033907ffe6f9ffae65cf2c41cdbb3faf5a94e71eab2c2c62215df2efd79e12e451d0b6290602090a4005b9150506020813d602011610878575b8161085d60209383610b8e565b810103126100c0578261087261080792610d66565b916107fb565b3d9150610850565b9091506020813d6020116108ac575b8161089c60209383610b8e565b810103126100c05751908461078d565b3d915061088f565b346100c0575f3660031901126100c0576103b56040516108d5604082610b8e565b60058152640312e312e360dc1b6020820152604051918291602083526020830190610c10565b346100c0575f3660031901126100c0577f00000000000000000000000003e65321dcba6565eb8ca90096633c790a9fd5a76001600160a01b031630036109525760206040515f516020612ccd5f395f51905f528152f35b63703e46dd60e11b5f5260045ffd5b60403660031901126100c057610975610b2e565b6024356001600160401b0381116100c057610994903690600401610bca565b6001600160a01b037f00000000000000000000000003e65321dcba6565eb8ca90096633c790a9fd5a716308114908115610b0c575b50610952576109d6610deb565b6040516352d1902d60e01b81526001600160a01b0383169290602081600481875afa5f9181610ad8575b50610a185783634c9c8ce360e01b5f5260045260245ffd5b805f516020612ccd5f395f51905f52859203610ac65750813b15610ab4575f516020612ccd5f395f51905f5280546001600160a01b031916821790557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115610a9c575f8083602061001895519101845af4610a96612ad3565b91612c67565b505034610aa557005b63b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b632a87526960e21b5f5260045260245ffd5b9091506020813d602011610b04575b81610af460209383610b8e565b810103126100c057519085610a00565b3d9150610ae7565b5f516020612ccd5f395f51905f52546001600160a01b031614159050836109c9565b600435906001600160a01b03821682036100c057565b606081019081106001600160401b03821117610b5f57604052565b634e487b7160e01b5f52604160045260245ffd5b604081019081106001600160401b03821117610b5f57604052565b90601f801991011681019081106001600160401b03821117610b5f57604052565b6001600160401b038111610b5f57601f01601f191660200190565b81601f820112156100c057803590610be182610baf565b92610bef6040519485610b8e565b828452602083830101116100c057815f926020809301838601378301015290565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b6001600160401b038111610b5f5760051b60200190565b9080601f830112156100c057813591610c6383610c34565b92610c716040519485610b8e565b80845260208085019160051b830101918383116100c05760208101915b838310610c9d57505050505090565b82356001600160401b0381116100c0578201906040828703601f1901126100c05760405190610ccb82610b73565b602083013582526040830135916001600160401b0383116100c057610cf888602080969581960101610bca565b83820152815201920191610c8e565b602081016020825282518091526040820191602060408360051b8301019401925f915b838310610d3957505050505090565b9091929394602080610d57600193603f198682030187528951610c10565b97019301930191939290610d2a565b51906001600160a01b03821682036100c057565b90610d8482610c34565b610d916040519182610b8e565b8281528092610da2601f1991610c34565b01905f5b828110610db257505050565b806060602080938501015201610da6565b8051821015610dd75760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b5f516020612cad5f395f51905f52546040516321f8a72160e01b81527f13a993c3bf3b4408a525cee20fb4780056c09c1378aeb33db21173b33d30bdd0600482015290602090829060249082906001600160a01b03165afa908115610514575f91610f05575b50604051632474521560e21b81527fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42600482015233602482015290602090829060449082906001600160a01b03165afa908115610514575f91610eca575b5015610eb757565b6367841c7b60e11b5f523360045260245ffd5b90506020813d602011610efd575b81610ee560209383610b8e565b810103126100c0575180151581036100c0575f610eaf565b3d9150610ed8565b90506020813d602011610f3c575b81610f2060209383610b8e565b810103126100c0576020610f35604492610d66565b9150610e51565b3d9150610f13565b7f2bb2653324aca374dde55b9e445a0741fa5fbabd9d913cb269b1b38c5839df005c906001600160a01b03821615610f7857565b627d197d60e41b5f5260045ffd5b9080815f9272184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b811015611197575b50806d04ee2d6d415b85acef8100000000600a92101561117c575b662386f26fc10000811015611168575b6305f5e100811015611157575b612710811015611148575b606481101561113a575b1015611130575b6001820190600a602161102961101385610baf565b946110216040519687610b8e565b808652610baf565b602085019590601f19013687378401015b5f1901916f181899199a1a9b1b9c1cb0b131b232b360811b8282061a83530490811561106857600a9061103a565b50506020916110b0603260405180938682019571343cb832b9323934bb329736b0b935b2ba1760711b87525180918484015e81015f838201520301601f198101835282610b8e565b5190206040516321f8a72160e01b8152600481019190915291829060249082906001600160a01b03165afa908115610514575f916110f6575b506001600160a01b031690565b90506020813d602011611128575b8161111160209383610b8e565b810103126100c05761112290610d66565b5f6110e9565b3d9150611104565b9060010190610ffe565b606460029104930192610ff7565b61271060049104930192610fed565b6305f5e10060089104930192610fe2565b662386f26fc1000060109104930192610fd5565b6d04ee2d6d415b85acef810000000060209104930192610fc5565b6040935072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b90049050600a610faa565b91908260809103126100c057604051608081018181106001600160401b03821117610b5f5760405260608193805183526111f960208201610d66565b60208401526040810151604084015201519060028210156100c05760600152565b91908260609103126100c05760405161123281610b44565b60408193805183526020810151602084015201519060028210156100c05760400152565b81601f820112156100c05780519061126d82610baf565b9261127b6040519485610b8e565b828452602083830101116100c057815f9260208093018386015e8301015290565b91908260409103126100c0576040516112b481610b73565b60208082946112c281610d66565b84520151910152565b91908260a09103126100c05760405160a081018181106001600160401b03821117610b5f5760405280926112fe81610d66565b8252602081015160208301526040810151604083015260608101519060028210156100c057608091606084015201519060028210156100c05760800152565b6040516020808201525f60408201526040815261135b606082610b8e565b90565b80519060015f9214612701576002815114612524576003815114612325576004815114612239576005815114612142576006815114611f80576007815114611cb357600c815114611bee57600d815114611b8d57600e815114611a9a5760088151146118d457600981511461163d57600a81511461153b57600b8151146113e957505061135b61133d565b602001518051810160a082820312611537579060208061140b930191016112cb565b80516020820151608083015190916001600160a01b03169060028110156115235761143590612b74565b6060840151600281101561150f5791611491939186611455602095612b74565b604051635d043b2960e11b815260048101959095526001600160a01b039283166024860152909116604484015291938492839182906064820190565b03925af192831561150357926114cd575b508160406114b592015180821015612a5d565b6040519060208201526020815261135b604082610b8e565b9091506020813d6020116114fb575b816114e960209383610b8e565b810103126100c05751906114b56114a2565b3d91506114dc565b604051903d90823e3d90fd5b634e487b7160e01b86526021600452602486fd5b634e487b7160e01b85526021600452602485fd5b8280fd5b602001518051810160a082820312611537579060208061155d930191016112cb565b80516020820151608083015190916001600160a01b03169060028110156115235761158790612b74565b6060840151600281101561150f57916115e39391866115a7602095612b74565b604051632d182be560e21b815260048101959095526001600160a01b039283166024860152909116604484015291938492839182906064820190565b03925af19283156115035792611607575b508160406114b592015180821115612a5d565b9091506020813d602011611635575b8161162360209383610b8e565b810103126100c05751906114b56115f4565b3d9150611616565b602001518051810160a082820312611537579060208061165f930191016112cb565b9160018060a01b038351166040516338d52e0f60e01b8152602081600481855afa9081156118c957849161188b575b5060018060a01b031690606085018051600281101561150f5715611861575b85516040870180519093916116cc91906001600160a01b0316836128e5565b6020870151966080810151600281101561184d576117209697986116f1602092612b74565b6040516394bf804d60e01b815260048101929092526001600160a01b0316602482015296879081906044820190565b03818b865af195861561184257889661180a575b50906117599161174987865180821115612a5d565b516001600160a01b03169061282c565b805160028110156117f65761176d90612b74565b6001600160a01b0316301415806117ec575b6117a2575b5050509091506040519060208201526020815261135b604082610b8e565b51600281101561150f576117b590612b74565b9051918383039283116117d8576117ce939495506129a4565b81905f8080611784565b634e487b7160e01b86526011600452602486fd5b508151841061177f565b634e487b7160e01b87526021600452602487fd5b919095506020823d60201161183a575b8161182760209383610b8e565b810103126100c057905194611759611734565b3d915061181a565b6040513d8a823e3d90fd5b634e487b7160e01b88526021600452602488fd5b8051600281101561150f5761187861188691612b74565b604088015190309086612bc2565b6116ad565b90506020813d6020116118c1575b816118a660209383610b8e565b810103126118bd576118b790610d66565b5f61168e565b8380fd5b3d9150611899565b6040513d86823e3d90fd5b602001518051810160a08282031261153757906020806118f6930191016112cb565b9060018060a01b038251166040516338d52e0f60e01b8152602081600481855afa908115611a8f578391611a55575b5060018060a01b03169060608401805160028110156115235715611a17575b508351602085018051909161196391906001600160a01b0316856128e5565b51906080850151600281101561152357916020916119836119b894612b74565b604051636e553f6560e01b815260048101939093526001600160a01b0316602483015290928391908290879082906044820190565b03925af192831561150357926119e1575b50826117498360406114b59596015180821015612a5d565b91506020823d602011611a0f575b816119fc60209383610b8e565b810103126100c0576114b59151916119c9565b3d91506119ef565b516002811015611a4157611a2d611a3b91612b74565b602086015190309085612bc2565b5f611944565b634e487b7160e01b84526021600452602484fd5b90506020813d602011611a87575b81611a7060209383610b8e565b8101031261153757611a8190610d66565b5f611925565b3d9150611a63565b6040513d85823e3d90fd5b90602060018060a01b035f516020612cad5f395f51905f525416920151606081805181010312611b895760405192611ad184610b44565b611add60208301610d66565b84526060604083015192602086019384520151604085019081526020611b0161133d565b9560018060a01b0390511693516024604051809581936321f8a72160e01b835260048301525afa9182156118c9578492611b43575b5061135b935051916128e5565b915091926020823d602011611b81575b81611b6060209383610b8e565b81010312611b7e575090611b7761135b9392610d66565b905f611b36565b80fd5b3d9150611b53565b5080fd5b60200151908151820190604083830312611b7e575090602080611bb29301910161129c565b611bba61133d565b81516020909201805191926001600160a01b031691611bd857505090565b61135b91611be4610f44565b9151913091612bc2565b60200151805181016040828203126115375790602080611c109301910161129c565b611c1861133d565b91602060018060a01b038351169201515f1981145f14611cac57506040516370a0823160e01b8152306004820152602081602481865afa9182156115035791611c7a575b505b80611c6857505090565b61135b91611c74610f44565b906129a4565b90506020813d602011611ca4575b81611c9560209383610b8e565b810103126100c057515f611c5c565b3d9150611c88565b9050611c5e565b602001518051810160208101916020818303126118bd576020810151906001600160401b038211611eb95701916060838303126118bd5760405191611cf783610b44565b60208401518352604084015193602084019485526060810151906001600160401b038211611f7c5790602091010182601f82011215611f7857805191611d3c83610c34565b93611d4a6040519586610b8e565b83855260208086019460051b84010192818411611f745760208101945b848610611f0657505050505060408301918252505f516020612cad5f395f51905f525482516001600160a01b0391611da191908316610f86565b1691611db08151841515612a43565b835191611dbb610f44565b946040519563010c417d60e71b602088015260018060a01b031660248701526040604487015260c48601925160648701525160848601525190606060a4860152815180915260e4850190602060e48260051b88010193019187905b828210611eca5750505050918391611e3c8695611e66979503601f198101855284610b8e565b83604051809781958294635296a43160e01b84526004840152604060248401526044830190610c10565b03925af1918215611ebd578192611e7c57505090565b909291503d8084833e611e8f8183610b8e565b8101906020818303126118bd578051906001600160401b038211611eb95761135b93945001611256565b8480fd5b50604051903d90823e3d90fd5b90919293602080611ef860019360e3198c82030186526040838a518051845201519181858201520190610c10565b960192019201909291611e16565b85516001600160401b038111611f70578201604081860312611f705760405190611f2f82610b73565b602081015182526040810151906001600160401b038211611f6c5791611f5d86602080969481960101611256565b83820152815201950194611d67565b8c80fd5b8a80fd5b8880fd5b8580fd5b8680fd5b60200151805181016060828203126115375790602080611fa29301910161121a565b5f516020612cad5f395f51905f52548151611fc5916001600160a01b0316610f86565b91611fce61133d565b825190936001600160a01b03169190611fe990831515612a43565b6040516338d52e0f60e01b8152602081600481865afa9081156121375782916120fd575b5060018060a01b031692604081019081516002811015611a41576001146120e9575b6020612039612c06565b910151825160028110156115235761205090612b74565b91853b15611eb95760405163173aba7160e21b81526001600160a01b0391821660048201526024810192909252919091166044820152828160648183885af18015611a8f579083916120d4575b5050519060028210156120c057506001146120b757505090565b61135b9161282c565b634e487b7160e01b81526021600452602490fd5b816120de91610b8e565b611b8957815f61209d565b6120f8602082015185876128e5565b61202f565b90506020813d60201161212f575b8161211860209383610b8e565b81010312611b895761212990610d66565b5f61200d565b3d915061210b565b6040513d84823e3d90fd5b602001518051810160608282031261153757906020806121649301910161121a565b5f516020612cad5f395f51905f5254815191929161218a916001600160a01b0316610f86565b9161219361133d565b815190936001600160a01b0316906121ad90821515612a43565b6121b5612c06565b91604060208201519101516002811015611523576121d290612b74565b92823b15611eb957604051636c665a5560e01b81526001600160a01b0391821660048201526024810192909252909216604483015282908290818381606481015b03925af180156121375761222657505090565b612231828092610b8e565b611b7e575090565b6020015180518101608082820312611537579060208061225b930191016111bd565b5f516020612cad5f395f51905f52548151919291612281916001600160a01b0316610f86565b9161228a61133d565b815190936001600160a01b031691906122a590831515612a43565b6122ad612c06565b9160018060a01b0360208301511660606040840151930151600281101561150f576122d790612b74565b93823b15611f7857604051632d37a2ef60e11b81526001600160a01b039182166004820152918116602483015260448201939093529290911660648301528290829081838160848101612213565b60200151805181016080828203126115375790602080612347930191016111bd565b5f516020612cad5f395f51905f5254815161236a916001600160a01b0316610f86565b9161237361133d565b825190936001600160a01b0316919061238e90831515612a43565b60608301805160028110156125105760011461246e575b6123ad612c06565b6020850194604060018060a01b03875116910151918351600281101561150f576123d690612b74565b863b15611f785760405163582daa9760e11b81526001600160a01b03928316600482015292821660248401526044830193909352919091166064820152828160848183885af18015611a8f57908391612459575b5050519060028210156120c0575060011461244457505090565b905161135b91906001600160a01b031661282c565b8161246391610b8e565b611b8957815f61242a565b602084810180516040516370a0823160e01b81523060048201529290839060249082906001600160a01b03165afa9081156118c957859085926124d8575b6124d393506040880192835190818082109118021880935260018060a01b039051166128e5565b6123a5565b9150506020823d602011612508575b816124f460209383610b8e565b810103126100c057846124d39251916124ac565b3d91506124e7565b634e487b7160e01b83526021600452602483fd5b5f516020612cad5f395f51905f5254602090612548906001600160a01b03166129e0565b91015191606083805181010312611b7e576040519161256683610b44565b60208401518352604084015193600285101561153757602084019485526060015190600282101561153757604084019182526125a061133d565b9480516002811015611523575f19016126d1575b5083516040516370a0823160e01b81523060048201526001600160a01b039092169190602082602481865afa9182156126c6578592612692575b508180821091180218808552813b156118bd578391602483926040519485938492632e1a7d4d60e01b845260048401525af18015611a8f5790839161267d575b505080516002811015612510575f1901612649575b50505090565b519060028210156120c0575061267591906001600160a01b039061266c90612b74565b16905190612b02565b5f8080612643565b8161268791610b8e565b611b8957815f61262e565b9091506020813d6020116126be575b816126ae60209383610b8e565b810103126100c05751905f6125ee565b3d91506126a1565b6040513d87823e3d90fd5b516002811015611a41576126e76126fb91612b74565b85519030906001600160a01b038516612bc2565b5f6125b4565b90602061272360018060a01b035f516020612cad5f395f51905f5254166129e0565b920151906040828051810103126100c0576040519061274182610b73565b604060208401519384845201519260028410156100c05760208301938452803403612816575061276f61133d565b825190946001600160a01b03169390843b156100c0575f60049160405192838092630d0e30db60e41b8252895af1801561051457612801575b5080516002811015612510576127bd90612b74565b306001600160a01b03909116036127d6575b5050505090565b519060028210156120c05750906127f06127f89392612b74565b9051916129a4565b5f8080806127cf565b61280e9192505f90610b8e565b5f905f6127a8565b6307c83fcf60e41b5f526004523460245260445ffd5b6040519060205f8184019463095ea7b360e01b865260018060a01b03169485602486015281604486015260448552612865606486610b8e565b84519082855af15f513d826128c0575b50501561288157505050565b6128b96128be936040519063095ea7b360e01b602083015260248201525f6044820152604481526128b3606482610b8e565b82612a7b565b612a7b565b565b9091506128dd57506001600160a01b0381163b15155b5f80612875565b6001146128d6565b60405163095ea7b360e01b60208083019182526001600160a01b0385166024840152604480840196909652948252929390925f90612924606486610b8e565b84519082855af15f513d8261297f575b50501561294057505050565b60405163095ea7b360e01b60208201526001600160a01b0390931660248401525f60448085019190915283526128be926128b9906128b3606482610b8e565b90915061299c57506001600160a01b0381163b15155b5f80612934565b600114612995565b60405163a9059cbb60e01b60208201526001600160a01b039290921660248301526044808301939093529181526128be916128b9606483610b8e565b6040516321f8a72160e01b81527f0f8a193ff464434486c0daf7db2a895884365d2bc84ba47a68fcf89c1b14b5b8600482015290602090829060249082906001600160a01b03165afa908115610514575f916110f657506001600160a01b031690565b15612a4b5750565b6369616b8760e01b5f5260045260245ffd5b15612a66575050565b6371c4efed60e01b5f5260045260245260445ffd5b905f602091828151910182855af115610514575f513d612aca57506001600160a01b0381163b155b612aaa5750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b60011415612aa3565b3d15612afd573d90612ae482610baf565b91612af26040519384610b8e565b82523d5f602084013e565b606090565b814710612b32575f918291829182916001600160a01b03165af1612b24612ad3565b9015612b2d5750565b612c49565b504763cf47918160e01b5f5260045260245260445ffd5b60ff5f516020612ced5f395f51905f525460401c1615612b6557565b631afcd79f60e31b5f5260045ffd5b906002821015612bae578115612ba45760018214612b9f575063ee7bbe9d60e01b5f5260045260245ffd5b309150565b905061135b610f44565b634e487b7160e01b5f52602160045260245ffd5b6040516323b872dd60e01b60208201526001600160a01b0392831660248201529290911660448301526064808301939093529181526128be916128b9608483610b8e565b7f77d7587726ce27a2d1a6421e65daa8ab8481b71227099b995512d28afa6b89005c906001600160a01b03821615612c3a57565b634c0c913f60e01b5f5260045ffd5b805115612c5857805190602001fd5b63d6bda27560e01b5f5260045ffd5b90612c725750612c49565b81511580612ca3575b612c83575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b15612c7b56fe24da5178c808c813cf7ebebe5cb60eb708540ed968d5353d43b24720d9a86500360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbcf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00e26c696bf0e34aaf444e67b257b0ce1f00d161ab27c76bcd8c8582bed8ddd000a2646970667358221220d69c0c59caa8d5ae83a972c81076ff7a2cfc1f39fbc046f8899d0dd05469fd8664736f6c634300081c0033

Block Transaction Gas Used Reward
view all blocks ##produced##

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.