ETH Price: $3,866.79 (+4.59%)

Contract

0xdB1E46B448e68a5E35CB693a99D59f784aD115CC

Overview

ETH Balance

0 ETH

ETH Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Transfer Ownersh...345746532024-05-21 19:32:20197 days ago1716319940IN
0xdB1E46B4...84aD115CC
0 ETH0.000004280.025

Latest 1 internal transaction

Parent Transaction Hash Block From To
345720952024-05-21 18:48:41197 days ago1716317321  Contract Creation0 ETH
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0xDf4a5F0F...9fF348422
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
ProxyAdmin

Compiler Version
v0.8.19+commit.7dd6d404

ZkSolc Version
v1.3.18

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion, MIT license
File 1 of 43 : ProxyAdmin.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/transparent/ProxyAdmin.sol)

pragma solidity ^0.8.0;

import "./TransparentUpgradeableProxy.sol";
import "../../access/Ownable.sol";

/**
 * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
 * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
 */
contract ProxyAdmin is Ownable {
    /**
     * @dev Returns the current implementation of `proxy`.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     */
    function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
        // We need to manually run the static call since the getter cannot be flagged as view
        // bytes4(keccak256("implementation()")) == 0x5c60da1b
        (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
        require(success);
        return abi.decode(returndata, (address));
    }

    /**
     * @dev Returns the current admin of `proxy`.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     */
    function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
        // We need to manually run the static call since the getter cannot be flagged as view
        // bytes4(keccak256("admin()")) == 0xf851a440
        (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
        require(success);
        return abi.decode(returndata, (address));
    }

    /**
     * @dev Changes the admin of `proxy` to `newAdmin`.
     *
     * Requirements:
     *
     * - This contract must be the current admin of `proxy`.
     */
    function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
        proxy.changeAdmin(newAdmin);
    }

    /**
     * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     */
    function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
        proxy.upgradeTo(implementation);
    }

    /**
     * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
     * {TransparentUpgradeableProxy-upgradeToAndCall}.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     */
    function upgradeAndCall(
        TransparentUpgradeableProxy proxy,
        address implementation,
        bytes memory data
    ) public payable virtual onlyOwner {
        proxy.upgradeToAndCall{value: msg.value}(implementation, data);
    }
}

File 2 of 43 : AccessControlEnumerableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)

pragma solidity ^0.8.0;

import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
    function __AccessControlEnumerable_init() internal onlyInitializing {
    }

    function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
    }
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;

    mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
        return _roleMembers[role].at(index);
    }

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
        return _roleMembers[role].length();
    }

    /**
     * @dev Overload {_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override {
        super._grantRole(role, account);
        _roleMembers[role].add(account);
    }

    /**
     * @dev Overload {_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override {
        super._revokeRole(role, account);
        _roleMembers[role].remove(account);
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 3 of 43 : AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        StringsUpgradeable.toHexString(uint160(account), 20),
                        " is missing role ",
                        StringsUpgradeable.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 4 of 43 : IAccessControlEnumerableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
 */
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

File 5 of 43 : IAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControlUpgradeable {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

File 6 of 43 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

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

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
     */
    modifier initializer() {
        bool isTopLevelCall = _setInitializedVersion(1);
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
     * initialization step. This is essential to configure modules that are added through upgrades and that require
     * initialization.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     */
    modifier reinitializer(uint8 version) {
        bool isTopLevelCall = _setInitializedVersion(version);
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(version);
        }
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     */
    function _disableInitializers() internal virtual {
        _setInitializedVersion(type(uint8).max);
    }

    function _setInitializedVersion(uint8 version) private returns (bool) {
        // If the contract is initializing we ignore whether _initialized is set in order to support multiple
        // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level
        // of initializers, because in other contexts the contract may have been reentered.
        if (_initializing) {
            require(
                version == 1 && !AddressUpgradeable.isContract(address(this)),
                "Initializable: contract is already initialized"
            );
            return false;
        } else {
            require(_initialized < version, "Initializable: contract is already initialized");
            _initialized = version;
            return true;
        }
    }
}

File 7 of 43 : PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        require(!paused(), "Pausable: paused");
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        require(paused(), "Pausable: not paused");
        _;
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 8 of 43 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 9 of 43 : ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

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

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 10 of 43 : ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 11 of 43 : IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

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

File 12 of 43 : SafeCastUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCastUpgradeable {
    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

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

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

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

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

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

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

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128) {
        require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
        return int128(value);
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64) {
        require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
        return int64(value);
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32) {
        require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
        return int32(value);
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16) {
        require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
        return int16(value);
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8) {
        require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
        return int8(value);
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

File 13 of 43 : StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

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

File 14 of 43 : EnumerableSetUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (utils/structs/EnumerableSet.sol)

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 */
library EnumerableSetUpgradeable {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        return _values(set._inner);
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly {
            result := store
        }

        return result;
    }
}

File 15 of 43 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 16 of 43 : draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.0;

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

File 17 of 43 : BeaconProxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol)

pragma solidity ^0.8.0;

import "./IBeacon.sol";
import "../Proxy.sol";
import "../ERC1967/ERC1967Upgrade.sol";

/**
 * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
 *
 * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
 * conflict with the storage layout of the implementation behind the proxy.
 *
 * _Available since v3.4._
 */
contract BeaconProxy is Proxy, ERC1967Upgrade {
    /**
     * @dev Initializes the proxy with `beacon`.
     *
     * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
     * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
     * constructor.
     *
     * Requirements:
     *
     * - `beacon` must be a contract with the interface {IBeacon}.
     */
    constructor(address beacon, bytes memory data) payable {
        assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1));
        _upgradeBeaconToAndCall(beacon, data, false);
    }

    /**
     * @dev Returns the current beacon address.
     */
    function _beacon() internal view virtual returns (address) {
        return _getBeacon();
    }

    /**
     * @dev Returns the current implementation address of the associated beacon.
     */
    function _implementation() internal view virtual override returns (address) {
        return IBeacon(_getBeacon()).implementation();
    }

    /**
     * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
     *
     * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
     *
     * Requirements:
     *
     * - `beacon` must be a contract.
     * - The implementation returned by `beacon` must be a contract.
     */
    function _setBeacon(address beacon, bytes memory data) internal virtual {
        _upgradeBeaconToAndCall(beacon, data, false);
    }
}

File 18 of 43 : IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

File 19 of 43 : UpgradeableBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)

pragma solidity ^0.8.0;

import "./IBeacon.sol";
import "../../access/Ownable.sol";
import "../../utils/Address.sol";

/**
 * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
 * implementation contract, which is where they will delegate all function calls.
 *
 * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
 */
contract UpgradeableBeacon is IBeacon, Ownable {
    address private _implementation;

    /**
     * @dev Emitted when the implementation returned by the beacon is changed.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
     * beacon.
     */
    constructor(address implementation_) {
        _setImplementation(implementation_);
    }

    /**
     * @dev Returns the current implementation address.
     */
    function implementation() public view virtual override returns (address) {
        return _implementation;
    }

    /**
     * @dev Upgrades the beacon to a new implementation.
     *
     * Emits an {Upgraded} event.
     *
     * Requirements:
     *
     * - msg.sender must be the owner of the contract.
     * - `newImplementation` must be a contract.
     */
    function upgradeTo(address newImplementation) public virtual onlyOwner {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }

    /**
     * @dev Sets the implementation contract address for this beacon
     *
     * Requirements:
     *
     * - `newImplementation` must be a contract.
     */
    function _setImplementation(address newImplementation) private {
        require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract");
        _implementation = newImplementation;
    }
}

File 20 of 43 : ERC1967Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)

pragma solidity ^0.8.0;

import "../Proxy.sol";
import "./ERC1967Upgrade.sol";

/**
 * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
 * implementation address that can be changed. This address is stored in storage in the location specified by
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
 * implementation behind the proxy.
 */
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
    /**
     * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
     *
     * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
     * function call, and allows initializating the storage of the proxy like a Solidity constructor.
     */
    constructor(address _logic, bytes memory _data) payable {
        assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
        _upgradeToAndCall(_logic, _data, false);
    }

    /**
     * @dev Returns the current implementation address.
     */
    function _implementation() internal view virtual override returns (address impl) {
        return ERC1967Upgrade._getImplementation();
    }
}

File 21 of 43 : ERC1967Upgrade.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)

pragma solidity ^0.8.2;

import "../beacon/IBeacon.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 *
 * @custom:oz-upgrades-unsafe-allow delegatecall
 */
abstract contract ERC1967Upgrade {
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Returns the current implementation address.
     */
    function _getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }

    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(
        address newImplementation,
        bytes memory data,
        bool forceCall
    ) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            Address.functionDelegateCall(newImplementation, data);
        }
    }

    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallUUPS(
        address newImplementation,
        bytes memory data,
        bool forceCall
    ) internal {
        // Upgrades from old implementations will perform a rollback test. This test requires the new
        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
        // this special case will break upgrade paths from old UUPS implementation to new ones.
        if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
            _setImplementation(newImplementation);
        } else {
            try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
            } catch {
                revert("ERC1967Upgrade: new implementation is not UUPS");
            }
            _upgradeToAndCall(newImplementation, data, forceCall);
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

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

    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }

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

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

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

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

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            Address.isContract(IBeacon(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }

    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(
        address newBeacon,
        bytes memory data,
        bool forceCall
    ) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        }
    }
}

File 22 of 43 : Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)

pragma solidity ^0.8.0;

/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {
    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(address implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }

    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
     * and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);

    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _beforeFallback();
        _delegate(_implementation());
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
     * is empty.
     */
    receive() external payable virtual {
        _fallback();
    }

    /**
     * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
     * call, or as part of the Solidity `fallback` or `receive` functions.
     *
     * If overridden should call `super._beforeFallback()`.
     */
    function _beforeFallback() internal virtual {}
}

File 23 of 43 : TransparentUpgradeableProxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol)

pragma solidity ^0.8.0;

import "../ERC1967/ERC1967Proxy.sol";

/**
 * @dev This contract implements a proxy that is upgradeable by an admin.
 *
 * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
 * clashing], which can potentially be used in an attack, this contract uses the
 * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
 * things that go hand in hand:
 *
 * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
 * that call matches one of the admin functions exposed by the proxy itself.
 * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
 * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
 * "admin cannot fallback to proxy target".
 *
 * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
 * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
 * to sudden errors when trying to call a function from the proxy implementation.
 *
 * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
 * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
 */
contract TransparentUpgradeableProxy is ERC1967Proxy {
    /**
     * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
     * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
     */
    constructor(
        address _logic,
        address admin_,
        bytes memory _data
    ) payable ERC1967Proxy(_logic, _data) {
        assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
        _changeAdmin(admin_);
    }

    /**
     * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
     */
    modifier ifAdmin() {
        if (msg.sender == _getAdmin()) {
            _;
        } else {
            _fallback();
        }
    }

    /**
     * @dev Returns the current admin.
     *
     * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
     * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function admin() external ifAdmin returns (address admin_) {
        admin_ = _getAdmin();
    }

    /**
     * @dev Returns the current implementation.
     *
     * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
     * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
     */
    function implementation() external ifAdmin returns (address implementation_) {
        implementation_ = _implementation();
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {AdminChanged} event.
     *
     * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
     */
    function changeAdmin(address newAdmin) external virtual ifAdmin {
        _changeAdmin(newAdmin);
    }

    /**
     * @dev Upgrade the implementation of the proxy.
     *
     * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
     */
    function upgradeTo(address newImplementation) external ifAdmin {
        _upgradeToAndCall(newImplementation, bytes(""), false);
    }

    /**
     * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
     * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
     * proxied contract.
     *
     * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
     */
    function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
        _upgradeToAndCall(newImplementation, data, true);
    }

    /**
     * @dev Returns the current admin.
     */
    function _admin() internal view virtual returns (address) {
        return _getAdmin();
    }

    /**
     * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
     */
    function _beforeFallback() internal virtual override {
        require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
        super._beforeFallback();
    }
}

File 24 of 43 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

File 25 of 43 : ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * 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 ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these 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 override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override 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 value {ERC20} uses, unless this function is
     * 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 override returns (uint8) {
        return 18;
    }

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

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override 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 `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

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

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` 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 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * 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 `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * 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.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` 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.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}

File 26 of 43 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

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

File 27 of 43 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

File 28 of 43 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 29 of 43 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 30 of 43 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

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

File 31 of 43 : StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

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

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

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

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

File 32 of 43 : Exchange.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import {IRouter} from "./interface/IRouter.sol";
import {IExchange} from "./interface/IExchange.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {IIsolatedWalletLogic} from "./interface/IIsolatedWalletLogic.sol";
import {IQueuedRequests as IQR} from "./interface/IQueuedRequests.sol";
import {IIsolatedWalletFactory} from "./interface/IIsolatedWalletFactory.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {EnumerableSetUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import {SafeCastUpgradeable as SafeCast} from "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";

/**
 * @title Exchange
 * @dev This contract represents an implementation of an Exchange, adhering to the IExchange interface.
 * It inherits features from the Pausable and AccessControlEnumerable contracts.
 */
