ETH Price: $3,233.18 (-0.69%)

Contract

0xA1418018B06147e1C3aef8D873cd95130684e033

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Parent Transaction Hash Block From To
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
FacetManagement

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "@openzeppelin/contracts/proxy/beacon/IBeacon.sol";

import "../../interfaces/IFacetManagement.sol";
import "../Mux3FacetBase.sol";
import "./PoolManager.sol";
import "./MarketManager.sol";
import "./CollateralManager.sol";
import "./PricingManager.sol";

contract FacetManagement is
    Mux3FacetBase,
    Mux3RolesAdmin,
    PoolManager,
    MarketManager,
    CollateralManager,
    PricingManager,
    IFacetManagement,
    IBeacon
{
    using LibConfigMap for mapping(bytes32 => bytes32);

    /**
     * @notice Initializes the contract with WETH address
     * @param weth_ The address of the WETH contract
     * @dev Can only be called once due to initializer modifier
     */
    function initialize(address weth_) external initializer {
        __Mux3RolesAdmin_init_unchained();
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        require(weth_ != address(0), InvalidAddress(weth_));
        _weth = weth_;
    }

    /**
     * @notice Returns the implementation address for collateral pools (for beacon proxies)
     * @return The address of the current collateral pool implementation
     */
    function implementation() public view virtual override returns (address) {
        return _collateralPoolImplementation;
    }

    /**
     * @notice Sets a new implementation address for collateral pools (for beacon proxies)
     * @param newImplementation The address of the new implementation contract
     * @dev Only callable by admin role
     */
    function setCollateralPoolImplementation(address newImplementation) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _setImplementation(newImplementation);
        emit SetCollateralPoolImplementation(newImplementation);
    }

    /**
     * @notice Adds a new collateral token to the system
     * @param token The address of the collateral token
     * @param decimals The number of decimals for the token.
     *                 The provided decimals will be verified if the token contract has `decimals()` method.
     * @dev Token cannot be duplicated and cannot be removed
     */
    function addCollateralToken(address token, uint8 decimals, bool isStable) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _addCollateralToken(token, decimals, isStable);
        emit AddCollateralToken(token, decimals, isStable);
    }

    /**
     * @notice Sets whether an oracle ID represents a strict stable asset
     * @param oracleId The ID of the oracle
     * @param strictStable Boolean indicating if the asset is a strict stable
     * @dev A token set to be strict stable indicates that mux will treat the price within the ±dampener as $1.abi
     *      eg: assume the dampener is 0.001, a strict stable price within range of [0.999, 1.001] will be treated as 1.000
     */
    function setStrictStableId(bytes32 oracleId, bool strictStable) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _setStrictStableId(oracleId, strictStable);
        emit SetStrictStableId(oracleId, strictStable);
    }

    /**
     * @notice Sets the oracle provider whitelist
     * @param oracleProvider The address of the oracle provider
     * @param isValid Boolean indicating if the provider is valid
     * @dev An oracle provider provides validation and normalization of the price from external sources
     */
    function setOracleProvider(address oracleProvider, bool isValid) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _setOracleProvider(oracleProvider, isValid);
        emit SetOracleProvider(oracleProvider, isValid);
    }

    /**
     * @notice Creates a new collateral pool, duplicated (name, symbol, collateralToken) are not allowed.
     * @param name The name of the pool token
     * @param symbol The symbol of the pool token
     * @param collateralToken The address of the collateral token
     * @param expectedPoolCount the expected number of pools before creating. this is to prevent from submitting tx twice.
     *                         this number is also the expected index of pools array.
     * @return poolAddress The address of the newly created pool
     */
    function createCollateralPool(
        string memory name,
        string memory symbol,
        address collateralToken,
        uint256 expectedPoolCount
    ) external onlyRole(DEFAULT_ADMIN_ROLE) returns (address poolAddress) {
        require(_isCollateralExist(collateralToken), CollateralNotExist(collateralToken));
        poolAddress = _createCollateralPool(name, symbol, collateralToken, expectedPoolCount);
        emit CreateCollateralPool(
            name,
            symbol,
            collateralToken,
            _collateralTokens[collateralToken].decimals,
            poolAddress
        );
    }

    /**
     * @notice Creates a new market with specified backed pools, duplicated (marketId) are not allowed.
     * @param marketId The unique identifier for the market
     * @param symbol The symbol for the market
     * @param isLong Whether this is a long market
     * @param backedPools Array of pool addresses that back this market
     * @dev Note that the backed pools can be added later but cannot be removed
     */
    function createMarket(
        bytes32 marketId,
        string memory symbol,
        bool isLong,
        address[] memory backedPools
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _createMarket(marketId, symbol, isLong);
        emit CreateMarket(marketId, symbol, isLong, backedPools);
        _appendBackedPoolsToMarket(marketId, backedPools);
        emit AppendBackedPoolsToMarket(marketId, backedPools);
    }

    /**
     * @notice Adds additional backed pools to an existing market
     * @param marketId The ID of the market to modify
     * @param backedPools Array of pool addresses to add
     */
    function appendBackedPoolsToMarket(
        bytes32 marketId,
        address[] memory backedPools
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _appendBackedPoolsToMarket(marketId, backedPools);
        emit AppendBackedPoolsToMarket(marketId, backedPools);
    }

    /**
     * @notice Sets a global configuration value
     * @param key The configuration key
     * @param value The configuration value
     */
    function setConfig(bytes32 key, bytes32 value) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _configs.setBytes32(key, value);
        emit SetConfig(key, value);
    }

    /**
     * @notice Sets a market-specific configuration value
     * @param marketId The ID of the market
     * @param key The configuration key
     * @param value The configuration value
     */
    function setMarketConfig(bytes32 marketId, bytes32 key, bytes32 value) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _setMarketConfig(marketId, key, value);
        emit SetMarketConfig(marketId, key, value);
    }

    /**
     * @notice Sets a pool-specific configuration value
     * @param pool The address of the pool
     * @param key The configuration key
     * @param value The configuration value
     */
    function setPoolConfig(address pool, bytes32 key, bytes32 value) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _setPoolConfigs(pool, key, value);
        emit SetCollateralPoolConfig(pool, key, value);
    }

    /**
     * @notice Sets the price for an oracle ID using specified provider, the provider must be whitelisted by `setOracleProvider`
     * @param oracleId The ID of the oracle
     * @param provider The address of the oracle provider
     * @param oracleCalldata The calldata to be passed to the oracle
     */
    function setPrice(
        bytes32 oracleId,
        address provider,
        bytes memory oracleCalldata
    ) external virtual onlyRole(ORDER_BOOK_ROLE) {
        (uint256 price, uint256 timestamp) = _setPrice(oracleId, provider, oracleCalldata);
        emit SetPrice(oracleId, provider, price, timestamp);
    }
}