contract Exchange is IExchange, Initializable, PausableUpgradeable, AccessControlUpgradeable {
    using SafeERC20 for IERC20;
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set;

    bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
    bytes32 public constant ROUTER_ROLE = keccak256("ROUTER_ROLE");
    bytes32 public constant KEEPER_ROLE = keccak256("KEEPER_ROLE");
    bytes32 public constant AUTHORIZED_ROLE = keccak256("AUTHORIZED_ROLE");
    bytes32 public constant WHITELIST_ISSUER_ROLE = keccak256("WHITELIST_ISSUER_ROLE");

    uint8 public constant MIN_SIZE_PRECISION = 0;
    uint8 public constant MAX_SIZE_PRECISION = 18;
    uint24 public constant FEE_ONE_HUNDRED_WITH_ACCURACY = 100000; //100%
    string public constant VERSION = "0.0.2";

    address public collateralToken; // Only one collateral token for now, e.g. USDC
    address public router;
    address public isolatedWalletFactory;

    bool public isAuthorizationRequired;

    //total amount of collateral in lp pool
    //updated on deposit, withdraw
    uint256 public lpPoolBalance;
    uint256 public govWalletBalance;
    //total amount of shares minted
    //updated on deposit (kind of mint) or withdraw (kind of burn)
    uint256 public totalLpShares;
    int256 public totalExchangeRealizedPnl;
    uint256 public lpFee; //1050 = 1.05%
    FeeSplitSettings public feeSplitSettings;

    // Collateral token decimal precision
    mapping(address => uint8) public tokenDecimals;

    // Balances of user collateral deposits
    mapping(address => uint256) public accountBalances;

    // LP balance and shares for each user
    mapping(address => uint256) public lpBalances;
    mapping(address => uint256) public lpShares;

    // Cumulative balance of exchange reserve (only modified on deposit/withdraw)
    mapping(address => uint256) public poolBalances;

    // Exchange-owned liquidity (premiums and funding), used to calculate risk
    mapping(address => uint256) public exchangeBalances;

    // Insurance fund, used to make whole underwater positions or insolvency
    mapping(address => uint256) public insuranceBalances;

    // Markets
    mapping(bytes32 => Market) public marketParameters; //often update parameters
    mapping(bytes32 => MarketSettings) public marketSettings; //rarely updated settings
    mapping(bytes32 => bool) public tradeableMarkets;

    // Open positions
    mapping(bytes32 => Position) public positions;
    mapping(address => EnumerableSetUpgradeable.Bytes32Set) private accountPositionMarkets; // account to open position markets

    //key-value storage for backend.
    //string value is requirement
    mapping(string => string) public keyValStorage;

    function initialize() external initializer {
        __AccessControl_init();
        __Pausable_init();
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        feeSplitSettings.exchangeFee = 50000; //50%
        feeSplitSettings.lpFee = 50000; //50%
        lpFee = 0; //1050 = 1.05%
    }

    /**
     * @dev See {IExchange}.
     */
    function getAccountPositionMarketsLength(address _account) external view returns (uint256) {
        return accountPositionMarkets[_account].length();
    }

    /**
     * @dev See {IExchange}.
     */
    function getAccountPositionMarkets(address _account) external view returns (bytes32[] memory) {
        return accountPositionMarkets[_account].values();
    }

    /**
     * @dev See {IExchange}.
     */
    function getAllPositions(address _account) external view returns (PositionWithUnderlying[] memory) {
        bytes32[] memory markets = accountPositionMarkets[_account].values();
        PositionWithUnderlying[] memory positions_ = new PositionWithUnderlying[](markets.length);
        for (uint256 i = 0; i < markets.length; i++) {
            bytes32 key = getPositionKey(_account, markets[i]);
            positions_[i] = PositionWithUnderlying({
                underlying: markets[i],
                size: positions[key].size,
                cost: positions[key].cost
            });
        }
        return positions_;
    }

    /**
     * @dev See {IExchange}.
     */
    function getMarkets(bytes32[] calldata underlyings) external view returns (Market[] memory markets) {
        markets = new Market[](underlyings.length);
        for (uint256 i = 0; i < underlyings.length; i++) {
            markets[i] = marketParameters[underlyings[i]];
        }
    }

    /**
     * @dev See {IExchange}.
     */
    function getPosition(address _account, bytes32 _underlying) external view returns (int256, int256) {
        bytes32 key = getPositionKey(_account, _underlying);
        Position memory position = positions[key];

        return (position.size, position.cost);
    }

    /**
     * @dev See {IExchange}.
     */
    function isTradeable(bytes32 _underlying) external view returns (bool) {
        return tradeableMarkets[_underlying] && !marketSettings[_underlying].pauseStatus;
    }

    /**
     * @dev See {IExchange}.
     */
    function getStateVarsHash() public view returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(
                    exchangeBalances[collateralToken],
                    lpPoolBalance,
                    totalExchangeRealizedPnl,
                    totalLpShares
                )
            );
    }

    /**
     * @dev See {IExchange}.
     */
    function getMarketsHash(bytes32 stateHash, bytes32[] calldata underlyings) public view returns (bytes32) {
        for (uint256 i = 0; i < underlyings.length; i++) {
            Market memory market = marketParameters[underlyings[i]];
            stateHash = keccak256(abi.encodePacked(stateHash, market.longOi, market.shortOi, market.cumEntry));
        }
        return stateHash;
    }

    /**
     * @dev See {IExchange}.
     */
    function getAccountsHash(bytes32 stateHash, address[] calldata accounts) public view returns (bytes32) {
        for (uint256 i = 0; i < accounts.length; i++) {
            stateHash = keccak256(
                abi.encodePacked(
                    stateHash,
                    accountBalances[accounts[i]],
                    lpBalances[accounts[i]],
                    lpShares[accounts[i]]
                )
            );
        }
        return stateHash;
    }

    /**
     * @dev See {IExchange}.
     */
    function getPositionsHash(bytes32 stateHash, bytes32[] calldata _positions) public view returns (bytes32) {
        for (uint256 i = 0; i < _positions.length; i++) {
            Position memory position = positions[_positions[i]];
            stateHash = keccak256(abi.encodePacked(stateHash, position.size, position.cost));
        }
        return stateHash;
    }

    /**
     * @dev See {IExchange}.
     */
    function getStateHash(
        bytes32[] calldata underlyings,
        address[] calldata accounts,
        bytes32[] calldata _positions
    ) external view returns (bytes32) {
        bytes32 stateHash = getStateVarsHash();
        stateHash = getMarketsHash(stateHash, underlyings);
        stateHash = getAccountsHash(stateHash, accounts);
        stateHash = getPositionsHash(stateHash, _positions);
        return stateHash;
    }

    /**
     * @dev See {IExchange}.
     */
    function pause() external onlyRole(KEEPER_ROLE) whenNotPaused {
        _pause();
        IRouter r = IRouter(router);
        r.pauseRouter();
    }

    /**
     * @dev See {IExchange}.
     */
    function unpause() external onlyRole(KEEPER_ROLE) whenPaused {
        _unpause();
        IRouter r = IRouter(router);
        r.unpauseRouter();
    }

    /**
     * @dev See {IExchange}.
     */
    function accountDepositFromRouter(address account, uint256 tokenAmount) external onlyRole(ROUTER_ROLE) {
        _accountDeposit(account, tokenAmount);
    }

    /**
     * @dev See {IExchange}.
     */
    function accountDepositWithTransfer(uint256 tokenAmount) external {
        _accountDeposit(msg.sender, tokenAmount);
    }

    /**
     * @dev See {IExchange}.
     */
    function executeOrder(
        Order calldata _order,
        OrderData calldata _orderData,
        bool _isLiq
    ) external onlyRole(ROUTER_ROLE) returns (bytes32, int256, int256, uint256 execPrice) {
        if (_order.account == address(0)) {
            revert OrderDoesNotExist();
        }
        if (_isLiq && _orderData.sizeDelta == 0) {
            revert OrderSizeDeltaCannotBeEmpty();
        }

        //settle variable is so we don't ask unnecessary data on executeOrder function call
        //plus we are sure we pass to _settle function verified data only
        SettleOrder memory settleOrder = SettleOrder({
            account: _order.account,
            sizeDelta: _order.sizeDelta,
            underlying: _order.underlying,
            ammPremium: _orderData.ammPremium,
            lpPremium: _orderData.lpPremium,
            ammFunding: _orderData.ammFunding,
            lpFunding: _orderData.lpFunding,
            spotPrice: SafeCast.toInt256(_orderData.spotPrice), //will be overwritten
            notionalSize: 0 // In collateral token decimals
        });

        if (_order.limitOrder && !_isLiq) {
            uint256 _premiumPrice = (((settleOrder.ammPremium + settleOrder.lpPremium) *
                (10 ** marketSettings[_order.underlying].sizeDecimals)) / abs(settleOrder.sizeDelta)) /
                10 ** (tokenDecimals[collateralToken] - marketSettings[_order.underlying].priceDecimals);
            execPrice = settleOrder.sizeDelta > 0
                ? _orderData.spotPrice + _premiumPrice
                : _orderData.spotPrice - _premiumPrice;
            bool isLimitPriceValid = ((settleOrder.sizeDelta > 0) != (_order.slTpType == 1))
                ? _order.limitPrice >= SafeCast.toInt256(execPrice)
                : _order.limitPrice <= SafeCast.toInt256(execPrice);
            if (!isLimitPriceValid) {
                revert LimitPrice(settleOrder.sizeDelta, _order.limitPrice, execPrice);
            }
        } else {
            execPrice = _orderData.spotPrice;
        }

        settleOrder.notionalSize =
            abs(settleOrder.sizeDelta) *
            _orderData.spotPrice *
            uint256(
                10 **
                    (tokenDecimals[collateralToken] -
                        marketSettings[_order.underlying].sizeDecimals -
                        marketSettings[_order.underlying].priceDecimals)
            );

        bytes32 _key = getPositionKey(_order.account, _order.underlying);
        Position storage pos = positions[_key];

        // Create a new position
        if (pos.size == 0) {
            pos.cost = settleOrder.spotPrice * settleOrder.sizeDelta;
            _settle(settleOrder, pos.size, pos.cost, false, false);
            positions[_key] = Position(settleOrder.sizeDelta, pos.cost);
            _updateMarketParams(_order.underlying, pos, settleOrder.sizeDelta, settleOrder.spotPrice, false);
            accountPositionMarkets[_order.account].add(_order.underlying);
            return (_key, settleOrder.sizeDelta, settleOrder.spotPrice, execPrice);
        }

        // If position size has changed sign, _order is too large
        int256 newSize = pos.size + settleOrder.sizeDelta;
        if (newSize != 0 && newSize ^ pos.size < 0) {
            revert OrderTooLarge(settleOrder.sizeDelta);
        }

        bool isDecrease = pos.size ^ settleOrder.sizeDelta < 0;
        _settle(settleOrder, pos.size, pos.cost, isDecrease, _isLiq);

        // Update account position markets
        if (isDecrease && newSize == 0) {
            // Remove market from accountPositionMarkets
            EnumerableSetUpgradeable.Bytes32Set storage markets = accountPositionMarkets[_order.account];
            markets.remove(_order.underlying);
        }

        // Update position size and average size

        _updateMarketParams(_order.underlying, pos, settleOrder.sizeDelta, settleOrder.spotPrice, isDecrease);

        if (newSize == 0) {
            pos.cost = 0;
        } else if (!isDecrease) {
            pos.cost += settleOrder.spotPrice * settleOrder.sizeDelta;
        } else {
            pos.cost += (settleOrder.sizeDelta * pos.cost) / pos.size;
        }

        pos.size = newSize;
        return (_key, newSize, pos.cost, execPrice);
    }

    /**
     * @dev See {IExchange}.
     */
    function executeQueuedRequest(
        IQR.Type requestType,
        IQR.Data memory qrd,
        bytes memory _keeperArgs
    ) external onlyRole(ROUTER_ROLE) returns (bool) {
        if (requestType == IQR.Type.ACCOUNT_BALANCE_WITHDRAW) {
            IQR.AccountBalanceWithdrawArgs memory args1 = abi.decode(qrd.args, (IQR.AccountBalanceWithdrawArgs));
            _withdraw(qrd.account, args1.token, args1.amount, args1.recipient);
            return true;
        }

        uint256 _accountBalance = accountBalances[qrd.account];

        if (requestType == IQR.Type.LP_ADD) {
            uint256 requestedValue = abi.decode(qrd.args, (uint256));
            IQR.KeeperLiquidityAddArgs memory keeperArgs = abi.decode(_keeperArgs, (IQR.KeeperLiquidityAddArgs));
            if (_accountBalance < requestedValue) {
                revert InsufficientBalance(qrd.account);
            }
            accountBalances[qrd.account] -= requestedValue;
            lpBalances[qrd.account] += requestedValue;
            lpShares[qrd.account] += keeperArgs.sharesToMint;
            lpPoolBalance += requestedValue;
            totalLpShares += keeperArgs.sharesToMint;
            return true;
        }

        if (requestType == IQR.Type.LP_SCHEDULE_WITHDRAW || requestType == IQR.Type.LP_IMMEDIATE_WITHDRAW) {
            IQR.KeeperWithdrawArgs memory keeperArgs = abi.decode(_keeperArgs, (IQR.KeeperWithdrawArgs));
            address _collateralToken = collateralToken;

            uint256 _value = keeperArgs.value;

            if (lpPoolBalance < keeperArgs.value) {
                _value = lpPoolBalance;
            }
            lpPoolBalance -= _value;
            totalLpShares -= keeperArgs.sharesToBurn;

            _accountBalance += _value;

            uint256 fee;
            if (keeperArgs.yield > 0) {
                // we take fee from profit only
                fee = (SafeCast.toUint256(keeperArgs.yield) * uint256(lpFee)) / uint256(FEE_ONE_HUNDRED_WITH_ACCURACY);
            }

            // transfer penalty from lp to exchange
            if (_accountBalance > keeperArgs.penalty + fee) {
                exchangeBalances[_collateralToken] += keeperArgs.penalty;
                _accountBalance -= (keeperArgs.penalty + fee);
                govWalletBalance += fee;
            } else if (_accountBalance > keeperArgs.penalty) {
                exchangeBalances[_collateralToken] += keeperArgs.penalty;
                govWalletBalance += (_accountBalance - keeperArgs.penalty);
                _accountBalance = 0;
            } else {
                revert InsufficientBalanceForSettlement();
            }
            accountBalances[qrd.account] = _accountBalance;
            uint256 initialDeposit = SafeCast.toUint256(SafeCast.toInt256(keeperArgs.value) - keeperArgs.yield);
            lpBalances[qrd.account] -= initialDeposit;
            lpShares[qrd.account] -= keeperArgs.sharesToBurn;

            return true;
        }

        //just in case, inaccessible for now
        revert RequestTypeNotYetImplemented(requestType);
    }

    function setAuthorizationRequirements(bool flag) external onlyRole(MANAGER_ROLE) {
        isAuthorizationRequired = flag;
    }

    function grantBatchRoles(address[] calldata accounts) external onlyRole(WHITELIST_ISSUER_ROLE) {
        for (uint256 i = 0; i < accounts.length; i++) {
            _grantRole(AUTHORIZED_ROLE, accounts[i]);
        }
    }

    /**
     * @dev See {IExchange}.
     */
    function setup(
        address _collateralToken,
        address _router,
        address _isolatedWalletFactory,
        address _keeper,
        uint8 _collateralTokenDecimals,
        address _admin,
        address _manager
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (
            _collateralToken == address(0) ||
            _router == address(0) ||
            _isolatedWalletFactory == address(0) ||
            _keeper == address(0)
        ) revert ZeroAddressSet();

        if (_admin != msg.sender && _admin != address(0)) {
            _grantRole(DEFAULT_ADMIN_ROLE, _admin);
            _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
        }
        _grantRole(MANAGER_ROLE, _manager);
        _grantRole(KEEPER_ROLE, _keeper);
        _grantRole(ROUTER_ROLE, _router);

        collateralToken = _collateralToken;
        router = _router;
        isolatedWalletFactory = _isolatedWalletFactory;
        tokenDecimals[_collateralToken] = _collateralTokenDecimals;
    }

    /**
     * @dev See {IExchange}.
     */
    function insuranceDepositWithTransfer(uint256 tokenAmount) external {
        address _collateralToken = collateralToken;
        IERC20(_collateralToken).safeTransferFrom(msg.sender, address(this), tokenAmount);
        poolBalances[_collateralToken] = IERC20(_collateralToken).balanceOf(address(this));
        insuranceBalances[_collateralToken] += tokenAmount;
        IRouter(router).generateRouterEvent(
            IRouter.EventType.InsuranceDeposited,
            abi.encode(msg.sender, _collateralToken, tokenAmount)
        );
    }

    /**
     * @dev See {IExchange}.
     */
    function lpBalanceUpdate(int256 valueToAdd, int256 sharesToAdd) external onlyRole(KEEPER_ROLE) {
        //Note: can't simply do lpPoolBalance += valueToAdd cause
        //Built-in binary operator + cannot be applied to types uint256 and int256;
        uint256 _lpPoolBalance = lpPoolBalance;
        uint256 _totalLpShares = totalLpShares;
        if (valueToAdd > 0) {
            lpPoolBalance = _lpPoolBalance + uint256(valueToAdd);
        } else {
            uint256 diff = uint256(-valueToAdd);
            lpPoolBalance = (diff <= _lpPoolBalance) ? _lpPoolBalance - diff : 0;
        }
        if (sharesToAdd > 0) {
            totalLpShares = _totalLpShares + uint256(sharesToAdd);
        } else {
            uint256 diff = uint256(-sharesToAdd);
            totalLpShares = (diff <= _totalLpShares) ? _totalLpShares - diff : 0;
        }
    }

    /**
     * @dev See {IExchange}.
     */
    function setupMarkets(MarketSettings[] memory markets) external onlyRole(MANAGER_ROLE) {
        for (uint256 i = 0; i < markets.length; i++) {
            setupMarket(markets[i]);
        }
    }

    /**
     * @dev See {IExchange}.
     */
    function setValue(string calldata _key, string calldata _val) external onlyRole(KEEPER_ROLE) {
        keyValStorage[_key] = _val;
    }

    /**
     * @dev See {IExchange}.
     */
    function settleFunding(uint256 _ammFunding, uint256 _lpFunding) external onlyRole(ROUTER_ROLE) {
        exchangeBalances[collateralToken] += _ammFunding;
        lpPoolBalance += _lpFunding;
    }

    /**
     * @dev See {IExchange}.
     */
    function updateFeeSettings(
        uint256 _lpFee,
        FeeSplitSettings calldata _feeSplitSettings
    ) external onlyRole(MANAGER_ROLE) {
        if (_feeSplitSettings.exchangeFee + _feeSplitSettings.lpFee != FEE_ONE_HUNDRED_WITH_ACCURACY) {
            revert WrongFeeSplitCombination();
        }

        if (_lpFee > FEE_ONE_HUNDRED_WITH_ACCURACY) {
            revert feeOverflow();
        }
        feeSplitSettings = _feeSplitSettings;
        lpFee = _lpFee;
    }

    /**
     * @dev See {IExchange}.
     */
    function updateMarketFeeSettings(
        bytes32 _underlying,
        uint256 _fee,
        uint16 _liqPenalty
    ) external onlyRole(MANAGER_ROLE) {
        if (_fee > FEE_ONE_HUNDRED_WITH_ACCURACY) {
            revert feeOverflow();
        }
        marketSettings[_underlying].fee = _fee;
        marketSettings[_underlying].liqPenalty = _liqPenalty;
    }

    /**
     * @dev See {IExchange}.
     */
    function updateMarketPauseStatus(bytes32 _underlying, bool pauseStatus) external onlyRole(MANAGER_ROLE) {
        marketSettings[_underlying].pauseStatus = pauseStatus;
    }

    /**
     * @dev See {IExchange}.
     */
    function withdrawAccountBalanceByKeeper(
        address _account,
        uint256 _amount,
        address _recipient
    ) external onlyRole(KEEPER_ROLE) {
        if (_recipient != _account) {
            if (!IIsolatedWalletFactory(isolatedWalletFactory).wallets(_account)) {
                revert UnknownIsolatedWallet();
            }
            if (IIsolatedWalletLogic(_account).owner() != _recipient) {
                revert UnexpectedRecipient();
            }
        }
        _withdraw(_account, collateralToken, _amount, _recipient);
    }

    /**
     * @dev See {IExchange}.
     */
    function withdrawGovWalletBalance(address _recipient, uint256 _amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
        govWalletBalance -= _amount;
        IERC20(collateralToken).safeTransfer(_recipient, _amount);
    }

    /**
     * @dev See {IExchange}.
     */
    function getPositionKey(address _account, bytes32 _underlying) public pure returns (bytes32) {
        return keccak256(abi.encode(_account, _underlying));
    }

    /**
     * @dev See {IExchange}.
     */
    function setupMarket(MarketSettings memory market) public onlyRole(MANAGER_ROLE) whenNotPaused {
        if (!(market.sizeDecimals >= MIN_SIZE_PRECISION && market.sizeDecimals <= MAX_SIZE_PRECISION))
            revert InvalidSizePrecision(market.sizeDecimals, MIN_SIZE_PRECISION, MAX_SIZE_PRECISION);

        if (market.initialMarginRatioPercent <= market.maintenanceMarginRatioPercent)
            revert InitialMarginRatioIsLow(market.initialMarginRatioPercent, market.maintenanceMarginRatioPercent);

        if (tradeableMarkets[market.symbol]) revert MarketAlreadyExists(market.symbol);

        if (tokenDecimals[collateralToken] < market.sizeDecimals + market.priceDecimals) revert WrongMarketDecimals();

        tradeableMarkets[market.symbol] = true;

        marketSettings[market.symbol] = market;
    }

    /* INTERNAL */

    /**
     * @notice Calculate the liquidation penalty for a given liquidation order.
     * @dev This function computes the liquidation penalty based on the absolute size notional and market-specific parameters.
     * @param _order The liquidation order information.
     * @return The calculated liquidation penalty.
     */
    function _getLiquidationPenalty(SettleOrder memory _order) internal view returns (uint256) {
        uint256 absSizeNotional = abs(_order.sizeDelta * _order.spotPrice);
        return
            (absSizeNotional * marketSettings[_order.underlying].liqPenalty * 10 ** tokenDecimals[collateralToken]) /
            (10 ** (marketSettings[_order.underlying].sizeDecimals + marketSettings[_order.underlying].priceDecimals) *
                FEE_ONE_HUNDRED_WITH_ACCURACY);
    }

    /**
     * @notice Internal function to handle the deposit of collateral tokens into the Exchange.
     * @dev This function transfers a specified amount of collateral tokens from the account to the Exchange,
     * updates the pool and account balances accordingly, and emits a Deposited event.
     * @param account The address of the account making the deposit.
     * @param tokenAmount The amount of collateral tokens to be deposited.
     */
    function _accountDeposit(address account, uint256 tokenAmount) internal {
        if (isAuthorizationRequired && !hasRole(AUTHORIZED_ROLE, account)) revert NotAuthorized(account);
        address _collateralToken = collateralToken; //local copy to save gas
        IERC20(_collateralToken).safeTransferFrom(account, address(this), tokenAmount);
        poolBalances[_collateralToken] = IERC20(_collateralToken).balanceOf(address(this));
        accountBalances[account] += tokenAmount;
        IRouter(router).generateRouterEvent(IRouter.EventType.Deposited, abi.encode(account, tokenAmount));
    }

    /**
     * @dev Internal function to settle a trading order.
     * @param _order The details of the settlement order.
     * @param _size The size of the order.
     * @param _cost The cost of the order.
     * @param _isDecrease A boolean indicating whether the settlement results in a decrease in position size.
     * @param _isLiq A boolean indicating whether the settlement is due to liquidation.
     */
    function _settle(SettleOrder memory _order, int256 _size, int256 _cost, bool _isDecrease, bool _isLiq) internal {
        int256 pnl;
        address _collateralToken = collateralToken;
        if (_isDecrease) {
            pnl = (_cost * _order.sizeDelta) / _size - _order.sizeDelta * _order.spotPrice;

            pnl *= int256(
                10 **
                    (tokenDecimals[_collateralToken] -
                        marketSettings[_order.underlying].sizeDecimals -
                        marketSettings[_order.underlying].priceDecimals)
            );

            totalExchangeRealizedPnl -= pnl;
        }

        // Settle net payout for account
        uint256 fee = (_order.notionalSize * marketSettings[_order.underlying].fee) /
            uint256(FEE_ONE_HUNDRED_WITH_ACCURACY);
        // Settle net payout for account: positive means trader pays, negative means trader receives
        int256 netPayout = SafeCast.toInt256(fee) +
            SafeCast.toInt256(_order.ammPremium) +
            SafeCast.toInt256(_order.lpPremium) +
            _order.ammFunding +
            _order.lpFunding -
            pnl;

        if (netPayout > 0) {
            uint256 netPayoutAmount = uint256(netPayout);
            if (accountBalances[_order.account] >= netPayoutAmount) {
                accountBalances[_order.account] -= netPayoutAmount;
            } else {
                // Cover by insurance fund
                if (insuranceBalances[_collateralToken] < netPayoutAmount - accountBalances[_order.account]) {
                    revert InsufficientInsuranceFundForSettlement();
                }

                if (!_isLiq) {
                    revert InsufficientBalanceForSettlement();
                }

                insuranceBalances[_collateralToken] -= netPayoutAmount - accountBalances[_order.account];
                accountBalances[_order.account] = 0;
            }
        } else {
            uint256 netPayoutAmount = uint256(-netPayout);
            accountBalances[_order.account] += netPayoutAmount;
        }

        // Settle liquidation penalty
        if (_isLiq) {
            uint256 penalty = _getLiquidationPenalty(_order);
            if (accountBalances[_order.account] >= penalty) {
                insuranceBalances[_collateralToken] += penalty;
                accountBalances[_order.account] -= penalty;
            } else {
                insuranceBalances[_collateralToken] += accountBalances[_order.account];
                accountBalances[_order.account] = 0;
            }
        }

        uint256 feeToLp = (fee * feeSplitSettings.lpFee) / uint256(FEE_ONE_HUNDRED_WITH_ACCURACY);

        // Settle premium and funding for exchange and lp
        exchangeBalances[collateralToken] = exchangeBalances[collateralToken] + _order.ammPremium;
        lpPoolBalance = lpPoolBalance + _order.lpPremium + feeToLp;
        govWalletBalance += (fee - feeToLp);
    }

    /**
     * @notice Update cumulative market values based on a position change.
     * @dev This function adjusts the market parameters, including open interest and cumulative entry cost, based on the change in position.
     * @param _underlying The market identifier.
     * @param _pos The existing position information.
     * @param _sizeDelta The change in position size.
     * @param _price The current spot price.
     * @param _isDecrease A boolean indicating whether the position size is decreasing.
     */
    function _updateMarketParams(
        bytes32 _underlying,
        Position memory _pos,
        int256 _sizeDelta,
        int256 _price,
        bool _isDecrease
    ) internal {
        Market storage mkt = marketParameters[_underlying];

        if (_isDecrease) {
            _sizeDelta > 0 ? mkt.shortOi -= uint256(_sizeDelta) : mkt.longOi -= uint256(-_sizeDelta); // Note: _sizeDelta is negative
            mkt.cumEntry += (_sizeDelta * _pos.cost) / _pos.size;
        } else {
            _sizeDelta < 0
                ? mkt.shortOi += uint256(-_sizeDelta) // Note: _sizeDelta is negative
                : mkt.longOi += uint256(_sizeDelta);
            mkt.cumEntry += _price * _sizeDelta;
        }
    }

    /**
     * @notice Withdraw a specified amount of tokens from the Exchange.
     * @dev This function allows the withdrawal of a specific amount of tokens from the Exchange to the specified recipient.
     * @param _account The trader's account address.
     * @param _token The address of the collateral token to be withdrawn.
     * @param _amount The amount of tokens to be withdrawn in integer format.
     * @param _recipient The address where the withdrawn tokens will be sent.
     */
    function _withdraw(address _account, address _token, uint256 _amount, address _recipient) internal {
        if (_token != collateralToken) {
            revert NotTradeableMarketAddress(_token);
        }

        if (accountBalances[_account] < _amount) {
            revert InsufficientBalance(_account);
        }

        // check balance of exchange
        if (IERC20(_token).balanceOf(address(this)) < _amount) {
            revert PoolEmpty();
        }
        accountBalances[_account] -= _amount;
        IERC20(_token).safeTransfer(_recipient, _amount);
        poolBalances[_token] = IERC20(_token).balanceOf(address(this));
    }

    function abs(int256 x) private pure returns (uint256) {
        return x >= 0 ? uint256(x) : uint256(-x);
    }
}

File 33 of 43 : IExchange.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import {IQueuedRequests as IQR} from "./IQueuedRequests.sol";

interface IExchange {
    /**
     * STRUCTS *
     */

    struct Order {
        bool limitOrder;
        address account;
        bytes32 underlying;
        int256 sizeDelta;
        int256 limitPrice;
        uint8 slTpType; // 0: None, 1: Stop loss, 2: Take profit
    }

    //input variable during order processing
    struct OrderData {
        bytes32 orderId;
        address account; // liq only
        bytes32 underlying; // for liq only
        int256 sizeDelta; // for liq only
        uint256 spotPrice;
        uint256 ammPremium;
        uint256 lpPremium;
        int256 ammFunding;
        int256 lpFunding;
    }

    //processing of (Order + OrderData) give SettleOrder
    struct SettleOrder {
        address account;
        int256 sizeDelta;
        bytes32 underlying;
        uint256 ammPremium;
        uint256 lpPremium;
        int256 ammFunding;
        int256 lpFunding;
        int256 spotPrice;
        uint256 notionalSize;
    }

    struct MarketSettings {
        //note: we don't need `bytes32 symbol` here, cause we'll know it from mapping key..
        //but removing it will break back end logic, tests so I kept it for now;
        //plus in future we may store markets to array. In this case we'll need to keep the symbol here.
        bytes32 symbol;
        uint8 priceDecimals;
        uint256 fee; // fee percentage for feeCollector; 1.095% = 1095;
        uint16 liqPenalty; // percentage of notional size liquidated as penalty;
        uint8 sizeDecimals; // Order size precision
        uint8 initialMarginRatioPercent;
        uint8 maintenanceMarginRatioPercent; // Margin ratios (stored as a percent)
        bool pauseStatus;
    }