File 2 of 42 : IBeaconUpgradeable.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 IBeaconUpgradeable {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

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

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

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

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

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

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

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

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

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

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

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

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

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

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

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

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

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

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

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

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMathUpgradeable {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

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

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

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

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

pragma solidity ^0.8.0;

import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

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

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

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

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        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] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

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.
 *
 * ```solidity
 * 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.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
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) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // 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;

        /// @solidity memory-safe-assembly
        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 in 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;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

File 11 of 42 : 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 12 of 42 : IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.0;

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (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 an {UpgradeableBeacon}.
 *
 * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
 * conflict with the storage layout of the implementation behind the proxy.
 *
 * _Available since v3.4._
 */
contract BeaconProxy is Proxy, ERC1967Upgrade {
    /**
     * @dev Initializes the proxy with `beacon`.
     *
     * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
     * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity
     * constructor.
     *
     * Requirements:
     *
     * - `beacon` must be a contract with the interface {IBeacon}.
     */
    constructor(address beacon, bytes memory data) payable {
        _upgradeBeaconToAndCall(beacon, data, false);
    }

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

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

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

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

pragma solidity ^0.8.0;

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)

pragma solidity ^0.8.2;

import "../beacon/IBeacon.sol";
import "../../interfaces/IERC1967.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._
 */
abstract contract ERC1967Upgrade is IERC1967 {
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// 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 {}
}

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

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

pragma solidity ^0.8.0;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import "../Mux3FacetBase.sol";

contract CollateralManager is Mux3FacetBase {
    using LibConfigMap for mapping(bytes32 => bytes32);
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set;

    function _addCollateralToken(address token, uint8 decimals, bool isStable) internal {
        require(token != address(0), InvalidAddress(token));
        require(!_isCollateralExist(token), CollateralAlreadyExist(token));
        _collateralTokens[token] = CollateralTokenInfo({
            isExist: true,
            decimals: _retrieveDecimals(token, decimals),
            isStable: isStable
        });
        require(
            _collateralTokenList.length < MAX_COLLATERAL_TOKENS,
            CapacityExceeded(MAX_COLLATERAL_TOKENS, _collateralTokenList.length, 1)
        );
        _collateralTokenList.push(token);
    }

    function _setStrictStableId(bytes32 oracleId, bool strictStable) internal {
        _strictStableIds[oracleId] = strictStable;
    }

    function _retrieveDecimals(address token, uint8 defaultDecimals) internal view returns (uint8) {
        try IERC20MetadataUpgradeable(token).decimals() returns (uint8 tokenDecimals) {
            require(tokenDecimals == defaultDecimals, UnmatchedDecimals(tokenDecimals, defaultDecimals));
            return tokenDecimals;
        } catch {
            return defaultDecimals;
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import "../Mux3FacetBase.sol";

contract MarketManager is Mux3FacetBase {
    using LibConfigMap for mapping(bytes32 => bytes32);
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set;

    function _createMarket(bytes32 marketId, string memory symbol, bool isLong) internal {
        require(marketId != bytes32(0), InvalidMarketId(marketId));
        require(!_isMarketExist(marketId), MarketAlreadyExist(marketId));
        // create market
        _markets[marketId].symbol = symbol;
        _markets[marketId].isLong = isLong;
        require(_marketList.length() < MAX_MARKETS, CapacityExceeded(MAX_MARKETS, _marketList.length(), 1));
        require(_marketList.add(marketId), ArrayAppendFailed());
    }

    function _appendBackedPoolsToMarket(bytes32 marketId, address[] memory backedPools) internal {
        require(_isMarketExist(marketId), MarketNotExists(marketId));
        require(backedPools.length > 0, InvalidArrayLength(backedPools.length, 0));
        uint256 count = backedPools.length;
        MarketInfo storage market = _markets[marketId];
        require(
            market.pools.length + count <= MAX_MARKET_BACKED_POOLS,
            CapacityExceeded(MAX_MARKET_BACKED_POOLS, market.pools.length, count)
        );
        for (uint256 i = 0; i < count; i++) {
            address newBackedPool = backedPools[i];
            require(_isPoolExist(newBackedPool), PoolNotExists(newBackedPool));
            // this pool is not one of the existing backed pools
            for (uint256 j = 0; j < market.pools.length; j++) {
                require(market.pools[j].backedPool != newBackedPool, PoolAlreadyExist(newBackedPool));
            }
            market.pools.push(BackedPoolState({ backedPool: newBackedPool }));
            ICollateralPool(newBackedPool).setMarket(marketId, market.isLong);
        }
    }

    function _setMarketConfig(bytes32 marketId, bytes32 key, bytes32 value) internal {
        require(_isMarketExist(marketId), MarketNotExists(marketId));
        _markets[marketId].configs.setBytes32(key, value);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "@openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";

import "../Mux3FacetBase.sol";

contract PoolManager is Mux3FacetBase {
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;

    function _setImplementation(address newImplementation) internal {
        require(newImplementation != address(0), InvalidAddress(newImplementation));
        require(newImplementation != _collateralPoolImplementation, DuplicatedAddress(newImplementation));
        _collateralPoolImplementation = newImplementation;
    }

    function _createCollateralPool(
        string memory name,
        string memory symbol,
        address collateralToken,
        uint256 expectedPoolCount // the expected number of pools before creating
    ) internal returns (address) {
        require(collateralToken != address(0), InvalidAddress(collateralToken));
        address pool = _createPoolProxy(name, symbol, collateralToken);
        require(address(pool) != address(0), InvalidAddress(pool));
        require(
            _collateralPoolList.length() == expectedPoolCount,
            UnexpectedState(_collateralPoolList.length(), expectedPoolCount)
        );
        require(
            _collateralPoolList.length() < MAX_COLLATERAL_POOLS,
            CapacityExceeded(MAX_COLLATERAL_POOLS, _collateralPoolList.length(), 1)
        );
        require(_collateralPoolList.add(address(pool)), PoolAlreadyExist(pool));
        return address(pool);
    }

    function _setPoolConfigs(address pool, bytes32 key, bytes32 value) internal {
        require(pool != address(0), InvalidAddress(pool));
        require(_isPoolExist(pool), PoolNotExists(pool));
        ICollateralPool(pool).setConfig(key, value);
    }

    function _getProxyId(
        string memory name,
        string memory symbol,
        address collateralToken
    ) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(name, symbol, collateralToken));
    }

    function _getBytesCode(
        string memory name,
        string memory symbol,
        address collateralToken
    ) internal view returns (bytes memory) {
        bytes memory initCallData = abi.encodeWithSignature(
            "initialize(string,string,address)",
            name,
            symbol,
            collateralToken
        );
        bytes memory byteCode = abi.encodePacked(
            type(BeaconProxy).creationCode,
            abi.encode(address(this), initCallData)
        );
        return byteCode;
    }

    function _createPoolProxy(
        string memory name,
        string memory symbol,
        address collateralToken
    ) internal returns (address) {
        bytes memory byteCode = _getBytesCode(name, symbol, collateralToken);
        bytes32 salt = _getProxyId(name, symbol, collateralToken);
        return _createProxy(byteCode, salt);
    }

    function _createProxy(bytes memory bytecode, bytes32 salt) internal returns (address proxy) {
        assembly {
            proxy := create2(0x0, add(0x20, bytecode), mload(bytecode), salt)
        }
        require(proxy != address(0), CreateProxyFailed());
    }

    function _getPoolAddress(
        string memory name,
        string memory symbol,
        address collateralToken
    ) internal view returns (address) {
        bytes memory byteCode = _getBytesCode(name, symbol, collateralToken);
        bytes32 salt = _getProxyId(name, symbol, collateralToken);
        return _getAddress(byteCode, salt);
    }

    function _getAddress(bytes memory bytecode, bytes32 salt) internal view returns (address) {
        bytes32 hash = keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, keccak256(bytecode)));
        return address(uint160(uint256(hash)));
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "../../interfaces/IPriceProvider.sol";
import "../Mux3FacetBase.sol";

contract PricingManager is Mux3FacetBase {
    using LibTypeCast for bytes32;
    uint256 constant STABLE_TOKEN_PRICE = 1e18;

    function _setPrice(
        bytes32 oracleId,
        address provider,
        bytes memory oracleCallData
    ) internal returns (uint256 price, uint256 timestamp) {
        require(oracleId != bytes32(0), InvalidId("oracleId"));
        require(provider != address(0), InvalidAddress(provider));
        (price, timestamp) = IPriceProvider(provider).getOraclePrice(oracleId, oracleCallData);
        if (_strictStableIds[oracleId]) {
            uint256 deviation = _strictStableDeviation();
            uint256 tolerance = (STABLE_TOKEN_PRICE * deviation) / 1e18;
            if (STABLE_TOKEN_PRICE + tolerance >= price && price >= STABLE_TOKEN_PRICE - tolerance) {
                price = STABLE_TOKEN_PRICE;
            }
        }
        _setCachedPrice(oracleId, price);
    }

    function _setCachedPrice(bytes32 oracleId, uint256 price) internal {
        _writeCacheUint256(oracleId, price);
    }

    function _writeCacheUint256(bytes32 key, uint256 n) internal {
        assembly {
            tstore(key, n)
        }
    }

    function _setOracleProvider(address oracleProvider, bool isValid) internal {
        require(oracleProvider != address(0), InvalidAddress(oracleProvider));
        _oracleProviders[oracleProvider] = isValid;
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";

import "../interfaces/IConstants.sol";
import "../libraries/LibConfigMap.sol";
import "../libraries/LibTypeCast.sol";
import "./Mux3Store.sol";

contract Mux3Computed is Mux3Store, IErrors {
    using LibTypeCast for int256;
    using LibTypeCast for uint256;
    using LibConfigMap for mapping(bytes32 => bytes32);
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set;

    function _swapper() internal view returns (address swapper) {
        swapper = _configs.getAddress(MC_SWAPPER);
        require(swapper != address(0), EssentialConfigNotSet("MC_SWAPPER"));
    }

    function _priceOf(address token) internal view virtual returns (uint256 price) {
        price = _priceOf(bytes32(bytes20(token)));
    }

    function _priceOf(bytes32 oracleId) internal view virtual returns (uint256 price) {
        price = uint256(_readCacheUint256(oracleId));
        require(price > 0, MissingPrice(oracleId));
    }

    function _isOracleProvider(address oracleProvider) internal view returns (bool isProvider) {
        isProvider = _oracleProviders[oracleProvider];
    }

    function _isPoolExist(address pool) internal view returns (bool isExist) {
        isExist = _collateralPoolList.contains(pool);
    }

    function _isCollateralExist(address token) internal view returns (bool isExist) {
        isExist = _collateralTokens[token].isExist;
    }

    function _isMarketExist(bytes32 marketId) internal view returns (bool isExist) {
        isExist = _marketList.contains(marketId);
    }

    function _collateralToWad(address collateralToken, uint256 rawAmount) internal view returns (uint256 wadAmount) {
        uint8 decimals = _collateralTokens[collateralToken].decimals;
        if (decimals <= 18) {
            wadAmount = rawAmount * (10 ** (18 - decimals));
        } else {
            wadAmount = rawAmount / (10 ** (decimals - 18));
        }
    }

    function _collateralToRaw(address collateralToken, uint256 wadAmount) internal view returns (uint256 rawAmount) {
        uint8 decimals = _collateralTokens[collateralToken].decimals;
        if (decimals <= 18) {
            rawAmount = wadAmount / 10 ** (18 - decimals);
        } else {
            rawAmount = wadAmount * 10 ** (decimals - 18);
        }
    }

    function _marketPositionFeeRate(bytes32 marketId) internal view returns (uint256 rate) {
        rate = _markets[marketId].configs.getUint256(MM_POSITION_FEE_RATE);
        // 0 is valid
    }

    function _marketLiquidationFeeRate(bytes32 marketId) internal view returns (uint256 rate) {
        rate = _markets[marketId].configs.getUint256(MM_LIQUIDATION_FEE_RATE);
        // 0 is valid
    }

    function _marketInitialMarginRate(bytes32 marketId) internal view returns (uint256 rate) {
        rate = _markets[marketId].configs.getUint256(MM_INITIAL_MARGIN_RATE);
        require(rate > 0, EssentialConfigNotSet("MM_INITIAL_MARGIN_RATE"));
    }

    function _marketOracleId(bytes32 marketId) internal view returns (bytes32 oracleId) {
        oracleId = _markets[marketId].configs.getBytes32(MM_ORACLE_ID);
        require(oracleId != bytes32(0), EssentialConfigNotSet("MM_ORACLE_ID"));
    }

    function _marketOpenInterestCap(bytes32 marketId) internal view returns (uint256 capUsd) {
        capUsd = _markets[marketId].configs.getUint256(MM_OPEN_INTEREST_CAP_USD);
        require(capUsd > 0, EssentialConfigNotSet("MM_OPEN_INTEREST_CAP_USD"));
    }

    function _marketDisableTrade(bytes32 marketId) internal view returns (bool isDisabled) {
        isDisabled = _markets[marketId].configs.getBoolean(MM_DISABLE_TRADE);
    }

    function _marketDisableOpen(bytes32 marketId) internal view returns (bool isDisabled) {
        isDisabled = _markets[marketId].configs.getBoolean(MM_DISABLE_OPEN);
    }

    function _marketMaintenanceMarginRate(bytes32 marketId) internal view returns (uint256 rate) {
        rate = _markets[marketId].configs.getUint256(MM_MAINTENANCE_MARGIN_RATE);
        // 0 is valid
    }

    function _marketLotSize(bytes32 marketId) internal view returns (uint256 lotSize) {
        lotSize = _markets[marketId].configs.getUint256(MM_LOT_SIZE);
        require(lotSize > 0, EssentialConfigNotSet("MM_LOT_SIZE"));
    }

    function _feeDistributor() internal view returns (address feeDistributor) {
        feeDistributor = _configs.getAddress(MC_FEE_DISTRIBUTOR);
        require(feeDistributor != address(0), EssentialConfigNotSet("MC_FEE_DISTRIBUTOR"));
    }

    function _readCacheUint256(bytes32 key) internal view returns (bytes32 value) {
        assembly {
            value := tload(key)
        }
    }

    function _strictStableDeviation() internal view returns (uint256 deviation) {
        deviation = _configs.getUint256(MC_STRICT_STABLE_DEVIATION);
        require(deviation > 0, EssentialConfigNotSet("MC_STRICT_STABLE_DEVIATION"));
    }

    /**
     * @dev Get active collaterals of a trader
     *
     * @param lastConsumedToken optional. try to avoid consuming this token if possible.
     */
    function _activeCollateralsWithLastWithdraw(
        bytes32 positionId,
        address lastConsumedToken
    ) internal view returns (address[] memory collaterals) {
        collaterals = _positionAccounts[positionId].activeCollaterals.values();
        if (lastConsumedToken == address(0)) {
            return collaterals;
        }
        uint256 length = collaterals.length;
        if (length <= 1) {
            return collaterals;
        }
        // swap lastConsumedToken to the end
        for (uint256 i = 0; i < length - 1; i++) {
            if (collaterals[i] == lastConsumedToken) {
                collaterals[i] = collaterals[length - 1];
                collaterals[length - 1] = lastConsumedToken;
                break;
            }
        }
    }
}

File 24 of 42 : Mux3FacetBase.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "./Mux3Store.sol";
import "./Mux3Computed.sol";

contract Mux3FacetBase is Mux3Store, Mux3Computed {}

File 25 of 42 : Mux3Store.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

import "../interfaces/IMux3Core.sol";
import "../interfaces/IMarket.sol";
import "../interfaces/ICollateralPool.sol";
import "../libraries/LibMux3Roles.sol";

contract Mux3Store is Mux3RolesStore {
    mapping(bytes32 => bytes32) internal _configs;
    // collaterals
    address[] internal _collateralTokenList; // collateralAddresses
    mapping(address => CollateralTokenInfo) internal _collateralTokens; // collateralAddress => CollateralTokenInfo
    // accounts
    mapping(bytes32 => PositionAccountInfo) internal _positionAccounts; // positionId => PositionAccountInfo
    mapping(address => EnumerableSetUpgradeable.Bytes32Set) internal _positionIdListOf; // trader => positionIds. this list never recycles (because Trader can store some settings in position accounts which are never destroyed)
    // pools
    EnumerableSetUpgradeable.AddressSet internal _collateralPoolList; // collateralPoolAddresses
    // markets
    mapping(bytes32 => MarketInfo) internal _markets; // marketId => MarketInfo
    EnumerableSetUpgradeable.Bytes32Set internal _marketList; // marketIds
    // pool imp
    address internal _collateralPoolImplementation;
    // oracle
    mapping(address => bool) internal _oracleProviders; // oracleProviderAddress => isOracleProvider
    address internal _weth;
    mapping(bytes32 => bool) internal _strictStableIds; // oracleId => isStrictStable
    // accounts
    EnumerableSetUpgradeable.Bytes32Set internal _activatePositionIdList; // positionId that has positions. positionId with only collateral may not be in this list

    bytes32[47] private __gaps;
}

File 26 of 42 : IBorrowingRate.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

library IBorrowingRate {
    struct Global {
        int256 baseApy;
    }

    /**
     * @dev Borrowing config
     *
     *      k != 0
     *      reserveRate > 0
     *      0e18 < k + b < 10e18
     */
    struct AllocatePool {
        uint256 poolId; // the allocator does not care what is a poolId, you can use any index or address here
        int256 k;
        int256 b;
        int256 poolSizeUsd;
        int256 reservedUsd;
        int256 reserveRate;
        bool isDraining; // whether this pool is draining (only supports deallocate, not allocate)
    }

    struct AllocateResult {
        uint256 poolId; // the allocator does not care what is a poolId, you can use any index or address here
        int256 xi; // result of allocation. unit is usd
    }

    struct DeallocatePool {
        uint256 poolId; // the deallocator does not care what is a poolId, you can use any index or address here
        int256 mySizeForPool; // not necessarily usd. we even do not care about the unit of "mySizeForPool"
    }

    struct DeallocateResult {
        uint256 poolId; // the allocator does not care what is a poolId, you can use any index or address here
        int256 xi; // not necessarily usd. we even do not care about the unit of "mySizeForPool"
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "../interfaces/IBorrowingRate.sol";

struct MarketState {
    bool isLong;
    uint256 totalSize;
    uint256 averageEntryPrice;
    uint256 cumulatedBorrowingPerUsd; // $borrowingFee / $positionValue, always increasing
    uint256 lastBorrowingUpdateTime;
}

interface ICollateralPool {
    function setConfig(bytes32 key, bytes32 value) external;

    function configValue(bytes32 key) external view returns (bytes32);

    function collateralToken() external view returns (address);

    function borrowingFeeRateApy(bytes32 marketId) external view returns (uint256 feeRateApy);

    function markets() external view returns (bytes32[] memory);

    function marketState(bytes32 marketId) external view returns (MarketState memory);

    function marketStates() external view returns (bytes32[] memory marketIds, MarketState[] memory states);

    function setMarket(bytes32 marketId, bool isLong) external;

    function liquidityBalances() external view returns (address[] memory tokens, uint256[] memory balances);

    function getCollateralTokenUsd() external view returns (uint256);

    function getAumUsd() external view returns (uint256);

    function getReservedUsd() external view returns (uint256);

    function openPosition(bytes32 marketId, uint256 size, uint256 entryPrice) external;

    function closePosition(bytes32 marketId, uint256 size, uint256 entryPrice) external;

    function realizeProfit(
        uint256 pnlUsd
    )
        external
        returns (
            address token,
            uint256 wad // 1e18
        );

    function realizeLoss(
        address token,
        uint256 rawAmount // token decimals
    ) external;

    struct AddLiquidityArgs {
        address account; // lp address
        uint256 rawCollateralAmount; // token in. token decimals
        bool isUnwrapWeth; // useful for discount
    }

    struct AddLiquidityResult {
        uint256 shares;
        uint256 collateralPrice;
        uint256 lpPrice;
    }

    function addLiquidity(AddLiquidityArgs memory args) external returns (AddLiquidityResult memory result);

    struct RemoveLiquidityArgs {
        address account; // lp address
        uint256 shares; // token in. 1e18
        address token; // token out
        bool isUnwrapWeth; // useful for discount
        uint256 extraFeeCollateral; // 1e18. send to OrderBook
    }

    struct RemoveLiquidityResult {
        uint256 rawCollateralAmount; // token out. token decimals
        uint256 collateralPrice;
        uint256 lpPrice;
    }

    function removeLiquidity(RemoveLiquidityArgs memory args) external returns (RemoveLiquidityResult memory result);

    function rebalance(
        address rebalancer,
        address token0,
        uint256 rawAmount0, // token0 decimals
        uint256 maxRawAmount1, // collateralToken decimals
        bytes memory userData
    ) external returns (uint256 rawAmount1);

    function receiveFee(
        address token,
        uint256 rawAmount // token.decimals
    ) external;

    function updateMarketBorrowing(bytes32 marketId) external returns (uint256 newCumulatedBorrowingPerUsd);

    function makeBorrowingContext(bytes32 marketId) external view returns (IBorrowingRate.AllocatePool memory);

    function positionPnl(
        bytes32 marketId,
        uint256 size,
        uint256 entryPrice,
        uint256 marketPrice
    ) external view returns (int256 pnlUsd, int256 cappedPnlUsd);
}

File 28 of 42 : IConstants.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "./IRoles.sol";
import "./IErrors.sol";
import "./IKeys.sol";
import "./ILimits.sol";

File 29 of 42 : IErrors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

interface IErrors {
    // config
    error EssentialConfigNotSet(string key);
    error CapacityExceeded(uint256 capacity, uint256 old, uint256 appending);
    error UnexpectedState(uint256 expected, uint256 actual);

    // params
    error InvalidId(string key);
    error InvalidAmount(string key);
    error InvalidAddress(address addr);
    error InvalidArrayLength(uint256 a, uint256 b);
    error InvalidLotSize(uint256 positionSize, uint256 lotSize);
    error InvalidDecimals(uint256 decimals);
    error UnmatchedDecimals(uint256 decimals, uint256 expectDecimals);
    error InvalidCloseSize(uint256 closingSize, uint256 positionSize);

    // price
    error InvalidPriceTimestamp(uint256 timestamp);
    error MissingPrice(bytes32 oracleId);
    error LimitPriceNotMet(uint256 expected, uint256 actual);

    // access control
    error NotOwner(bytes32 positionId, address caller, address owner);
    error UnauthorizedRole(bytes32 requiredRole, address caller);
    error UnauthorizedAgent(address account, bytes32 positionId);
    error UnauthorizedCaller(address caller);

    // collateral
    error CollateralAlreadyExist(address tokenAddress);
    error CollateralNotExist(address tokenAddress);

    // market
    error InvalidMarketId(bytes32 marketId);
    error MarketNotExists(bytes32 marketId);
    error MarketAlreadyExist(bytes32 marketId);
    error MarketTradeDisabled(bytes32 marketId);
    error MarketFull();

    // pool
    error InsufficientLiquidity(uint256 requiredLiquidity, uint256 liquidityBalance); // 1e18, 1e18
    error DuplicatedAddress(address pool);
    error PoolAlreadyExist(address pool);
    error PoolNotExists(address pool);
    error CreateProxyFailed();
    error PoolBankrupt();

    // account
    error PositionAccountAlreadyExist(bytes32 positionId);
    error PositionAccountNotExist(bytes32 positionId);
    error UnsafePositionAccount(bytes32 positionId, uint256 safeType);
    error SafePositionAccount(bytes32 positionId, uint256 safeType);
    error InsufficientCollateralBalance(address collateralToken, uint256 balance, uint256 requiredAmount);
    error InsufficientCollateralUsd(uint256 requiredUsd, uint256 remainUsd);
    error InsufficientCollateral(uint256 required, uint256 remain);
    error InitialLeverageOutOfRange(uint256 leverage, uint256 leverageLimit);
    error PositionNotClosed(bytes32 positionId);
    error OnlySingleMarketPositionAllowed(bytes32 positionId);

    // potential bugs
    error ArrayAppendFailed();
    error AllocationLengthMismatch(uint256 len1, uint256 len2);
    error AllocationPositionMismatch(uint256 positionSize1, uint256 positionSize2);
    error OutOfBound(uint256 index, uint256 length);
    error BadAllocation(int256 maxX, int256 xi);

    // oracle
    error InvalidPrice(uint256 price);
    error InvalidPriceExpiration(uint256 expiration);
    error PriceExpired(uint256 timestamp, uint256 blockTimestamp);
    error IdMismatch(bytes32 id, bytes32 expectedId);
    error MissingSignature();
    error InvalidSequence(uint256 sequence, uint256 expectedSequence);
    error InvalidSinger(address signer);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

interface IFacetManagement {
    event AddCollateralToken(address token, uint8 decimals, bool isStable);
    event SetStrictStableId(bytes32 oracleId, bool strictStable);
    event CreateCollateralPool(string name, string symbol, address collateral, uint8 collateralDecimals, address pool);
    event AppendBackedPoolsToMarket(bytes32 marketId, address[] backedPools);
    event SetCollateralPoolImplementation(address newImplementation);
    event CreateMarket(bytes32 marketId, string symbol, bool isLong, address[] backedPools);
    event SetConfig(bytes32 key, bytes32 value);
    event SetMarketConfig(bytes32 marketId, bytes32 key, bytes32 value);
    event SetCollateralPoolConfig(address pool, bytes32 key, bytes32 value);
    event SetCollateralTokenEnabled(address token, bool enabled);
    event SetOracleProvider(address oracleProvider, bool isValid);
    event SetPrice(bytes32 oracleId, address provider, uint256 price, uint256 timestamp);

    function setPrice(bytes32 oracleId, address provider, bytes memory oracleCalldata) external;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "../interfaces/IPositionAccount.sol";
import "../interfaces/IMarket.sol";

struct AccountReader {
    bytes32 positionId;
    CollateralReader[] collaterals;
    PositionReader[] positions;
}

struct CollateralReader {
    address collateralAddress;
    uint256 collateralAmount;
}

struct PositionReader {
    bytes32 marketId;
    uint256 initialLeverage;
    uint256 lastIncreasedTime;
    uint256 realizedBorrowingUsd;
    PositionPoolReader[] pools;
}

struct PositionPoolReader {
    address poolAddress;
    uint256 size;
    uint256 entryPrice;
    uint256 entryBorrowing;
}

interface IFacetReader {
    /**
     * @dev Get price of a token
     */
    function priceOf(address token) external view returns (uint256 price);

    /**
     * @dev Get price of an OracleId
     */
    function priceOf(bytes32 oracleId) external view returns (uint256 price);

    /**
     * @dev Get core global config
     */
    function configValue(bytes32 key) external view returns (bytes32 value);

    /**
     * @dev Get Market config
     */
    function marketConfigValue(bytes32 marketId, bytes32 key) external view returns (bytes32 value);

    /**
     * @dev Get Market state
     */
    function marketState(bytes32 marketId) external view returns (string memory symbol, bool isLong);

    /**
     * @dev Get Collateral config
     */
    function getCollateralToken(address token) external view returns (bool isExist, uint8 decimals, bool isStable);

    /**
     * @dev List collateral tokens
     */
    function listCollateralTokens() external view returns (address[] memory tokens);

    /**
     * @dev Get CollateralPool config
     */
    function getCollateralPool(address pool) external view returns (bool isExist);

    /**
     * @dev List CollateralPool addresses
     */
    function listCollateralPool() external view returns (address[] memory pools);

    /**
     * @dev List Markets
     */
    function listMarkets() external view returns (bytes32[] memory marketIds);

    /**
     * @dev List backed CollateralPool in a Market
     */
    function listMarketPools(bytes32 marketId) external view returns (BackedPoolState[] memory pools);

    /**
     * @dev List PositionIds of a Trader
     */
    function listPositionIdsOf(address trader) external view returns (bytes32[] memory positionIds);

    /**
     * @dev List active PositionIds
     *
     *      "active" means positionId that likely has positions. positionId with only collateral may not be in this list
     */
    function listActivePositionIds(
        uint256 begin,
        uint256 end
    ) external view returns (bytes32[] memory positionIds, uint256 totalLength);

    /**
     * @dev Get Position of (positionId, marketId)
     */
    function getPositionAccount(
        bytes32 positionId,
        bytes32 marketId
    ) external view returns (PositionReader memory position);

    /**
     * @dev List Collaterals of a PositionAccount
     */
    function listAccountCollaterals(bytes32 positionId) external view returns (CollateralReader[] memory collaterals);

    /**
     * @dev List Positions of a PositionAccount
     */
    function listAccountPositions(bytes32 positionId) external view returns (PositionReader[] memory positions);

    /**
     * @dev List Collaterals and Positions of all PositionAccounts of a Trader
     */
    function listCollateralsAndPositionsOf(address trader) external view returns (AccountReader[] memory positions);

    /**
     * @dev List active Collaterals and Positions
     *
     *      "active" means positionId that likely has positions. positionId with only collateral may not be in this list
     */
    function listActiveCollateralsAndPositions(
        uint256 begin,
        uint256 end
    ) external view returns (AccountReader[] memory positions, uint256 totalLength);

    /**
     * @dev Check if deleverage is allowed
     */
    function isDeleverageAllowed(bytes32 positionId, bytes32 marketId) external view returns (bool);
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "./IConstants.sol";

interface IFacetOpen {
    event OpenPosition(
        address indexed owner,
        bytes32 indexed positionId,
        bytes32 indexed marketId,
        bool isLong,
        uint256 size,
        uint256 tradingPrice,
        address[] backedPools,
        uint256[] allocations, // 1e18
        uint256[] newSizes, // 1e18
        uint256[] newEntryPrices, // 1e18
        uint256 positionFeeUsd, // 1e18
        uint256 borrowingFeeUsd, // 1e18
        address[] newCollateralTokens,
        uint256[] newCollateralAmounts // 1e18
    );

    event ReallocatePosition(
        address indexed owner,
        bytes32 indexed positionId,
        bytes32 indexed marketId,
        bool isLong,
        address fromPool,
        address toPool,
        uint256 size,
        uint256 tradingPrice, // the price for settling between pools
        uint256 fromPoolOldEntryPrice, // previous entry price from the fromPool
        address[] backedPools,
        uint256[] newSizes,
        uint256[] newEntryPrices,
        // reallocation doesn't settle upnl for the PositionAccount.
        // this represents pnL settlement between pools where only the fromPool generates pnl
        int256[] poolPnlUsds,
        uint256 borrowingFeeUsd, // 1e18
        address[] newCollateralTokens,
        uint256[] newCollateralAmounts
    );

    struct OpenPositionArgs {
        bytes32 positionId;
        bytes32 marketId;
        uint256 size;
        address lastConsumedToken;
        bool isUnwrapWeth;
    }

    struct OpenPositionResult {
        uint256 tradingPrice;
        uint256 borrowingFeeUsd;
        uint256 positionFeeUsd;
    }

    struct ReallocatePositionArgs {
        bytes32 positionId;
        bytes32 marketId;
        address fromPool;
        address toPool;
        uint256 size;
        address lastConsumedToken;
        bool isUnwrapWeth;
    }

    struct ReallocatePositionResult {
        uint256 tradingPrice;
        uint256 borrowingFeeUsd;
        // note: reallocate does not settle upnl for this PositionAccount
    }

    function openPosition(OpenPositionArgs memory args) external returns (OpenPositionResult memory result);

    function reallocatePosition(
        ReallocatePositionArgs memory args
    ) external returns (ReallocatePositionResult memory result);
}

interface IFacetClose {
    event ClosePosition(
        address indexed owner,
        bytes32 indexed positionId,
        bytes32 indexed marketId,
        bool isLong,
        uint256 size, // closing
        uint256 tradingPrice,
        address[] backedPools,
        uint256[] allocations, // 1e18
        uint256[] newSizes, // 1e18
        uint256[] newEntryPrices, // 1e18
        int256[] poolPnlUsds, // 1e18
        uint256 positionFeeUsd, // 1e18
        uint256 borrowingFeeUsd, // 1e18
        address[] newCollateralTokens,
        uint256[] newCollateralAmounts // 1e18
    );

    event LiquidatePosition(
        address indexed owner,
        bytes32 indexed positionId,
        bytes32 indexed marketId,
        bool isLong,
        uint256 size, // size before liquidate = liquidate size
        uint256 tradingPrice, // 1e18
        address[] backedPools,
        uint256[] allocations, // 1e18
        int256[] poolPnlUsds, // 1e18
        uint256 positionFeeUsd, // 1e18
        uint256 borrowingFeeUsd, // 1e18
        address[] newCollateralTokens,
        uint256[] newCollateralAmounts // 1e18
    );

    struct ClosePositionArgs {
        bytes32 positionId;
        bytes32 marketId;
        uint256 size;
        address lastConsumedToken;
        bool isUnwrapWeth;
    }

    struct ClosePositionResult {
        uint256 tradingPrice;
        int256[] poolPnlUsds;
        uint256 borrowingFeeUsd;
        uint256 positionFeeUsd;
    }

    function closePosition(ClosePositionArgs memory args) external returns (ClosePositionResult memory result);

    struct LiquidateArgs {
        bytes32 positionId;
        address lastConsumedToken;
        bool isUnwrapWeth;
    }

    struct LiquidatePositionResult {
        bytes32 marketId;
        uint256 tradingPrice;
        int256[] poolPnlUsds;
        uint256 borrowingFeeUsd;
        uint256 positionFeeUsd;
    }

    struct LiquidateResult {
        LiquidatePositionResult[] positions;
    }

    function liquidate(LiquidateArgs memory args) external returns (LiquidateResult memory result);
}

interface IFacetPositionAccount {
    event Deposit(
        address indexed owner,
        bytes32 indexed positionId,
        address collateralToken,
        uint256 collateralAmount // token.decimals
    );

    event Withdraw(
        address indexed owner,
        bytes32 indexed positionId,
        address collateralToken,
        uint256 collateralWad, // 1e18
        address withdrawToken, // if swap, this is the tokeOut. if not swap, this is the collateralToken
        uint256 withdrawAmount // token.decimals
    );

    event DepositWithdrawFinish(
        address indexed owner,
        bytes32 indexed positionId,
        uint256 borrowingFeeUsd, // 1e18
        address[] newCollateralTokens,
        uint256[] newCollateralAmounts
    );

    event CreatePositionAccount(address indexed owner, uint256 index, bytes32 indexed positionId);

    event SetInitialLeverage(address indexed owner, bytes32 indexed positionId, bytes32 marketId, uint256 leverage);

    event UpdatePositionBorrowingFee(
        address indexed owner,
        bytes32 indexed positionId,
        bytes32 indexed marketId,
        uint256 borrowingFeeUsd
    );

    function setInitialLeverage(bytes32 positionId, bytes32 marketId, uint256 leverage) external;

    function deposit(bytes32 positionId, address collateralToken, uint256 amount) external;

    struct WithdrawArgs {
        bytes32 positionId;
        address collateralToken;
        uint256 amount;
        address lastConsumedToken;
        bool isUnwrapWeth;
        address withdrawSwapToken;
        uint256 withdrawSwapSlippage;
    }

    function withdraw(WithdrawArgs memory args) external;

    struct WithdrawAllArgs {
        bytes32 positionId;
        bool isUnwrapWeth;
        address withdrawSwapToken;
        uint256 withdrawSwapSlippage;
    }

    function withdrawAll(WithdrawAllArgs memory args) external;

    struct WithdrawUsdArgs {
        bytes32 positionId;
        uint256 collateralUsd; // 1e18
        address lastConsumedToken;
        bool isUnwrapWeth;
        address withdrawSwapToken;
        uint256 withdrawSwapSlippage;
    }

    function withdrawUsd(WithdrawUsdArgs memory args) external;

    function updateBorrowingFee(
        bytes32 positionId,
        bytes32 marketId,
        address lastConsumedToken,
        bool isUnwrapWeth
    ) external;
}

File 33 of 42 : IKeys.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

// ==================== core ====================

// borrowingFeeRate = MC_BORROWING_BASE_APY + E^(MCP_BORROWING_K * util + MCP_BORROWING_B),
// where util = reservedUsd / poolSizeUsd. decimals = 18
bytes32 constant MC_BORROWING_BASE_APY = keccak256("MC_BORROWING_BASE_APY");

// an interval in seconds. CollateralPool collects borrowing fee every interval
bytes32 constant MC_BORROWING_INTERVAL = keccak256("MC_BORROWING_INTERVAL");

// an IMux3FeeDistributor address that receives positionFee, borrowingFee and liquidityFee
bytes32 constant MC_FEE_DISTRIBUTOR = keccak256("MC_FEE_DISTRIBUTOR");

// an ISwapper address that swaps collateral/profit to another collateral token when requested by trader
bytes32 constant MC_SWAPPER = keccak256("MC_SWAPPER");

// for collateral tokens marked as strict stable via IFacetManagement.setStrictStableId,
// oracle prices within the range [1 - MC_STRICT_STABLE_DEVIATION, 1 + MC_STRICT_STABLE_DEVIATION] are normalized to 1.000
// decimals = 18
bytes32 constant MC_STRICT_STABLE_DEVIATION = keccak256("MC_STRICT_STABLE_DEVIATION");

// rebalance slippage between two tokens. decimals = 18
bytes32 constant MC_REBALANCE_SLIPPAGE = keccak256("MC_REBALANCE_SLIPPAGE");

// ==================== market ====================

// positionFee = price * size * MM_POSITION_FEE_RATE when openPosition/closePosition. decimals = 18
bytes32 constant MM_POSITION_FEE_RATE = keccak256("MM_POSITION_FEE_RATE");

// positionFee = price * size * MM_LIQUIDATION_FEE_RATE when liquidatePosition. decimals = 18
bytes32 constant MM_LIQUIDATION_FEE_RATE = keccak256("MM_LIQUIDATION_FEE_RATE");

// when openPosition, require marginBalance >= Σ(price * size * MM_INITIAL_MARGIN_RATE). decimals = 18
bytes32 constant MM_INITIAL_MARGIN_RATE = keccak256("MM_INITIAL_MARGIN_RATE");

// when marginBalance < Σ(price * size * MM_MAINTENANCE_MARGIN_RATE), liquidate is allowed. decimals = 18
bytes32 constant MM_MAINTENANCE_MARGIN_RATE = keccak256("MM_MAINTENANCE_MARGIN_RATE");

// openPosition/closePosition/liquidatePosition size must be a multiple of MM_LOT_SIZE. decimals = 18
bytes32 constant MM_LOT_SIZE = keccak256("MM_LOT_SIZE");

// market price is identified and fetched from oracle using this ID
bytes32 constant MM_ORACLE_ID = keccak256("MM_ORACLE_ID");

// pause trade of a market
bytes32 constant MM_DISABLE_TRADE = keccak256("MM_DISABLE_TRADE");

// pause openPosition of a market. if MM_DISABLE_OPEN && !MM_DISABLE_TRADE, only closePosition is allowed
bytes32 constant MM_DISABLE_OPEN = keccak256("MM_DISABLE_OPEN");

// the maximum open interest limit for a single market. the open interest is constrained by both
// this cap and MCP_ADL_RESERVE_RATE of each pool. decimals = 18
bytes32 constant MM_OPEN_INTEREST_CAP_USD = keccak256("MM_OPEN_INTEREST_CAP_USD");

// ==================== pool ====================

// if not empty, override CollateralPool ERC20 name
bytes32 constant MCP_TOKEN_NAME = keccak256("MCP_TOKEN_NAME");

// if not empty, override CollateralPool ERC20 symbol
bytes32 constant MCP_TOKEN_SYMBOL = keccak256("MCP_TOKEN_SYMBOL");

// liquidityFee = price * liquidity * MCP_LIQUIDITY_FEE_RATE. decimals = 18
bytes32 constant MCP_LIQUIDITY_FEE_RATE = keccak256("MCP_LIQUIDITY_FEE_RATE");

// reject addLiquidity if aumUsdWithoutPnl > MCP_LIQUIDITY_CAP_USD. decimals = 18
bytes32 constant MCP_LIQUIDITY_CAP_USD = keccak256("MCP_LIQUIDITY_CAP_USD");

// borrowingFeeRate = MC_BORROWING_BASE_APY + E^(MCP_BORROWING_K * util + MCP_BORROWING_B), where util = reservedUsd / poolSizeUsd
bytes32 constant MCP_BORROWING_K = keccak256("MCP_BORROWING_K");

// borrowingFeeRate = MC_BORROWING_BASE_APY + E^(MCP_BORROWING_K * util + MCP_BORROWING_B), where util = reservedUsd / poolSizeUsd
bytes32 constant MCP_BORROWING_B = keccak256("MCP_BORROWING_B");

// if true, allocate algorithm will skip this CollateralPool when openPosition
bytes32 constant MCP_IS_DRAINING = keccak256("MCP_IS_DRAINING");

// ==================== pool + market ====================

// reserve = (entryPrice or marketPrice) * positions * MCP_ADL_RESERVE_RATE. affects borrowing fee rate and open interest.
// the open interest is constrained by both this rate and MM_OPEN_INTEREST_CAP_USD of the market. decimals = 18
bytes32 constant MCP_ADL_RESERVE_RATE = keccak256("MCP_ADL_RESERVE_RATE");

// position pnl is capped at (entryPrice or marketPrice) * positions * MCP_ADL_MAX_PNL_RATE. decimals = 18
bytes32 constant MCP_ADL_MAX_PNL_RATE = keccak256("MCP_ADL_MAX_PNL_RATE");

// if upnl > (entryPrice or marketPrice) * positions * MCP_ADL_TRIGGER_RATE, ADL is allowed. decimals = 18
bytes32 constant MCP_ADL_TRIGGER_RATE = keccak256("MCP_ADL_TRIGGER_RATE");

// ==================== order book ====================

// only allow fillLiquidityOrder after this seconds
bytes32 constant MCO_LIQUIDITY_LOCK_PERIOD = keccak256("MCO_LIQUIDITY_LOCK_PERIOD");

// pause position order
bytes32 constant MCO_POSITION_ORDER_PAUSED = keccak256("MCO_POSITION_ORDER_PAUSED");

// pause liquidity order
bytes32 constant MCO_LIQUIDITY_ORDER_PAUSED = keccak256("MCO_LIQUIDITY_ORDER_PAUSED");

// pause withdrawal order
bytes32 constant MCO_WITHDRAWAL_ORDER_PAUSED = keccak256("MCO_WITHDRAWAL_ORDER_PAUSED");

// pause rebalance order
bytes32 constant MCO_REBALANCE_ORDER_PAUSED = keccak256("MCO_REBALANCE_ORDER_PAUSED");

// pause adl order
bytes32 constant MCO_ADL_ORDER_PAUSED = keccak256("MCO_ADL_ORDER_PAUSED");

// pause liquidate order
bytes32 constant MCO_LIQUIDATE_ORDER_PAUSED = keccak256("MCO_LIQUIDATE_ORDER_PAUSED");

// timeout for market order. after this seconds, Broker can cancel the order
bytes32 constant MCO_MARKET_ORDER_TIMEOUT = keccak256("MCO_MARKET_ORDER_TIMEOUT");

// timeout for limit order. after this seconds, Broker can cancel the order
bytes32 constant MCO_LIMIT_ORDER_TIMEOUT = keccak256("MCO_LIMIT_ORDER_TIMEOUT");

// an IReferralManager address
bytes32 constant MCO_REFERRAL_MANAGER = keccak256("MCO_REFERRAL_MANAGER");

// Trader can not cancelOrder before this number of seconds has elapsed
bytes32 constant MCO_CANCEL_COOL_DOWN = keccak256("MCO_CANCEL_COOL_DOWN");

// when calling fillPositionOrder, fillLiquidityOrder, fillWithdrawalOrder, send (MCO_ORDER_GAS_FEE_GWEI * 1e9) ETH
// to Broker as a gas compensation
bytes32 constant MCO_ORDER_GAS_FEE_GWEI = keccak256("MCO_ORDER_GAS_FEE_GWEI");

// minimum order value in USD for adding/removing liquidity
bytes32 constant MCO_MIN_LIQUIDITY_ORDER_USD = keccak256("MCO_MIN_LIQUIDITY_ORDER_USD");

// callback gas limit for liquidity order
bytes32 constant MCO_CALLBACK_GAS_LIMIT = keccak256("MCO_CALLBACK_GAS_LIMIT");

// to verify that callback is whitelisted
bytes32 constant MCO_CALLBACK_REGISTER = keccak256("MCO_CALLBACK_REGISTER");

File 34 of 42 : ILimits.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

uint256 constant MAX_COLLATERAL_TOKENS = 128;
uint256 constant MAX_MARKETS = 128;
uint256 constant MAX_COLLATERAL_POOLS = 256;
uint256 constant MAX_MARKET_BACKED_POOLS = 16;

uint256 constant MAX_COLLATERALS_PER_POSITION_ACCOUNT = 16;
uint256 constant MAX_MARKETS_PER_POSITION_ACCOUNT = 16;
uint256 constant MAX_POSITION_ACCOUNT_PER_TRADER = 64;

uint256 constant MAX_TP_SL_ORDERS = 32;

File 35 of 42 : IMarket.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

struct BackedPoolState {
    address backedPool;
}

struct MarketInfo {
    string symbol;
    bool isLong;
    mapping(bytes32 => bytes32) configs;
    BackedPoolState[] pools;
}

struct AllocationData {
    bytes32 marketId;
    uint256 size;
}

interface IMarket {
    event CollectFee(address feeToken, uint256 wad);
}

File 36 of 42 : IMux3Core.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "../interfaces/IFacetTrade.sol";
import "../interfaces/IFacetManagement.sol";
import "../interfaces/IFacetReader.sol";

struct CollateralTokenInfo {
    bool isExist;
    uint8 decimals;
    bool isStable;
}

File 37 of 42 : IPositionAccount.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";

uint256 constant SAFE_INITIAL_MARGIN = 0x1;
uint256 constant SAFE_MAINTENANCE_MARGIN = 0x2;
uint256 constant SAFE_LEVERAGE = 0x3;

struct PositionAccountInfo {
    address owner;
    EnumerableSetUpgradeable.AddressSet activeCollaterals;
    EnumerableSetUpgradeable.Bytes32Set activeMarkets;
    mapping(address => uint256) collaterals; // decimals = 18
    mapping(bytes32 => PositionData) positions; // marketId (implied isLong) => PositionData
}

struct PositionData {
    uint256 initialLeverage;
    uint256 lastIncreasedTime;
    uint256 realizedBorrowingUsd;
    mapping(address => PositionPoolData) pools; // poolId => PositionPoolData
}

struct PositionPoolData {
    uint256 size;
    uint256 entryPrice;
    uint256 entryBorrowing;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

interface IPriceProvider {
    function getOraclePrice(bytes32 oracleId, bytes memory data) external returns (uint256, uint256);
}

File 39 of 42 : IRoles.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

bytes32 constant PRICE_SETTER_ROLE = keccak256("PRICE_SETTER_ROLE");
bytes32 constant ORDER_BOOK_ROLE = keccak256("ORDER_BOOK_ROLE");
bytes32 constant BROKER_ROLE = keccak256("BROKER_ROLE");
bytes32 constant MAINTAINER_ROLE = keccak256("MAINTAINER_ROLE");
bytes32 constant DELEGATOR_ROLE = keccak256("DELEGATOR_ROLE");
bytes32 constant FEE_DISTRIBUTOR_USER_ROLE = keccak256("FEE_DISTRIBUTOR_USER_ROLE");
bytes32 constant REBALANCER_ROLE = keccak256("REBALANCER_ROLE");
bytes32 constant FEE_DONATOR_ROLE = keccak256("FEE_DONATOR_ROLE");
bytes32 constant ORACLE_SIGNER = keccak256("ORACLE_SIGNER");

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import "./LibTypeCast.sol";

library LibConfigMap {
    using LibTypeCast for bytes32;
    using LibTypeCast for address;
    using LibTypeCast for uint256;
    using LibTypeCast for bool;

    event SetValue(bytes32 key, bytes32 value);

    // ================================== single functions ======================================

    function setUint256(mapping(bytes32 => bytes32) storage store, bytes32 key, uint256 value) internal {
        setBytes32(store, key, bytes32(value));
    }

    function setAddress(mapping(bytes32 => bytes32) storage store, bytes32 key, address value) internal {
        setBytes32(store, key, bytes32(bytes20(value)));
    }

    function setBytes32(mapping(bytes32 => bytes32) storage store, bytes32 key, bytes32 value) internal {
        store[key] = value;
        emit SetValue(key, value);
    }

    function setBoolean(mapping(bytes32 => bytes32) storage store, bytes32 key, bool flag) internal {
        bytes32 value = bytes32(uint256(flag ? 1 : 0));
        setBytes32(store, key, value);
    }

    function getBytes32(mapping(bytes32 => bytes32) storage store, bytes32 key) internal view returns (bytes32) {
        return store[key];
    }

    function getUint256(mapping(bytes32 => bytes32) storage store, bytes32 key) internal view returns (uint256) {
        return store[key].toUint256();
    }

    function getInt256(mapping(bytes32 => bytes32) storage store, bytes32 key) internal view returns (int256) {
        return store[key].toInt256();
    }

    function getAddress(mapping(bytes32 => bytes32) storage store, bytes32 key) internal view returns (address) {
        return store[key].toAddress();
    }

    function getBoolean(mapping(bytes32 => bytes32) storage store, bytes32 key) internal view returns (bool) {
        return store[key].toBoolean();
    }

    function getString(mapping(bytes32 => bytes32) storage store, bytes32 key) internal view returns (string memory) {
        return toString(store[key]);
    }

    function toBytes32(address a) internal pure returns (bytes32) {
        return bytes32(bytes20(a));
    }

    function toString(bytes32 b) internal pure returns (string memory) {
        uint256 length = 0;
        while (length < 32 && b[length] != 0) {
            length++;
        }
        bytes memory bytesArray = new bytes(length);
        for (uint256 i = 0; i < length; i++) {
            bytesArray[i] = b[i];
        }
        return string(bytesArray);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { EnumerableSetUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import { StringsUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";

/**
 * a simplified AccessControlEnumerableUpgradeable that does not implement ERC165.
 * this is the store part that does not have any external functions.
 */
contract Mux3RolesStore is Initializable {
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;

    bytes32 internal constant DEFAULT_ADMIN_ROLE = 0x00;

    mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) internal _roleMembers;
    uint256[50] private __gap;

    modifier onlyRole(bytes32 role) {
        _checkRole(role, msg.sender);
        _;
    }

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

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

    function _hasRole(bytes32 role, address account) internal view returns (bool) {
        return _roleMembers[role].contains(account);
    }

    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!_hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        StringsUpgradeable.toHexString(account),
                        " is missing role ",
                        StringsUpgradeable.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    function _grantRole(bytes32 role, address account) internal virtual {
        if (!_hasRole(role, account)) {
            _roleMembers[role].add(account);
            emit RoleGranted(role, account, msg.sender);
        }
    }

    function _revokeRole(bytes32 role, address account) internal virtual {
        if (_hasRole(role, account)) {
            _roleMembers[role].remove(account);
            emit RoleRevoked(role, account, msg.sender);
        }
    }
}

/**
 * a simplified AccessControlEnumerableUpgradeable that does not implement ERC165.
 * this is the external part that only contains management functions.
 */
contract Mux3RolesAdmin is Mux3RolesStore {
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;

    function __Mux3RolesAdmin_init_unchained() internal onlyInitializing {}

    function grantRole(bytes32 role, address account) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _grantRole(role, account);
    }

    function revokeRole(bytes32 role, address account) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _revokeRole(role, account);
    }

    function hasRole(bytes32 role, address account) external view returns (bool) {
        return _hasRole(role, account);
    }

    function getRoleMemberCount(bytes32 role) external view returns (uint256) {
        return _roleMembers[role].length();
    }

    function getRoleMember(bytes32 role, uint256 index) external view returns (address) {
        return _roleMembers[role].at(index);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

library LibTypeCast {
    bytes32 private constant ADDRESS_GUARD_MASK = 0x0000000000000000000000000000000000000000ffffffffffffffffffffffff;

    function toAddress(bytes32 v) internal pure returns (address) {
        require(v & ADDRESS_GUARD_MASK == 0, "LibTypeCast::INVALID_ADDRESS");
        return address(bytes20(v));
    }

    function toBytes32(address v) internal pure returns (bytes32) {
        return bytes32(bytes20(v));
    }

    function toUint256(bytes32 v) internal pure returns (uint256) {
        return uint256(v);
    }

    function toUint256(int256 v) internal pure returns (uint256) {
        require(v >= 0, "LibTypeCast::UNDERFLOW");
        return uint256(v);
    }

    function toBytes32(int256 v) internal pure returns (bytes32) {
        return bytes32(uint256(v));
    }

    function toInt256(bytes32 v) internal pure returns (int256) {
        return int256(uint256(v));
    }

    function toBytes32(uint256 v) internal pure returns (bytes32) {
        return bytes32(v);
    }

    function toBoolean(bytes32 v) internal pure returns (bool) {
        uint256 n = toUint256(v);
        require(n == 0 || n == 1, "LibTypeCast::INVALID_BOOLEAN");
        return n == 1;
    }

    function toBytes32(bool v) internal pure returns (bytes32) {
        return toBytes32(v ? 1 : 0);
    }

    function toInt256(uint256 n) internal pure returns (int256) {
        require(n <= uint256(type(int256).max), "LibTypeCast::OVERFLOW");
        return int256(n);
    }

    function toUint96(uint256 n) internal pure returns (uint96) {
        require(n <= uint256(type(uint96).max), "LibTypeCast::OVERFLOW");
        return uint96(n);
    }

    function toUint64(uint256 n) internal pure returns (uint64) {
        require(n <= uint256(type(uint64).max), "LibTypeCast::OVERFLOW");
        return uint64(n);
    }

    function negInt256(int256 n) internal pure returns (uint256) {
        if (n >= 0) {
            return uint256(n);
        }
        require(n != type(int256).min, "LibTypeCast::UNDERFLOW");
        return uint256(-n);
    }
}

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

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"uint256","name":"len1","type":"uint256"},{"internalType":"uint256","name":"len2","type":"uint256"}],"name":"AllocationLengthMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"positionSize1","type":"uint256"},{"internalType":"uint256","name":"positionSize2","type":"uint256"}],"name":"AllocationPositionMismatch","type":"error"},{"inputs":[],"name":"ArrayAppendFailed","type":"error"},{"inputs":[{"internalType":"int256","name":"maxX","type":"int256"},{"internalType":"int256","name":"xi","type":"int256"}],"name":"BadAllocation","type":"error"},{"inputs":[{"internalType":"uint256","name":"capacity","type":"uint256"},{"internalType":"uint256","name":"old","type":"uint256"},{"internalType":"uint256","name":"appending","type":"uint256"}],"name":"CapacityExceeded","type":"error"},{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"}],"name":"CollateralAlreadyExist","type":"error"},{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"}],"name":"CollateralNotExist","type":"error"},{"inputs":[],"name":"CreateProxyFailed","type":"error"},{"inputs":[{"internalType":"address","name":"pool","type":"address"}],"name":"DuplicatedAddress","type":"error"},{"inputs":[{"internalType":"string","name":"key","type":"string"}],"name":"EssentialConfigNotSet","type":"error"},{"inputs":[{"internalType":"bytes32","name":"id","type":"bytes32"},{"internalType":"bytes32","name":"expectedId","type":"bytes32"}],"name":"IdMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"leverage","type":"uint256"},{"internalType":"uint256","name":"leverageLimit","type":"uint256"}],"name":"InitialLeverageOutOfRange","type":"error"},{"inputs":[{"internalType":"uint256","name":"required","type":"uint256"},{"internalType":"uint256","name":"remain","type":"uint256"}],"name":"InsufficientCollateral","type":"error"},{"inputs":[{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"requiredAmount","type":"uint256"}],"name":"InsufficientCollateralBalance","type":"error"},{"inputs":[{"internalType":"uint256","name":"requiredUsd","type":"uint256"},{"internalType":"uint256","name":"remainUsd","type":"uint256"}],"name":"InsufficientCollateralUsd","type":"error"},{"inputs":[{"internalType":"uint256","name":"requiredLiquidity","type":"uint256"},{"internalType":"uint256","name":"liquidityBalance","type":"uint256"}],"name":"InsufficientLiquidity","type":"error"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"InvalidAddress","type":"error"},{"inputs":[{"internalType":"string","name":"key","type":"string"}],"name":"InvalidAmount","type":"error"},{"inputs":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","name":"b","type":"uint256"}],"name":"InvalidArrayLength","type":"error"},{"inputs":[{"internalType":"uint256","name":"closingSize","type":"uint256"},{"internalType":"uint256","name":"positionSize","type":"uint256"}],"name":"InvalidCloseSize","type":"error"},{"inputs":[{"internalType":"uint256","name":"decimals","type":"uint256"}],"name":"InvalidDecimals","type":"error"},{"inputs":[{"internalType":"string","name":"key","type":"string"}],"name":"InvalidId","type":"error"},{"inputs":[{"internalType":"uint256","name":"positionSize","type":"uint256"},{"internalType":"uint256","name":"lotSize","type":"uint256"}],"name":"InvalidLotSize","type":"error"},{"inputs":[{"internalType":"bytes32","name":"marketId","type":"bytes32"}],"name":"InvalidMarketId","type":"error"},{"inputs":[{"internalType":"uint256","name":"price","type":"uint256"}],"name":"InvalidPrice","type":"error"},{"inputs":[{"internalType":"uint256","name":"expiration","type":"uint256"}],"name":"InvalidPriceExpiration","type":"error"},{"inputs":[{"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"InvalidPriceTimestamp","type":"error"},{"inputs":[{"internalType":"uint256","name":"sequence","type":"uint256"},{"internalType":"uint256","name":"expectedSequence","type":"uint256"}],"name":"InvalidSequence","type":"error"},{"inputs":[{"internalType":"address","name":"signer","type":"address"}],"name":"InvalidSinger","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"actual","type":"uint256"}],"name":"LimitPriceNotMet","type":"error"},{"inputs":[{"internalType":"bytes32","name":"marketId","type":"bytes32"}],"name":"MarketAlreadyExist","type":"error"},{"inputs":[],"name":"MarketFull","type":"error"},{"inputs":[{"internalType":"bytes32","name":"marketId","type":"bytes32"}],"name":"MarketNotExists","type":"error"},{"inputs":[{"internalType":"bytes32","name":"marketId","type":"bytes32"}],"name":"MarketTradeDisabled","type":"error"},{"inputs":[{"internalType":"bytes32","name":"oracleId","type":"bytes32"}],"name":"MissingPrice","type":"error"},{"inputs":[],"name":"MissingSignature","type":"error"},{"inputs":[{"internalType":"bytes32","name":"positionId","type":"bytes32"},{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"NotOwner","type":"error"},{"inputs":[{"internalType":"bytes32","name":"positionId","type":"bytes32"}],"name":"OnlySingleMarketPositionAllowed","type":"error"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"uint256","name":"length","type":"uint256"}],"name":"OutOfBound","type":"error"},{"inputs":[{"internalType":"address","name":"pool","type":"address"}],"name":"PoolAlreadyExist","type":"error"},{"inputs":[],"name":"PoolBankrupt","type":"error"},{"inputs":[{"internalType":"address","name":"pool","type":"address"}],"name":"PoolNotExists","type":"error"},{"inputs":[{"internalType":"bytes32","name":"positionId","type":"bytes32"}],"name":"PositionAccountAlreadyExist","type":"error"},{"inputs":[{"internalType":"bytes32","name":"positionId","type":"bytes32"}],"name":"PositionAccountNotExist","type":"error"},{"inputs":[{"internalType":"bytes32","name":"positionId","type":"bytes32"}],"name":"PositionNotClosed","type":"error"},{"inputs":[{"internalType":"uint256","name":"timestamp","type":"uint256"},{"internalType":"uint256","name":"blockTimestamp","type":"uint256"}],"name":"PriceExpired","type":"error"},{"inputs":[{"internalType":"bytes32","name":"positionId","type":"bytes32"},{"internalType":"uint256","name":"safeType","type":"uint256"}],"name":"SafePositionAccount","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"positionId","type":"bytes32"}],"name":"UnauthorizedAgent","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"UnauthorizedCaller","type":"error"},{"inputs":[{"internalType":"bytes32","name":"requiredRole","type":"bytes32"},{"internalType":"address","name":"caller","type":"address"}],"name":"UnauthorizedRole","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"actual","type":"uint256"}],"name":"UnexpectedState","type":"error"},{"inputs":[{"internalType":"uint256","name":"decimals","type":"uint256"},{"internalType":"uint256","name":"expectDecimals","type":"uint256"}],"name":"UnmatchedDecimals","type":"error"},{"inputs":[{"internalType":"bytes32","name":"positionId","type":"bytes32"},{"internalType":"uint256","name":"safeType","type":"uint256"}],"name":"UnsafePositionAccount","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint8","name":"decimals","type":"uint8"},{"indexed":false,"internalType":"bool","name":"isStable","type":"bool"}],"name":"AddCollateralToken","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"marketId","type":"bytes32"},{"indexed":false,"internalType":"address[]","name":"backedPools","type":"address[]"}],"name":"AppendBackedPoolsToMarket","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"name","type":"string"},{"indexed":false,"internalType":"string","name":"symbol","type":"string"},{"indexed":false,"internalType":"address","name":"collateral","type":"address"},{"indexed":false,"internalType":"uint8","name":"collateralDecimals","type":"uint8"},{"indexed":false,"internalType":"address","name":"pool","type":"address"}],"name":"CreateCollateralPool","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"marketId","type":"bytes32"},{"indexed":false,"internalType":"string","name":"symbol","type":"string"},{"indexed":false,"internalType":"bool","name":"isLong","type":"bool"},{"indexed":false,"internalType":"address[]","name":"backedPools","type":"address[]"}],"name":"CreateMarket","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"pool","type":"address"},{"indexed":false,"internalType":"bytes32","name":"key","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"value","type":"bytes32"}],"name":"SetCollateralPoolConfig","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newImplementation","type":"address"}],"name":"SetCollateralPoolImplementation","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"bool","name":"enabled","type":"bool"}],"name":"SetCollateralTokenEnabled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"key","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"value","type":"bytes32"}],"name":"SetConfig","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"marketId","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"key","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"value","type":"bytes32"}],"name":"SetMarketConfig","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oracleProvider","type":"address"},{"indexed":false,"internalType":"bool","name":"isValid","type":"bool"}],"name":"SetOracleProvider","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"oracleId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"provider","type":"address"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"SetPrice","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"oracleId","type":"bytes32"},{"indexed":false,"internalType":"bool","name":"strictStable","type":"bool"}],"name":"SetStrictStableId","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"key","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"value","type":"bytes32"}],"name":"SetValue","type":"event"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint8","name":"decimals","type":"uint8"},{"internalType":"bool","name":"isStable","type":"bool"}],"name":"addCollateralToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"marketId","type":"bytes32"},{"internalType":"address[]","name":"backedPools","type":"address[]"}],"name":"appendBackedPoolsToMarket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"uint256","name":"expectedPoolCount","type":"uint256"}],"name":"createCollateralPool","outputs":[{"internalType":"address","name":"poolAddress","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"marketId","type":"bytes32"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"bool","name":"isLong","type":"bool"},{"internalType":"address[]","name":"backedPools","type":"address[]"}],"name":"createMarket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"implementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"weth_","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"}],"name":"setCollateralPoolImplementation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"key","type":"bytes32"},{"internalType":"bytes32","name":"value","type":"bytes32"}],"name":"setConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"marketId","type":"bytes32"},{"internalType":"bytes32","name":"key","type":"bytes32"},{"internalType":"bytes32","name":"value","type":"bytes32"}],"name":"setMarketConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"oracleProvider","type":"address"},{"internalType":"bool","name":"isValid","type":"bool"}],"name":"setOracleProvider","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"pool","type":"address"},{"internalType":"bytes32","name":"key","type":"bytes32"},{"internalType":"bytes32","name":"value","type":"bytes32"}],"name":"setPoolConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"oracleId","type":"bytes32"},{"internalType":"address","name":"provider","type":"address"},{"internalType":"bytes","name":"oracleCalldata","type":"bytes"}],"name":"setPrice","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"oracleId","type":"bytes32"},{"internalType":"bool","name":"strictStable","type":"bool"}],"name":"setStrictStableId","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60808060405234601557612839908161001a8239f35b5f80fdfe60806040526004361015610011575f80fd5b5f3560e01c80630606fd4f14610134578063157fdf121461012f5780632f2ff15d1461012a5780633e13fdb61461012557806347f391de1461012057806349ffd5671461011b5780635315f030146101165780635c60da1b1461011157806364ca47291461010c5780639010d07c146101075780639019d0221461010257806391d14854146100fd578063ab02b870146100f8578063c4d66de8146100f3578063ca15c873146100ee578063d1fd27b3146100e9578063d547741f146100e45763e1e735bd146100df575f80fd5b610fab565b610f1b565b610e73565b610e49565b610d56565b610cba565b610c67565b610aa9565b610a64565b6109e3565b6109bb565b610765565b6105cb565b61052d565b61047f565b6103ee565b6102e9565b61026c565b634e487b7160e01b5f52604160045260245ffd5b90601f8019910116810190811067ffffffffffffffff82111761016f57604052565b610139565b6040519061018360608361014d565b565b6040519061018360208361014d565b90610183604051928361014d565b600435906001600160a01b03821682036101b857565b5f80fd5b602435906001600160a01b03821682036101b857565b604435906001600160a01b03821682036101b857565b35906001600160a01b03821682036101b857565b9080601f830112156101b85781359167ffffffffffffffff831161016f578260051b9060405193610230602084018661014d565b84526020808501928201019283116101b857602001905b8282106102545750505090565b60208091610261846101e8565b815201910190610247565b346101b85760403660031901126101b85760243560043567ffffffffffffffff82116101b8576102c17f886eab8a483379fbfe2239e3fa4f879253ef970d01df960ff94a2a73d8d771579236906004016101fc565b906102cb336113e5565b6102d582826116fa565b6102e460405192839283611154565b0390a1005b346101b85760603660031901126101b8576103026101a2565b60243560443591610312336113e5565b6001600160a01b038116926103298285151561123c565b61034782610342865f52603a60205260405f2054151590565b611635565b833b156101b85760405163d1fd27b360e01b81526004810184905260248101829052935f908590604490829084905af19081156103e9577fcfb31fed64957f3c78f11afea8503e0d7cfb03d1fcb195acea5f6fa7e51419ca946102e4926103cf575b5060405193849384604091949392606082019560018060a01b0316825260208201520152565b806103dd5f6103e39361014d565b806109b1565b5f6103a9565b6116ef565b346101b85760403660031901126101b85760043561040a6101bc565b610413336113e5565b5f8281526001602081815260408084206001600160a01b039095168085529490920190529020541561044157005b815f5260016020526104568160405f20611fe3565b5033917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d5f80a4005b346101b85760603660031901126101b8577f19f33359217c73dfadcd5891584423e897185805b3fc3a163f279115dde5f8a260606004356044356024356104c5336113e5565b6104e3836104de815f52603d60205260405f2054151590565b61154f565b825f52603b6020526104fc8282600260405f2001611a4e565b60405192835260208301526040820152a1005b6024359081151582036101b857565b6044359081151582036101b857565b346101b85760403660031901126101b8577f7958ffc90e123bc1edc47c475e4d4fa2983d16b1c82f6874a565642939bdba9560406105696101a2565b61057161050f565b61057a336113e5565b6001600160a01b038216916105919083151561123c565b815f52603f6020526105b181845f209060ff801983541691151516179055565b825191825215156020820152a1005b60ff8116036101b857565b346101b85760603660031901126101b8576105e46101a2565b6024356105f0816105c0565b6105f861051e565b91610602336113e5565b6001600160a01b0381166106188282151561123c565b805f52603660205260ff60405f2054166106e357506102e47f22a35aa1cd3e43c59ed5bd7131b6cc41d6bb6b178ab74e69753f345aad29b0759361069d61065f8585611df5565b61067961066a610174565b600181529160ff166020830152565b82151560408201526001600160a01b0385165f90815260366020526040902061187f565b6106ac603554608081106118ca565b6106b583611913565b604080516001600160a01b03909416845260ff90941660208401521515928201929092529081906060820190565b632e1c6ef760e11b5f5260045260245ffd5b67ffffffffffffffff811161016f57601f01601f191660200190565b92919261071d826106f5565b9161072b604051938461014d565b8294818452818301116101b8578281602093845f960137010152565b9080601f830112156101b85781602061076293359101610711565b90565b346101b85760803660031901126101b85760043567ffffffffffffffff81116101b857610796903690600401610747565b60243567ffffffffffffffff81116101b8576107b6903690600401610747565b6107be6101d2565b916064356107cb336113e5565b6001600160a01b0384165f8181526036602052604090205490949060ff161561099e579161097d6109209492846108ee6108d76108dd8a6108327f60a67166e17b7187511118d6c049f9583680009d6e5fe1381879aadb468d27259a61099a9d151561123c565b61088460405180926303bf912560e11b60208301526060602483015261087061085e608484018d61116b565b8381036023190160448501528d61116b565b90606483015203601f19810183528261014d565b6108b96108b96108c761064d9361089d60208601610194565b948086526121b760208701396040519283913060208401612036565b03601f19810183528261014d565b60405194859360208501906113c2565b906113c2565b6108e8838888612058565b906120a2565b968792610906846001600160a01b038116151561123c565b6109166039549182818114611978565b61010081106118ee565b61094b826109466109416001600160a01b0383165b6001600160a01b031690565b611f2c565b611672565b6001600160a01b0381165f908152603660205260409020610970905460081c60ff1690565b906040519586958661118f565b0390a16040516001600160a01b0390911681529081906020820190565b0390f35b846319ec4ea760e11b5f5260045260245ffd5b5f9103126101b857565b346101b8575f3660031901126101b857603e546040516001600160a01b039091168152602090f35b346101b85760403660031901126101b8577f1f457e2e7d9037059e3ec29ef5de83ec84fe9be0a77700765e171a0e9fcfd3fc600435610a2061050f565b90610a2a336113e5565b805f526041602052610a4b8260405f209060ff801983541691151516179055565b60408051918252911515602082015290819081016102e4565b346101b85760403660031901126101b8576020610a90600435602435905f526001835260405f2061165d565b905460405160039290921b1c6001600160a01b03168152f35b346101b85760603660031901126101b857600435610ac56101bc565b6044359167ffffffffffffffff83116101b857366023840112156101b8576040610b44610afd5f953690602481600401359101610711565b610b06336114bb565b610b11841515611996565b6001600160a01b03851690610b288683151561123c565b8351968780948193633fb6f06760e21b835288600484016119e4565b03925af19283156103e9577facb4574539203a32ae0ff5b51718b5b2645bf595a95f67e1ae15d29a9754a6bb936102e4915f905f92610c35575b5080610b9c610b95865f52604160205260405f2090565b5460ff1690565b610bd0575b5080845d60405194859485909493926060926080830196835260018060a01b0316602083015260408201520152565b610bf1610be3610bde611e93565b6119fb565b670de0b6b3a7640000900490565b9080610bfc8361159b565b10159182610c21575b5050610c12575b5f610ba1565b50670de0b6b3a7640000610c0c565b610c2c919250611a32565b11155f80610c05565b9050610c59915060403d604011610c60575b610c51818361014d565b8101906119ce565b905f610b7e565b503d610c47565b346101b85760403660031901126101b8576020610cb0600435610c886101bc565b5f918252600180855260408084206001600160a01b0390931684529101602052902054151590565b6040519015158152f35b346101b85760203660031901126101b857610cd36101a2565b610cdc336113e5565b6001600160a01b03811690610cf39082151561123c565b603e546001600160a01b0381168214610d43576001600160a01b0319168117603e556040519081527f5d4f24edeca778592467fa8d7b21e4a61b4195320b43d5bfbb0dec53f976549290602090a1005b5063749da11360e11b5f5260045260245ffd5b346101b85760203660031901126101b857610d6f6101a2565b610dbd5f5491610da3610d8d610d898560ff9060081c1690565b1590565b80948195610e3b575b8115610e1b575b506111d9565b82610db4600160ff195f5416175f55565b610e0457611264565b610dc357005b610dd15f5461ff0019165f55565b604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989080602081016102e4565b610e166101005f5461ff001916175f55565b611264565b303b15915081610e2d575b505f610d9d565b60ff1660011490505f610e26565b600160ff8216109150610d96565b346101b85760203660031901126101b8576004355f526001602052602060405f2054604051908152f35b346101b85760403660031901126101b8577fc5f4eda54c0dc8244a27193c9ba57b1f24e57ca6787830fc5835325a04ddb06b602435600435610eb4336113e5565b805f5260346020528160405f20557f926b2cda941e79b7fc4ae2533b0a876ab25766c11d4903f47ffb33bedfc1e67360405180610eff85858360209093929193604081019481520152565b0390a160408051918252602082019290925290819081016102e4565b346101b85760403660031901126101b857600435610f376101bc565b610f40336113e5565b5f8281526001602081815260408084206001600160a01b03909516808552949092019052902054610f6d57005b815f526001602052610f828160405f20612106565b5033917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b5f80a4005b346101b85760803660031901126101b85760043560243567ffffffffffffffff81116101b857610fdf903690600401610747565b610fe761051e565b60643567ffffffffffffffff81116101b8576110079036906004016101fc565b91611011336113e5565b83156111055761102c845f52603d60205260405f2054151590565b6110f25783917f18a6f1b86d393c747ca9045668cfcd87c44772c238de9a4a536bbfb7f8c33d30917f886eab8a483379fbfe2239e3fa4f879253ef970d01df960ff94a2a73d8d77157955f52603b60205261108a8160405f20611b43565b6110b48260016110a2875f52603b60205260405f2090565b019060ff801983541691151516179055565b6110c3603c54608081106118ca565b6110d46110cf85611f95565b611c0b565b6110e5856040519384938785611390565b0390a16102d582826116fa565b83634db7281d60e11b5f5260045260245ffd5b836337e9e5d160e11b5f5260045260245ffd5b90602080835192838152019201905f5b8181106111355750505090565b82516001600160a01b0316845260209384019390920191600101611128565b604090610762939281528160208201520190611118565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b936111bb6080949796936111ad60ff9460a0895260a089019061116b565b90878203602089015261116b565b6001600160a01b039788166040870152911660608501529416910152565b156111e057565b60405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608490fd5b156112445750565b634726455360e11b5f9081526001600160a01b0391909116600452602490fd5b60ff5f5460081c161561133757335f8181527fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb4a6020526040902054156112d7575b506001600160a01b038116906112bd9082151561123c565b6bffffffffffffffffffffffff60a01b6040541617604055565b5f80526001602052611309817fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb49611fe3565b5033905f7f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d8180a45f6112a5565b60405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608490fd5b9061076294926113ad91835260806020840152608083019061116b565b92151560408201526060818403910152611118565b805191908290602001825e015f815290565b90602061076292818152019061116b565b6001600160a01b03165f8181527fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb4a6020526040902054156114235750565b6114796114976114356114b793611cd8565b6108b96114415f611d72565b60116040519586946017602087017f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815201906113c2565b7001034b99036b4b9b9b4b733903937b6329607d1b815201906113c2565b60405162461bcd60e51b815260206004820152918291602483019061116b565b0390fd5b6001600160a01b03165f8181527f1dcf711afb65f2ac88b320cf38bd6f6279d286578a3288c803f3e3c71e44c9fe6020526040902054156114f95750565b61147961153761150b6114b793611cd8565b6108b96114417f1f6ff8cdb729dffbc2de528d342591f244815601111ae4e0ae059cc92f120c59611d72565b60405162461bcd60e51b8152918291600483016113d4565b156115575750565b639773311360e01b5f5260045260245ffd5b156115715750565b633b5cfc6960e21b5f526004525f60245260445ffd5b634e487b7160e01b5f52601160045260245ffd5b670de0b6b3a7640000019081670de0b6b3a7640000116115b757565b611587565b90600282018092116115b757565b90600182018092116115b757565b919082018092116115b757565b156115ee575050565b63e12f2cd160e01b5f52601060045260245260445260645ffd5b634e487b7160e01b5f52603260045260245ffd5b80518210156116305760209160051b010190565b611608565b1561163d5750565b633f36c1ab60e01b5f9081526001600160a01b0391909116600452602490fd5b8054821015611630575f5260205f2001905f90565b1561167a5750565b635d6c86f960e11b5f9081526001600160a01b0391909116600452602490fd5b8054600160401b81101561016f576116b79160018201815561165d565b9190916116dc575181546001600160a01b0319166001600160a01b0391909116179055565b634e487b7160e01b5f525f60045260245ffd5b6040513d5f823e3d90fd5b611713816104de815f52603d60205260405f2054151590565b6117208251801515611569565b815190611735815f52603b60205260405f2090565b6003810193611753848654601061174c83836115d8565b11156115e5565b60015f9201915b84811061176957505050505050565b611783611776828461161c565b516001600160a01b031690565b6001600160a01b0381165f908152603a60205260409020549091906117ab9083901515611635565b86546001600160a01b03831692905f5b848a83831061184c57505050506117ec906117e66117d7610185565b6001600160a01b039092168252565b8861169a565b835460ff1691803b156101b857604051630dc4184760e21b81526004810187905292151560248401525f908390604490829084905af19182156103e957600192611838575b500161175a565b806103dd5f6118469361014d565b5f611831565b8483926118726109356118646001976118799661165d565b50546001600160a01b031690565b1415611672565b016117bb565b9061189981511515839060ff801983541691151516179055565b602081015182546040929092015162ffff001990921660089190911b61ff00161790151560101b62ff000016179055565b156118d25750565b63e12f2cd160e01b5f526080600452602452600160445260645ffd5b156118f65750565b63e12f2cd160e01b5f52610100600452602452600160445260645ffd5b603554600160401b81101561016f57600181016035556035548110156116305760355f527fcfa4bec1d3298408bb5afcfcd9c430549c5b31f8aa5c5848151c0a55f473c34d0180546001600160a01b0319166001600160a01b03909216919091179055565b15611981575050565b6323994f6360e21b5f5260045260245260445ffd5b1561199d57565b6040516356e22f5760e11b81526020600482015260086024820152671bdc9858db19525960c21b6044820152606490fd5b91908260409103126101b8576020825192015190565b60409061076293928152816020820152019061116b565b9081670de0b6b3a76400000291670de0b6b3a76400008304036115b757565b600181901b91906001600160ff1b038116036115b757565b670de0b6b3a76400000390670de0b6b3a764000082116115b757565b907f926b2cda941e79b7fc4ae2533b0a876ab25766c11d4903f47ffb33bedfc1e6739291815f526020528160405f2055611a9a6040519283928360209093929193604081019481520152565b0390a1565b90600182811c92168015611acd575b6020831014611ab957565b634e487b7160e01b5f52602260045260245ffd5b91607f1691611aae565b91611af09183549060031b91821b915f19901b19161790565b9055565b601f8211611b0157505050565b5f5260205f20906020601f840160051c83019310611b39575b601f0160051c01905b818110611b2e575050565b5f8155600101611b23565b9091508190611b1a565b919091825167ffffffffffffffff811161016f57611b6b81611b658454611a9f565b84611af4565b6020601f8211600114611ba6578190611af09394955f92611b9b575b50508160011b915f199060031b1c19161790565b015190505f80611b87565b601f19821690611bb9845f5260205f2090565b915f5b818110611bf357509583600195969710611bdb575b505050811b019055565b01515f1960f88460031b161c191690555f8080611bd1565b9192602060018192868b015181550194019201611bbc565b15611c1257565b63320e5acb60e21b5f5260045ffd5b90611c2b826106f5565b611c38604051918261014d565b8281528092611c49601f19916106f5565b0190602036910137565b8051156116305760200190565b8051600110156116305760210190565b908151811015611630570160200190565b80156115b7575f190190565b15611c9457565b606460405162461bcd60e51b815260206004820152602060248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152fd5b611cea611ce560286115bc565b611c21565b906030611cf683611c53565b536078611d0283611c60565b53611d15611d106014611a1a565b6115ca565b905b60018211611d2a57610762915015611c8d565b600f8116601081101561163057611d6c91611d66916f181899199a1a9b1b9c1cb0b131b232b360811b901a611d5f8587611c70565b5360041c90565b91611c81565b90611d17565b611d7f611ce560406115bc565b906030611d8b83611c53565b536078611d9783611c60565b53611da5611d106020611a1a565b905b60018211611dba57610762915015611c8d565b600f8116601081101561163057611def91611d66916f181899199a1a9b1b9c1cb0b131b232b360811b901a611d5f8587611c70565b90611da7565b60405163313ce56760e01b815290602090829060049082906001600160a01b03165afa5f9181611e56575b50611e29575090565b9060ff811660ff831603611e3b575090565b60ff8092633c2b8a3160e01b5f52166004521660245260445ffd5b9091506020813d602011611e8b575b81611e726020938361014d565b810103126101b85751611e84816105c0565b905f611e20565b3d9150611e65565b7f3d3e547c06f13c203a848d7a9a911ecfabd1babd962359e8ed13468eea4c53025f5260346020527f60c60c5eb342733610d378487dda5807456142f7c29814df68dca7e89b2715c954908115611ee657565b60405163574b009160e11b815260206004820152601a60248201527f4d435f5354524943545f535441424c455f444556494154494f4e0000000000006044820152606490fd5b5f818152603a6020526040902054611f9057603954600160401b81101561016f57611f79611f63826001859401603955603961165d565b819391549060031b91821b915f19901b19161790565b9055603954905f52603a60205260405f2055600190565b505f90565b5f818152603d6020526040902054611f9057603c54600160401b81101561016f57611fcc611f63826001859401603c55603c61165d565b9055603c54905f52603d60205260405f2055600190565b5f82815260018201602052604090205461203057805490600160401b82101561016f578261201b611f6384600180960185558461165d565b90558054925f520160205260405f2055600190565b50505f90565b6001600160a01b0390911681526040602082018190526107629291019061116b565b9160146120779261209c926040519485926108d76020850180996113c2565b906bffffffffffffffffffffffff199060601b16815203600b1981018452018261014d565b51902090565b8051906020015ff5906001600160a01b038216156120bc57565b6330e6a5f960e11b5f5260045ffd5b805480156120f2575f1901906120e1828261165d565b8154905f199060031b1b1916905555565b634e487b7160e01b5f52603160045260245ffd5b6001810191805f528260205260405f2054928315155f146121ae575f1984018481116115b75783545f198101949085116115b7575f958583612154946121619803612167575b5050506120cb565b905f5260205260405f2090565b55600190565b6121976121919161218861217e6121a5958861165d565b90549060031b1c90565b9283918761165d565b90611ad7565b85905f5260205260405f2090565b555f808061214c565b505050505f9056fe60808060405261064d8038038091610017828561033c565b83398101906040818303126102335761002f81610373565b602082015190916001600160401b03821161023357019082601f8301121561023357815161005c81610387565b9261006a604051948561033c565b81845260208401946020838301011161023357815f926020809301875e84010152803b156102e957604051635c60da1b60e01b81526001600160a01b03919091169290602081600481875afa90811561023f575f916102af575b503b15610251577fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d5080546001600160a01b0319168417905560405192807f1cf3b03a6cf19fa2baba4df148e9dcabedea7f8a5c07840e207e5c089be95d3e5f80a282511580159061024a575b610144575b6040516101f690816104578239f35b83600481602093635c60da1b60e01b82525afa92831561023f575f936101fa575b50915f806101e8946040519461017c60608761033c565b602786527f416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c6020870152660819985a5b195960ca1b60408701525190845af43d156101f2573d916101cc83610387565b926101da604051948561033c565b83523d5f602085013e6103a2565b505f808080610135565b6060916103a2565b92506020833d602011610237575b816102156020938361033c565b81010312610233575f8061022b6101e895610373565b945050610165565b5f80fd5b3d9150610208565b6040513d5f823e3d90fd5b505f610130565b60405162461bcd60e51b815260206004820152603060248201527f455243313936373a20626561636f6e20696d706c656d656e746174696f6e206960448201526f1cc81b9bdd08184818dbdb9d1c9858dd60821b6064820152608490fd5b90506020813d6020116102e1575b816102ca6020938361033c565b81010312610233576102db90610373565b5f6100c4565b3d91506102bd565b60405162461bcd60e51b815260206004820152602560248201527f455243313936373a206e657720626561636f6e206973206e6f74206120636f6e6044820152641d1c9858dd60da1b6064820152608490fd5b601f909101601f19168101906001600160401b0382119082101761035f57604052565b634e487b7160e01b5f52604160045260245ffd5b51906001600160a01b038216820361023357565b6001600160401b03811161035f57601f01601f191660200190565b9192901561040457508151156103b6575090565b3b156103bf5790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b8251909150156104175750805190602001fd5b604460209160405192839162461bcd60e51b83528160048401528051918291826024860152018484015e5f828201840152601f01601f19168101030190fdfe6080604052366100be577fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d5054635c60da1b60e01b608090815260209160049082906001600160a01b03165afa80156100b3575f90156101a3575060203d6020116100ac575b601f19601f820116608001906080821067ffffffffffffffff831117610098576100939160405260800161015e565b6101a3565b634e487b7160e01b5f52604160045260245ffd5b503d610064565b6040513d5f823e3d90fd5b7fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d5054604051635c60da1b60e01b815290602090829060049082906001600160a01b03165afa9081156100b3575f91610117575b506101a3565b602091503d8211610156575b601f8201601f191681019167ffffffffffffffff8311828410176100985761015092604052810190610184565b5f610111565b3d9150610123565b602090607f190112610180576080516001600160a01b03811681036101805790565b5f80fd5b9081602091031261018057516001600160a01b03811681036101805790565b5f8091368280378136915af43d5f803e156101bc573d5ff35b3d5ffdfea2646970667358221220649c1156f9b4a727ad70a6b0b758353287fbb190d1adf588c7a52a229881f91e64736f6c634300081c0033a2646970667358221220857c4336af7634b9fcea595c21c92bd5b4400592d07b2e4f880582e506f176ac64736f6c634300081c0033

Deployed Bytecode

0x60806040526004361015610011575f80fd5b5f3560e01c80630606fd4f14610134578063157fdf121461012f5780632f2ff15d1461012a5780633e13fdb61461012557806347f391de1461012057806349ffd5671461011b5780635315f030146101165780635c60da1b1461011157806364ca47291461010c5780639010d07c146101075780639019d0221461010257806391d14854146100fd578063ab02b870146100f8578063c4d66de8146100f3578063ca15c873146100ee578063d1fd27b3146100e9578063d547741f146100e45763e1e735bd146100df575f80fd5b610fab565b610f1b565b610e73565b610e49565b610d56565b610cba565b610c67565b610aa9565b610a64565b6109e3565b6109bb565b610765565b6105cb565b61052d565b61047f565b6103ee565b6102e9565b61026c565b634e487b7160e01b5f52604160045260245ffd5b90601f8019910116810190811067ffffffffffffffff82111761016f57604052565b610139565b6040519061018360608361014d565b565b6040519061018360208361014d565b90610183604051928361014d565b600435906001600160a01b03821682036101b857565b5f80fd5b602435906001600160a01b03821682036101b857565b604435906001600160a01b03821682036101b857565b35906001600160a01b03821682036101b857565b9080601f830112156101b85781359167ffffffffffffffff831161016f578260051b9060405193610230602084018661014d565b84526020808501928201019283116101b857602001905b8282106102545750505090565b60208091610261846101e8565b815201910190610247565b346101b85760403660031901126101b85760243560043567ffffffffffffffff82116101b8576102c17f886eab8a483379fbfe2239e3fa4f879253ef970d01df960ff94a2a73d8d771579236906004016101fc565b906102cb336113e5565b6102d582826116fa565b6102e460405192839283611154565b0390a1005b346101b85760603660031901126101b8576103026101a2565b60243560443591610312336113e5565b6001600160a01b038116926103298285151561123c565b61034782610342865f52603a60205260405f2054151590565b611635565b833b156101b85760405163d1fd27b360e01b81526004810184905260248101829052935f908590604490829084905af19081156103e9577fcfb31fed64957f3c78f11afea8503e0d7cfb03d1fcb195acea5f6fa7e51419ca946102e4926103cf575b5060405193849384604091949392606082019560018060a01b0316825260208201520152565b806103dd5f6103e39361014d565b806109b1565b5f6103a9565b6116ef565b346101b85760403660031901126101b85760043561040a6101bc565b610413336113e5565b5f8281526001602081815260408084206001600160a01b039095168085529490920190529020541561044157005b815f5260016020526104568160405f20611fe3565b5033917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d5f80a4005b346101b85760603660031901126101b8577f19f33359217c73dfadcd5891584423e897185805b3fc3a163f279115dde5f8a260606004356044356024356104c5336113e5565b6104e3836104de815f52603d60205260405f2054151590565b61154f565b825f52603b6020526104fc8282600260405f2001611a4e565b60405192835260208301526040820152a1005b6024359081151582036101b857565b6044359081151582036101b857565b346101b85760403660031901126101b8577f7958ffc90e123bc1edc47c475e4d4fa2983d16b1c82f6874a565642939bdba9560406105696101a2565b61057161050f565b61057a336113e5565b6001600160a01b038216916105919083151561123c565b815f52603f6020526105b181845f209060ff801983541691151516179055565b825191825215156020820152a1005b60ff8116036101b857565b346101b85760603660031901126101b8576105e46101a2565b6024356105f0816105c0565b6105f861051e565b91610602336113e5565b6001600160a01b0381166106188282151561123c565b805f52603660205260ff60405f2054166106e357506102e47f22a35aa1cd3e43c59ed5bd7131b6cc41d6bb6b178ab74e69753f345aad29b0759361069d61065f8585611df5565b61067961066a610174565b600181529160ff166020830152565b82151560408201526001600160a01b0385165f90815260366020526040902061187f565b6106ac603554608081106118ca565b6106b583611913565b604080516001600160a01b03909416845260ff90941660208401521515928201929092529081906060820190565b632e1c6ef760e11b5f5260045260245ffd5b67ffffffffffffffff811161016f57601f01601f191660200190565b92919261071d826106f5565b9161072b604051938461014d565b8294818452818301116101b8578281602093845f960137010152565b9080601f830112156101b85781602061076293359101610711565b90565b346101b85760803660031901126101b85760043567ffffffffffffffff81116101b857610796903690600401610747565b60243567ffffffffffffffff81116101b8576107b6903690600401610747565b6107be6101d2565b916064356107cb336113e5565b6001600160a01b0384165f8181526036602052604090205490949060ff161561099e579161097d6109209492846108ee6108d76108dd8a6108327f60a67166e17b7187511118d6c049f9583680009d6e5fe1381879aadb468d27259a61099a9d151561123c565b61088460405180926303bf912560e11b60208301526060602483015261087061085e608484018d61116b565b8381036023190160448501528d61116b565b90606483015203601f19810183528261014d565b6108b96108b96108c761064d9361089d60208601610194565b948086526121b760208701396040519283913060208401612036565b03601f19810183528261014d565b60405194859360208501906113c2565b906113c2565b6108e8838888612058565b906120a2565b968792610906846001600160a01b038116151561123c565b6109166039549182818114611978565b61010081106118ee565b61094b826109466109416001600160a01b0383165b6001600160a01b031690565b611f2c565b611672565b6001600160a01b0381165f908152603660205260409020610970905460081c60ff1690565b906040519586958661118f565b0390a16040516001600160a01b0390911681529081906020820190565b0390f35b846319ec4ea760e11b5f5260045260245ffd5b5f9103126101b857565b346101b8575f3660031901126101b857603e546040516001600160a01b039091168152602090f35b346101b85760403660031901126101b8577f1f457e2e7d9037059e3ec29ef5de83ec84fe9be0a77700765e171a0e9fcfd3fc600435610a2061050f565b90610a2a336113e5565b805f526041602052610a4b8260405f209060ff801983541691151516179055565b60408051918252911515602082015290819081016102e4565b346101b85760403660031901126101b8576020610a90600435602435905f526001835260405f2061165d565b905460405160039290921b1c6001600160a01b03168152f35b346101b85760603660031901126101b857600435610ac56101bc565b6044359167ffffffffffffffff83116101b857366023840112156101b8576040610b44610afd5f953690602481600401359101610711565b610b06336114bb565b610b11841515611996565b6001600160a01b03851690610b288683151561123c565b8351968780948193633fb6f06760e21b835288600484016119e4565b03925af19283156103e9577facb4574539203a32ae0ff5b51718b5b2645bf595a95f67e1ae15d29a9754a6bb936102e4915f905f92610c35575b5080610b9c610b95865f52604160205260405f2090565b5460ff1690565b610bd0575b5080845d60405194859485909493926060926080830196835260018060a01b0316602083015260408201520152565b610bf1610be3610bde611e93565b6119fb565b670de0b6b3a7640000900490565b9080610bfc8361159b565b10159182610c21575b5050610c12575b5f610ba1565b50670de0b6b3a7640000610c0c565b610c2c919250611a32565b11155f80610c05565b9050610c59915060403d604011610c60575b610c51818361014d565b8101906119ce565b905f610b7e565b503d610c47565b346101b85760403660031901126101b8576020610cb0600435610c886101bc565b5f918252600180855260408084206001600160a01b0390931684529101602052902054151590565b6040519015158152f35b346101b85760203660031901126101b857610cd36101a2565b610cdc336113e5565b6001600160a01b03811690610cf39082151561123c565b603e546001600160a01b0381168214610d43576001600160a01b0319168117603e556040519081527f5d4f24edeca778592467fa8d7b21e4a61b4195320b43d5bfbb0dec53f976549290602090a1005b5063749da11360e11b5f5260045260245ffd5b346101b85760203660031901126101b857610d6f6101a2565b610dbd5f5491610da3610d8d610d898560ff9060081c1690565b1590565b80948195610e3b575b8115610e1b575b506111d9565b82610db4600160ff195f5416175f55565b610e0457611264565b610dc357005b610dd15f5461ff0019165f55565b604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989080602081016102e4565b610e166101005f5461ff001916175f55565b611264565b303b15915081610e2d575b505f610d9d565b60ff1660011490505f610e26565b600160ff8216109150610d96565b346101b85760203660031901126101b8576004355f526001602052602060405f2054604051908152f35b346101b85760403660031901126101b8577fc5f4eda54c0dc8244a27193c9ba57b1f24e57ca6787830fc5835325a04ddb06b602435600435610eb4336113e5565b805f5260346020528160405f20557f926b2cda941e79b7fc4ae2533b0a876ab25766c11d4903f47ffb33bedfc1e67360405180610eff85858360209093929193604081019481520152565b0390a160408051918252602082019290925290819081016102e4565b346101b85760403660031901126101b857600435610f376101bc565b610f40336113e5565b5f8281526001602081815260408084206001600160a01b03909516808552949092019052902054610f6d57005b815f526001602052610f828160405f20612106565b5033917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b5f80a4005b346101b85760803660031901126101b85760043560243567ffffffffffffffff81116101b857610fdf903690600401610747565b610fe761051e565b60643567ffffffffffffffff81116101b8576110079036906004016101fc565b91611011336113e5565b83156111055761102c845f52603d60205260405f2054151590565b6110f25783917f18a6f1b86d393c747ca9045668cfcd87c44772c238de9a4a536bbfb7f8c33d30917f886eab8a483379fbfe2239e3fa4f879253ef970d01df960ff94a2a73d8d77157955f52603b60205261108a8160405f20611b43565b6110b48260016110a2875f52603b60205260405f2090565b019060ff801983541691151516179055565b6110c3603c54608081106118ca565b6110d46110cf85611f95565b611c0b565b6110e5856040519384938785611390565b0390a16102d582826116fa565b83634db7281d60e11b5f5260045260245ffd5b836337e9e5d160e11b5f5260045260245ffd5b90602080835192838152019201905f5b8181106111355750505090565b82516001600160a01b0316845260209384019390920191600101611128565b604090610762939281528160208201520190611118565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b936111bb6080949796936111ad60ff9460a0895260a089019061116b565b90878203602089015261116b565b6001600160a01b039788166040870152911660608501529416910152565b156111e057565b60405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608490fd5b156112445750565b634726455360e11b5f9081526001600160a01b0391909116600452602490fd5b60ff5f5460081c161561133757335f8181527fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb4a6020526040902054156112d7575b506001600160a01b038116906112bd9082151561123c565b6bffffffffffffffffffffffff60a01b6040541617604055565b5f80526001602052611309817fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb49611fe3565b5033905f7f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d8180a45f6112a5565b60405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608490fd5b9061076294926113ad91835260806020840152608083019061116b565b92151560408201526060818403910152611118565b805191908290602001825e015f815290565b90602061076292818152019061116b565b6001600160a01b03165f8181527fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb4a6020526040902054156114235750565b6114796114976114356114b793611cd8565b6108b96114415f611d72565b60116040519586946017602087017f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815201906113c2565b7001034b99036b4b9b9b4b733903937b6329607d1b815201906113c2565b60405162461bcd60e51b815260206004820152918291602483019061116b565b0390fd5b6001600160a01b03165f8181527f1dcf711afb65f2ac88b320cf38bd6f6279d286578a3288c803f3e3c71e44c9fe6020526040902054156114f95750565b61147961153761150b6114b793611cd8565b6108b96114417f1f6ff8cdb729dffbc2de528d342591f244815601111ae4e0ae059cc92f120c59611d72565b60405162461bcd60e51b8152918291600483016113d4565b156115575750565b639773311360e01b5f5260045260245ffd5b156115715750565b633b5cfc6960e21b5f526004525f60245260445ffd5b634e487b7160e01b5f52601160045260245ffd5b670de0b6b3a7640000019081670de0b6b3a7640000116115b757565b611587565b90600282018092116115b757565b90600182018092116115b757565b919082018092116115b757565b156115ee575050565b63e12f2cd160e01b5f52601060045260245260445260645ffd5b634e487b7160e01b5f52603260045260245ffd5b80518210156116305760209160051b010190565b611608565b1561163d5750565b633f36c1ab60e01b5f9081526001600160a01b0391909116600452602490fd5b8054821015611630575f5260205f2001905f90565b1561167a5750565b635d6c86f960e11b5f9081526001600160a01b0391909116600452602490fd5b8054600160401b81101561016f576116b79160018201815561165d565b9190916116dc575181546001600160a01b0319166001600160a01b0391909116179055565b634e487b7160e01b5f525f60045260245ffd5b6040513d5f823e3d90fd5b611713816104de815f52603d60205260405f2054151590565b6117208251801515611569565b815190611735815f52603b60205260405f2090565b6003810193611753848654601061174c83836115d8565b11156115e5565b60015f9201915b84811061176957505050505050565b611783611776828461161c565b516001600160a01b031690565b6001600160a01b0381165f908152603a60205260409020549091906117ab9083901515611635565b86546001600160a01b03831692905f5b848a83831061184c57505050506117ec906117e66117d7610185565b6001600160a01b039092168252565b8861169a565b835460ff1691803b156101b857604051630dc4184760e21b81526004810187905292151560248401525f908390604490829084905af19182156103e957600192611838575b500161175a565b806103dd5f6118469361014d565b5f611831565b8483926118726109356118646001976118799661165d565b50546001600160a01b031690565b1415611672565b016117bb565b9061189981511515839060ff801983541691151516179055565b602081015182546040929092015162ffff001990921660089190911b61ff00161790151560101b62ff000016179055565b156118d25750565b63e12f2cd160e01b5f526080600452602452600160445260645ffd5b156118f65750565b63e12f2cd160e01b5f52610100600452602452600160445260645ffd5b603554600160401b81101561016f57600181016035556035548110156116305760355f527fcfa4bec1d3298408bb5afcfcd9c430549c5b31f8aa5c5848151c0a55f473c34d0180546001600160a01b0319166001600160a01b03909216919091179055565b15611981575050565b6323994f6360e21b5f5260045260245260445ffd5b1561199d57565b6040516356e22f5760e11b81526020600482015260086024820152671bdc9858db19525960c21b6044820152606490fd5b91908260409103126101b8576020825192015190565b60409061076293928152816020820152019061116b565b9081670de0b6b3a76400000291670de0b6b3a76400008304036115b757565b600181901b91906001600160ff1b038116036115b757565b670de0b6b3a76400000390670de0b6b3a764000082116115b757565b907f926b2cda941e79b7fc4ae2533b0a876ab25766c11d4903f47ffb33bedfc1e6739291815f526020528160405f2055611a9a6040519283928360209093929193604081019481520152565b0390a1565b90600182811c92168015611acd575b6020831014611ab957565b634e487b7160e01b5f52602260045260245ffd5b91607f1691611aae565b91611af09183549060031b91821b915f19901b19161790565b9055565b601f8211611b0157505050565b5f5260205f20906020601f840160051c83019310611b39575b601f0160051c01905b818110611b2e575050565b5f8155600101611b23565b9091508190611b1a565b919091825167ffffffffffffffff811161016f57611b6b81611b658454611a9f565b84611af4565b6020601f8211600114611ba6578190611af09394955f92611b9b575b50508160011b915f199060031b1c19161790565b015190505f80611b87565b601f19821690611bb9845f5260205f2090565b915f5b818110611bf357509583600195969710611bdb575b505050811b019055565b01515f1960f88460031b161c191690555f8080611bd1565b9192602060018192868b015181550194019201611bbc565b15611c1257565b63320e5acb60e21b5f5260045ffd5b90611c2b826106f5565b611c38604051918261014d565b8281528092611c49601f19916106f5565b0190602036910137565b8051156116305760200190565b8051600110156116305760210190565b908151811015611630570160200190565b80156115b7575f190190565b15611c9457565b606460405162461bcd60e51b815260206004820152602060248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152fd5b611cea611ce560286115bc565b611c21565b906030611cf683611c53565b536078611d0283611c60565b53611d15611d106014611a1a565b6115ca565b905b60018211611d2a57610762915015611c8d565b600f8116601081101561163057611d6c91611d66916f181899199a1a9b1b9c1cb0b131b232b360811b901a611d5f8587611c70565b5360041c90565b91611c81565b90611d17565b611d7f611ce560406115bc565b906030611d8b83611c53565b536078611d9783611c60565b53611da5611d106020611a1a565b905b60018211611dba57610762915015611c8d565b600f8116601081101561163057611def91611d66916f181899199a1a9b1b9c1cb0b131b232b360811b901a611d5f8587611c70565b90611da7565b60405163313ce56760e01b815290602090829060049082906001600160a01b03165afa5f9181611e56575b50611e29575090565b9060ff811660ff831603611e3b575090565b60ff8092633c2b8a3160e01b5f52166004521660245260445ffd5b9091506020813d602011611e8b575b81611e726020938361014d565b810103126101b85751611e84816105c0565b905f611e20565b3d9150611e65565b7f3d3e547c06f13c203a848d7a9a911ecfabd1babd962359e8ed13468eea4c53025f5260346020527f60c60c5eb342733610d378487dda5807456142f7c29814df68dca7e89b2715c954908115611ee657565b60405163574b009160e11b815260206004820152601a60248201527f4d435f5354524943545f535441424c455f444556494154494f4e0000000000006044820152606490fd5b5f818152603a6020526040902054611f9057603954600160401b81101561016f57611f79611f63826001859401603955603961165d565b819391549060031b91821b915f19901b19161790565b9055603954905f52603a60205260405f2055600190565b505f90565b5f818152603d6020526040902054611f9057603c54600160401b81101561016f57611fcc611f63826001859401603c55603c61165d565b9055603c54905f52603d60205260405f2055600190565b5f82815260018201602052604090205461203057805490600160401b82101561016f578261201b611f6384600180960185558461165d565b90558054925f520160205260405f2055600190565b50505f90565b6001600160a01b0390911681526040602082018190526107629291019061116b565b9160146120779261209c926040519485926108d76020850180996113c2565b906bffffffffffffffffffffffff199060601b16815203600b1981018452018261014d565b51902090565b8051906020015ff5906001600160a01b038216156120bc57565b6330e6a5f960e11b5f5260045ffd5b805480156120f2575f1901906120e1828261165d565b8154905f199060031b1b1916905555565b634e487b7160e01b5f52603160045260245ffd5b6001810191805f528260205260405f2054928315155f146121ae575f1984018481116115b75783545f198101949085116115b7575f958583612154946121619803612167575b5050506120cb565b905f5260205260405f2090565b55600190565b6121976121919161218861217e6121a5958861165d565b90549060031b1c90565b9283918761165d565b90611ad7565b85905f5260205260405f2090565b555f808061214c565b505050505f9056fe60808060405261064d8038038091610017828561033c565b83398101906040818303126102335761002f81610373565b602082015190916001600160401b03821161023357019082601f8301121561023357815161005c81610387565b9261006a604051948561033c565b81845260208401946020838301011161023357815f926020809301875e84010152803b156102e957604051635c60da1b60e01b81526001600160a01b03919091169290602081600481875afa90811561023f575f916102af575b503b15610251577fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d5080546001600160a01b0319168417905560405192807f1cf3b03a6cf19fa2baba4df148e9dcabedea7f8a5c07840e207e5c089be95d3e5f80a282511580159061024a575b610144575b6040516101f690816104578239f35b83600481602093635c60da1b60e01b82525afa92831561023f575f936101fa575b50915f806101e8946040519461017c60608761033c565b602786527f416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c6020870152660819985a5b195960ca1b60408701525190845af43d156101f2573d916101cc83610387565b926101da604051948561033c565b83523d5f602085013e6103a2565b505f808080610135565b6060916103a2565b92506020833d602011610237575b816102156020938361033c565b81010312610233575f8061022b6101e895610373565b945050610165565b5f80fd5b3d9150610208565b6040513d5f823e3d90fd5b505f610130565b60405162461bcd60e51b815260206004820152603060248201527f455243313936373a20626561636f6e20696d706c656d656e746174696f6e206960448201526f1cc81b9bdd08184818dbdb9d1c9858dd60821b6064820152608490fd5b90506020813d6020116102e1575b816102ca6020938361033c565b81010312610233576102db90610373565b5f6100c4565b3d91506102bd565b60405162461bcd60e51b815260206004820152602560248201527f455243313936373a206e657720626561636f6e206973206e6f74206120636f6e6044820152641d1c9858dd60da1b6064820152608490fd5b601f909101601f19168101906001600160401b0382119082101761035f57604052565b634e487b7160e01b5f52604160045260245ffd5b51906001600160a01b038216820361023357565b6001600160401b03811161035f57601f01601f191660200190565b9192901561040457508151156103b6575090565b3b156103bf5790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b8251909150156104175750805190602001fd5b604460209160405192839162461bcd60e51b83528160048401528051918291826024860152018484015e5f828201840152601f01601f19168101030190fdfe6080604052366100be577fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d5054635c60da1b60e01b608090815260209160049082906001600160a01b03165afa80156100b3575f90156101a3575060203d6020116100ac575b601f19601f820116608001906080821067ffffffffffffffff831117610098576100939160405260800161015e565b6101a3565b634e487b7160e01b5f52604160045260245ffd5b503d610064565b6040513d5f823e3d90fd5b7fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d5054604051635c60da1b60e01b815290602090829060049082906001600160a01b03165afa9081156100b3575f91610117575b506101a3565b602091503d8211610156575b601f8201601f191681019167ffffffffffffffff8311828410176100985761015092604052810190610184565b5f610111565b3d9150610123565b602090607f190112610180576080516001600160a01b03811681036101805790565b5f80fd5b9081602091031261018057516001600160a01b03811681036101805790565b5f8091368280378136915af43d5f803e156101bc573d5ff35b3d5ffdfea2646970667358221220649c1156f9b4a727ad70a6b0b758353287fbb190d1adf588c7a52a229881f91e64736f6c634300081c0033a2646970667358221220857c4336af7634b9fcea595c21c92bd5b4400592d07b2e4f880582e506f176ac64736f6c634300081c0033

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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

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