    struct Market {
        uint256 longOi;
        uint256 shortOi;
        int256 cumEntry; // exchange liability notional exposure due to imbalance
    }

    struct Position {
        int256 size;
        int256 cost;
    }

    struct PositionWithUnderlying {
        bytes32 underlying;
        int256 size;
        int256 cost;
    }

    struct FeeSplitSettings {
        uint256 exchangeFee; //3500 = 3.5%
        uint256 lpFee;
    }

    /**
     * ERRORS *
     */
    error NotAuthorized(address account);
    error WrongFeeSplitCombination();
    error feeOverflow();
    error ZeroAddressSet();
    error NotTradeableMarketAddress(address token);
    error OrderTooLarge(int256 sizeDelta);
    error PoolEmpty(); // Exchange has no funds to cover the order
    error InsufficientBalance(address account);
    error MarketAlreadyExists(bytes32 token);
    error InvalidSizePrecision(uint256 sizeDecimals, uint256 MIN_SIZE_PRECISION, uint256 MAX_SIZE_PRECISION);
    error InitialMarginRatioIsLow(uint256 initialMarginRatioPercent, uint256 maintenanceMarginRatioPercent);
    error OrderSizeDeltaIs0();
    error OrderDoesNotExist();
    error InsufficientBalanceForSettlement();
    error InsufficientInsuranceFundForSettlement();
    error LimitPrice(int256 sizeDelta, int256 limitPrice, uint256 price);
    error RequestTypeNotYetImplemented(IQR.Type requestType);
    error UnexpectedRecipient();
    error UnknownIsolatedWallet();
    error SizeDeltaOverflow(int256 sizeDelta, int256 size);
    error OrderSizeDeltaCannotBeEmpty();
    error WrongMarketDecimals();

    /**
     * @notice Get the balance of collateral for a specific account.
     * @dev This external view function takes the address of an account as a parameter
     *      and returns the balance of collateral associated with that account.
     * @param account The address of the account to query.
     * @return balance The balance of collateral for the specified account.
     */
    function accountBalances(address account) external view returns (uint256);

    /**
     * @notice Get the address of the collateral token.
     * @dev This external view function returns the address of the collateral token.
     * @return collateralToken The address of the collateral token.
     */
    function collateralToken() external view returns (address);

    /**
     * @notice Get the decimal precision of a specific token.
     * @dev This external view function takes the address of a token as a parameter
     *      and returns the decimal precision of that token.
     * @param token The address of the token to query.
     * @return decimals The decimal precision of the specified token.
     */
    function tokenDecimals(address token) external view returns (uint8);

    /**
     * @notice Check if a market (identified by underlying) is tradeable.
     * @dev This external view function takes the bytes32 representation of the underlying market
     *      and returns a boolean indicating whether that market is tradeable.
     * @param underlying The bytes32 identifier of the underlying market.
     * @return isTradeable Boolean indicating whether the market is tradeable or not.
     */
    function tradeableMarkets(bytes32 underlying) external view returns (bool);

    /**
     * @notice Returns the liquidity pool balances of the specified account.
     * @param _account The address of the account for which liquidity pool balances are queried.
     * @return The liquidity pool balances of the specified account.
     */
    function lpBalances(address _account) external view returns (uint256);

    /**
     * @notice Get the number of markets in which the account has open positions.
     * @param _account The trader's account address.
     * @return The length of the array representing the markets with open positions for the given account.
     */
    function getAccountPositionMarketsLength(address _account) external view returns (uint256);

    /**
     * @notice Retrieves the markets in which the specified trader's account has open positions.
     * @dev This function is a view function and does not modify the contract state. It returns an array
     * of markets where the trader's account has open positions.
     * @param _account The trader's account address.
     * @return An array of markets with open positions for the specified trader's account.
     */
    function getAccountPositionMarkets(address _account) external view returns (bytes32[] memory);

    /**
     * @notice Get all positions for a specific trader account.
     * @param _account The trader's account address.
     * @return An array of PositionWithUnderlying structs, each representing a market position with its underlying market, size, and cost.
     */
    function getAllPositions(address _account) external view returns (PositionWithUnderlying[] memory);

    /**
     * @notice Retrieves market parameters and data for multiple markets.
     * @dev This function is a view function and does not modify the contract state. It takes an array of
     * market identifiers (underlyings) and returns an array of Market structs containing the parameters
     * and data for each specified market.
     * @param underlyings An array of market identifiers for which market data is requested.
     * @return markets An array of Market structs containing parameters and data for the specified markets.
     */
    function getMarkets(bytes32[] calldata underlyings) external view returns (Market[] memory markets);

    /**
     * @notice Get position information for a specific account and market.
     * @param _account The trader's account address.
     * @param _underlying The market identifier.
     * @return A tuple containing the size and cost of the position.
     */
    function getPosition(address _account, bytes32 _underlying) external view returns (int256, int256);

    /**
     * @notice Check if a given market is tradeable.
     * @dev This function returns whether a given market is marked as tradeable.
     * @param _underlying The market selector.
     * @return A boolean indicating whether the market is tradeable.
     */
    function isTradeable(bytes32 _underlying) external view returns (bool);

    /**
     * @notice Computes hash of state variables.
     * @return A bytes32 hash of the state variables.
     */
    function getStateVarsHash() external view returns (bytes32);

    /**
     * @notice Computes hash of the markets state.
     * @param stateHash Current state hash.
     * @param underlyings An array of all market identifiers for which state is requested.
     * @return A bytes32 hash of the markets state.
     */
    function getMarketsHash(bytes32 stateHash, bytes32[] calldata underlyings) external view returns (bytes32);

    /**
     * @notice Computes hash of accounts state.
     * @param stateHash Current state hash.
     * @param accounts An array of all account addresses for which state is requested.
     * @return A bytes32 hash of the accounts state.
     */
    function getAccountsHash(bytes32 stateHash, address[] calldata accounts) external view returns (bytes32);

    /**
     * @notice Computes hash of positions state.
     * @param stateHash Current state hash.
     * @param _positions An array of all position keys for which state is requested.
     * @return A bytes32 hash of the positions state.
     */
    function getPositionsHash(bytes32 stateHash, bytes32[] calldata _positions) external view returns (bytes32);

    /**
     * @notice Computes hash of the state.
     * @dev This function returns the hash of the state for the backend to check if it is in sync.
     * @param underlyings An array of all market identifiers for which state is requested.
     * @param accounts An array of all account addresses for which state is requested.
     * @param _positions An array of all position keys for which state is requested.
     * @return A bytes32 hash of the state.
     */
    function getStateHash(
        bytes32[] calldata underlyings,
        address[] calldata accounts,
        bytes32[] calldata _positions
    ) external view returns (bytes32);

    /**
     * @notice Deposit collateral tokens in the Exchange on behalf of an account.
     * @dev This function is restricted to the ROUTER_ROLE and allows the router to deposit tokens into an account.
     * Used for deposit via Router contract with simultaneous addition to the pool.
     * @param account The target account address to deposit tokens into.
     * @param tokenAmount The amount of tokens to transfer.
     */
    function accountDepositFromRouter(address account, uint256 tokenAmount) external;

    /**
     * @notice Deposit a collateral token in the Exchange.
     * @dev This function allows the user to deposit a specified amount of tokens.
     * @param tokenAmount The amount of tokens to transfer.
     */
    function accountDepositWithTransfer(uint256 tokenAmount) external;

    /**
     * @notice Executes an order. This function can only be called by the Router.
     * @dev Executes an order based on the provided order details and order data. It returns the position key,
     * size, and average price after executing the order.
     * @param _order The order details, as per the IExchange.Order struct.
     * @param _orderData Additional order data needed for execution, as per the IExchange.OrderData struct.
     * @param _isLiq A boolean flag indicating whether the order is a liquidation.
     * @return A tuple containing the position key, updated size, updated average price and execution price after executing the order.
     */
    function executeOrder(
        Order calldata _order,
        OrderData calldata _orderData,
        bool _isLiq
    ) external returns (bytes32, int256, int256, uint256);

    /**
     * @notice Execute a queued request of various types.
     * @dev This function processes different types of queued requests, such as LP additions, LP withdrawals, and account balance withdrawals.
     * @param requestType The type of the queued request. See `IQueuedRequests` for details.
     * @param qrd The data structure containing details of the queued request. See `IQueuedRequests` for structure details.
     * @param _keeperArgs Array of encoded structures that should be passed to the `executeQueuedRequest` function. See `IQueuedRequests` for details.
     * @return A boolean indicating the success of the operation.
     */
    function executeQueuedRequest(
        IQR.Type requestType,
        IQR.Data memory qrd,
        bytes memory _keeperArgs
    ) external returns (bool);

    /**
     * @notice Setup contract parameters.
     * @dev This function is only callable by the DEFAULT_ADMIN_ROLE address and is used to set contract parameters.
     * It sets the addresses of the collateral token, router, isolated wallet factory, and keeper.
     * It also specifies the number of decimal places for the collateral token.
     * If an admin address is provided, it grants the DEFAULT_ADMIN_ROLE to the new admin and revokes it from the caller,
     * ensuring smooth ownership transfer. Additionally, it grants the KEEPER_ROLE to the keeper and ROUTER_ROLE to the router.
     * @param _collateralToken Address of the collateral token.
     * @param _router Address of the router.
     * @param _isolatedWalletFactory Address of the isolated wallet factory.
     * @param _keeper Address of the keeper.
     * @param _collateralTokenDecimals Number of decimal places for the collateral token.
     * @param _admin Main admin of this contract.
     * @param _manager Manager of this contract.
     */
    function setup(
        address _collateralToken,
        address _router,
        address _isolatedWalletFactory,
        address _keeper,
        uint8 _collateralTokenDecimals,
        address _admin,
        address _manager
    ) external;

    /**
     * @notice Deposit into the insurance fund.
     * @dev This function allows users to deposit tokens into the insurance fund.
     * @param tokenAmount The amount of tokens to deposit.
     */
    function insuranceDepositWithTransfer(uint256 tokenAmount) external;

    /**
     * @notice Update the LP pool balance and total LP shares.
     * @dev This function is called by the keeper after receiving an LP_SCHEDULE_WITHDRAW request.
     * @param valueToAdd The value to be added to the LP pool balance.
     * @param sharesToAdd The shares to be added to the total LP shares.
     */
    function lpBalanceUpdate(int256 valueToAdd, int256 sharesToAdd) external;

    /**
     * @notice Pauses the exchange when insolvent.
     * @dev This function is callable only by the Keeper role and can be used to pause the exchange
     * when it becomes insolvent. It internally pauses the contract, deletes all market orders, and
     * pauses the connected router.
     */
    function pause() external;

    /**
     * @notice Unpauses the exchange when solvent again.
     * @dev This function is callable only by the Keeper role and can be used to unpause the exchange
     * when it becomes solvent again. It internally unpauses the contract and unpauses the connected router.
     */
    function unpause() external;

    /**
     * @notice Set up multiple markets with specified parameters.
     * @dev This function is only callable by the governance address and is used to configure multiple markets at once.
     * @param markets An array of markets to set up. See MarketSettings for details.
     */
    function setupMarkets(MarketSettings[] memory markets) external;

    /**
     * @notice Store data in the contract.
     * @dev This function is intended for backend use to store any data.
     * @param _key The variable name.
     * @param _val The variable value.
     */
    function setValue(string calldata _key, string calldata _val) external;

    /**
     * @notice Settles funding across all positions for all markets.
     * @dev This function is callable only by the Router role and is used to settle funding across
     * all positions for all markets. It takes in the funding amounts for the AMM (Automated Market Maker)
     * and LP (Liquidity Provider) and adjusts the exchange balances accordingly. This is typically used
     * to update funding positions and maintain the financial state of the system.
     * @param _ammFunding The funding amount for the Automated Market Maker.
     * @param _lpFunding The funding amount for the Liquidity Provider.
     */
    function settleFunding(uint256 _ammFunding, uint256 _lpFunding) external;

    /**
     * @notice Update Fee Settings
     * @dev Allows the administrator to update the fee settings for the protocol. The LP (Liquidity Provider) fee is specified as a percentage,
     * where 100 corresponds to 1%. The fee split settings structure includes both the exchange fee and the LP fee, both in percentage terms.
     * @param _lpFee The new LP fee, expressed as a percentage.
     * @param _feeSplitSettings A structure containing the exchange fee and LP fee as percentages. The sum of these percentages should equal 100.
     * @dev Reverts if the sum of exchange and LP fees does not equal 100, or if the LP fee exceeds 100%.
     */
    function updateFeeSettings(uint256 _lpFee, FeeSplitSettings calldata _feeSplitSettings) external;

    /**
     * @notice Update fee/penalty settings for a specific market.
     * @dev Allows the protocol administrator to modify the fee and liquidation penalty settings for a designated market.
     * The fee is expressed as a percentage, where 100 corresponds to 1%. The liquidation penalty represents the percentage
     * of the notional size that is charged as a penalty during liquidation.
     * @param _underlying The market selector identifying the target market.
     * @param _fee The new fee for the market, expressed as a percentage.
     * @param _liqPenalty The updated liquidation penalty for the market, expressed as a percentage of the notional size.
     * @dev Reverts if the specified fee exceeds 100%. MarketFeeUpdated Event emitted upon successful update,
     * indicating the changes made to the market's fee and liquidation penalty.
     */
    function updateMarketFeeSettings(bytes32 _underlying, uint256 _fee, uint16 _liqPenalty) external;

    /**
     * @notice Allows a designated keeper to withdraw funds from a trader's account.
     * @dev This function is callable only by the KEEPER_ROLE and is used to withdraw funds
     * from a trader's account. The designated keeper can specify the trader's account, the
     * withdrawal amount, and the recipient address for the withdrawn funds. If the recipient
     * address is different from the trader's account, additional checks are performed to ensure
     * the withdrawal is legitimate, including validating that the trader's account is an isolated
     * wallet owned by the specified recipient.
     * @param _account The trader's account address.
     * @param _amount The amount to withdraw from the trader's account.
     * @param _recipient The recipient address for the withdrawn funds.
     */
    function withdrawAccountBalanceByKeeper(address _account, uint256 _amount, address _recipient) external;

    /**
     * @notice Withdraw a specified amount from the governance wallet.
     * @dev This function is used to withdraw funds from the governance wallet. It is restricted to users with the DEFAULT_ADMIN_ROLE.
     * @param _recipient The address to which the collateral will be sent.
     * @param _amount The amount to withdraw from the governance wallet.
     */
    function withdrawGovWalletBalance(address _recipient, uint256 _amount) external;

    /**
     * @notice Get the unique hash key for a position based on the trader account and underlying market.
     * @param _account The trader's account address.
     * @param _underlying The market identifier.
     * @return The keccak256 hash of the position.
     */
    function getPositionKey(address _account, bytes32 _underlying) external pure returns (bytes32);

    /**
     * @notice Create a new tradeable market.
     * @dev This function is used to set up a new market with the specified parameters.
     * It is only callable by the DEFAULT_ADMIN_ROLE and when the contract is not paused.
     * @param market The market settings. See MarketSettings for details.
     */
    function setupMarket(MarketSettings memory market) external;
}

File 34 of 43 : IIsolatedWalletFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {IIsolatedWalletLogic} from "./IIsolatedWalletLogic.sol";

interface IIsolatedWalletFactory {
    /**
     * @notice Check if a wallet address is registered.
     * @dev This external function takes a wallet address as a parameter
     *      and returns a boolean indicating whether the wallet is registered.
     * @param walletAddress The address of the wallet to check.
     * @return isRegistered A boolean indicating whether the wallet is registered.
     */
    function wallets(address walletAddress) external returns (bool);

    /**
     * @notice Creates a new isolated wallet and initializes it with specified parameters.
     * @dev Users can create isolated wallets with custom calls and an initial deposit.
     * @param calls An array of function calls to initialize the isolated wallet.
     * @param deposit Details of the initial deposit, including token address and value.
     * @return isolatedWallet The address of the newly created isolated wallet.
     */
    function createIsolatedWallet(
        IIsolatedWalletLogic.Call[] calldata calls,
        IIsolatedWalletLogic.Deposit calldata deposit
    ) external returns (address);
}

File 35 of 43 : IIsolatedWalletLogic.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface IIsolatedWalletLogic {
    struct Call {
        address target;
        uint256 value;
        bytes callData;
    }

    struct Deposit {
        address token;
        uint256 value;
    }

    /**
     * @notice Get the current owner of the contract.
     * @dev This function provides the address of the current owner of the contract.
     * @return The address of the contract owner.
     */
    function owner() external view returns (address);

    /**
     * @dev Initializes the isolated wallet with the provided owner and executes a series of calls.
     * This function is only callable once during contract initialization.
     * @param _owner The address to be set as the owner of the isolated wallet.
     * @param calls An array of Call structures representing the calls to be executed.
     */
    function initialize(address _owner, IIsolatedWalletLogic.Call[] calldata calls) external;

    /**
     * @dev Executes a series of calls in a single transaction.
     * Only the owner is allowed to invoke this function, and it is protected against reentrancy.
     * @param calls An array of Call structures representing the calls to be executed.
     */
    function multiCall(IIsolatedWalletLogic.Call[] calldata calls) external payable;
}

File 36 of 43 : IQueuedRequests.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface IQueuedRequests {
    enum Type {
        LP_ADD,
        LP_SCHEDULE_WITHDRAW,
        LP_IMMEDIATE_WITHDRAW,
        ACCOUNT_BALANCE_WITHDRAW,
        DELETE_ORDER,
        EXECUTE_ORDER,
        PROCESS_QUEUED_REQUESTS
    }

    struct Settings {
        uint256 removed; //total count of removed requests
        uint256 last; //last id
    }

    struct Data {
        address account;
        bytes args;
    }

    struct DataWithId {
        uint256 id;
        address account;
        bytes args;
    }

    struct InputArgsStruct {
        uint256 value;
    }

    struct AccountBalanceWithdrawArgs {
        address recipient;
        address token;
        uint256 amount;
    }

    struct KeeperWithdrawArgs {
        uint256 value;
        int256 yield;
        uint256 penalty;
        uint256 sharesToBurn;
    }

    struct KeeperLiquidityAddArgs {
        uint256 sharesToMint;
    }

    struct MultiTypeRequest {
        uint256 id;
        Type requestType;
        bool validRequest;
        bytes keeperArgs;
        bytes32[] searchKey;
        uint256 totalAmmFunding;
        uint256 totalLpFunding;
    }
}

File 37 of 43 : IRequestExecutor.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

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

interface IRequestExecutor {
    /**
     * @notice Execute a queued request based on the specified type.
     * @dev This function is responsible for processing queued requests based on the provided type.
     * @param requestType The type of the queued request. See {IQueuedRequests.Type} for details.
     * @param qrd The data associated with the queued request. See {IQueuedRequests.Data} for structure details.
     * @param _keeperArgs Array of encoded structures to be passed to the executeQueuedRequest function.
     * @return A boolean indicating the success of the queued request execution.
     */
    function executeQueuedRequest(
        IQueuedRequests.Type requestType,
        IQueuedRequests.Data memory qrd,
        bytes memory _keeperArgs
    ) external returns (bool);

    function processQueuedRequests(IQueuedRequests.MultiTypeRequest[] memory mtRequests) external returns (bool);
}

File 38 of 43 : IRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import {IExchange} from "./IExchange.sol";
import {IQueuedRequests as IQR} from "./IQueuedRequests.sol";

interface IRouter {
    enum EventType {
        NewQueuedRequest,
        Deposited,
        QueuedRequestAccepted,
        QueuedRequestDeclined,
        QueuedRequestFailed,
        OrderEnqueue,
        OrderDequeue,
        MarketOrderDeleted,
        AddLimitOrder,
        ExecuteLimitOrder,
        OrderExecutionFailed,
        ExecuteLiqBatchFailed,
        ExecuteLiqBatchSuccess,
        InsuranceDeposited
    }

    /**
     * EVENTS *
     */

    event ContractEvent(EventType indexed eventName, bytes args);

    event AccountLinked(address linkedAddress, address ownerAddress);
    //note: initially we added maximum info to every event.
    //after we finish to implement this on backend, we'll clear unused variables
    event Log(string message);
    event LogPanic(uint256 code, string message);
    event LowLevelLog(bytes lowLevelData);

    event DeleteLimitOrderPublic(bytes32 indexed orderId, address indexed account, bytes32 indexed underlying);

    /**
     * ERRORS *
     */
    error AlreadyLinked(address abstractAccountAddress, address ownerAddress);
    error ZeroAddressSet();
    error InsufficientBalance(address);
    error NotKeeperOrExchange(address);
    error NotKeeperOrSystem(address);
    error NotLimitOrder();
    error NotSystemCall();
    error OrderSizeDeltaCannotBeEmpty();
    error OrderDoesNotExist(bytes32 orderId);
    error NotOwnerOfOrder(address account, address sender);
    error RequestsNotFound(IQR.Type requestType, uint256 id);
    error CannotIncreasePositionWhileInsolvent();
    error NotTradeableOrPausedMarket(bytes32 underlying);
    error RequestTypeNotYetImplemented(IQR.Type requestType);
    error liquidationFailed(bytes32 failedOrderId);
    error DuplicateLimitOrder(bytes32 orderId);
    error DuplicateSlTpIds(bytes32 orderId);
    error WrongSizeDelta(int256 orderDataSizeDelta, int256 orderSizeDelta);
    error NotCollateral(address token);
    error ZeroWithdrawAmount();

    /**
     * @dev Get the index of the first order in the order queue.
     * @return uint256 The index of the first order.
     */
    function firstOrder() external returns (uint256);

    /**
     * @dev Get the index of the last order in the order queue.
     * @return uint256 The index of the last order.
     */
    function lastOrder() external returns (uint256);

    /**
     * @dev Get all market orders in the order queue.
     * @return The starting index of the orders and an array of Order structs.
     */
    function getMarketOrders() external view returns (uint256, IExchange.Order[] memory);

    /**
     * @dev Return limit orders based on the specified account.
     * @param account The address of the account to filter (zero address if all).
     * @return orderIds An array of orderIds corresponding to the retrieved limit orders.
     * @return orders An array of IExchange.Order objects representing the limit orders.
     */
    function getLimitOrders(address account) external view returns (bytes32[] memory, IExchange.Order[] memory);

    /**
     * @dev Get all the queued requests of a specific type.
     * @param requestType The type of queued request (refer to IQueuedRequests for details).
     * @param count The number of requests to return; set to 0 to return all.
     * @return An array of Queued Requests structs containing the queue index, account, and arguments.
     */
    function getQueuedRequestsData(IQR.Type requestType, uint256 count) external view returns (IQR.DataWithId[] memory);

    /**
     * @dev Delete all market orders in the order queue. Only callable by the keeper or exchange.
     * Used in case of a pause when the exchange goes insolvent or the keeper restarts.
     */
    //Can be removed?
    //function deleteAllMarketOrders() external;

    /**
     * @notice Pauses the Router contract.
     * @dev This function can only be called by an account with the EXCHANGE_ROLE.
     * Emits a {Paused} event.
     */
    function pauseRouter() external;

    /**
     * @notice to generage event on router, so we don't have to listen to exchange
     * @dev This function can only be called by an account with the EXCHANGE_ROLE.
     * @param eventType see IRouter EventType for details
     * @param args encoded packets variables of the event
     * Emits an {ContractEvent} event.
     */
    function generateRouterEvent(EventType eventType, bytes memory args) external;

    /**
     * @notice Unpauses the Router contract.
     * @dev This function can only be called by an account with the EXCHANGE_ROLE.
     * Emits an {Unpaused} event.
     */
    function unpauseRouter() external;

    /**
     * @dev Enqueue a batch of orders for deletion and add a batch of limit orders in one transaction.
     * @param _deleteOrderIds Array of order IDs to be deleted.
     * @param _addLimitOrders Array of limit orders to be added.
     */
    function deleteAndAddLimitOrders(bytes[] memory _deleteOrderIds, IExchange.Order[] memory _addLimitOrders) external;

    /**
     * @dev Deletes all stop loss or take profit orders of a position, typically called when a position is closed.
     * @param positionKey The key of the position for which the orders will be deleted.
     */
    function deleteSlTpOrdersByPosition(bytes32 positionKey) external;

    /**
     * @dev Execute a queued request.
     * @param requestType The type of the queued request. Check IQueuedRequests.Type for details.
     * @param qrd The data associated with the queued request.
     * @param * Additional arguments for the keeper (not used in this implementation).
     * @return bool Returns true if the execution is successful.
     */
    function executeQueuedRequest(IQR.Type requestType, IQR.Data memory qrd, bytes memory) external returns (bool);

    /**
     * @dev Enqueue/add different kinds of orders in one transaction.
     * @param _enqueueOrders Array of orders to be enqueued.
     * @param _limitOrders Array of limit orders to be added.
     */
    function enqueueOrdersAndAddLimitOrders(
        IExchange.Order[] memory _enqueueOrders,
        IExchange.Order[] memory _limitOrders
    ) external;

    /**
     * @dev Deposit directly into LP by ERC20 transfer.
     * @param tokenAmount The amount of tokens to be deposited.
     */
    function liquidityDepositWithERC20(uint256 tokenAmount) external;

    /**
     * @dev Execute requests of different types.
     * @param mtRequests Array of multi-type structures. See {IQueuedRequests.MultiTypeRequest} for details.
     */
    function processQueuedRequests(IQR.MultiTypeRequest[] memory mtRequests) external returns (bool);

    /**
     * @dev Adds a limit order to the exchange.
     * @param order The limit order to be added.
     * @return orderId The orderId of the added order.
     */
    function addLimitOrder(IExchange.Order memory order) external returns (bytes32);

    /**
     * @dev Adds multiple limit orders in a single transaction.
     * @param orders An array of limit orders to be added.
     * @return orderIds An array containing the orderIds of the added orders.
     */
    function addLimitOrders(IExchange.Order[] memory orders) external returns (bytes32[] memory orderIds);

    /**
     * @dev Enqueue multiple orders to the order queue.
     * @param orders Orders to be enqueued.
     */
    function batchEnqueueOrders(IExchange.Order[] memory orders) external;

    /**
     * @dev Register users requests for frontend interaction.
     * One function for all requests to minimize contract size.
     * Note: No verification in the function at this stage.
     * @param requestType The type of the queued request. See {IQueuedRequests.Type} for details.
     * @param args An array of encoded arguments, where each element represents a request.
     */
    function createQueuedRequest(IQR.Type requestType, bytes[] memory args) external;
}

File 39 of 43 : IsolatedWalletFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IsolatedWalletLogic, IIsolatedWalletLogic} from "./IsolatedWalletLogic.sol";

/**
 * @title IsolatedWalletFactory
 * @dev Factory contract for creating IsolatedWalletLogic instances.
 */
contract IsolatedWalletFactory {
    using SafeERC20 for IERC20;

    // Mapping to track whether an address represents an isolated wallet
    mapping(address => bool) public wallets;

    // Event emitted when a new isolated wallet is created
    event IsolatedWalletCreated(address indexed isolatedWallet);

    /**
     * @dev See {IIsolatedWalletFactory}.
     */
    function createIsolatedWallet(
        IIsolatedWalletLogic.Call[] calldata calls,
        IIsolatedWalletLogic.Deposit calldata deposit
    ) external returns (address isolatedWallet) {
        isolatedWallet = address(new IsolatedWalletLogic());
        wallets[isolatedWallet] = true;
        if (deposit.value > 0 && deposit.token != address(0)) {
            IERC20(deposit.token).safeTransferFrom(msg.sender, isolatedWallet, deposit.value);
        }
        IsolatedWalletLogic(payable(isolatedWallet)).initialize(msg.sender, calls);
        emit IsolatedWalletCreated(isolatedWallet);
        return isolatedWallet;
    }
}

File 40 of 43 : IsolatedWalletLogic.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IIsolatedWalletLogic} from "./interface/IIsolatedWalletLogic.sol";

/**
 * @title IsolatedWalletLogic
 * @dev Smart contract representing the logic for an isolated wallet.
 * This contract is Ownable and uses ReentrancyGuard to ensure non-reentrancy in specific functions.
 */
contract IsolatedWalletLogic is Ownable, ReentrancyGuard {
    // Flag indicating whether the contract has been initialized
    bool public initializeStatus;

    // Event emitted when a result is obtained from a multi-call
    event MultiCallResult(uint256 i, bytes result);

    // Custom error for multi-call failure
    error MultiCallError(uint256 i, bytes result);
    error AlreadyInitialized();

    /**
     * @dev Fallback function to receive Ether.
     */
    receive() external payable {}

    /**
     * @dev Modifier to ensure that a function can only be called once during initialization.
     */
    modifier initializer() {
        if (initializeStatus) revert AlreadyInitialized();
        initializeStatus = true;
        _;
    }

    /**
     * @dev See {IIsolatedWalletLogic}.
     */
    function initialize(address _owner, IIsolatedWalletLogic.Call[] calldata calls) external initializer {
        transferOwnership(_owner);
        _multiCall(calls);
    }

    /**
     * @dev See {IIsolatedWalletLogic}.
     */
    function multiCall(IIsolatedWalletLogic.Call[] calldata calls) external payable onlyOwner nonReentrant {
        _multiCall(calls);
    }

    /**
     * @dev Internal function to execute a series of calls.
     * If any of the calls fails, it reverts and provides information about the failed call.
     * @param calls An array of Call structures representing the calls to be executed.
     */
    function _multiCall(IIsolatedWalletLogic.Call[] calldata calls) internal {
        for (uint256 i = 0; i < calls.length; i++) {
            (bool status, bytes memory result) = calls[i].target.call{value: calls[i].value}(calls[i].callData);
            if (!status) {
                revert MultiCallError(i, result);
            }
            emit MultiCallResult(i, result);
        }
    }
}

File 41 of 43 : ContractMock.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract ContractMock {
    error FailedToCallOnBlock(uint256 block);

    event NewCall(uint256 count);

    bool approved;

    mapping(address => uint256) public numberOfCalls; // analytic data;

    //constructor() {}

    function testFunctionCall() external payable {
        numberOfCalls[msg.sender] += 1;
        emit NewCall(numberOfCalls[msg.sender]);
    }

    function testFailedCall() external pure {
        require(false, "failed to call");
    }

    function testErrorMessage() external pure {
        revert FailedToCallOnBlock(7);
    }

    function deposit(address collateralToken, uint256 tokenAmount) external payable {
        IERC20(collateralToken).transferFrom(msg.sender, address(this), tokenAmount);
    }

    function approve(address collateralToken, uint256 tokenAmount) external returns (bool) {
        approved = true;
        return approved;
    }
}

File 42 of 43 : MockERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

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

contract MockERC20 is ERC20, Ownable {
    constructor(string memory name, string memory symbol) ERC20(name, symbol) {}

    function decimals() public pure override(ERC20) returns (uint8) {
        return 6;
    }

    function mint(address account, uint256 amount) external onlyOwner {
        _mint(account, amount);
    }

    function mintBatch(address[] calldata accounts, uint256 amount) external onlyOwner {
        for (uint256 i; i < accounts.length; i++) {
            _mint(accounts[i], amount);
        }
    }

    function burn(address account, uint256 amount) external onlyOwner {
        _burn(account, amount);
    }

    function publicMint(uint256 amount) external {
        _mint(msg.sender, amount);
    }
}

File 43 of 43 : Router.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {IRequestExecutor} from "./interface/IRequestExecutor.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {IRouter, IQR, IExchange} from "./interface/IRouter.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {EnumerableSetUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";

/**
 * @notice Router contract implementing IRouter interface.
 * @dev This contract handles routing of requests, execution of queued requests, and has pausable functionality.
 * It also utilizes AccessControlEnumerable for role-based access control.
 * Implements the IRouter, IRequestExecutor, Pausable, and AccessControlEnumerable interfaces.
 */
contract Router is IRouter, IRequestExecutor, Initializable, PausableUpgradeable, AccessControlUpgradeable {
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set;

    bytes32 public constant EXCHANGE_ROLE = keccak256("EXCHANGE_ROLE");
    bytes32 public constant KEEPER_ROLE = keccak256("KEEPER_ROLE");
    bytes32 public constant ACCOUNT_MANAGER_ROLE = keccak256("ACCOUNT_MANAGER");
    string public constant VERSION = "0.0.2";

    uint256 public firstOrder; // Start from 1 for move away from LIQ id
    uint256 public lastOrder; // Start from 1 for move away from LIQ id

    address public exchange;

    EnumerableSetUpgradeable.Bytes32Set private limitOrderIds;
    mapping(address => address) public accountLinks; // link AA with owner address
    mapping(IQR.Type => mapping(uint256 => IQR.Data)) public queuedRequestsData;
    mapping(IQR.Type => IQR.Settings) public queuedRequestsSettings;
    // Market orders
    mapping(uint256 => IExchange.Order) public orderQueue;
    // Limit orders
    mapping(bytes32 => IExchange.Order) public limitOrders;
    mapping(address => EnumerableSetUpgradeable.Bytes32Set) private accountLimitOrderIds;
    // Maps position key to list of stop loss/take profit limit orders
    // Used to cancel all stop loss/take profit limit orders when position is closed
    mapping(bytes32 => EnumerableSetUpgradeable.Bytes32Set) private positionSlTpIds;

    /**
     * @dev Modifier to restrict access to functions only to accounts with the KEEPER_ROLE or EXCHANGE_ROLE.
     * @notice Reverts if the sender does not have either the KEEPER_ROLE or EXCHANGE_ROLE.
     */
    modifier onlyKeeperOrExchange() {
        if (!hasRole(KEEPER_ROLE, msg.sender) && !hasRole(EXCHANGE_ROLE, msg.sender))
            revert NotKeeperOrExchange(msg.sender);
        _;
    }

    /**
     * @notice Initializer for the Router contract.
     * @dev Initializes the contract with specified roles and addresses.
     * @param _exchange Address of the associated Exchange contract.
     * @param _keeper Address of the keeper associated with this Router.
     * @param _admin Address with the DEFAULT_ADMIN_ROLE for administrative functions.
     * Requirements:
     * - The provided addresses must not be zero addresses.
     */
    function initialize(address _exchange, address _keeper, address _admin) external initializer {
        __AccessControl_init();
        __Pausable_init();
        firstOrder = 1;
        lastOrder = 1;
        if (_exchange == address(0) || _keeper == address(0) || _admin == address(0)) revert ZeroAddressSet();
        _grantRole(DEFAULT_ADMIN_ROLE, _admin);
        _grantRole(EXCHANGE_ROLE, _exchange);
        _grantRole(KEEPER_ROLE, _keeper);
        exchange = _exchange;
    }

    /**
     * @dev Modifier to restrict access to functions only to accounts with the KEEPER_ROLE or system.
     * @notice Reverts if the sender does not have either the KEEPER_ROLE or ROUTER_ROLE.
     */
    modifier onlyKeeperOrSystem() {
        if (!hasRole(KEEPER_ROLE, msg.sender) && msg.sender != address(this)) revert NotKeeperOrSystem(msg.sender);
        _;
    }

    /* EXTERNAL */

    /**
     * @dev See {IRouter}.
     */
    function getMarketOrders() external view returns (uint256, IExchange.Order[] memory) {
        uint256 numOrders = lastOrder - firstOrder;
        IExchange.Order[] memory orders = new IExchange.Order[](numOrders);
        for (uint256 i; i < numOrders; i++) {
            orders[i] = orderQueue[firstOrder + i];
        }
        return (firstOrder, orders);
    }

    /**
     * @dev See {IRouter}.
     */
    function getLimitOrders(address account) external view returns (bytes32[] memory, IExchange.Order[] memory) {
        bytes32[] memory orderIds = (account == address(0))
            ? limitOrderIds.values()
            : accountLimitOrderIds[account].values();
        IExchange.Order[] memory orders = new IExchange.Order[](orderIds.length);
        for (uint256 i; i < orderIds.length; i++) {
            orders[i] = limitOrders[orderIds[i]];
        }
        return (orderIds, orders);
    }

    /**
     * @dev See {IRouter}.
     */
    function getQueuedRequestsData(
        IQR.Type requestType,
        uint256 count
    ) external view returns (IQR.DataWithId[] memory) {
        IQR.Settings memory qrs = queuedRequestsSettings[requestType];
        uint256 numRequests = qrs.last - qrs.removed;
        if (numRequests == 0) {
            return new IQR.DataWithId[](0);
        }

        if (count < numRequests && count != 0) numRequests = count;

        IQR.DataWithId[] memory requests = new IQR.DataWithId[](numRequests);

        uint256 found;
        for (uint256 i = qrs.last; i >= 0; i--) {
            if (queuedRequestsData[requestType][i].account != address(0)) {
                requests[found] = IQR.DataWithId(
                    i,
                    queuedRequestsData[requestType][i].account,
                    queuedRequestsData[requestType][i].args
                );
                found++;
                if (found == numRequests) break;
            }
        }
        return requests;
    }

    function getProxyOwner() public view returns (address) {
        if (accountLinks[msg.sender] != address(0)) return accountLinks[msg.sender];
        return msg.sender;
    }

    /**
     * @dev See {IRouter}.
     */
    function pauseRouter() external onlyRole(EXCHANGE_ROLE) {
        _pause();
    }

    /**
     * @notice Unpauses the Router contract.
     * @dev This function can only be called by an account with the EXCHANGE_ROLE.
     * Emits an {Unpaused} event.
     */
    function unpauseRouter() external onlyRole(EXCHANGE_ROLE) {
        _unpause();
    }

    /**
     * @dev See {IRouter}.
     */
    function generateRouterEvent(EventType eventType, bytes memory args) external onlyRole(EXCHANGE_ROLE) {
        emit ContractEvent(eventType, args);
    }

    /**
     * @dev See {IRouter}.
     */
    function deleteAndAddLimitOrders(
        bytes[] memory _deleteOrderIds,
        IExchange.Order[] memory _addLimitOrders
    ) external {
        createQueuedRequest(IQR.Type.DELETE_ORDER, _deleteOrderIds);
        addLimitOrders(_addLimitOrders);
    }

    /**
     * @dev See {IRouter}.
     */
    function deleteSlTpOrdersByPosition(bytes32 positionKey) external onlyKeeperOrExchange {
        bytes32[] memory ordersIds = positionSlTpIds[positionKey].values();
        if (ordersIds.length > 0) {
            _deleteAllSetValues(positionSlTpIds[positionKey]);
            for (uint256 i = 0; i < ordersIds.length; i++) {
                IExchange.Order memory order = limitOrders[ordersIds[i]];
                _deleteLimitOrder(ordersIds[i], order, false, true);
            }
        }
    }

    /**
     * @dev See {IRouter}.
     */
    function executeQueuedRequest(
        IQR.Type requestType,
        IQR.Data memory qrd,
        bytes memory
    ) external override(IRouter, IRequestExecutor) returns (bool) {
        if (msg.sender != address(this)) {
            revert NotSystemCall();
        }
        if (requestType == IQR.Type.DELETE_ORDER) {
            bytes32 limitOrderId = bytes32(qrd.args);
            _deleteLimitOrderByRequest(limitOrderId, qrd.account);
            return true;
        }
        //just in case, inaccessible for now
        revert RequestTypeNotYetImplemented(requestType);
    }

    /**
     * @dev See {IRouter}.
     */
    function enqueueOrdersAndAddLimitOrders(
        IExchange.Order[] memory _enqueueOrders,
        IExchange.Order[] memory _limitOrders
    ) external {
        batchEnqueueOrders(_enqueueOrders);
        addLimitOrders(_limitOrders);
    }

    /**
     * @dev See {IRouter}.
     */
    function liquidityDepositWithERC20(uint256 tokenAmount) external {
        IExchange(exchange).accountDepositFromRouter(getProxyOwner(), tokenAmount);
        bytes[] memory args = new bytes[](1);
        args[0] = abi.encode(tokenAmount);
        createQueuedRequest(IQR.Type.LP_ADD, args);
    }

    /**
     * @dev See {IRouter}.
     */
    function processQueuedRequests(
        IQR.MultiTypeRequest[] memory mtRequests
    ) external override(IRouter, IRequestExecutor) onlyKeeperOrSystem returns (bool) {
        uint256 ammFunding = 0;
        uint256 lpFunding = 0;
        bool foundError;
        for (uint256 i = 0; i < mtRequests.length; i++) {
            if (mtRequests[i].requestType == IQR.Type.PROCESS_QUEUED_REQUESTS) {
                bool validExecution;
                IQR.MultiTypeRequest[] memory mtChildBatchRequests = abi.decode(
                    mtRequests[i].keeperArgs,
                    (IQR.MultiTypeRequest[])
                );

                try IRequestExecutor(address(this)).processQueuedRequests(mtChildBatchRequests) returns (
                    bool _validExecution
                ) {
                    validExecution = _validExecution;
                    if (validExecution) {
                        emit ContractEvent(EventType.ExecuteLiqBatchSuccess, abi.encode(i, mtRequests[i].searchKey));
                    } else {
                        emit ContractEvent(EventType.ExecuteLiqBatchFailed, abi.encode(i, mtRequests[i].searchKey));
                    }
                } catch Error(string memory reason) {
                    emit Log(reason);
                    emit ContractEvent(EventType.ExecuteLiqBatchFailed, abi.encode(i, mtRequests[i].searchKey));
                } catch Panic(uint256 code) {
                    emit LogPanic(code, "Panic");
                    emit ContractEvent(EventType.ExecuteLiqBatchFailed, abi.encode(i, mtRequests[i].searchKey));
                } catch (bytes memory lowLevelData) {
                    emit LowLevelLog(lowLevelData);
                    emit ContractEvent(EventType.ExecuteLiqBatchFailed, abi.encode(i, mtRequests[i].searchKey));
                }

                if (!validExecution) {
                    foundError = true;
                    break;
                }
                continue;
            }

            if (mtRequests[i].requestType == IQR.Type.EXECUTE_ORDER) {
                IExchange.OrderData memory orderData = abi.decode(mtRequests[i].keeperArgs, (IExchange.OrderData));
                bool validExecution = _executeOrder(orderData); //, mtRequests[i].searchKey
                if (validExecution) {
                    ammFunding += mtRequests[i].totalAmmFunding;
                    lpFunding += mtRequests[i].totalLpFunding;
                    continue;
                } else {
                    foundError = true;
                    break;
                }
            }
            if (mtRequests[i].requestType == IQR.Type.DELETE_ORDER) {
                bytes32 orderId = bytes32(mtRequests[i].keeperArgs);
                uint256 marketOrderIndex = firstOrder;
                if (keccak256(abi.encodePacked(marketOrderIndex)) == orderId) {
                    delete orderQueue[marketOrderIndex];
                    firstOrder++;
                    ammFunding += mtRequests[i].totalAmmFunding;
                    lpFunding += mtRequests[i].totalLpFunding;
                    emit ContractEvent(EventType.MarketOrderDeleted, abi.encode(marketOrderIndex));
                    continue;
                }
            }

            IQR.Data memory qrd = queuedRequestsData[mtRequests[i].requestType][mtRequests[i].id];
            if (qrd.account == address(0)) {
                revert RequestsNotFound(mtRequests[i].requestType, mtRequests[i].id);
            }
            delete queuedRequestsData[mtRequests[i].requestType][mtRequests[i].id];
            queuedRequestsSettings[mtRequests[i].requestType].removed++;

            if (mtRequests[i].validRequest) {
                IRequestExecutor executor = (uint8(mtRequests[i].requestType) < 4)
                    ? IRequestExecutor(exchange) //LP_ADD, LP_SCHEDULE_WITHDRAW, LP_IMMEDIATE_WITHDRAW, ACCOUNT_BALANCE_WITHDRAW
                    : IRequestExecutor(address(this)); //DELETE_ORDER, EXECUTE_ORDER

                // Execute Request
                //qrs.first is equal to orderIndex during request creation;
                //it's update +1 in the end of this cycle
                try executor.executeQueuedRequest(mtRequests[i].requestType, qrd, mtRequests[i].keeperArgs) {
                    ammFunding += mtRequests[i].totalAmmFunding;
                    lpFunding += mtRequests[i].totalLpFunding;
                    emit ContractEvent(
                        EventType.QueuedRequestAccepted,
                        abi.encode(mtRequests[i].id, mtRequests[i].requestType, qrd.args)
                    );
                } catch Error(string memory reason) {
                    foundError = true;
                    emit Log(reason);
                    emit ContractEvent(
                        EventType.QueuedRequestFailed,
                        abi.encode(mtRequests[i].id, mtRequests[i].requestType, qrd.args)
                    );
                } catch Panic(uint256 code) {
                    foundError = true;
                    emit LogPanic(code, "Panic");
                    emit ContractEvent(
                        EventType.QueuedRequestFailed,
                        abi.encode(mtRequests[i].id, mtRequests[i].requestType, qrd.args)
                    );
                } catch (bytes memory lowLevelData) {
                    foundError = true;
                    emit LowLevelLog(lowLevelData); //debug event
                    emit ContractEvent(
                        EventType.QueuedRequestFailed,
                        abi.encode(mtRequests[i].id, mtRequests[i].requestType, qrd.args)
                    );
                }
            } else {
                ammFunding += mtRequests[i].totalAmmFunding;
                lpFunding += mtRequests[i].totalLpFunding;
                emit ContractEvent(
                    EventType.QueuedRequestDeclined,
                    abi.encode(mtRequests[i].id, mtRequests[i].requestType, qrd.args)
                );
            }
            if (foundError) break;
        }
        if (ammFunding > 0 || lpFunding > 0) IExchange(exchange).settleFunding(ammFunding, lpFunding);
        return !foundError;
    }

    function setAccountLink(
        address abstractAccountAddress,
        address ownerAddress
    ) external onlyRole(ACCOUNT_MANAGER_ROLE) {
        if (accountLinks[abstractAccountAddress] != address(0) && ownerAddress != address(0))
            revert AlreadyLinked(abstractAccountAddress, ownerAddress);
        accountLinks[abstractAccountAddress] = ownerAddress;
        emit AccountLinked(abstractAccountAddress, ownerAddress);
    }

    /* PUBLIC */

    /**
     * @dev See {IRouter}.
     */
    function addLimitOrder(IExchange.Order memory order) public returns (bytes32) {
        if (order.limitOrder != true) {
            revert NotLimitOrder();
        }
        _validateNewOrder(order);

        EnumerableSetUpgradeable.Bytes32Set storage _accountLimitOrderIds = accountLimitOrderIds[order.account];
        bytes32 orderId = keccak256(abi.encode(order, _accountLimitOrderIds.length()));

        // If order is a stop loss or take profit, add to positionSlTpIds
        if (order.slTpType != 0) {
            IExchange e = IExchange(exchange);
            bytes32 positionKey = e.getPositionKey(order.account, order.underlying);
            if (!positionSlTpIds[positionKey].add(orderId)) {
                revert DuplicateSlTpIds(orderId);
            }
        }

        if (!limitOrderIds.add(orderId) || !_accountLimitOrderIds.add(orderId)) {
            revert DuplicateLimitOrder(orderId);
        }

        limitOrders[orderId] = order;

        emit ContractEvent(
            EventType.AddLimitOrder,
            abi.encode(orderId, order.account, order.underlying, order.sizeDelta, order.limitPrice, order.slTpType)
        );
        return orderId;
    }

    /**
     * @dev See {IRouter}.
     */
    function addLimitOrders(IExchange.Order[] memory orders) public returns (bytes32[] memory orderIds) {
        orderIds = new bytes32[](orders.length);
        for (uint256 i = 0; i < orders.length; i++) {
            orderIds[i] = addLimitOrder(orders[i]);
        }
    }

    /**
     * @dev See {IRouter}.
     */
    function batchEnqueueOrders(IExchange.Order[] memory orders) public {
        // Ensure the input arrays have the same length
        uint256 numOrders = orders.length;
        uint256 _lastOrder = lastOrder; //local copy to save gas

        for (uint256 i; i < numOrders; ++i) {
            // Create a new order and store it in the OrderQueue
            orders[i].limitOrder = false; //for limit orders we have another function
            _validateNewOrder(orders[i]);
            uint256 orderIndex = _lastOrder + i;
            orderQueue[orderIndex] = orders[i];
            emit ContractEvent(
                EventType.OrderEnqueue,
                abi.encode(
                    orderIndex,
                    orders[i].account,
                    orders[i].underlying,
                    orders[i].sizeDelta,
                    orders[i].limitPrice
                )
            );
        }

        lastOrder += numOrders;
    }

    /**
     * @dev See {IRouter}.
     */
    function createQueuedRequest(IQR.Type requestType, bytes[] memory args) public whenNotPaused {
        address requestCreator = getProxyOwner();
        if (
            IExchange(exchange).accountBalances(requestCreator) == 0 &&
            IExchange(exchange).lpBalances(requestCreator) == 0
        ) revert InsufficientBalance(requestCreator);
        uint256 requestIndex = queuedRequestsSettings[requestType].last;
        for (uint256 i; i < args.length; i++) {
            if (requestType == IQR.Type.ACCOUNT_BALANCE_WITHDRAW) {
                IQR.AccountBalanceWithdrawArgs memory withdrawArgs = abi.decode(
                    args[i],
                    (IQR.AccountBalanceWithdrawArgs)
                );

                if (withdrawArgs.token != IExchange(exchange).collateralToken()) {
                    revert NotCollateral(withdrawArgs.token);
                }
                if (withdrawArgs.amount == 0) {
                    revert ZeroWithdrawAmount();
                }
            }

            queuedRequestsData[requestType][requestIndex] = IQR.Data(requestCreator, args[i]);
            emit ContractEvent(
                EventType.NewQueuedRequest,
                abi.encode(requestIndex, requestType, requestCreator, args[i])
            );
            requestIndex++;
        }
        queuedRequestsSettings[requestType].last = requestIndex;
    }

    /* INTERNAL */

    function _shouldDeleteOrder(IExchange.Order memory order) internal view returns (bool) {
        if (order.limitOrder) {
            // Delete if currently insolvent and increasing LO was added prior to insolvency
            // Or if SL/TP order increases position size
            if (paused() || order.slTpType != 0) {
                (int256 size, ) = IExchange(exchange).getPosition(order.account, order.underlying);
                if (size == 0 || size ^ order.sizeDelta >= 0) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @dev Internal function to validate a new order.
     * @param order The order to be validated.
     * @notice Throws an error if the order is invalid.
     */
    function _validateNewOrder(IExchange.Order memory order) internal view {
        if (order.account != getProxyOwner()) {
            revert NotOwnerOfOrder(order.account, getProxyOwner());
        }
        if (order.sizeDelta == 0) {
            revert OrderSizeDeltaCannotBeEmpty();
        }

        IExchange e = IExchange(exchange);
        if (e.accountBalances(order.account) == 0) {
            revert InsufficientBalance(order.account);
        }
        if (e.isTradeable(order.underlying) != true) {
            revert NotTradeableOrPausedMarket(order.underlying);
        }

        if (paused()) {
            (int256 size, ) = e.getPosition(order.account, order.underlying);
            if (size == 0 || size ^ order.sizeDelta >= 0) {
                //isIncrease
                // Don't add if currently insolvent and order increases position
                revert CannotIncreasePositionWhileInsolvent();
            }
        }
    }

    /**
     * @dev Deletes all values from the given EnumerableSetUpgradeable.Bytes32Set.
     * @param set The EnumerableSetUpgradeable.Bytes32Set to delete values from.
     * @notice This function removes all values from the provided set by iterating over each element
     * and removing it individually.
     */
    function _deleteAllSetValues(EnumerableSetUpgradeable.Bytes32Set storage set) internal {
        uint256 setLength = set.length();
        for (uint256 i = 0; i < setLength; i++) {
            set.remove(set.at(0));
        }
    }

    /**
     * @dev Internal function to delete a limit order.
     * @param orderId The ID of the limit order to be deleted.
     * @param order The limit order details.
     * @param removedFromAccount Indicates whether the order has been removed from the account's order list.
     * @param removedFromSlTpList Indicates whether the order has been removed from the stop-loss/take-profit list.
     */
    function _deleteLimitOrder(
        bytes32 orderId,
        IExchange.Order memory order,
        bool removedFromAccount,
        bool removedFromSlTpList
    ) internal {
        // Remove order from limitOrderIds and limitOrders
        limitOrderIds.remove(orderId);
        delete limitOrders[orderId];

        if (!removedFromAccount) {
            accountLimitOrderIds[order.account].remove(orderId);
        }

        // If order is a stop loss or take profit, remove from positionSlTpIds
        if (order.slTpType != 0 && !removedFromSlTpList) {
            bytes32 positionKey = IExchange(exchange).getPositionKey(order.account, order.underlying);
            if (positionSlTpIds[positionKey].length() > 0) positionSlTpIds[positionKey].remove(orderId);
        }
    }

    /**
     * @dev Deletes all limit orders of an account, typically called during account liquidation.
     * @param account The address of the account for which the orders will be deleted.
     */
    function _deleteLimitOrdersByAccount(address account) internal {
        // Remove all limit orders from account (which includes TP/SL orders)
        bytes32[] memory ordersIds = accountLimitOrderIds[account].values();
        if (ordersIds.length > 0) {
            _deleteAllSetValues(accountLimitOrderIds[account]);
            for (uint256 i = 0; i < ordersIds.length; i++) {
                IExchange.Order memory order = limitOrders[ordersIds[i]];
                _deleteLimitOrder(ordersIds[i], order, true, false);
            }
        }
    }

    /**
     * @dev Deletes a limit order by request.
     * @param orderId The unique identifier of the order to be deleted.
     * @param requestCreator The address of the entity initiating the deletion request.
     */
    function _deleteLimitOrderByRequest(bytes32 orderId, address requestCreator) internal {
        if (limitOrders[orderId].account == address(0)) {
            revert OrderDoesNotExist(orderId);
        }
        IExchange.Order memory order = limitOrders[orderId];
        if (order.account != requestCreator) {
            revert NotOwnerOfOrder(order.account, requestCreator);
        }
        _deleteLimitOrder(orderId, order, false, false);
    }

    /**
     * @dev Executes an order using custom pricing.
     * Only decreasing orders can be executed when paused.
     * @param orderData The data associated with the order.
     * @return executionStatus A boolean indicating the success of the execution.
     */
    function _executeOrder(IExchange.OrderData memory orderData) internal returns (bool executionStatus) {
        uint256 marketOrderIndex = firstOrder;
        IExchange.Order memory order;
        bytes32 orderId = orderData.orderId;

        bool liquidation = (orderData.account != address(0) &&
            orderData.sizeDelta != 0 &&
            orderData.underlying != bytes32(0));
        if (liquidation) {
            // Liquidation order
            order = IExchange.Order({
                limitOrder: false,
                account: orderData.account,
                underlying: orderData.underlying,
                sizeDelta: orderData.sizeDelta,
                limitPrice: 0,
                slTpType: 0
            });
        } else {
            if (keccak256(abi.encodePacked(marketOrderIndex)) == orderId) {
                // Market order
                order = orderQueue[marketOrderIndex];
                if (orderData.sizeDelta != 0) {
                    if (orderData.sizeDelta ^ order.sizeDelta < 0 || abs(orderData.sizeDelta) > abs(order.sizeDelta)) {
                        revert WrongSizeDelta(orderData.sizeDelta, order.sizeDelta);
                    }
                    order.sizeDelta = orderData.sizeDelta;
                }
                delete orderQueue[marketOrderIndex];
                firstOrder++;
            } else {
                // Limit order
                order = limitOrders[orderId];
                if (orderData.sizeDelta != 0) order.sizeDelta = orderData.sizeDelta;
                _deleteLimitOrder(orderId, order, false, false);
            }
        }

        if (!_shouldDeleteOrder(order)) {
            try IExchange(exchange).executeOrder(order, orderData, liquidation) returns (
                bytes32,
                int256,
                int256,
                uint256 // execPrice
            ) {
                if (!liquidation) {
                    if (order.limitOrder) {
                        emit ContractEvent(EventType.ExecuteLimitOrder, abi.encode(orderId));
                    } else {
                        emit ContractEvent(EventType.OrderDequeue, abi.encode(marketOrderIndex));
                    }
                }
                executionStatus = true;
            } catch Error(string memory reason) {
                emit Log(reason);
            } catch Panic(uint256 code) {
                emit LogPanic(code, "Panic");
            } catch (bytes memory lowLevelData) {
                emit LowLevelLog(lowLevelData);
            }

            if (!executionStatus) {
                if (liquidation) {
                    revert liquidationFailed(orderId);
                }
                emit ContractEvent(EventType.OrderExecutionFailed, abi.encode(orderId));
            }
        }
    }

    function abs(int256 x) private pure returns (uint256) {
        return x >= 0 ? uint256(x) : uint256(-x);
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "mode": "3"
  },
  "outputSelection": {
    "*": {
      "*": [
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[{"internalType":"contract TransparentUpgradeableProxy","name":"proxy","type":"address"},{"internalType":"address","name":"newAdmin","type":"address"}],"name":"changeProxyAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract TransparentUpgradeableProxy","name":"proxy","type":"address"}],"name":"getProxyAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract TransparentUpgradeableProxy","name":"proxy","type":"address"}],"name":"getProxyImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract TransparentUpgradeableProxy","name":"proxy","type":"address"},{"internalType":"address","name":"implementation","type":"address"}],"name":"upgrade","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract TransparentUpgradeableProxy","name":"proxy","type":"address"},{"internalType":"address","name":"implementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeAndCall","outputs":[],"stateMutability":"payable","type":"function"}]

Deployed Bytecode

0x00010000000000020003000000000002000000000301034f0000008009000039000000400090043f00000000010300190000006001100270000000c4041001970000000101200190000000300000c13d000000040140008c000001f20000413d000000000143034f000000000203043b000000e002200270000000ca0520009c0000004a0000213d000000d00520009c000000940000213d000000d30520009c000000b60000613d000000d40120009c000001f20000c13d0000000001000416000000000101004b000001f20000c13d000000000100041a000000c7021001970000000005000411000000000252004b000001c20000c13d000000c501100197000000000010041b000000c4010000410000000002000414000000c40320009c0000000002018019000000c001200210000000c6011001c70000800d020000390000000303000039000000c8040000410000000006000019030a03000000040f0000000101200190000001f20000613d00000000010000190000030b0001042e0000000001000416000000000101004b000001f20000c13d000000000200041a000000c5012001970000000006000411000000000161019f000000000010041b000000c4010000410000000003000414000000c40430009c0000000003018019000000c001300210000000c6011001c7000000c7052001970000800d020000390000000303000039000000c804000041030a03000000040f0000000101200190000001f20000613d000000200100003900000100001004430000012000000443000000c9010000410000030b0001042e000000cb0520009c000000a00000213d000000ce0120009c000000c80000613d000000cf0120009c000001f20000c13d0000000001000416000000000101004b000001f20000c13d000000040140008a000000400110008c000001f20000413d0000000401300370000000000401043b000000c70140009c000001f20000213d0000002401300370000000000301043b000000c70130009c000001f20000213d000000000100041a000000c7011001970000000002000411000000000121004b000001c20000c13d000200000003001d000000dd010000410000000000100439000300000004001d0000000400400443000000c4010000410000000002000414000000c40320009c0000000002018019000000c001200210000000de011001c70000800202000039030a03050000040f0000000102200190000002350000613d000000000101043b000000000101004b00000003020000290000000203000029000001f20000613d000000400500043d000000df010000410000000000150435000000040150003900000000003104350000000001000414000000040320008c000000910000613d000000c404000041000000c40310009c0000000001048019000000c40350009c00000000040540190000004003400210000000c001100210000000000131019f000000e0011001c7000300000005001d030a03000000040f000000030500002900000000030100190000006003300270000000c40030019d000000c40330019700000001022001900000026d0000613d000000d70150009c000002220000213d000001a20000013d000000d10120009c0000015f0000613d000000d20120009c000001f20000c13d0000000001000416000000000101004b000001f20000c13d000000000100041a000000c701100197000000800010043f000000e5010000410000030b0001042e000000cc0520009c000001a50000613d000000cd0220009c000001f20000c13d0000000002000416000000000202004b000001f20000c13d000000040240008a000000200220008c000001f20000413d0000000402300370000000000202043b000000c70320009c000001f20000213d000000d503000041000000800030043f0000000003000414000000040420008c000001cb0000c13d00000000040000310000000002000019000001d80000013d0000000002000416000000000202004b000001f20000c13d000000040240008a000000200220008c000001f20000413d0000000402300370000000000202043b000000c70320009c000001f20000213d000000e803000041000000800030043f0000000003000414000000040420008c000001e10000c13d00000000050000310000000002000019000001ec0000013d000000040140008a000000600110008c000001f20000413d0000000401300370000000000801043b000000c70180009c000001f20000213d0000002401300370000000000901043b000000c70190009c000001f20000213d0000004401300370000000000201043b000000d70120009c000001f20000213d0000002301200039000000e105000041000000000641004b00000000060000190000000006058019000000e101100197000000000701004b0000000005008019000000e10110009c000000000506c019000000000105004b000001f20000c13d0000000405200039000000000153034f000000000101043b000000d70610009c000002220000213d000000bf06100039000000200a00008a0000000006a6016f000000d70760009c000002220000213d000000400060043f000000800010043f00000000021200190000002402200039000000000242004b000001f20000213d0000002002500039000000000223034f0000001f0310018f0000000504100272000001010000613d00000000050000190000000506500210000000000762034f000000000707043b000000a00660003900000000007604350000000105500039000000000645004b000000f90000413d000000000503004b000001100000613d0000000504400210000000000242034f0000000303300210000000a004400039000000000504043300000000053501cf000000000535022f000000000202043b0000010003300089000000000232022f00000000023201cf000000000252019f000000000024043500020000000a001d000300000009001d000000a0011000390000000000010435000000000100041a000000c7011001970000000002000411000000000121004b0000028a0000c13d000000dd010000410000000000100439000100000008001d0000000400800443000000c4010000410000000002000414000000c40320009c0000000002018019000000c001200210000000de011001c70000800202000039030a03050000040f0000000102200190000002350000613d000000000101043b000000000101004b0000000303000029000001f20000613d000000400400043d000000240140003900000040020000390000000000210435000000e4010000410000000000140435000000040140003900000000003104350000004402400039000000800100043d0000000000120435000300000004001d0000006402400039000000000301004b000001420000613d00000000030000190000000004230019000000a005300039000000000505043300000000005404350000002003300039000000000413004b0000013b0000413d00000000022100190000000000020435000000000300041600000000020004140000000104000029000000040440008c000002c90000613d0000001f01100039000000020110017f000000c4040000410000000306000029000000c40560009c0000000005040019000000000506401900000040055002100000006401100039000000c40610009c00000000010480190000006001100210000000000151019f000000c40520009c0000000002048019000000c002200210000000000112019f000000000203004b000002be0000c13d0000000102000029030a03000000040f000002c30000013d0000000001000416000000000101004b000001f20000c13d000000040140008a000000400110008c000001f20000413d0000000401300370000000000401043b000000c70140009c000001f20000213d0000002401300370000000000301043b000000c70130009c000001f20000213d000000000100041a000000c7011001970000000002000411000000000121004b000001c20000c13d000200000003001d000000dd010000410000000000100439000300000004001d0000000400400443000000c4010000410000000002000414000000c40320009c0000000002018019000000c001200210000000de011001c70000800202000039030a03050000040f0000000102200190000002350000613d000000000101043b000000000101004b00000003020000290000000203000029000001f20000613d000000400500043d000000e6010000410000000000150435000000040150003900000000003104350000000001000414000000040320008c000001a00000613d000000c404000041000000c40310009c0000000001048019000000c40350009c00000000040540190000004003400210000000c001100210000000000131019f000000e0011001c7000300000005001d030a03000000040f000000030500002900000000030100190000006003300270000000c40030019d000000c40330019700000001022001900000029b0000613d000000d70150009c000002220000213d000000400050043f00000000010000190000030b0001042e0000000001000416000000000101004b000001f20000c13d000000040140008a000000200110008c000001f20000413d0000000401300370000000000601043b000000c70160009c000001f20000213d000000000100041a000000c7021001970000000005000411000000000252004b000001c20000c13d000000000206004b000002360000c13d000000d901000041000000800010043f0000002001000039000000840010043f0000002601000039000000a40010043f000000da01000041000000c40010043f000000db01000041000000e40010043f000000dc010000410000030c00010430000000d901000041000000800010043f0000002001000039000000840010043f000000a40010043f000000e201000041000000c40010043f000000e7010000410000030c00010430000000c401000041000000c40430009c0000000003018019000000c001300210000000d6011001c7000300000009001d030a03050000040f0000000309000029000000010220015f00000000030100190000006003300270000000c40030019d000000c4043001970000006003000039000000000504004b000001f40000c13d0000000101200190000001f20000c13d0000000001030433000000000291001900000000010900190000022b0000013d000000c401000041000000c40430009c0000000003018019000000c001300210000000d6011001c7030a03050000040f000000010220015f00000000030100190000006003300270000000c40030019d000000c40530019700000060040000390000008003000039000000000605004b000002200000c13d0000000101200190000002280000613d00000000010000190000030c00010430000000d70340009c000002220000213d0000003f03400039000000200500008a000000000553016f000000400300043d0000000005530019000000000635004b00000000060000190000000106004039000000d70750009c000002220000213d0000000106600190000002220000c13d000000400050043f0000001f0540018f00000000094304360000000504400272000002100000613d000000000600001900000005076002100000000008790019000000000771034f000000000707043b00000000007804350000000106600039000000000746004b000002080000413d000000000605004b000001db0000613d0000000504400210000000000141034f00000000044900190000000305500210000000000604043300000000065601cf000000000656022f000000000101043b0000010005500089000000000151022f00000000015101cf000000000161019f0000000000140435000001db0000013d000000e90350009c000002430000413d000000ea0100004100000000001004350000004101000039000000040010043f000000e0010000410000030c00010430000000000104043300000000023100190000000001030019030a02ed0000040f000000c701100197000000400200043d0000000000120435000000c401000041000000c40320009c00000000020180190000004001200210000000d8011001c70000030b0001042e000000000001042f000000c501100197000000000161019f000000000010041b000000c4010000410000000002000414000000c40320009c0000000002018019000000c001200210000000c6011001c70000800d020000390000000303000039000000c8040000410000002b0000013d0000003f03500039000000200400008a000000000343016f000000400400043d0000000003340019000000000643004b00000000060000190000000106004039000000d70730009c000002220000213d0000000106600190000002220000c13d000000400030043f0000001f0650018f000000000354043600000005055002720000025d0000613d000000000700001900000005087002100000000009830019000000000881034f000000000808043b00000000008904350000000107700039000000000857004b000002550000413d000000000706004b000001f00000613d0000000505500210000000000151034f00000000055300190000000306600210000000000705043300000000076701cf000000000767022f000000000101043b0000010006600089000000000161022f00000000016101cf000000000171019f0000000000150435000001f00000013d000000400200043d0000001f0430018f00000005053002720000027a0000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000002720000413d000000000604004b000002890000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000002b70000013d000000400100043d0000004402100039000000e2030000410000000000320435000000d902000041000000000021043500000024021000390000002003000039000000000032043500000004021000390000000000320435000000c402000041000000c40310009c00000000010280190000004001100210000000e3011001c70000030c00010430000000400200043d0000001f0430018f0000000505300272000002a80000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000002a00000413d000000000604004b000002b70000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000000c401000041000000c40420009c000000000201801900000040012002100000006002300210000000000121019f0000030c00010430000000c6011001c7000080090200003900000001040000290000000005000019030a03000000040f00000000030100190000006003300270000000c40030019d000000c4033001970000000102200190000002d00000613d0000000301000029000000d70110009c000002220000213d0000000301000029000000400010043f00000000010000190000030b0001042e000000400200043d0000001f0430018f0000000505300272000002dd0000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000002d50000413d000000000604004b000002ec0000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000002b70000013d0000000002120049000000e1030000410000001f0420008c00000000040000190000000004032019000000e102200197000000000502004b0000000003008019000000e10220009c000000000304c019000000000203004b000002fd0000613d0000000001010433000000c70210009c000002fd0000213d000000000001042d00000000010000190000030c00010430000000000001042f00000303002104210000000102000039000000000001042d0000000002000019000000000001042d00000308002104230000000102000039000000000001042d0000000002000019000000000001042d0000030a000004320000030b0001042e0000030c0001043000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffff00000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffff8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e00000000200000000000000000000000000000040000001000000000000000000000000000000000000000000000000000000000000000000000000009623609c00000000000000000000000000000000000000000000000000000000f2fde38a00000000000000000000000000000000000000000000000000000000f2fde38b00000000000000000000000000000000000000000000000000000000f3b7dead000000000000000000000000000000000000000000000000000000009623609d0000000000000000000000000000000000000000000000000000000099a88ec4000000000000000000000000000000000000000000000000000000007eff275d000000000000000000000000000000000000000000000000000000007eff275e000000000000000000000000000000000000000000000000000000008da5cb5b00000000000000000000000000000000000000000000000000000000204e1c7a00000000000000000000000000000000000000000000000000000000715018a6f851a440000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000800000000000000000000000000000000000000000000000000000000000000000ffffffffffffffff000000000000000000000000000000000000002000000000000000000000000008c379a0000000000000000000000000000000000000000000000000000000004f776e61626c653a206e6577206f776e657220697320746865207a65726f2061646472657373000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000840000008000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b8302000002000000000000000000000000000000240000000000000000000000003659cfe600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002400000000000000000000000080000000000000000000000000000000000000000000000000000000000000004f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657200000000000000000000000000000000000000640000000000000000000000004f1ef2860000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000008000000000000000008f2839700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000640000008000000000000000005c60da1b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000004e487b71000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c87dd69fb59055312fa12e7a49ea377c2549b0f96876d668e73efd41229f7b53

Block Transaction Gas Used Reward
view all blocks produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]
[ Download: CSV Export  ]

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.