{"sources":{"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.20;\n\nimport {IAccessControl} from \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {ERC165Upgradeable} from \"../utils/introspection/ERC165Upgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```solidity\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```solidity\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}\n * to enforce additional security measures for this role.\n */\nabstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {\n    struct RoleData {\n        mapping(address account => bool) hasRole;\n        bytes32 adminRole;\n    }\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl\n    struct AccessControlStorage {\n        mapping(bytes32 role => RoleData) _roles;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.AccessControl\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;\n\n    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {\n        assembly {\n            $.slot := AccessControlStorageLocation\n        }\n    }\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with an {AccessControlUnauthorizedAccount} error including the required role.\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role);\n        _;\n    }\n\n    function __AccessControl_init() internal onlyInitializing {\n    }\n\n    function __AccessControl_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        return $._roles[role].hasRole[account];\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`\n     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.\n     */\n    function _checkRole(bytes32 role) internal view virtual {\n        _checkRole(role, _msgSender());\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`\n     * is missing `role`.\n     */\n    function _checkRole(bytes32 role, address account) internal view virtual {\n        if (!hasRole(role, account)) {\n            revert AccessControlUnauthorizedAccount(account, role);\n        }\n    }\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        return $._roles[role].adminRole;\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been revoked `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `callerConfirmation`.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) public virtual {\n        if (callerConfirmation != _msgSender()) {\n            revert AccessControlBadConfirmation();\n        }\n\n        _revokeRole(role, callerConfirmation);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``'s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        bytes32 previousAdminRole = getRoleAdmin(role);\n        $._roles[role].adminRole = adminRole;\n        emit RoleAdminChanged(role, previousAdminRole, adminRole);\n    }\n\n    /**\n     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        if (!hasRole(role, account)) {\n            $._roles[role].hasRole[account] = true;\n            emit RoleGranted(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        if (hasRole(role, account)) {\n            $._roles[role].hasRole[account] = false;\n            emit RoleRevoked(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Storage of the initializable contract.\n     *\n     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n     * when using with upgradeable contracts.\n     *\n     * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n     */\n    struct InitializableStorage {\n        /**\n         * @dev Indicates that the contract has been initialized.\n         */\n        uint64 _initialized;\n        /**\n         * @dev Indicates that the contract is in the process of being initialized.\n         */\n        bool _initializing;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n    /**\n     * @dev The contract is already initialized.\n     */\n    error InvalidInitialization();\n\n    /**\n     * @dev The contract is not initializing.\n     */\n    error NotInitializing();\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint64 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n     * production.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        // Cache values to avoid duplicated sloads\n        bool isTopLevelCall = !$._initializing;\n        uint64 initialized = $._initialized;\n\n        // Allowed calls:\n        // - initialSetup: the contract is not in the initializing state and no previous version was\n        //                 initialized\n        // - construction: the contract is initialized at version 1 (no reininitialization) and the\n        //                 current contract is just being deployed\n        bool initialSetup = initialized == 0 && isTopLevelCall;\n        bool construction = initialized == 1 && address(this).code.length == 0;\n\n        if (!initialSetup && !construction) {\n            revert InvalidInitialization();\n        }\n        $._initialized = 1;\n        if (isTopLevelCall) {\n            $._initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            $._initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint64 version) {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing || $._initialized >= version) {\n            revert InvalidInitialization();\n        }\n        $._initialized = version;\n        $._initializing = true;\n        _;\n        $._initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        _checkInitializing();\n        _;\n    }\n\n    /**\n     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n     */\n    function _checkInitializing() internal view virtual {\n        if (!_isInitializing()) {\n            revert NotInitializing();\n        }\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing) {\n            revert InvalidInitialization();\n        }\n        if ($._initialized != type(uint64).max) {\n            $._initialized = type(uint64).max;\n            emit Initialized(type(uint64).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint64) {\n        return _getInitializableStorage()._initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _getInitializableStorage()._initializing;\n    }\n\n    /**\n     * @dev Returns a pointer to the storage namespace.\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n        assembly {\n            $.slot := INITIALIZABLE_STORAGE\n        }\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport {IERC721Receiver} from \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\nimport {IERC721Metadata} from \"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol\";\nimport {ContextUpgradeable} from \"../../utils/ContextUpgradeable.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {ERC165Upgradeable} from \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport {IERC721Errors} from \"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\nabstract contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721, IERC721Metadata, IERC721Errors {\n    using Strings for uint256;\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC721\n    struct ERC721Storage {\n        // Token name\n        string _name;\n\n        // Token symbol\n        string _symbol;\n\n        mapping(uint256 tokenId => address) _owners;\n\n        mapping(address owner => uint256) _balances;\n\n        mapping(uint256 tokenId => address) _tokenApprovals;\n\n        mapping(address owner => mapping(address operator => bool)) _operatorApprovals;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC721StorageLocation = 0x80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab0079300;\n\n    function _getERC721Storage() private pure returns (ERC721Storage storage $) {\n        assembly {\n            $.slot := ERC721StorageLocation\n        }\n    }\n\n    /**\n     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n     */\n    function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n        __ERC721_init_unchained(name_, symbol_);\n    }\n\n    function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n        ERC721Storage storage $ = _getERC721Storage();\n        $._name = name_;\n        $._symbol = symbol_;\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {\n        return\n            interfaceId == type(IERC721).interfaceId ||\n            interfaceId == type(IERC721Metadata).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev See {IERC721-balanceOf}.\n     */\n    function balanceOf(address owner) public view virtual returns (uint256) {\n        ERC721Storage storage $ = _getERC721Storage();\n        if (owner == address(0)) {\n            revert ERC721InvalidOwner(address(0));\n        }\n        return $._balances[owner];\n    }\n\n    /**\n     * @dev See {IERC721-ownerOf}.\n     */\n    function ownerOf(uint256 tokenId) public view virtual returns (address) {\n        return _requireOwned(tokenId);\n    }\n\n    /**\n     * @dev See {IERC721Metadata-name}.\n     */\n    function name() public view virtual returns (string memory) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._name;\n    }\n\n    /**\n     * @dev See {IERC721Metadata-symbol}.\n     */\n    function symbol() public view virtual returns (string memory) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._symbol;\n    }\n\n    /**\n     * @dev See {IERC721Metadata-tokenURI}.\n     */\n    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {\n        _requireOwned(tokenId);\n\n        string memory baseURI = _baseURI();\n        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : \"\";\n    }\n\n    /**\n     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n     * by default, can be overridden in child contracts.\n     */\n    function _baseURI() internal view virtual returns (string memory) {\n        return \"\";\n    }\n\n    /**\n     * @dev See {IERC721-approve}.\n     */\n    function approve(address to, uint256 tokenId) public virtual {\n        _approve(to, tokenId, _msgSender());\n    }\n\n    /**\n     * @dev See {IERC721-getApproved}.\n     */\n    function getApproved(uint256 tokenId) public view virtual returns (address) {\n        _requireOwned(tokenId);\n\n        return _getApproved(tokenId);\n    }\n\n    /**\n     * @dev See {IERC721-setApprovalForAll}.\n     */\n    function setApprovalForAll(address operator, bool approved) public virtual {\n        _setApprovalForAll(_msgSender(), operator, approved);\n    }\n\n    /**\n     * @dev See {IERC721-isApprovedForAll}.\n     */\n    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._operatorApprovals[owner][operator];\n    }\n\n    /**\n     * @dev See {IERC721-transferFrom}.\n     */\n    function transferFrom(address from, address to, uint256 tokenId) public virtual {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        // Setting an \"auth\" arguments enables the `_isAuthorized` check which verifies that the token exists\n        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.\n        address previousOwner = _update(to, tokenId, _msgSender());\n        if (previousOwner != from) {\n            revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n        }\n    }\n\n    /**\n     * @dev See {IERC721-safeTransferFrom}.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId) public {\n        safeTransferFrom(from, to, tokenId, \"\");\n    }\n\n    /**\n     * @dev See {IERC721-safeTransferFrom}.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {\n        transferFrom(from, to, tokenId);\n        _checkOnERC721Received(from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n     *\n     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the\n     * core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances\n     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by\n     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.\n     */\n    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._owners[tokenId];\n    }\n\n    /**\n     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.\n     */\n    function _getApproved(uint256 tokenId) internal view virtual returns (address) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._tokenApprovals[tokenId];\n    }\n\n    /**\n     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in\n     * particular (ignoring whether it is owned by `owner`).\n     *\n     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n     * assumption.\n     */\n    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {\n        return\n            spender != address(0) &&\n            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);\n    }\n\n    /**\n     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.\n     * Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets\n     * the `spender` for the specific `tokenId`.\n     *\n     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n     * assumption.\n     */\n    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {\n        if (!_isAuthorized(owner, spender, tokenId)) {\n            if (owner == address(0)) {\n                revert ERC721NonexistentToken(tokenId);\n            } else {\n                revert ERC721InsufficientApproval(spender, tokenId);\n            }\n        }\n    }\n\n    /**\n     * @dev Unsafe write access to the balances, used by extensions that \"mint\" tokens using an {ownerOf} override.\n     *\n     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that\n     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.\n     *\n     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the\n     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership\n     * remain consistent with one another.\n     */\n    function _increaseBalance(address account, uint128 value) internal virtual {\n        ERC721Storage storage $ = _getERC721Storage();\n        unchecked {\n            $._balances[account] += value;\n        }\n    }\n\n    /**\n     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner\n     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.\n     *\n     * The `auth` argument is optional. If the value passed is non 0, then this function will check that\n     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.\n     */\n    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {\n        ERC721Storage storage $ = _getERC721Storage();\n        address from = _ownerOf(tokenId);\n\n        // Perform (optional) operator check\n        if (auth != address(0)) {\n            _checkAuthorized(from, auth, tokenId);\n        }\n\n        // Execute the update\n        if (from != address(0)) {\n            // Clear approval. No need to re-authorize or emit the Approval event\n            _approve(address(0), tokenId, address(0), false);\n\n            unchecked {\n                $._balances[from] -= 1;\n            }\n        }\n\n        if (to != address(0)) {\n            unchecked {\n                $._balances[to] += 1;\n            }\n        }\n\n        $._owners[tokenId] = to;\n\n        emit Transfer(from, to, tokenId);\n\n        return from;\n    }\n\n    /**\n     * @dev Mints `tokenId` and transfers it to `to`.\n     *\n     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - `to` cannot be the zero address.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _mint(address to, uint256 tokenId) internal {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        address previousOwner = _update(to, tokenId, address(0));\n        if (previousOwner != address(0)) {\n            revert ERC721InvalidSender(address(0));\n        }\n    }\n\n    /**\n     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeMint(address to, uint256 tokenId) internal {\n        _safeMint(to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {\n        _mint(to, tokenId);\n        _checkOnERC721Received(address(0), to, tokenId, data);\n    }\n\n    /**\n     * @dev Destroys `tokenId`.\n     * The approval is cleared when the token is burned.\n     * This is an internal function that does not check if the sender is authorized to operate on the token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _burn(uint256 tokenId) internal {\n        address previousOwner = _update(address(0), tokenId, address(0));\n        if (previousOwner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        }\n    }\n\n    /**\n     * @dev Transfers `tokenId` from `from` to `to`.\n     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _transfer(address from, address to, uint256 tokenId) internal {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        address previousOwner = _update(to, tokenId, address(0));\n        if (previousOwner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        } else if (previousOwner != from) {\n            revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n        }\n    }\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients\n     * are aware of the ERC721 standard to prevent tokens from being forever locked.\n     *\n     * `data` is additional data, it has no specified format and it is sent in call to `to`.\n     *\n     * This internal function is like {safeTransferFrom} in the sense that it invokes\n     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.\n     * implement alternative mechanisms to perform token transfer, such as signature-based.\n     *\n     * Requirements:\n     *\n     * - `tokenId` token must exist and be owned by `from`.\n     * - `to` cannot be the zero address.\n     * - `from` cannot be the zero address.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeTransfer(address from, address to, uint256 tokenId) internal {\n        _safeTransfer(from, to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {\n        _transfer(from, to, tokenId);\n        _checkOnERC721Received(from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Approve `to` to operate on `tokenId`\n     *\n     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is\n     * either the owner of the token, or approved to operate on all tokens held by this owner.\n     *\n     * Emits an {Approval} event.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address to, uint256 tokenId, address auth) internal {\n        _approve(to, tokenId, auth, true);\n    }\n\n    /**\n     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not\n     * emitted in the context of transfers.\n     */\n    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {\n        ERC721Storage storage $ = _getERC721Storage();\n        // Avoid reading the owner unless necessary\n        if (emitEvent || auth != address(0)) {\n            address owner = _requireOwned(tokenId);\n\n            // We do not use _isAuthorized because single-token approvals should not be able to call approve\n            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {\n                revert ERC721InvalidApprover(auth);\n            }\n\n            if (emitEvent) {\n                emit Approval(owner, to, tokenId);\n            }\n        }\n\n        $._tokenApprovals[tokenId] = to;\n    }\n\n    /**\n     * @dev Approve `operator` to operate on all of `owner` tokens\n     *\n     * Requirements:\n     * - operator can't be the address zero.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n        ERC721Storage storage $ = _getERC721Storage();\n        if (operator == address(0)) {\n            revert ERC721InvalidOperator(operator);\n        }\n        $._operatorApprovals[owner][operator] = approved;\n        emit ApprovalForAll(owner, operator, approved);\n    }\n\n    /**\n     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).\n     * Returns the owner.\n     *\n     * Overrides to ownership logic should be done to {_ownerOf}.\n     */\n    function _requireOwned(uint256 tokenId) internal view returns (address) {\n        address owner = _ownerOf(tokenId);\n        if (owner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        }\n        return owner;\n    }\n\n    /**\n     * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the\n     * recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract.\n     *\n     * @param from address representing the previous owner of the given token ID\n     * @param to target address that will receive the tokens\n     * @param tokenId uint256 ID of the token to be transferred\n     * @param data bytes optional data to send along with the call\n     */\n    function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private {\n        if (to.code.length > 0) {\n            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n                if (retval != IERC721Receiver.onERC721Received.selector) {\n                    revert ERC721InvalidReceiver(to);\n                }\n            } catch (bytes memory reason) {\n                if (reason.length == 0) {\n                    revert ERC721InvalidReceiver(to);\n                } else {\n                    /// @solidity memory-safe-assembly\n                    assembly {\n                        revert(add(32, reason), mload(reason))\n                    }\n                }\n            }\n        }\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Enumerable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC721Upgradeable} from \"../ERC721Upgradeable.sol\";\nimport {IERC721Enumerable} from \"@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev This implements an optional extension of {ERC721} defined in the EIP that adds enumerability\n * of all the token ids in the contract as well as all token ids owned by each account.\n *\n * CAUTION: `ERC721` extensions that implement custom `balanceOf` logic, such as `ERC721Consecutive`,\n * interfere with enumerability and should not be used together with `ERC721Enumerable`.\n */\nabstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721Enumerable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC721Enumerable\n    struct ERC721EnumerableStorage {\n        mapping(address owner => mapping(uint256 index => uint256)) _ownedTokens;\n        mapping(uint256 tokenId => uint256) _ownedTokensIndex;\n\n        uint256[] _allTokens;\n        mapping(uint256 tokenId => uint256) _allTokensIndex;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721Enumerable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC721EnumerableStorageLocation = 0x645e039705490088daad89bae25049a34f4a9072d398537b1ab2425f24cbed00;\n\n    function _getERC721EnumerableStorage() private pure returns (ERC721EnumerableStorage storage $) {\n        assembly {\n            $.slot := ERC721EnumerableStorageLocation\n        }\n    }\n\n    /**\n     * @dev An `owner`'s token query was out of bounds for `index`.\n     *\n     * NOTE: The owner being `address(0)` indicates a global out of bounds index.\n     */\n    error ERC721OutOfBoundsIndex(address owner, uint256 index);\n\n    /**\n     * @dev Batch mint is not allowed.\n     */\n    error ERC721EnumerableForbiddenBatchMint();\n\n    function __ERC721Enumerable_init() internal onlyInitializing {\n    }\n\n    function __ERC721Enumerable_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721Upgradeable) returns (bool) {\n        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n     */\n    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        if (index >= balanceOf(owner)) {\n            revert ERC721OutOfBoundsIndex(owner, index);\n        }\n        return $._ownedTokens[owner][index];\n    }\n\n    /**\n     * @dev See {IERC721Enumerable-totalSupply}.\n     */\n    function totalSupply() public view virtual returns (uint256) {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        return $._allTokens.length;\n    }\n\n    /**\n     * @dev See {IERC721Enumerable-tokenByIndex}.\n     */\n    function tokenByIndex(uint256 index) public view virtual returns (uint256) {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        if (index >= totalSupply()) {\n            revert ERC721OutOfBoundsIndex(address(0), index);\n        }\n        return $._allTokens[index];\n    }\n\n    /**\n     * @dev See {ERC721-_update}.\n     */\n    function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {\n        address previousOwner = super._update(to, tokenId, auth);\n\n        if (previousOwner == address(0)) {\n            _addTokenToAllTokensEnumeration(tokenId);\n        } else if (previousOwner != to) {\n            _removeTokenFromOwnerEnumeration(previousOwner, tokenId);\n        }\n        if (to == address(0)) {\n            _removeTokenFromAllTokensEnumeration(tokenId);\n        } else if (previousOwner != to) {\n            _addTokenToOwnerEnumeration(to, tokenId);\n        }\n\n        return previousOwner;\n    }\n\n    /**\n     * @dev Private function to add a token to this extension's ownership-tracking data structures.\n     * @param to address representing the new owner of the given token ID\n     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address\n     */\n    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        uint256 length = balanceOf(to) - 1;\n        $._ownedTokens[to][length] = tokenId;\n        $._ownedTokensIndex[tokenId] = length;\n    }\n\n    /**\n     * @dev Private function to add a token to this extension's token tracking data structures.\n     * @param tokenId uint256 ID of the token to be added to the tokens list\n     */\n    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        $._allTokensIndex[tokenId] = $._allTokens.length;\n        $._allTokens.push(tokenId);\n    }\n\n    /**\n     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that\n     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\n     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\n     * This has O(1) time complexity, but alters the order of the _ownedTokens array.\n     * @param from address representing the previous owner of the given token ID\n     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\n     */\n    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\n        // then delete the last slot (swap and pop).\n\n        uint256 lastTokenIndex = balanceOf(from);\n        uint256 tokenIndex = $._ownedTokensIndex[tokenId];\n\n        // When the token to delete is the last token, the swap operation is unnecessary\n        if (tokenIndex != lastTokenIndex) {\n            uint256 lastTokenId = $._ownedTokens[from][lastTokenIndex];\n\n            $._ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n            $._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n        }\n\n        // This also deletes the contents at the last position of the array\n        delete $._ownedTokensIndex[tokenId];\n        delete $._ownedTokens[from][lastTokenIndex];\n    }\n\n    /**\n     * @dev Private function to remove a token from this extension's token tracking data structures.\n     * This has O(1) time complexity, but alters the order of the _allTokens array.\n     * @param tokenId uint256 ID of the token to be removed from the tokens list\n     */\n    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\n        ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\n        // then delete the last slot (swap and pop).\n\n        uint256 lastTokenIndex = $._allTokens.length - 1;\n        uint256 tokenIndex = $._allTokensIndex[tokenId];\n\n        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\n        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\n        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)\n        uint256 lastTokenId = $._allTokens[lastTokenIndex];\n\n        $._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n        $._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n\n        // This also deletes the contents at the last position of the array\n        delete $._allTokensIndex[tokenId];\n        $._allTokens.pop();\n    }\n\n    /**\n     * See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch\n     */\n    function _increaseBalance(address account, uint128 amount) internal virtual override {\n        if (amount > 0) {\n            revert ERC721EnumerableForbiddenBatchMint();\n        }\n        super._increaseBalance(account, amount);\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165 {\n    function __ERC165_init() internal onlyInitializing {\n    }\n\n    function __ERC165_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"},"@openzeppelin/contracts/access/IAccessControl.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n    /**\n     * @dev The `account` is missing a role.\n     */\n    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);\n\n    /**\n     * @dev The caller of a function is not the expected one.\n     *\n     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.\n     */\n    error AccessControlBadConfirmation();\n\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted signaling this.\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call, an admin role\n     * bearer except when using {AccessControl-_setupRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) external view returns (bool);\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function grantRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function revokeRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `callerConfirmation`.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) external;\n}\n"},"@openzeppelin/contracts/interfaces/draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\n     * Used in balance queries.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721InvalidOwner(address owner);\n\n    /**\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721NonexistentToken(uint256 tokenId);\n\n    /**\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param tokenId Identifier number of a token.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC721InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC721InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC721InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\n */\ninterface IERC1155Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC1155InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC1155InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC1155MissingApprovalForAll(address operator, address owner);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC1155InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC1155InvalidOperator(address operator);\n\n    /**\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n     * Used in batch transfers.\n     * @param idsLength Length of the array of token identifiers\n     * @param valuesLength Length of the array of token amounts\n     */\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"},"@openzeppelin/contracts/token/ERC721/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n    /**\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n     */\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n     */\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n    /**\n     * @dev Returns the number of tokens in ``owner``'s account.\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @dev Returns the owner of the `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n     *   a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or\n     *   {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n     *   a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n     * understand this adds an external call which potentially creates a reentrancy vulnerability.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the address zero.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function setApprovalForAll(address operator, bool approved) external;\n\n    /**\n     * @dev Returns the account approved for `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function getApproved(uint256 tokenId) external view returns (address operator);\n\n    /**\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n     *\n     * See {setApprovalForAll}\n     */\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"},"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n    /**\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n     * by `operator` from `from`, this function is called.\n     *\n     * It must return its Solidity selector to confirm the token transfer.\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be\n     * reverted.\n     *\n     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address operator,\n        address from,\n        uint256 tokenId,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"},"@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n    /**\n     * @dev Returns the total amount of tokens stored by the contract.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.\n     */\n    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);\n\n    /**\n     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n     * Use along with {totalSupply} to enumerate all tokens.\n     */\n    function tokenByIndex(uint256 index) external view returns (uint256);\n}\n"},"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n    /**\n     * @dev Returns the token collection name.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the token collection symbol.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n     */\n    function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"},"@openzeppelin/contracts/utils/Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n    uint8 private constant ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev The `value` string doesn't fit in the specified `length`.\n     */\n    error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            /// @solidity memory-safe-assembly\n            assembly {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                /// @solidity memory-safe-assembly\n                assembly {\n                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toStringSigned(int256 value) internal pure returns (string memory) {\n        return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        uint256 localValue = value;\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = HEX_DIGITS[localValue & 0xf];\n            localValue >>= 4;\n        }\n        if (localValue != 0) {\n            revert StringsInsufficientHexLength(value, length);\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n     * representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n}\n"},"@openzeppelin/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"@openzeppelin/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    /**\n     * @dev Muldiv operation overflow.\n     */\n    error MathOverflowedMulDiv();\n\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            uint256 c = a + b;\n            if (c < a) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b > a) return (false, 0);\n            return (true, a - b);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n            // benefit is lost if 'b' is also tested.\n            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n            if (a == 0) return (true, 0);\n            uint256 c = a * b;\n            if (c / a != b) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a / b);\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a % b);\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            return a / b;\n        }\n\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0 = x * y; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            if (denominator <= prod1) {\n                revert MathOverflowedMulDiv();\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n}\n"},"@openzeppelin/contracts/utils/math/SignedMath.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // must be unchecked in order to support `n = type(int256).min`\n            return uint256(n >= 0 ? n : -n);\n        }\n    }\n}\n"},"contracts/common/codec/WordCodec.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n// solhint-disable no-inline-assembly\n\n/// @dev A subset copied from the following contracts:\n///\n/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol`\n/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodecHelpers.sol`\nlibrary WordCodec {\n  /// @dev Inserts an unsigned integer of bitLength, shifted by an offset, into a 256 bit word,\n  /// replacing the old value. Returns the new word.\n  function insertUint(\n    bytes32 word,\n    uint256 value,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (bytes32 result) {\n    // Equivalent to:\n    // uint256 mask = (1 << bitLength) - 1;\n    // bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));\n    // result = clearedWord | bytes32(value << offset);\n    assembly {\n      let mask := sub(shl(bitLength, 1), 1)\n      let clearedWord := and(word, not(shl(offset, mask)))\n      result := or(clearedWord, shl(offset, value))\n    }\n  }\n\n  /// @dev Decodes and returns an unsigned integer with `bitLength` bits, shifted by an offset, from a 256 bit word.\n  function decodeUint(\n    bytes32 word,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (uint256 result) {\n    // Equivalent to:\n    // result = uint256(word >> offset) & ((1 << bitLength) - 1);\n    assembly {\n      result := and(shr(offset, word), sub(shl(bitLength, 1), 1))\n    }\n  }\n\n  /// @dev Inserts a signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns\n  /// the new word.\n  ///\n  /// Assumes `value` can be represented using `bitLength` bits.\n  function insertInt(\n    bytes32 word,\n    int256 value,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (bytes32) {\n    unchecked {\n      uint256 mask = (1 << bitLength) - 1;\n      bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));\n      // Integer values need masking to remove the upper bits of negative values.\n      return clearedWord | bytes32((uint256(value) & mask) << offset);\n    }\n  }\n\n  /// @dev Decodes and returns a signed integer with `bitLength` bits, shifted by an offset, from a 256 bit word.\n  function decodeInt(\n    bytes32 word,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (int256 result) {\n    unchecked {\n      int256 maxInt = int256((1 << (bitLength - 1)) - 1);\n      uint256 mask = (1 << bitLength) - 1;\n\n      int256 value = int256(uint256(word >> offset) & mask);\n      // In case the decoded value is greater than the max positive integer that can be represented with bitLength\n      // bits, we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit\n      // representation.\n      //\n      // Equivalent to:\n      // result = value > maxInt ? (value | int256(~mask)) : value;\n      assembly {\n        result := or(mul(gt(value, maxInt), not(mask)), value)\n      }\n    }\n  }\n\n  /// @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.\n  function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool result) {\n    // Equivalent to:\n    // result = (uint256(word >> offset) & 1) == 1;\n    assembly {\n      result := and(shr(offset, word), 1)\n    }\n  }\n\n  /// @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new\n  /// word.\n  function insertBool(\n    bytes32 word,\n    bool value,\n    uint256 offset\n  ) internal pure returns (bytes32 result) {\n    // Equivalent to:\n    // bytes32 clearedWord = bytes32(uint256(word) & ~(1 << offset));\n    // bytes32 referenceInsertBool = clearedWord | bytes32(uint256(value ? 1 : 0) << offset);\n    assembly {\n      let clearedWord := and(word, not(shl(offset, 1)))\n      result := or(clearedWord, shl(offset, value))\n    }\n  }\n\n  function clearWordAtPosition(\n    bytes32 word,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (bytes32 clearedWord) {\n    unchecked {\n      uint256 mask = (1 << bitLength) - 1;\n      clearedWord = bytes32(uint256(word) & ~(mask << offset));\n    }\n  }\n}\n"},"contracts/core/pool/BasePool.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nimport { IPool } from \"../../interfaces/IPool.sol\";\nimport { IPoolConfiguration } from \"../../interfaces/IPoolConfiguration.sol\";\nimport { IPoolManager } from \"../../interfaces/IPoolManager.sol\";\nimport { IPriceOracle } from \"../../price-oracle/interfaces/IPriceOracle.sol\";\n\nimport { WordCodec } from \"../../common/codec/WordCodec.sol\";\nimport { Math } from \"../../libraries/Math.sol\";\nimport { TickBitmap } from \"../../libraries/TickBitmap.sol\";\nimport { PositionLogic } from \"./PositionLogic.sol\";\nimport { TickLogic } from \"./TickLogic.sol\";\n\nabstract contract BasePool is TickLogic, PositionLogic {\n  using TickBitmap for mapping(int8 => uint256);\n  using WordCodec for bytes32;\n\n  /***********\n   * Structs *\n   ***********/\n\n  struct OperationMemoryVar {\n    int256 tick;\n    uint48 node;\n    uint256 positionColl;\n    uint256 positionDebt;\n    int256 newColl;\n    int256 newDebt;\n    uint256 collIndex;\n    uint256 debtIndex;\n    uint256 globalColl;\n    uint256 globalDebt;\n    uint256 price;\n  }\n\n  /*************\n   * Modifiers *\n   *************/\n\n  modifier onlyPoolManager() {\n    if (_msgSender() != poolManager) {\n      revert ErrorCallerNotPoolManager();\n    }\n    _;\n  }\n\n  /***************\n   * Constructor *\n   ***************/\n\n  constructor(address _poolManager, address _configuration) {\n    _checkAddressNotZero(_poolManager);\n\n    poolManager = _poolManager;\n    fxUSD = IPoolManager(_poolManager).fxUSD();\n    configuration = _configuration;\n  }\n\n  function __BasePool_init() internal onlyInitializing {\n    _updateDebtIndex(E96);\n    _updateCollateralIndex(E96);\n    _updateDebtRatioRange(500000000000000000, 857142857142857142); // 1/2 ~ 6/7\n    _updateMaxRedeemRatioPerTick(200000000); // 20%\n  }\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc IPool\n  function operate(\n    uint256 positionId,\n    int256 newRawColl,\n    int256 newRawDebt,\n    address owner\n  ) external onlyPoolManager returns (uint256, int256, int256, uint256) {\n    if (newRawColl == 0 && newRawDebt == 0) revert ErrorNoSupplyAndNoBorrow();\n    if (newRawColl != 0 && (newRawColl > -MIN_COLLATERAL && newRawColl < MIN_COLLATERAL)) {\n      revert ErrorCollateralTooSmall();\n    }\n    if (newRawDebt != 0 && (newRawDebt > -MIN_DEBT && newRawDebt < MIN_DEBT)) {\n      revert ErrorDebtTooSmall();\n    }\n    if (newRawDebt > 0 && (_isBorrowPaused() || !IPoolConfiguration(configuration).isBorrowAllowed())) {\n      revert ErrorBorrowPaused();\n    }\n\n    OperationMemoryVar memory op;\n    // price precision and ratio precision are both 1e18, use min price here\n    op.price = IPriceOracle(priceOracle).getExchangePrice();\n    (op.globalDebt, op.globalColl) = _getDebtAndCollateralShares();\n    (op.collIndex, op.debtIndex) = _updateCollAndDebtIndex();\n    if (positionId == 0) {\n      positionId = _mintPosition(owner);\n    } else {\n      // make sure position is owned and check owner only in case of withdraw or borrow\n      if (ownerOf(positionId) != owner && (newRawColl < 0 || newRawDebt > 0)) {\n        revert ErrorNotPositionOwner();\n      }\n      PositionInfo memory position = _getAndUpdatePosition(positionId);\n      // temporarily remove position from tick tree for simplicity\n      _removePositionFromTick(position);\n      op.tick = position.tick;\n      op.node = position.nodeId;\n      op.positionDebt = position.debts;\n      op.positionColl = position.colls;\n\n      // cannot withdraw or borrow when the position is above liquidation ratio\n      if (newRawColl < 0 || newRawDebt > 0) {\n        uint256 rawColls = _convertToRawColl(op.positionColl, op.collIndex, Math.Rounding.Down);\n        uint256 rawDebts = _convertToRawDebt(op.positionDebt, op.debtIndex, Math.Rounding.Down);\n        (uint256 debtRatio, ) = _getLiquidateRatios();\n        if (rawDebts * PRECISION * PRECISION > debtRatio * rawColls * op.price) revert ErrorPositionInLiquidationMode();\n      }\n    }\n\n    uint256 protocolFees;\n    // supply or withdraw\n    if (newRawColl > 0) {\n      protocolFees = _deductProtocolFees(newRawColl);\n      newRawColl -= int256(protocolFees);\n      op.newColl = int256(_convertToCollShares(uint256(newRawColl), op.collIndex, Math.Rounding.Down));\n      op.positionColl += uint256(op.newColl);\n      op.globalColl += uint256(op.newColl);\n    } else if (newRawColl < 0) {\n      if (newRawColl == type(int256).min) {\n        // this is max withdraw\n        newRawColl = -int256(_convertToRawColl(op.positionColl, op.collIndex, Math.Rounding.Down));\n        op.newColl = -int256(op.positionColl);\n      } else {\n        // this is partial withdraw, rounding up removing extra wei from collateral\n        op.newColl = -int256(_convertToCollShares(uint256(-newRawColl), op.collIndex, Math.Rounding.Up));\n        if (uint256(-op.newColl) > op.positionColl) revert ErrorWithdrawExceedSupply();\n      }\n      unchecked {\n        op.positionColl -= uint256(-op.newColl);\n        op.globalColl -= uint256(-op.newColl);\n      }\n      protocolFees = _deductProtocolFees(newRawColl);\n      newRawColl += int256(protocolFees);\n    }\n\n    // borrow or repay\n    if (newRawDebt > 0) {\n      // rounding up adding extra wei in debt\n      op.newDebt = int256(_convertToDebtShares(uint256(newRawDebt), op.debtIndex, Math.Rounding.Up));\n      op.positionDebt += uint256(op.newDebt);\n      op.globalDebt += uint256(op.newDebt);\n    } else if (newRawDebt < 0) {\n      if (newRawDebt == type(int256).min) {\n        // this is max repay, rounding up amount that will be transferred in to pay back full debt:\n        // subtracting -1 of negative debtAmount newDebt_ for safe rounding (increasing payback)\n        newRawDebt = -int256(_convertToRawDebt(op.positionDebt, op.debtIndex, Math.Rounding.Up));\n        op.newDebt = -int256(op.positionDebt);\n      } else {\n        // this is partial repay, safe rounding up negative amount to rounding reduce payback\n        op.newDebt = -int256(_convertToDebtShares(uint256(-newRawDebt), op.debtIndex, Math.Rounding.Up));\n      }\n      op.positionDebt -= uint256(-op.newDebt);\n      op.globalDebt -= uint256(-op.newDebt);\n    }\n\n    // final debt ratio check\n    {\n      // check position debt ratio is between `minDebtRatio` and `maxDebtRatio`.\n      uint256 rawColls = _convertToRawColl(op.positionColl, op.collIndex, Math.Rounding.Down);\n      uint256 rawDebts = _convertToRawDebt(op.positionDebt, op.debtIndex, Math.Rounding.Down);\n      (uint256 minDebtRatio, uint256 maxDebtRatio) = _getDebtRatioRange();\n      if (rawDebts * PRECISION * PRECISION > maxDebtRatio * rawColls * op.price) revert ErrorDebtRatioTooLarge();\n      if (rawDebts * PRECISION * PRECISION < minDebtRatio * rawColls * op.price) revert ErrorDebtRatioTooSmall();\n    }\n\n    // update position state to storage\n    (op.tick, op.node) = _addPositionToTick(op.positionColl, op.positionDebt, true);\n\n    if (op.positionColl > type(uint96).max) revert ErrorOverflow();\n    if (op.positionDebt > type(uint96).max) revert ErrorOverflow();\n    positionData[positionId] = PositionInfo(int16(op.tick), op.node, uint96(op.positionColl), uint96(op.positionDebt));\n\n    // update global state to storage\n    _updateDebtAndCollateralShares(op.globalDebt, op.globalColl);\n\n    emit PositionSnapshot(positionId, int16(op.tick), op.positionColl, op.positionDebt, op.price);\n\n    return (positionId, newRawColl, newRawDebt, protocolFees);\n  }\n\n  /// @inheritdoc IPool\n  function redeem(uint256 rawDebts) external onlyPoolManager returns (uint256 actualRawDebts, uint256 rawColls) {\n    if (_isRedeemPaused()) revert ErrorRedeemPaused();\n\n    (actualRawDebts, rawColls) = _redeem(rawDebts, false);\n  }\n\n  /// @inheritdoc IPool\n  function rebalance(int16 tick, uint256 maxRawDebts) external onlyPoolManager returns (RebalanceResult memory result) {\n    (uint256 cachedCollIndex, uint256 cachedDebtIndex) = _updateCollAndDebtIndex();\n    (, uint256 price, ) = IPriceOracle(priceOracle).getPrice(); // use min price\n    uint256 node = tickData[tick];\n    bytes32 value = tickTreeData[node].value;\n    uint256 tickRawColl = _convertToRawColl(\n      value.decodeUint(COLL_SHARE_OFFSET, 128),\n      cachedCollIndex,\n      Math.Rounding.Down\n    );\n    uint256 tickRawDebt = _convertToRawDebt(\n      value.decodeUint(DEBT_SHARE_OFFSET, 128),\n      cachedDebtIndex,\n      Math.Rounding.Down\n    );\n    (uint256 rebalanceDebtRatio, uint256 rebalanceBonusRatio) = _getRebalanceRatios();\n    (uint256 liquidateDebtRatio, ) = _getLiquidateRatios();\n    // rebalance only debt ratio >= `rebalanceDebtRatio` and ratio < `liquidateDebtRatio`\n    if (tickRawDebt * PRECISION * PRECISION < rebalanceDebtRatio * tickRawColl * price) {\n      revert ErrorRebalanceDebtRatioNotReached();\n    }\n    if (tickRawDebt * PRECISION * PRECISION >= liquidateDebtRatio * tickRawColl * price) {\n      revert ErrorRebalanceOnLiquidatableTick();\n    }\n\n    // compute debts to rebalance to make debt ratio to `rebalanceDebtRatio`\n    result.rawDebts = _getRawDebtToRebalance(tickRawColl, tickRawDebt, price, rebalanceDebtRatio, rebalanceBonusRatio);\n    if (maxRawDebts < result.rawDebts) result.rawDebts = maxRawDebts;\n\n    uint256 debtShareToRebalance = _convertToDebtShares(result.rawDebts, cachedDebtIndex, Math.Rounding.Down);\n    result.rawColls = (result.rawDebts * PRECISION) / price;\n    result.bonusRawColls = (result.rawColls * rebalanceBonusRatio) / FEE_PRECISION;\n    if (result.bonusRawColls > tickRawColl - result.rawColls) {\n      result.bonusRawColls = tickRawColl - result.rawColls;\n    }\n    uint256 collShareToRebalance = _convertToCollShares(\n      result.rawColls + result.bonusRawColls,\n      cachedCollIndex,\n      Math.Rounding.Down\n    );\n\n    _liquidateTick(tick, collShareToRebalance, debtShareToRebalance, price);\n    unchecked {\n      (uint256 totalDebts, uint256 totalColls) = _getDebtAndCollateralShares();\n      _updateDebtAndCollateralShares(totalDebts - debtShareToRebalance, totalColls - collShareToRebalance);\n    }\n  }\n\n  struct RebalanceVars {\n    uint256 tickCollShares;\n    uint256 tickDebtShares;\n    uint256 tickRawColls;\n    uint256 tickRawDebts;\n    uint256 maxRawDebts;\n    uint256 rebalanceDebtRatio;\n    uint256 rebalanceBonusRatio;\n    uint256 price;\n    uint256 collIndex;\n    uint256 debtIndex;\n    uint256 totalCollShares;\n    uint256 totalDebtShares;\n  }\n\n  /// @inheritdoc IPool\n  function rebalance(uint256 maxRawDebts) external onlyPoolManager returns (RebalanceResult memory result) {\n    RebalanceVars memory vars;\n    vars.maxRawDebts = maxRawDebts;\n    (vars.rebalanceDebtRatio, vars.rebalanceBonusRatio) = _getRebalanceRatios();\n    (, vars.price, ) = IPriceOracle(priceOracle).getPrice();\n    (vars.collIndex, vars.debtIndex) = _updateCollAndDebtIndex();\n    (vars.totalDebtShares, vars.totalCollShares) = _getDebtAndCollateralShares();\n    (uint256 liquidateDebtRatio, ) = _getLiquidateRatios();\n\n    int16 tick = _getTopTick();\n    bool hasDebt = true;\n    while (vars.maxRawDebts > 0) {\n      if (!hasDebt) {\n        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);\n      } else {\n        (vars.tickCollShares, vars.tickDebtShares, vars.tickRawColls, vars.tickRawDebts) = _getTickRawCollAndDebts(\n          tick,\n          vars.collIndex,\n          vars.debtIndex\n        );\n        // skip bad debt and liquidatable positions: coll * price * liquidateDebtRatio <= debts\n        if (vars.tickRawColls * vars.price * liquidateDebtRatio <= vars.tickRawDebts * PRECISION * PRECISION) {\n          hasDebt = false;\n          tick = tick;\n          continue;\n        }\n        // skip dust\n        if (vars.tickRawDebts < uint256(MIN_DEBT)) {\n          hasDebt = false;\n          tick = tick;\n          continue;\n        }\n        // no more rebalanceable tick: coll * price * rebalanceDebtRatio > debts\n        if (vars.tickRawColls * vars.price * vars.rebalanceDebtRatio > vars.tickRawDebts * PRECISION * PRECISION) {\n          break;\n        }\n        // rebalance this tick\n        (uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls) = _rebalanceTick(tick, vars);\n        result.rawDebts += rawDebts;\n        result.rawColls += rawColls;\n        result.bonusRawColls += bonusRawColls;\n\n        // goto next tick\n        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);\n      }\n      if (tick == type(int16).min) break;\n    }\n\n    _updateDebtAndCollateralShares(vars.totalDebtShares, vars.totalCollShares);\n  }\n\n  struct LiquidateVars {\n    uint256 tickCollShares;\n    uint256 tickDebtShares;\n    uint256 tickRawColls;\n    uint256 tickRawDebts;\n    uint256 maxRawDebts;\n    uint256 reservedRawColls;\n    uint256 liquidateDebtRatio;\n    uint256 liquidateBonusRatio;\n    uint256 price;\n    uint256 collIndex;\n    uint256 debtIndex;\n    uint256 totalCollShares;\n    uint256 totalDebtShares;\n  }\n\n  /// @inheritdoc IPool\n  function liquidate(\n    uint256 maxRawDebts,\n    uint256 reservedRawColls\n  ) external onlyPoolManager returns (LiquidateResult memory result) {\n    LiquidateVars memory vars;\n    vars.maxRawDebts = maxRawDebts;\n    vars.reservedRawColls = reservedRawColls;\n    (vars.liquidateDebtRatio, vars.liquidateBonusRatio) = _getLiquidateRatios();\n    vars.price = IPriceOracle(priceOracle).getLiquidatePrice();\n    (vars.collIndex, vars.debtIndex) = _updateCollAndDebtIndex();\n    (vars.totalDebtShares, vars.totalCollShares) = _getDebtAndCollateralShares();\n\n    int16 tick = _getTopTick();\n    bool hasDebt = true;\n    while (vars.maxRawDebts > 0) {\n      if (!hasDebt) {\n        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);\n      } else {\n        (vars.tickCollShares, vars.tickDebtShares, vars.tickRawColls, vars.tickRawDebts) = _getTickRawCollAndDebts(\n          tick,\n          vars.collIndex,\n          vars.debtIndex\n        );\n        // no more liquidatable tick: coll * price * liquidateDebtRatio > debts\n        if (vars.tickRawColls * vars.price * vars.liquidateDebtRatio > vars.tickRawDebts * PRECISION * PRECISION) {\n          // skip dust, since the results might be wrong\n          if (vars.tickRawDebts < uint256(MIN_DEBT)) {\n            hasDebt = false;\n            tick = tick;\n            continue;\n          }\n          break;\n        }\n        // rebalance this tick\n        (uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls, uint256 bonusFromReserve) = _liquidateTick(\n          tick,\n          vars\n        );\n        result.rawDebts += rawDebts;\n        result.rawColls += rawColls;\n        result.bonusRawColls += bonusRawColls;\n        result.bonusFromReserve += bonusFromReserve;\n\n        // goto next tick\n        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);\n      }\n      if (tick == type(int16).min) break;\n    }\n\n    _updateDebtAndCollateralShares(vars.totalDebtShares, vars.totalCollShares);\n    _updateDebtIndex(vars.debtIndex);\n  }\n\n  /// @inheritdoc IPool\n  function reduceDebt(uint256 rawAmount) external onlyPoolManager {\n    (, uint256 debtIndex) = _updateCollAndDebtIndex();\n    (uint256 totalDebtShares, ) = _getDebtAndCollateralShares();\n    uint256 totalRawDebts = _convertToRawDebt(totalDebtShares, debtIndex, Math.Rounding.Down);\n    // cannot reduce more than 10% of total debts to avoid precision loss\n    if (rawAmount * 10 > totalRawDebts) {\n      revert ErrorReduceTooMuchDebt();\n    }\n\n    debtIndex -= (rawAmount * E96) / totalDebtShares;\n    _updateDebtIndex(debtIndex);\n  }\n\n  /************************\n   * Restricted Functions *\n   ************************/\n\n  /// @notice Update the borrow and redeem status.\n  /// @param borrowStatus The new borrow status.\n  /// @param redeemStatus The new redeem status.\n  function updateBorrowAndRedeemStatus(bool borrowStatus, bool redeemStatus) external onlyRole(EMERGENCY_ROLE) {\n    _updateBorrowStatus(borrowStatus);\n    _updateRedeemStatus(redeemStatus);\n  }\n\n  /// @notice Update debt ratio range.\n  /// @param minRatio The minimum allowed debt ratio to update, multiplied by 1e18.\n  /// @param maxRatio The maximum allowed debt ratio to update, multiplied by 1e18.\n  function updateDebtRatioRange(uint256 minRatio, uint256 maxRatio) external onlyRole(OPERATOR_ROLE) {\n    _updateDebtRatioRange(minRatio, maxRatio);\n  }\n\n  /// @notice Update maximum redeem ratio per tick.\n  /// @param ratio The ratio to update, multiplied by 1e9.\n  function updateMaxRedeemRatioPerTick(uint256 ratio) external onlyRole(OPERATOR_ROLE) {\n    _updateMaxRedeemRatioPerTick(ratio);\n  }\n\n  /// @notice Update ratio for rebalance.\n  /// @param debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.\n  /// @param bonusRatio The bonus ratio during rebalance, multiplied by 1e9.\n  function updateRebalanceRatios(uint256 debtRatio, uint256 bonusRatio) external onlyRole(OPERATOR_ROLE) {\n    _updateRebalanceRatios(debtRatio, bonusRatio);\n  }\n\n  /// @notice Update ratio for liquidate.\n  /// @param debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.\n  /// @param bonusRatio The bonus ratio during liquidate, multiplied by 1e9.\n  function updateLiquidateRatios(uint256 debtRatio, uint256 bonusRatio) external onlyRole(OPERATOR_ROLE) {\n    _updateLiquidateRatios(debtRatio, bonusRatio);\n  }\n\n  /// @notice Update the address of price oracle.\n  /// @param newOracle The address of new price oracle.\n  function updatePriceOracle(address newOracle) external onlyRole(OPERATOR_ROLE) {\n    _updatePriceOracle(newOracle);\n  }\n\n  /// @notice Update the address of counterparty.\n  /// @param newCounterparty The address of new counterparty.\n  function updateCounterparty(address newCounterparty) external onlyRole(OPERATOR_ROLE) {\n    _updateCounterparty(newCounterparty);\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @dev Internal function to redeem debt tokens to get collateral tokens.\n  /// @param rawDebts The amount of debt tokens to redeem.\n  /// @return actualRawDebts The actual amount of debt tokens used.\n  /// @return rawColls The amount of collateral tokens to redeemed.\n  function _redeem(\n    uint256 rawDebts,\n    bool allowTickNotMoved\n  ) internal returns (uint256 actualRawDebts, uint256 rawColls) {\n    (uint256 cachedCollIndex, uint256 cachedDebtIndex) = _updateCollAndDebtIndex();\n    (uint256 cachedTotalDebts, uint256 cachedTotalColls) = _getDebtAndCollateralShares();\n    uint256 price = IPriceOracle(priceOracle).getRedeemPrice();\n    // check global debt ratio, if global debt ratio >= 1, disable redeem\n    {\n      uint256 totalRawColls = _convertToRawColl(cachedTotalColls, cachedCollIndex, Math.Rounding.Down);\n      uint256 totalRawDebts = _convertToRawDebt(cachedTotalDebts, cachedDebtIndex, Math.Rounding.Down);\n      if (totalRawDebts * PRECISION >= totalRawColls * price) revert ErrorPoolUnderCollateral();\n    }\n\n    int16 tick = _getTopTick();\n    bool hasDebt = true;\n    uint256 debtShare = _convertToDebtShares(rawDebts, cachedDebtIndex, Math.Rounding.Down);\n    while (debtShare > 0) {\n      if (!hasDebt) {\n        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);\n      } else {\n        uint256 tickDebtShare;\n        {\n          uint256 node = tickData[tick];\n          bytes32 value = tickTreeData[node].value;\n          tickDebtShare = value.decodeUint(DEBT_SHARE_OFFSET, 128);\n          // skip bad debt\n          {\n            uint256 tickCollShare = value.decodeUint(COLL_SHARE_OFFSET, 128);\n            if (\n              _convertToRawDebt(tickDebtShare, cachedDebtIndex, Math.Rounding.Down) * PRECISION >\n              _convertToRawColl(tickCollShare, cachedCollIndex, Math.Rounding.Down) * price\n            ) {\n              hasDebt = false;\n              tick = tick;\n              continue;\n            }\n          }\n          // skip dust\n          if (tickDebtShare < uint256(MIN_DEBT)) {\n            hasDebt = false;\n            tick = tick;\n            continue;\n          }\n        }\n\n        // redeem at most `maxRedeemRatioPerTick`\n        uint256 debtShareToRedeem = (tickDebtShare * _getMaxRedeemRatioPerTick()) / FEE_PRECISION;\n        if (debtShareToRedeem > debtShare) debtShareToRedeem = debtShare;\n        uint256 rawDebtsToRedeem = _convertToRawDebt(debtShareToRedeem, cachedDebtIndex, Math.Rounding.Down);\n        uint256 rawCollRedeemed = (rawDebtsToRedeem * PRECISION) / price;\n        uint256 collShareRedeemed = _convertToCollShares(rawCollRedeemed, cachedCollIndex, Math.Rounding.Down);\n\n        // If the tick won't move, break the loop (except for redeem credit note)\n        if (!allowTickNotMoved && !_tickWillMove(tick, collShareRedeemed, debtShareToRedeem)) break;\n\n        _liquidateTick(tick, collShareRedeemed, debtShareToRedeem, price);\n        debtShare -= debtShareToRedeem;\n        actualRawDebts += rawDebtsToRedeem;\n        rawColls += rawCollRedeemed;\n\n        cachedTotalColls -= collShareRedeemed;\n        cachedTotalDebts -= debtShareToRedeem;\n\n        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);\n      }\n      if (tick == type(int16).min) break;\n    }\n    _updateDebtAndCollateralShares(cachedTotalDebts, cachedTotalColls);\n  }\n\n  /// @dev Internal function to compute the amount of debt to rebalance to reach certain debt ratio.\n  /// @param coll The amount of collateral tokens.\n  /// @param debt The amount of debt tokens.\n  /// @param price The price of the collateral token.\n  /// @param targetDebtRatio The target debt ratio, multiplied by 1e18.\n  /// @param incentiveRatio The bonus ratio, multiplied by 1e9.\n  /// @return rawDebts The amount of debt tokens to rebalance.\n  function _getRawDebtToRebalance(\n    uint256 coll,\n    uint256 debt,\n    uint256 price,\n    uint256 targetDebtRatio,\n    uint256 incentiveRatio\n  ) internal pure returns (uint256 rawDebts) {\n    // we have\n    //   1. (debt - x) / (price * (coll - y * (1 + incentive))) <= target_ratio\n    //   2. debt / (price * coll) >= target_ratio\n    // then\n    // => debt - x <= target * price * (coll - y * (1 + incentive)) and y = x / price\n    // => debt - target_ratio * price * coll <= (1 - (1 + incentive) * target) * x\n    // => x >= (debt - target_ratio * price * coll) / (1 - (1 + incentive) * target)\n    rawDebts =\n      (debt * PRECISION * PRECISION - targetDebtRatio * price * coll) /\n      (PRECISION * PRECISION - (PRECISION * targetDebtRatio * (FEE_PRECISION + incentiveRatio)) / FEE_PRECISION);\n  }\n\n  function _getTickRawCollAndDebts(\n    int16 tick,\n    uint256 collIndex,\n    uint256 debtIndex\n  ) internal view returns (uint256 colls, uint256 debts, uint256 rawColls, uint256 rawDebts) {\n    uint256 node = tickData[tick];\n    bytes32 value = tickTreeData[node].value;\n    colls = value.decodeUint(COLL_SHARE_OFFSET, 128);\n    debts = value.decodeUint(DEBT_SHARE_OFFSET, 128);\n    rawColls = _convertToRawColl(colls, collIndex, Math.Rounding.Down);\n    rawDebts = _convertToRawDebt(debts, debtIndex, Math.Rounding.Down);\n  }\n\n  function _rebalanceTick(\n    int16 tick,\n    RebalanceVars memory vars\n  ) internal returns (uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls) {\n    // compute debts to rebalance to make debt ratio to `rebalanceDebtRatio`\n    rawDebts = _getRawDebtToRebalance(\n      vars.tickRawColls,\n      vars.tickRawDebts,\n      vars.price,\n      vars.rebalanceDebtRatio,\n      vars.rebalanceBonusRatio\n    );\n    if (vars.maxRawDebts < rawDebts) rawDebts = vars.maxRawDebts;\n\n    uint256 debtShares = _convertToDebtShares(rawDebts, vars.debtIndex, Math.Rounding.Down);\n    rawColls = (rawDebts * PRECISION) / vars.price;\n    bonusRawColls = (rawColls * vars.rebalanceBonusRatio) / FEE_PRECISION;\n    if (bonusRawColls > vars.tickRawColls - rawColls) {\n      bonusRawColls = vars.tickRawColls - rawColls;\n    }\n    uint256 collShares = _convertToCollShares(rawColls + bonusRawColls, vars.collIndex, Math.Rounding.Down);\n\n    _liquidateTick(tick, collShares, debtShares, vars.price);\n    vars.totalCollShares -= collShares;\n    vars.totalDebtShares -= debtShares;\n    vars.maxRawDebts -= rawDebts;\n  }\n\n  function _liquidateTick(\n    int16 tick,\n    LiquidateVars memory vars\n  ) internal virtual returns (uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls, uint256 bonusFromReserve) {\n    uint256 virtualTickRawColls = vars.tickRawColls + vars.reservedRawColls;\n    rawDebts = vars.tickRawDebts;\n    if (rawDebts > vars.maxRawDebts) rawDebts = vars.maxRawDebts;\n    rawColls = (rawDebts * PRECISION) / vars.price;\n    uint256 debtShares;\n    uint256 collShares;\n    if (rawDebts == vars.tickRawDebts) {\n      // full liquidation\n      debtShares = vars.tickDebtShares;\n    } else {\n      // partial liquidation\n      debtShares = _convertToDebtShares(rawDebts, vars.debtIndex, Math.Rounding.Down);\n    }\n    if (virtualTickRawColls <= rawColls) {\n      // even reserve funds cannot cover bad debts, no bonus and will trigger bad debt redistribution\n      rawColls = virtualTickRawColls;\n      bonusFromReserve = vars.reservedRawColls;\n      rawDebts = (virtualTickRawColls * vars.price) / PRECISION;\n      debtShares = _convertToDebtShares(rawDebts, vars.debtIndex, Math.Rounding.Down);\n      collShares = vars.tickCollShares;\n    } else {\n      // Bonus is from colls in tick, if it is not enough will use reserve funds\n      bonusRawColls = (rawColls * vars.liquidateBonusRatio) / FEE_PRECISION;\n      uint256 rawCollWithBonus = bonusRawColls + rawColls;\n      if (rawCollWithBonus > virtualTickRawColls) {\n        rawCollWithBonus = virtualTickRawColls;\n        bonusRawColls = rawCollWithBonus - rawColls;\n      }\n      if (rawCollWithBonus >= vars.tickRawColls) {\n        bonusFromReserve = rawCollWithBonus - vars.tickRawColls;\n        collShares = vars.tickCollShares;\n      } else {\n        collShares = _convertToCollShares(rawCollWithBonus, vars.collIndex, Math.Rounding.Down);\n      }\n    }\n\n    vars.reservedRawColls -= bonusFromReserve;\n    if (collShares == vars.tickCollShares && debtShares < vars.tickDebtShares) {\n      // trigger bad debt redistribution\n      uint256 rawBadDebt = _convertToRawDebt(vars.tickDebtShares - debtShares, vars.debtIndex, Math.Rounding.Down);\n      debtShares = vars.tickDebtShares;\n      vars.totalCollShares -= collShares;\n      vars.totalDebtShares -= debtShares;\n      vars.debtIndex += (rawBadDebt * E96) / vars.totalDebtShares;\n    } else {\n      vars.totalCollShares -= collShares;\n      vars.totalDebtShares -= debtShares;\n    }\n    vars.maxRawDebts -= rawDebts;\n    _liquidateTick(tick, collShares, debtShares, vars.price);\n  }\n\n  /// @dev Internal function to update collateral and debt index.\n  /// @return newCollIndex The updated collateral index.\n  /// @return newDebtIndex The updated debt index.\n  function _updateCollAndDebtIndex() internal virtual returns (uint256 newCollIndex, uint256 newDebtIndex);\n\n  /// @dev Internal function to compute the protocol fees.\n  /// @param rawColl The amount of collateral tokens involved.\n  /// @return fees The expected protocol fees.\n  function _deductProtocolFees(int256 rawColl) internal view virtual returns (uint256 fees);\n\n  /**\n   * @dev This empty reserved space is put in place to allow future versions to add new\n   * variables without shifting down storage in the inheritance chain.\n   */\n  uint256[50] private __gap;\n}\n"},"contracts/core/pool/PoolConstant.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nimport { IPool } from \"../../interfaces/IPool.sol\";\n\nabstract contract PoolConstant is IPool {\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev The role for emergency operations.\n  bytes32 public constant EMERGENCY_ROLE = keccak256(\"EMERGENCY_ROLE\");\n\n  /// @dev The role for opreator.\n  bytes32 public constant OPERATOR_ROLE = keccak256(\"OPERATOR_ROLE\");\n\n  /// @dev The value of minimum collateral.\n  int256 internal constant MIN_COLLATERAL = 1e9;\n\n  /// @dev The value of minimum debts.\n  int256 internal constant MIN_DEBT = 1e9;\n\n  /// @dev The precision used for various calculation.\n  uint256 internal constant PRECISION = 1e18;\n\n  /// @dev The precision used for fee ratio calculation.\n  uint256 internal constant FEE_PRECISION = 1e9;\n\n  /// @dev bit operation related constants\n  uint256 internal constant E60 = 2 ** 60; // 2^60\n  uint256 internal constant E96 = 2 ** 96; // 2^96\n\n  uint256 internal constant X60 = 0xfffffffffffffff; // 2^60 - 1\n  uint256 internal constant X96 = 0xffffffffffffffffffffffff; // 2^96 - 1\n\n  /***********************\n   * Immutable Variables *\n   ***********************/\n\n  /// @inheritdoc IPool\n  address public immutable fxUSD;\n\n  /// @inheritdoc IPool\n  address public immutable poolManager;\n\n  /// @inheritdoc IPool\n  address public immutable configuration;\n}\n"},"contracts/core/pool/PoolErrors.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nabstract contract PoolErrors {\n  /**********\n   * Errors *\n   **********/\n  \n  /// @dev Thrown when the given address is zero.\n  error ErrorZeroAddress();\n\n  /// @dev Thrown when the given value exceeds maximum value.\n  error ErrorValueTooLarge();\n  \n  /// @dev Thrown when the caller is not pool manager.\n  error ErrorCallerNotPoolManager();\n  \n  /// @dev Thrown when the debt amount is too small.\n  error ErrorDebtTooSmall();\n\n  /// @dev Thrown when the collateral amount is too small.\n  error ErrorCollateralTooSmall();\n  \n  /// @dev Thrown when both collateral amount and debt amount are zero.\n  error ErrorNoSupplyAndNoBorrow();\n  \n  /// @dev Thrown when borrow is paused.\n  error ErrorBorrowPaused();\n\n  /// @dev Thrown when redeem is paused.\n  error ErrorRedeemPaused();\n  \n  /// @dev Thrown when the caller is not position owner during withdraw or borrow.\n  error ErrorNotPositionOwner();\n  \n  /// @dev Thrown when withdraw more than supplied.\n  error ErrorWithdrawExceedSupply();\n  \n  /// @dev Thrown when the debt ratio is too small.\n  error ErrorDebtRatioTooSmall();\n\n  /// @dev Thrown when the debt ratio is too large.\n  error ErrorDebtRatioTooLarge();\n  \n  /// @dev Thrown when pool is under collateral.\n  error ErrorPoolUnderCollateral();\n  \n  /// @dev Thrown when the current debt ratio <= rebalance debt ratio.\n  error ErrorRebalanceDebtRatioNotReached();\n\n  /// @dev Thrown when the current debt ratio > liquidate debt ratio.\n  error ErrorPositionInLiquidationMode();\n\n  error ErrorRebalanceOnLiquidatableTick();\n\n  error ErrorRebalanceOnLiquidatablePosition();\n\n  error ErrorInsufficientCollateralToLiquidate();\n\n  error ErrorOverflow();\n\n  error ErrorReduceTooMuchDebt();\n\n  error ErrorTickNotMoved();\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @dev Internal function to check value not too large.\n  /// @param value The value to check.\n  /// @param upperBound The upper bound for the given value.\n  function _checkValueTooLarge(uint256 value, uint256 upperBound) internal pure {\n    if (value > upperBound) revert ErrorValueTooLarge();\n  }\n\n  function _checkAddressNotZero(address value) internal pure {\n    if (value == address(0)) revert ErrorZeroAddress();\n  }\n}\n"},"contracts/core/pool/PoolStorage.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nimport { AccessControlUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol\";\nimport { ERC721EnumerableUpgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol\";\n\nimport { IPool } from \"../../interfaces/IPool.sol\";\n\nimport { WordCodec } from \"../../common/codec/WordCodec.sol\";\nimport { PoolConstant } from \"./PoolConstant.sol\";\nimport { PoolErrors } from \"./PoolErrors.sol\";\n\nabstract contract PoolStorage is ERC721EnumerableUpgradeable, AccessControlUpgradeable, PoolConstant, PoolErrors {\n  using WordCodec for bytes32;\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev Below are offsets of each variables in `miscData`.\n  uint256 private constant BORROW_FLAG_OFFSET = 0;\n  uint256 private constant REDEEM_FLAG_OFFSET = 1;\n  uint256 private constant TOP_TICK_OFFSET = 2;\n  uint256 private constant NEXT_POSITION_OFFSET = 18;\n  uint256 private constant NEXT_NODE_OFFSET = 50;\n  uint256 private constant MIN_DEBT_RATIO_OFFSET = 98;\n  uint256 private constant MAX_DEBT_RATIO_OFFSET = 158;\n  uint256 private constant MAX_REDEEM_RATIO_OFFSET = 218;\n\n  /// @dev Below are offsets of each variables in `rebalanceRatioData`.\n  uint256 private constant REBALANCE_DEBT_RATIO_OFFSET = 0;\n  uint256 private constant REBALANCE_BONUS_RATIO_OFFSET = 60;\n  uint256 private constant LIQUIDATE_DEBT_RATIO_OFFSET = 90;\n  uint256 private constant LIQUIDATE_BONUS_RATIO_OFFSET = 150;\n\n  /// @dev Below are offsets of each variables in `indexData`.\n  uint256 private constant DEBT_INDEX_OFFSET = 0;\n  uint256 private constant COLLATERAL_INDEX_OFFSET = 128;\n\n  /// @dev Below are offsets of each variables in `sharesData`.\n  uint256 private constant DEBT_SHARES_OFFSET = 0;\n  uint256 private constant COLLATERAL_SHARES_OFFSET = 128;\n\n  /***********\n   * Structs *\n   ***********/\n\n  /// @dev if nodeId = 0, tick is not used and this position only has collateral\n  ///\n  /// @param tick The tick this position belongs to at the beginning.\n  /// @param nodeId The tree node id this position belongs to at the beginning.\n  /// @param colls The collateral shares this position has.\n  /// @param debts The debt shares this position has.\n  struct PositionInfo {\n    int16 tick;\n    uint48 nodeId;\n    // `uint96` is enough, since we use `86` bits in `PoolManager`.\n    uint96 colls;\n    // `uint96` is enough, since we use `96` bits in `PoolManager`.\n    uint96 debts;\n  }\n\n  /// @dev The compiler will pack it into two `uint256`.\n  /// @param metadata The metadata for tree node.\n  ///   ```text\n  ///   * Field           Bits    Index       Comments\n  ///   * parent          48      0           The index for parent tree node.\n  ///   * tick            16      48          The original tick for this tree node.\n  ///   * coll ratio      64      64          The remained coll share ratio base on parent node, the value is real ratio * 2^60.\n  ///   * debt ratio      64      128         The remained debt share ratio base on parent node, the value is real ratio * 2^60.\n  ///   ```\n  /// @param value The value for tree node\n  ///   ```text\n  ///   * Field           Bits    Index       Comments\n  ///   * coll share      128     0           The original total coll share before rebalance or redeem.\n  ///   * debt share      128     128         The original total debt share before rebalance or redeem.\n  ///   ```\n  struct TickTreeNode {\n    bytes32 metadata;\n    bytes32 value;\n  }\n\n  /*********************\n   * Storage Variables *\n   *********************/\n\n  /// @inheritdoc IPool\n  address public collateralToken;\n\n  /// @inheritdoc IPool\n  address public priceOracle;\n\n  /// @dev `miscData` is a storage slot that can be used to store unrelated pieces of information.\n  ///\n  /// - The *borrow flag* indicates whether borrow fxUSD is allowed, 1 means paused.\n  /// - The *redeem flag* indicates whether redeem fxUSD is allowed, 1 means paused.\n  /// - The *top tick* is the largest tick with debts.\n  /// - The *next position* is the next unassigned position id.\n  /// - The *next node* is the next unassigned tree node id.\n  /// - The *min debt ratio* is the minimum allowed debt ratio, multiplied by 1e18.\n  /// - The *max debt ratio* is the maximum allowed debt ratio, multiplied by 1e18.\n  /// - The *max redeem ratio* is the maximum allowed redeem ratio per tick, multiplied by 1e9.\n  ///\n  /// [ borrow flag | redeem flag | top tick | next position | next node | min debt ratio | max debt ratio | max redeem ratio | reserved ]\n  /// [    1 bit    |    1 bit    | 16  bits |    32 bits    |  48 bits  |    60  bits    |    60  bits    |      30 bits     |  8 bits  ]\n  /// [ MSB                                                                                                                          LSB ]\n  bytes32 private miscData;\n\n  /// @dev `rebalanceRatioData` is a storage slot used to store rebalance and liquidate information.\n  ///\n  /// - The *rebalance debt ratio* is the min debt ratio to start rebalance, multiplied by 1e18.\n  /// - The *rebalance bonus ratio* is the bonus ratio during rebalance, multiplied by 1e9.\n  /// - The *liquidate debt ratio* is the min debt ratio to start liquidate, multiplied by 1e18.\n  /// - The *liquidate bonus ratio* is the bonus ratio during liquidate, multiplied by 1e9.\n  ///\n  /// [ rebalance debt ratio | rebalance bonus ratio | liquidate debt ratio | liquidate bonus ratio | reserved ]\n  /// [       60  bits       |        30 bits        |       60  bits       |        30 bits        | 76  bits ]\n  /// [ MSB                                                                                                LSB ]\n  bytes32 private rebalanceRatioData;\n\n  /// @dev `indexData` is a storage slot used to store debt/collateral index.\n  ///\n  /// - The *debt index* is the index for each debt shares, only increasing, starting from 2^96, max 2^128-1.\n  /// - The *collateral index* is the index for each collateral shares, only increasing, starting from 2^96, max 2^128-1\n  ///\n  /// [ debt index | collateral index ]\n  /// [  128 bits  |     128 bits     ]\n  /// [ MSB                       LSB ]\n  bytes32 private indexData;\n\n  /// @dev `sharesData` is a storage slot used to store debt/collateral shares.\n  ///\n  /// - The *debt shares* is the total debt shares. The actual number of total debts\n  ///   is `<debt shares> * <debt index>`.\n  /// - The *collateral shares* is the total collateral shares. The actual number of\n  ///   total collateral is `<collateral shares> / <collateral index>`.\n  ///\n  /// [ debt shares | collateral shares ]\n  /// [  128  bits  |     128  bits     ]\n  /// [ MSB                         LSB ]\n  bytes32 private sharesData;\n\n  /// @dev Mapping from position id to position information.\n  mapping(uint256 => PositionInfo) public positionData;\n\n  /// @dev Mapping from position id to position metadata.\n  /// [ open timestamp | reserved ]\n  /// [    40  bits    | 216 bits ]\n  /// [ MSB                   LSB ]\n  mapping(uint256 => bytes32) public positionMetadata;\n\n  /// @dev The bitmap for ticks with debts.\n  mapping(int8 => uint256) public tickBitmap;\n\n  /// @dev Mapping from tick to tree node id.\n  mapping(int256 => uint48) public tickData;\n\n  /// @dev Mapping from tree node id to tree node data.\n  mapping(uint256 => TickTreeNode) public tickTreeData;\n\n  /// @notice The address of counterparty pool.\n  address public counterparty;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  function __PoolStorage_init(address _collateralToken, address _priceOracle) internal onlyInitializing {\n    // _checkAddressNotZero(_collateralToken);\n\n    collateralToken = _collateralToken;\n    _updatePriceOracle(_priceOracle);\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @inheritdoc AccessControlUpgradeable\n  function supportsInterface(\n    bytes4 interfaceId\n  ) public view virtual override(AccessControlUpgradeable, ERC721EnumerableUpgradeable) returns (bool) {\n    return super.supportsInterface(interfaceId);\n  }\n\n  /// @inheritdoc IPool\n  function isBorrowPaused() external view returns (bool) {\n    return _isBorrowPaused();\n  }\n\n  /// @inheritdoc IPool\n  function isRedeemPaused() external view returns (bool) {\n    return _isRedeemPaused();\n  }\n\n  /// @inheritdoc IPool\n  function getTopTick() external view returns (int16) {\n    return _getTopTick();\n  }\n\n  /// @inheritdoc IPool\n  function getNextPositionId() external view returns (uint32) {\n    return _getNextPositionId();\n  }\n\n  /// @inheritdoc IPool\n  function getNextTreeNodeId() external view returns (uint48) {\n    return _getNextTreeNodeId();\n  }\n\n  /// @inheritdoc IPool\n  function getDebtRatioRange() external view returns (uint256, uint256) {\n    return _getDebtRatioRange();\n  }\n\n  /// @inheritdoc IPool\n  function getMaxRedeemRatioPerTick() external view returns (uint256) {\n    return _getMaxRedeemRatioPerTick();\n  }\n\n  /// @inheritdoc IPool\n  function getRebalanceRatios() external view returns (uint256, uint256) {\n    return _getRebalanceRatios();\n  }\n\n  /// @inheritdoc IPool\n  function getLiquidateRatios() external view returns (uint256, uint256) {\n    return _getLiquidateRatios();\n  }\n\n  /// @inheritdoc IPool\n  function getDebtAndCollateralIndex() external view returns (uint256, uint256) {\n    return _getDebtAndCollateralIndex();\n  }\n\n  /// @inheritdoc IPool\n  function getDebtAndCollateralShares() external view returns (uint256, uint256) {\n    return _getDebtAndCollateralShares();\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @dev Internal function to update price oracle.\n  /// @param newOracle The address of new price oracle;\n  function _updatePriceOracle(address newOracle) internal {\n    // _checkAddressNotZero(newOracle);\n\n    address oldOracle = priceOracle;\n    priceOracle = newOracle;\n\n    emit UpdatePriceOracle(oldOracle, newOracle);\n  }\n\n  /*************************************\n   * Internal Functions For `miscData` *\n   *************************************/\n\n  /// @dev Internal function to get the borrow pause status.\n  function _isBorrowPaused() internal view returns (bool) {\n    return miscData.decodeBool(BORROW_FLAG_OFFSET);\n  }\n\n  /// @dev Internal function to update borrow pause status.\n  /// @param status The status to update.\n  function _updateBorrowStatus(bool status) internal {\n    miscData = miscData.insertBool(status, BORROW_FLAG_OFFSET);\n\n    emit UpdateBorrowStatus(status);\n  }\n\n  /// @dev Internal function to get the redeem pause status.\n  function _isRedeemPaused() internal view returns (bool) {\n    return miscData.decodeBool(REDEEM_FLAG_OFFSET);\n  }\n\n  /// @dev Internal function to update redeem pause status.\n  /// @param status The status to update.\n  function _updateRedeemStatus(bool status) internal {\n    miscData = miscData.insertBool(status, REDEEM_FLAG_OFFSET);\n\n    emit UpdateRedeemStatus(status);\n  }\n\n  /// @dev Internal function to get the value of top tick.\n  function _getTopTick() internal view returns (int16) {\n    return int16(miscData.decodeInt(TOP_TICK_OFFSET, 16));\n  }\n\n  /// @dev Internal function to update the top tick.\n  /// @param tick The new top tick.\n  function _updateTopTick(int16 tick) internal {\n    miscData = miscData.insertInt(tick, TOP_TICK_OFFSET, 16);\n  }\n\n  /// @dev Internal function to get next available position id.\n  function _getNextPositionId() internal view returns (uint32) {\n    return uint32(miscData.decodeUint(NEXT_POSITION_OFFSET, 32));\n  }\n\n  /// @dev Internal function to update next available position id.\n  /// @param id The position id to update.\n  function _updateNextPositionId(uint32 id) internal {\n    miscData = miscData.insertUint(id, NEXT_POSITION_OFFSET, 32);\n  }\n\n  /// @dev Internal function to get next available tree node id.\n  function _getNextTreeNodeId() internal view returns (uint48) {\n    return uint48(miscData.decodeUint(NEXT_NODE_OFFSET, 48));\n  }\n\n  /// @dev Internal function to update next available tree node id.\n  /// @param id The tree node id to update.\n  function _updateNextTreeNodeId(uint48 id) internal {\n    miscData = miscData.insertUint(id, NEXT_NODE_OFFSET, 48);\n  }\n\n  /// @dev Internal function to get `minDebtRatio` and `maxDebtRatio`, both multiplied by 1e18.\n  function _getDebtRatioRange() internal view returns (uint256 minDebtRatio, uint256 maxDebtRatio) {\n    bytes32 data = miscData;\n    minDebtRatio = data.decodeUint(MIN_DEBT_RATIO_OFFSET, 60);\n    maxDebtRatio = data.decodeUint(MAX_DEBT_RATIO_OFFSET, 60);\n  }\n\n  /// @dev Internal function to update debt ratio range.\n  /// @param minDebtRatio The minimum allowed debt ratio to update, multiplied by 1e18.\n  /// @param maxDebtRatio The maximum allowed debt ratio to update, multiplied by 1e18.\n  function _updateDebtRatioRange(uint256 minDebtRatio, uint256 maxDebtRatio) internal {\n    // _checkValueTooLarge(minDebtRatio, maxDebtRatio);\n    // _checkValueTooLarge(maxDebtRatio, PRECISION);\n\n    bytes32 data = miscData;\n    data = data.insertUint(minDebtRatio, MIN_DEBT_RATIO_OFFSET, 60);\n    miscData = data.insertUint(maxDebtRatio, MAX_DEBT_RATIO_OFFSET, 60);\n\n    emit UpdateDebtRatioRange(minDebtRatio, maxDebtRatio);\n  }\n\n  /// @dev Internal function to get the `maxRedeemRatioPerTick`.\n  function _getMaxRedeemRatioPerTick() internal view returns (uint256) {\n    return miscData.decodeUint(MAX_REDEEM_RATIO_OFFSET, 30);\n  }\n\n  /// @dev Internal function to update maximum redeem ratio per tick.\n  /// @param ratio The ratio to update, multiplied by 1e9.\n  function _updateMaxRedeemRatioPerTick(uint256 ratio) internal {\n    // _checkValueTooLarge(ratio, FEE_PRECISION);\n\n    miscData = miscData.insertUint(ratio, MAX_REDEEM_RATIO_OFFSET, 30);\n\n    emit UpdateMaxRedeemRatioPerTick(ratio);\n  }\n\n  /***********************************************\n   * Internal Functions For `rebalanceRatioData` *\n   ***********************************************/\n\n  /// @dev Internal function to get `debtRatio` and `bonusRatio` for rebalance.\n  /// @return debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.\n  /// @return bonusRatio The bonus ratio during rebalance, multiplied by 1e9.\n  function _getRebalanceRatios() internal view returns (uint256 debtRatio, uint256 bonusRatio) {\n    bytes32 data = rebalanceRatioData;\n    debtRatio = data.decodeUint(REBALANCE_DEBT_RATIO_OFFSET, 60);\n    bonusRatio = data.decodeUint(REBALANCE_BONUS_RATIO_OFFSET, 30);\n  }\n\n  /// @dev Internal function to update ratio for rebalance.\n  /// @param debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.\n  /// @param bonusRatio The bonus ratio during rebalance, multiplied by 1e9.\n  function _updateRebalanceRatios(uint256 debtRatio, uint256 bonusRatio) internal {\n    // _checkValueTooLarge(debtRatio, PRECISION);\n    // _checkValueTooLarge(bonusRatio, FEE_PRECISION);\n\n    bytes32 data = rebalanceRatioData;\n    data = data.insertUint(debtRatio, REBALANCE_DEBT_RATIO_OFFSET, 60);\n    rebalanceRatioData = data.insertUint(bonusRatio, REBALANCE_BONUS_RATIO_OFFSET, 30);\n\n    emit UpdateRebalanceRatios(debtRatio, bonusRatio);\n  }\n\n  /// @dev Internal function to get `debtRatio` and `bonusRatio` for liquidate.\n  /// @return debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.\n  /// @return bonusRatio The bonus ratio during liquidate, multiplied by 1e9.\n  function _getLiquidateRatios() internal view returns (uint256 debtRatio, uint256 bonusRatio) {\n    bytes32 data = rebalanceRatioData;\n    debtRatio = data.decodeUint(LIQUIDATE_DEBT_RATIO_OFFSET, 60);\n    bonusRatio = data.decodeUint(LIQUIDATE_BONUS_RATIO_OFFSET, 30);\n  }\n\n  /// @dev Internal function to update ratio for liquidate.\n  /// @param debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.\n  /// @param bonusRatio The bonus ratio during liquidate, multiplied by 1e9.\n  function _updateLiquidateRatios(uint256 debtRatio, uint256 bonusRatio) internal {\n    // _checkValueTooLarge(debtRatio, PRECISION);\n    // _checkValueTooLarge(bonusRatio, FEE_PRECISION);\n\n    bytes32 data = rebalanceRatioData;\n    data = data.insertUint(debtRatio, LIQUIDATE_DEBT_RATIO_OFFSET, 60);\n    rebalanceRatioData = data.insertUint(bonusRatio, LIQUIDATE_BONUS_RATIO_OFFSET, 30);\n\n    emit UpdateLiquidateRatios(debtRatio, bonusRatio);\n  }\n\n  /**************************************\n   * Internal Functions For `indexData` *\n   **************************************/\n\n  /// @dev Internal function to get debt and collateral index.\n  /// @return debtIndex The index for debt shares.\n  /// @return collIndex The index for collateral shares.\n  function _getDebtAndCollateralIndex() internal view returns (uint256 debtIndex, uint256 collIndex) {\n    bytes32 data = indexData;\n    debtIndex = data.decodeUint(DEBT_INDEX_OFFSET, 128);\n    collIndex = data.decodeUint(COLLATERAL_INDEX_OFFSET, 128);\n  }\n\n  /// @dev Internal function to update debt index.\n  /// @param index The debt index to update.\n  function _updateDebtIndex(uint256 index) internal {\n    indexData = indexData.insertUint(index, DEBT_INDEX_OFFSET, 128);\n\n    emit DebtIndexSnapshot(index);\n  }\n\n  /// @dev Internal function to update collateral index.\n  /// @param index The collateral index to update.\n  function _updateCollateralIndex(uint256 index) internal {\n    indexData = indexData.insertUint(index, COLLATERAL_INDEX_OFFSET, 128);\n\n    emit CollateralIndexSnapshot(index);\n  }\n\n  /**************************************\n   * Internal Functions For `sharesData` *\n   **************************************/\n\n  /// @dev Internal function to get debt and collateral shares.\n  /// @return debtShares The total number of debt shares.\n  /// @return collShares The total number of collateral shares.\n  function _getDebtAndCollateralShares() internal view returns (uint256 debtShares, uint256 collShares) {\n    bytes32 data = sharesData;\n    debtShares = data.decodeUint(DEBT_SHARES_OFFSET, 128);\n    collShares = data.decodeUint(COLLATERAL_SHARES_OFFSET, 128);\n  }\n\n  /// @dev Internal function to update debt and collateral shares.\n  /// @param debtShares The debt shares to update.\n  /// @param collShares The collateral shares to update.\n  function _updateDebtAndCollateralShares(uint256 debtShares, uint256 collShares) internal {\n    bytes32 data = sharesData;\n    data = data.insertUint(debtShares, DEBT_SHARES_OFFSET, 128);\n    sharesData = data.insertUint(collShares, COLLATERAL_SHARES_OFFSET, 128);\n  }\n\n  /// @dev Internal function to update debt shares.\n  /// @param shares The debt shares to update.\n  function _updateDebtShares(uint256 shares) internal {\n    sharesData = sharesData.insertUint(shares, DEBT_SHARES_OFFSET, 128);\n  }\n\n  /// @dev Internal function to update collateral shares.\n  /// @param shares The collateral shares to update.\n  function _updateCollateralShares(uint256 shares) internal {\n    sharesData = sharesData.insertUint(shares, COLLATERAL_SHARES_OFFSET, 128);\n  }\n\n  /*****************************************\n   * Internal Functions For `counterparty` *\n   *****************************************/\n\n  /// @dev Internal function to update counterparty.\n  /// @param newCounterparty The new counterparty to update.\n  function _updateCounterparty(address newCounterparty) internal {\n    _checkAddressNotZero(newCounterparty);\n\n    address oldCounterparty = counterparty;\n    counterparty = newCounterparty;\n\n    emit UpdateCounterparty(oldCounterparty, newCounterparty);\n  }\n\n  /**\n   * @dev This empty reserved space is put in place to allow future versions to add new\n   * variables without shifting down storage in the inheritance chain.\n   */\n  uint256[39] private __gap;\n}\n"},"contracts/core/pool/PositionLogic.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nimport { IPool } from \"../../interfaces/IPool.sol\";\nimport { IPriceOracle } from \"../../price-oracle/interfaces/IPriceOracle.sol\";\n\nimport { WordCodec } from \"../../common/codec/WordCodec.sol\";\nimport { Math } from \"../../libraries/Math.sol\";\nimport { TickLogic } from \"./TickLogic.sol\";\n\nabstract contract PositionLogic is TickLogic {\n  using WordCodec for bytes32;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  function __PositionLogic_init() internal onlyInitializing {\n    _updateNextPositionId(1);\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @inheritdoc IPool\n  function getPosition(uint256 tokenId) public view returns (uint256 rawColls, uint256 rawDebts) {\n    // compute actual shares\n    PositionInfo memory position = positionData[tokenId];\n    rawColls = position.colls;\n    rawDebts = position.debts;\n    if (position.nodeId > 0) {\n      (, uint256 collRatio, uint256 debtRatio) = _getRootNode(position.nodeId);\n      rawColls = (rawColls * collRatio) >> 60;\n      rawDebts = (rawDebts * debtRatio) >> 60;\n    }\n\n    // convert shares to actual amount\n    (uint256 debtIndex, uint256 collIndex) = _getDebtAndCollateralIndex();\n    rawColls = _convertToRawColl(rawColls, collIndex, Math.Rounding.Down);\n    rawDebts = _convertToRawDebt(rawDebts, debtIndex, Math.Rounding.Down);\n  }\n\n  /// @inheritdoc IPool\n  function getPositionDebtRatio(uint256 tokenId) external view returns (uint256 debtRatio) {\n    (uint256 rawColls, uint256 rawDebts) = getPosition(tokenId);\n    // price precision and ratio precision are both 1e18, use anchor price here\n    (uint256 price, , ) = IPriceOracle(priceOracle).getPrice();\n    if (rawColls == 0) return 0;\n    return (rawDebts * PRECISION * PRECISION) / (price * rawColls);\n  }\n\n  /// @inheritdoc IPool\n  function getTotalRawCollaterals() external view returns (uint256) {\n    (, uint256 totalColls) = _getDebtAndCollateralShares();\n    (, uint256 collIndex) = _getDebtAndCollateralIndex();\n    return _convertToRawColl(totalColls, collIndex, Math.Rounding.Down);\n  }\n\n  /// @inheritdoc IPool\n  function getTotalRawDebts() external view returns (uint256) {\n    (uint256 totalDebts, ) = _getDebtAndCollateralShares();\n    (uint256 debtIndex, ) = _getDebtAndCollateralIndex();\n    return _convertToRawDebt(totalDebts, debtIndex, Math.Rounding.Down);\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @dev Internal function to mint a new position.\n  /// @param owner The address of position owner.\n  /// @return positionId The id of the position.\n  function _mintPosition(address owner) internal returns (uint32 positionId) {\n    unchecked {\n      positionId = _getNextPositionId();\n      _updateNextPositionId(positionId + 1);\n    }\n\n    positionMetadata[positionId] = bytes32(0).insertUint(block.timestamp, 0, 40);\n    _mint(owner, positionId);\n  }\n\n  /// @dev Internal function to get and update position.\n  /// @param tokenId The id of the position.\n  /// @return position The position struct.\n  function _getAndUpdatePosition(uint256 tokenId) internal returns (PositionInfo memory position) {\n    position = positionData[tokenId];\n    if (position.nodeId > 0) {\n      (uint256 root, uint256 collRatio, uint256 debtRatio) = _getRootNodeAndCompress(position.nodeId);\n      position.colls = uint96((position.colls * collRatio) >> 60);\n      position.debts = uint96((position.debts * debtRatio) >> 60);\n      position.nodeId = uint32(root);\n      positionData[tokenId] = position;\n    }\n  }\n\n  /// @dev Internal function to convert raw collateral amounts to collateral shares.\n  function _convertToCollShares(\n    uint256 raw,\n    uint256 index,\n    Math.Rounding rounding\n  ) internal pure returns (uint256 shares) {\n    shares = Math.mulDiv(raw, index, E96, rounding);\n  }\n\n  /// @dev Internal function to convert raw debt amounts to debt shares.\n  function _convertToDebtShares(\n    uint256 raw,\n    uint256 index,\n    Math.Rounding rounding\n  ) internal pure returns (uint256 shares) {\n    shares = Math.mulDiv(raw, E96, index, rounding);\n  }\n\n  /// @dev Internal function to convert raw collateral shares to collateral amounts.\n  function _convertToRawColl(\n    uint256 shares,\n    uint256 index,\n    Math.Rounding rounding\n  ) internal pure returns (uint256 raw) {\n    raw = Math.mulDiv(shares, E96, index, rounding);\n  }\n\n  /// @dev Internal function to convert raw debt shares to debt amounts.\n  function _convertToRawDebt(\n    uint256 shares,\n    uint256 index,\n    Math.Rounding rounding\n  ) internal pure returns (uint256 raw) {\n    raw = Math.mulDiv(shares, index, E96, rounding);\n  }\n\n  /**\n   * @dev This empty reserved space is put in place to allow future versions to add new\n   * variables without shifting down storage in the inheritance chain.\n   */\n  uint256[50] private __gap;\n}\n"},"contracts/core/pool/SigmaLongPool.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nimport { IPoolConfiguration } from \"../../interfaces/IPoolConfiguration.sol\";\n\nimport { Math } from \"../../libraries/Math.sol\";\nimport { BasePool } from \"./BasePool.sol\";\n\ncontract SigmaLongPool is BasePool {\n  /// @dev Error when reducing more than total collateral.\n  error ErrorReduceTooMuchCollateral();\n\n  /***********\n   * Structs *\n   ***********/\n\n  /// @dev The struct for AAVE borrow rate snapshot.\n  /// @param borrowIndex The current borrow index of AAVE, multiplied by 1e27.\n  /// @param lastInterestRate The last recorded interest rate, multiplied by 1e18.\n  /// @param timestamp The timestamp when the snapshot is taken.\n  struct BorrowRateSnapshot {\n    // The initial value of `borrowIndex` is `10^27`, it is very unlikely this value will exceed `2^128`.\n    uint128 borrowIndex;\n    uint80 lastInterestRate;\n    uint48 timestamp;\n  }\n\n  /*********************\n   * Storage Variables *\n   *********************/\n\n  /// @dev deprecated\n  /// @dev `fundingMiscData` is a storage slot that can be used to store unrelated pieces of information.\n  ///\n  /// - The *open ratio* is the fee ratio for opening position, multiplied by 1e9.\n  /// - The *open ratio step* is the fee ratio step for opening position, multiplied by 1e18.\n  /// - The *close fee ratio* is the fee ratio for closing position, multiplied by 1e9.\n  /// - The *funding ratio* is the scalar for funding rate, multiplied by 1e9.\n  ///   The maximum value is `4.294967296`.\n  ///\n  /// [ open ratio | open ratio step | close fee ratio | funding ratio | reserved ]\n  /// [  30  bits  |     60 bits     |     30 bits     |    32 bits    | 104 bits ]\n  /// [ MSB                                                                   LSB ]\n  bytes32 private fundingMiscData;\n\n  /// @notice The snapshot for AAVE borrow rate.\n  /// @dev `borrowIndex` and `lastInterestRate` are deprecated\n  BorrowRateSnapshot public borrowRateSnapshot;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  constructor(address _poolManager, address _configuration) BasePool(_poolManager, _configuration) {}\n\n  function initialize(\n    address admin,\n    string memory name_,\n    string memory symbol_,\n    address _collateralToken,\n    address _priceOracle\n  ) external initializer {\n    // __Context_init();\n    // __ERC165_init();\n    __ERC721_init(name_, symbol_);\n    // __AccessControl_init();\n\n    __PoolStorage_init(_collateralToken, _priceOracle);\n    __TickLogic_init();\n    __PositionLogic_init();\n    __BasePool_init();\n\n    _grantRole(DEFAULT_ADMIN_ROLE, admin);\n\n    borrowRateSnapshot.timestamp = uint40(block.timestamp);\n  }\n\n  function reduceCollateral(uint256 amount) external onlyPoolManager {\n    (, uint256 totalColls) = _getDebtAndCollateralShares();\n    (, uint256 collIndex) = _getDebtAndCollateralIndex();\n    uint256 totalRawColls = _convertToRawColl(totalColls, collIndex, Math.Rounding.Down);\n    if (totalRawColls < amount) {\n      revert ErrorReduceTooMuchCollateral();\n    }\n\n    uint256 newCollIndex = (collIndex * totalRawColls) / (totalRawColls - amount);\n    _updateCollateralIndex(newCollIndex);\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @inheritdoc BasePool\n  function _updateCollAndDebtIndex() internal virtual override returns (uint256 newCollIndex, uint256 newDebtIndex) {\n    (newDebtIndex, newCollIndex) = _getDebtAndCollateralIndex();\n\n    BorrowRateSnapshot memory snapshot = borrowRateSnapshot;\n    uint256 duration = block.timestamp - snapshot.timestamp;\n    if (duration > 0) {\n      uint256 fundingRatio = IPoolConfiguration(configuration).getLongPoolFundingRatio(address(this));\n      if (fundingRatio > 0) {\n        (, uint256 totalColls) = _getDebtAndCollateralShares();\n        uint256 totalRawColls = _convertToRawColl(totalColls, newCollIndex, Math.Rounding.Down);\n        if (totalRawColls > 0) {\n          uint256 funding = (totalRawColls * fundingRatio * duration) / (PRECISION * 365 days);\n\n          // update collateral index with funding costs\n          newCollIndex = (newCollIndex * totalRawColls) / (totalRawColls - funding);\n          _updateCollateralIndex(newCollIndex);\n        }\n      }\n\n      // checkpoint on pool configuration\n      IPoolConfiguration(configuration).checkpoint(address(this));\n\n      borrowRateSnapshot.timestamp = uint40(block.timestamp);\n    }\n  }\n\n  /// @inheritdoc BasePool\n  function _deductProtocolFees(int256) internal view virtual override returns (uint256) {\n    return 0;\n  }\n}\n"},"contracts/core/pool/TickLogic.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nimport { WordCodec } from \"../../common/codec/WordCodec.sol\";\nimport { TickBitmap } from \"../../libraries/TickBitmap.sol\";\nimport { TickMath } from \"../../libraries/TickMath.sol\";\nimport { PoolStorage } from \"./PoolStorage.sol\";\n\nabstract contract TickLogic is PoolStorage {\n  using TickBitmap for mapping(int8 => uint256);\n  using WordCodec for bytes32;\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev Below are offsets of each variables in `TickTreeNode.metadata`.\n  uint256 private constant PARENT_OFFSET = 0;\n  uint256 private constant TICK_OFFSET = 48;\n  uint256 private constant COLL_RATIO_OFFSET = 64;\n  uint256 private constant DEBT_RATIO_OFFSET = 128;\n\n  /// @dev Below are offsets of each variables in `TickTreeNode.value`.\n  uint256 internal constant COLL_SHARE_OFFSET = 0;\n  uint256 internal constant DEBT_SHARE_OFFSET = 128;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  function __TickLogic_init() internal onlyInitializing {\n    _updateNextTreeNodeId(1);\n    _updateTopTick(type(int16).min);\n  }\n\n  /************************\n   * Restricted Functions *\n   ************************/\n\n  /// @notice Get the root node and compress the path.\n  /// @dev This function is only callable by the default admin, in case someone create a long chain of nodes.\n  /// @param node The id of the given tree node.\n  /// @return root The root node id.\n  /// @return collRatio The actual collateral ratio of the given node, multiplied by 2^60.\n  /// @return debtRatio The actual debt ratio of the given node, multiplied by 2^60.\n  function getRootNodeAndCompress(\n    uint256 node\n  ) external onlyRole(DEFAULT_ADMIN_ROLE) returns (uint256 root, uint256 collRatio, uint256 debtRatio) {\n    (root, collRatio, debtRatio) = _getRootNodeAndCompress(node);\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @dev Internal function to get the root of the given tree node.\n  /// @param node The id of the given tree node.\n  /// @return root The root node id.\n  /// @return collRatio The actual collateral ratio of the given node, multiplied by 2^60.\n  /// @return debtRatio The actual debt ratio of the given node, multiplied by 2^60.\n  function _getRootNode(uint256 node) internal view returns (uint256 root, uint256 collRatio, uint256 debtRatio) {\n    collRatio = E60;\n    debtRatio = E60;\n    while (true) {\n      bytes32 metadata = tickTreeData[node].metadata;\n      uint256 parent = metadata.decodeUint(PARENT_OFFSET, 48);\n      collRatio = (collRatio * metadata.decodeUint(COLL_RATIO_OFFSET, 64)) >> 60;\n      debtRatio = (debtRatio * metadata.decodeUint(DEBT_RATIO_OFFSET, 64)) >> 60;\n      if (parent == 0) break;\n      node = parent;\n    }\n    root = node;\n  }\n\n  /// @dev Internal function to get the root of the given tree node and compress path.\n  /// @param node The id of the given tree node.\n  /// @return root The root node id.\n  /// @return collRatio The actual collateral ratio of the given node, multiplied by 2^60.\n  /// @return debtRatio The actual debt ratio of the given node, multiplied by 2^60.\n  function _getRootNodeAndCompress(uint256 node) internal returns (uint256 root, uint256 collRatio, uint256 debtRatio) {\n    // @note On average, the expected length of the chain should be `log(n)`, where `n` is the total number of tree nodes.\n    // So we don't need to worry much about the gas usage.\n    // In normal cases, the length is bounded by `max(min(adjacent tick gap))`. And in worse case, someone try to create\n    // a long chain of nodes. We have `ErrorTickNotMoved` check in `_liquidateTick`, the maximum length of the chain is `65536`.\n    // And if someone did create a long chain, we have a public admin function to compress the chain manually and externally.\n    uint256 depth;\n    bytes32 metadata;\n    root = node;\n    while (true) {\n      // @dev no need to clean the transient storage, it will be overwritten.\n      assembly {\n        tstore(depth, root)\n        depth := add(depth, 1)\n      }\n      metadata = tickTreeData[root].metadata;\n      uint256 parent = metadata.decodeUint(PARENT_OFFSET, 48);\n      if (parent == 0) break;\n      root = parent;\n    }\n    // depth - 1\n    metadata = tickTreeData[root].metadata;\n    collRatio = metadata.decodeUint(COLL_RATIO_OFFSET, 64);\n    debtRatio = metadata.decodeUint(DEBT_RATIO_OFFSET, 64);\n    if (depth > 1) {\n      for (uint256 i = depth - 2; ; --i) {\n        assembly {\n          node := tload(i)\n        }\n        metadata = tickTreeData[node].metadata;\n        collRatio = (collRatio * metadata.decodeUint(COLL_RATIO_OFFSET, 64)) >> 60;\n        debtRatio = (debtRatio * metadata.decodeUint(DEBT_RATIO_OFFSET, 64)) >> 60;\n        metadata = metadata.insertUint(root, PARENT_OFFSET, 48);\n        metadata = metadata.insertUint(collRatio, COLL_RATIO_OFFSET, 64);\n        metadata = metadata.insertUint(debtRatio, DEBT_RATIO_OFFSET, 64);\n        tickTreeData[node].metadata = metadata;\n        if (i == 0) break;\n      }\n    }\n  }\n\n  /// @dev Internal function to create a new tree node.\n  /// @param tick The tick where this tree node belongs to.\n  /// @return node The created tree node id.\n  function _newTickTreeNode(int16 tick) internal returns (uint48 node) {\n    unchecked {\n      node = _getNextTreeNodeId();\n      _updateNextTreeNodeId(node + 1);\n    }\n    tickData[tick] = node;\n\n    bytes32 metadata = bytes32(0);\n    metadata = metadata.insertInt(tick, TICK_OFFSET, 16); // set tick\n    metadata = metadata.insertUint(E60, COLL_RATIO_OFFSET, 64); // set coll ratio\n    metadata = metadata.insertUint(E60, DEBT_RATIO_OFFSET, 64); // set debt ratio\n    tickTreeData[node].metadata = metadata;\n  }\n\n  /// @dev Internal function to find first tick such that `TickMath.getRatioAtTick(tick) >= debts/colls`.\n  /// @param colls The collateral shares.\n  /// @param debts The debt shares.\n  /// @return tick The value of found first tick.\n  function _getTick(uint256 colls, uint256 debts) internal pure returns (int256 tick) {\n    uint256 ratio = (debts * TickMath.ZERO_TICK_SCALED_RATIO) / colls;\n    (tick, ) = TickMath.getTickAtRatio(ratio);\n    if (tick < TickMath.MIN_TICK) {\n      tick = TickMath.MIN_TICK;\n    }\n    uint256 ratioAtTick = TickMath.getRatioAtTick(tick);\n    unchecked {\n      if (ratioAtTick < ratio) tick++;\n    }\n    if (tick > TickMath.MAX_TICK) {\n      tick = TickMath.MAX_TICK;\n    }\n  }\n\n  /// @dev Internal function to retrieve or create a tree node.\n  /// @param tick The tick where this tree node belongs to.\n  /// @return node The tree node id.\n  function _getOrCreateTickNode(int256 tick) internal returns (uint48 node) {\n    node = tickData[tick];\n    if (node == 0) {\n      node = _newTickTreeNode(int16(tick));\n    }\n  }\n\n  /// @dev Internal function to add position collaterals and debts to some tick.\n  /// @param colls The collateral shares.\n  /// @param debts The debt shares.\n  /// @param checkDebts Whether we should check the value of `debts`.\n  /// @return tick The tick where this position belongs to.\n  /// @return node The corresponding tree node id for this tick.\n  function _addPositionToTick(\n    uint256 colls,\n    uint256 debts,\n    bool checkDebts\n  ) internal returns (int256 tick, uint48 node) {\n    if (debts > 0) {\n      if (checkDebts && int256(debts) < MIN_DEBT) {\n        revert ErrorDebtTooSmall();\n      }\n\n      tick = _getTick(colls, debts);\n      node = _getOrCreateTickNode(tick);\n      bytes32 value = tickTreeData[node].value;\n      uint256 newColls = value.decodeUint(COLL_SHARE_OFFSET, 128) + colls;\n      uint256 newDebts = value.decodeUint(DEBT_SHARE_OFFSET, 128) + debts;\n      value = value.insertUint(newColls, COLL_SHARE_OFFSET, 128);\n      value = value.insertUint(newDebts, DEBT_SHARE_OFFSET, 128);\n      tickTreeData[node].value = value;\n\n      if (newDebts == debts) {\n        tickBitmap.flipTick(int16(tick));\n      }\n\n      // update top tick\n      if (tick > _getTopTick()) {\n        _updateTopTick(int16(tick));\n      }\n    }\n  }\n\n  /// @dev Internal function to remove position from tick.\n  /// @param position The position struct to remove.\n  function _removePositionFromTick(PositionInfo memory position) internal {\n    if (position.nodeId == 0) return;\n\n    bytes32 value = tickTreeData[position.nodeId].value;\n    uint256 oldDebts = value.decodeUint(DEBT_SHARE_OFFSET, 128);\n    uint256 newColls = value.decodeUint(COLL_SHARE_OFFSET, 128) - position.colls;\n    uint256 newDebts = oldDebts - position.debts;\n    value = value.insertUint(newColls, COLL_SHARE_OFFSET, 128);\n    value = value.insertUint(newDebts, DEBT_SHARE_OFFSET, 128);\n    tickTreeData[position.nodeId].value = value;\n\n    if (newDebts == 0 && oldDebts > 0) {\n      int16 tick = int16(tickTreeData[position.nodeId].metadata.decodeInt(TICK_OFFSET, 16));\n      tickBitmap.flipTick(tick);\n\n      // top tick gone, update it to new one\n      int16 topTick = _getTopTick();\n      if (topTick == tick) {\n        _resetTopTick(topTick);\n      }\n    }\n  }\n\n  /// @dev Internal function to check if the tick will move after liquidation.\n  /// @param tick The tick to check.\n  /// @param liquidatedColl The amount of collateral shares liquidated.\n  /// @param liquidatedDebt The amount of debt shares liquidated.\n  /// @return Whether the tick will move.\n  function _tickWillMove(int16 tick, uint256 liquidatedColl, uint256 liquidatedDebt) internal view returns (bool) {\n    uint48 node = tickData[tick];\n    bytes32 value = tickTreeData[node].value;\n    uint256 tickColl = value.decodeUint(COLL_SHARE_OFFSET, 128);\n    uint256 tickDebt = value.decodeUint(DEBT_SHARE_OFFSET, 128);\n    uint256 tickCollAfter = tickColl - liquidatedColl;\n    uint256 tickDebtAfter = tickDebt - liquidatedDebt;\n    if (tickDebtAfter == 0) return true;\n\n    int256 newTick = _getTick(tickCollAfter, tickDebtAfter);\n    return newTick != int256(tick);\n  }\n\n  /// @dev Internal function to liquidate a tick.\n  ///      The caller make sure `max(liquidatedColl, liquidatedDebt) > 0`.\n  ///\n  /// @param tick The id of tick to liquidate.\n  /// @param liquidatedColl The amount of collateral shares liquidated.\n  /// @param liquidatedDebt The amount of debt shares liquidated.\n  function _liquidateTick(\n    int16 tick,\n    uint256 liquidatedColl,\n    uint256 liquidatedDebt,\n    uint256 price\n  ) internal {\n    uint48 node = tickData[tick];\n    // create new tree node for this tick\n    _newTickTreeNode(tick);\n    // clear bitmap first, and it will be updated later if needed.\n    tickBitmap.flipTick(tick);\n\n    bytes32 value = tickTreeData[node].value;\n    bytes32 metadata = tickTreeData[node].metadata;\n    uint256 tickColl = value.decodeUint(COLL_SHARE_OFFSET, 128);\n    uint256 tickDebt = value.decodeUint(DEBT_SHARE_OFFSET, 128);\n    uint256 tickCollAfter = tickColl - liquidatedColl;\n    uint256 tickDebtAfter = tickDebt - liquidatedDebt;\n\n    // update metadata, scope to avoid stack too deep\n    {\n      uint256 collRatio = (tickCollAfter * E60) / tickColl;\n      uint256 debtRatio = (tickDebtAfter * E60) / tickDebt;\n      metadata = metadata.insertUint(collRatio, COLL_RATIO_OFFSET, 64);\n      metadata = metadata.insertUint(debtRatio, DEBT_RATIO_OFFSET, 64);\n    }\n\n    int256 newTick = type(int256).min;\n    if (tickDebtAfter > 0) {\n      // partial liquidated, move funds to another tick\n      uint48 parentNode;\n      (newTick, parentNode) = _addPositionToTick(tickCollAfter, tickDebtAfter, false);\n      metadata = metadata.insertUint(parentNode, PARENT_OFFSET, 48);\n\n      // @note When it is redeem, we want the tick must be moved. since the attackers can use redeem to create a long\n      // chain. As for rebalance and liquidate, we don't check this. The attacker cannot control the price, it is hard\n      // to create a long chain in normal cases. And in normal reblance and liquidate, move to the same tick happens\n      // frequently and it is expected. And when attacker try to create a long chain during rebalance and liquidate,\n      // we still have admin function `getRootNodeAndCompress` to fix the issue.\n      // \n      // @note for redeem, we have `_tickWillMove` to check whether the tick will move. So this check is not needed.\n      // if (newTick == tick) {\n      //  revert ErrorTickNotMoved();\n      //}\n    }\n    if (newTick == type(int256).min) {\n      emit TickMovement(tick, type(int16).min, tickCollAfter, tickDebtAfter, price);\n    } else {\n      emit TickMovement(tick, int16(newTick), tickCollAfter, tickDebtAfter, price);\n    }\n\n    // top tick liquidated, update it to new one\n    int16 topTick = _getTopTick();\n    if (topTick == tick && newTick != int256(tick)) {\n      _resetTopTick(topTick);\n    }\n    tickTreeData[node].metadata = metadata;\n  }\n\n  /// @dev Internal function to reset top tick.\n  /// @param oldTopTick The previous value of top tick.\n  function _resetTopTick(int16 oldTopTick) internal {\n    while (oldTopTick > type(int16).min) {\n      bool hasDebt;\n      (oldTopTick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(oldTopTick - 1);\n      if (hasDebt) break;\n    }\n    _updateTopTick(oldTopTick);\n  }\n\n  /**\n   * @dev This empty reserved space is put in place to allow future versions to add new\n   * variables without shifting down storage in the inheritance chain.\n   */\n  uint256[50] private __gap;\n}\n"},"contracts/interfaces/IPool.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPool {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when price oracle is updated.\n  /// @param oldOracle The previous address of price oracle.\n  /// @param newOracle The current address of price oracle.\n  event UpdatePriceOracle(address oldOracle, address newOracle);\n\n  /// @notice Emitted when borrow status is updated.\n  /// @param status The updated borrow status.\n  event UpdateBorrowStatus(bool status);\n\n  /// @notice Emitted when redeem status is updated.\n  /// @param status The updated redeem status.\n  event UpdateRedeemStatus(bool status);\n\n  /// @notice Emitted when debt ratio range is updated.\n  /// @param minDebtRatio The current value of minimum debt ratio, multiplied by 1e18.\n  /// @param maxDebtRatio The current value of maximum debt ratio, multiplied by 1e18.\n  event UpdateDebtRatioRange(uint256 minDebtRatio, uint256 maxDebtRatio);\n\n  /// @notice Emitted when max redeem ratio per tick is updated.\n  /// @param ratio The current value of max redeem ratio per tick, multiplied by 1e9.\n  event UpdateMaxRedeemRatioPerTick(uint256 ratio);\n\n  /// @notice Emitted when the rebalance ratio is updated.\n  /// @param debtRatio The current value of rebalance debt ratio, multiplied by 1e18.\n  /// @param bonusRatio The current value of rebalance bonus ratio, multiplied by 1e9.\n  event UpdateRebalanceRatios(uint256 debtRatio, uint256 bonusRatio);\n\n  /// @notice Emitted when the liquidate ratio is updated.\n  /// @param debtRatio The current value of liquidate debt ratio, multiplied by 1e18.\n  /// @param bonusRatio The current value of liquidate bonus ratio, multiplied by 1e9.\n  event UpdateLiquidateRatios(uint256 debtRatio, uint256 bonusRatio);\n\n  /// @notice Emitted when position is updated.\n  /// @param position The index of this position.\n  /// @param tick The index of tick, this position belongs to.\n  /// @param collShares The amount of collateral shares in this position.\n  /// @param debtShares The amount of debt shares in this position.\n  /// @param price The price used for this operation.\n  event PositionSnapshot(uint256 position, int16 tick, uint256 collShares, uint256 debtShares, uint256 price);\n\n  /// @notice Emitted when tick moved due to rebalance, liquidate or redeem.\n  /// @param oldTick The index of the previous tick.\n  /// @param newTick The index of the current tick.\n  /// @param collShares The amount of collateral shares added to new tick.\n  /// @param debtShares The amount of debt shares added to new tick.\n  /// @param price The price used for this operation.\n  event TickMovement(int16 oldTick, int16 newTick, uint256 collShares, uint256 debtShares, uint256 price);\n\n  /// @notice Emitted when debt index increase.\n  event DebtIndexSnapshot(uint256 index);\n\n  /// @notice Emitted when collateral index increase.\n  event CollateralIndexSnapshot(uint256 index);\n\n  /// @notice Emitted when counterparty is updated.\n  /// @param oldCounterparty The previous address of counterparty.\n  /// @param newCounterparty The new address of counterparty.\n  event UpdateCounterparty(address oldCounterparty, address newCounterparty);\n\n  /***********\n   * Structs *\n   ***********/\n\n  /// @dev The result for liquidation.\n  /// @param rawColls The amount of collateral tokens liquidated.\n  /// @param rawDebts The amount of debt tokens liquidated.\n  /// @param bonusRawColls The amount of bonus collateral tokens given.\n  /// @param bonusFromReserve The amount of bonus collateral tokens coming from reserve pool.\n  struct LiquidateResult {\n    uint256 rawColls;\n    uint256 rawDebts;\n    uint256 bonusRawColls;\n    uint256 bonusFromReserve;\n  }\n\n  /// @dev The result for rebalance.\n  /// @param rawColls The amount of collateral tokens rebalanced.\n  /// @param rawDebts The amount of debt tokens rebalanced.\n  /// @param bonusRawColls The amount of bonus collateral tokens given.\n  struct RebalanceResult {\n    uint256 rawColls;\n    uint256 rawDebts;\n    uint256 bonusRawColls;\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of counterparty.\n  function counterparty() external view returns (address);\n\n  /// @notice The address of fxUSD.\n  function fxUSD() external view returns (address);\n\n  /// @notice The address of `PoolManager` contract.\n  function poolManager() external view returns (address);\n\n  /// @notice The address of `PoolConfiguration` contract.\n  function configuration() external view returns (address);\n\n  /// @notice The address of collateral token.\n  function collateralToken() external view returns (address);\n\n  /// @notice The address of price oracle.\n  function priceOracle() external view returns (address);\n\n  /// @notice Return whether borrow is paused.\n  function isBorrowPaused() external view returns (bool);\n\n  /// @notice Return whether redeem is paused.\n  function isRedeemPaused() external view returns (bool);\n\n  /// @notice Return the current top tick with debts.\n  function getTopTick() external view returns (int16);\n\n  /// @notice Return the next position id.\n  function getNextPositionId() external view returns (uint32);\n\n  /// @notice Return the next tick tree node id.\n  function getNextTreeNodeId() external view returns (uint48);\n\n  /// @notice Return the debt ratio range.\n  /// @param minDebtRatio The minimum required debt ratio, multiplied by 1e18.\n  /// @param maxDebtRatio The minimum allowed debt ratio, multiplied by 1e18.\n  function getDebtRatioRange() external view returns (uint256 minDebtRatio, uint256 maxDebtRatio);\n\n  /// @notice Return the maximum redeem percentage per tick, multiplied by 1e9.\n  function getMaxRedeemRatioPerTick() external view returns (uint256);\n\n  /// @notice Get `debtRatio` and `bonusRatio` for rebalance.\n  /// @return debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.\n  /// @return bonusRatio The bonus ratio during rebalance, multiplied by 1e9.\n  function getRebalanceRatios() external view returns (uint256 debtRatio, uint256 bonusRatio);\n\n  /// @notice Get `debtRatio` and `bonusRatio` for liquidate.\n  /// @return debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.\n  /// @return bonusRatio The bonus ratio during liquidate, multiplied by 1e9.\n  function getLiquidateRatios() external view returns (uint256 debtRatio, uint256 bonusRatio);\n\n  /// @notice Get debt and collateral index.\n  /// @return debtIndex The index for debt shares.\n  /// @return collIndex The index for collateral shares.\n  function getDebtAndCollateralIndex() external view returns (uint256 debtIndex, uint256 collIndex);\n\n  /// @notice Get debt and collateral shares.\n  /// @return debtShares The total number of debt shares.\n  /// @return collShares The total number of collateral shares.\n  function getDebtAndCollateralShares() external view returns (uint256 debtShares, uint256 collShares);\n\n  /// @notice Return the details of the given position.\n  /// @param tokenId The id of position to query.\n  /// @return rawColls The amount of collateral tokens supplied in this position.\n  /// @return rawDebts The amount of debt tokens borrowed in this position.\n  function getPosition(uint256 tokenId) external view returns (uint256 rawColls, uint256 rawDebts);\n\n  /// @notice Return the debt ratio of the given position.\n  /// @param tokenId The id of position to query.\n  /// @return debtRatio The debt ratio of this position.\n  function getPositionDebtRatio(uint256 tokenId) external view returns (uint256 debtRatio);\n\n  /// @notice The total amount of raw collateral tokens.\n  function getTotalRawCollaterals() external view returns (uint256);\n\n  /// @notice The total amount of raw debt tokens.\n  function getTotalRawDebts() external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Open a new position or operate on an old position.\n  /// @param positionId The id of the position. If `positionId=0`, it means we need to open a new position.\n  /// @param newRawColl The amount of collateral token to supply (positive value) or withdraw (negative value).\n  /// @param newRawColl The amount of debt token to borrow (positive value) or repay (negative value).\n  /// @param owner The address of position owner.\n  /// @return actualPositionId The id of this position.\n  /// @return actualRawColl The actual amount of collateral tokens supplied (positive value) or withdrawn (negative value).\n  /// @return actualRawDebt The actual amount of debt tokens borrowed (positive value) or repay (negative value).\n  function operate(\n    uint256 positionId,\n    int256 newRawColl,\n    int256 newRawDebt,\n    address owner\n  ) external returns (uint256 actualPositionId, int256 actualRawColl, int256 actualRawDebt, uint256 protocolFees);\n\n  /// @notice Redeem debt tokens to get collateral tokens.\n  /// @param rawDebts The amount of debt tokens to redeem.\n  /// @return actualRawDebts The actual amount of debt tokens used.\n  /// @return rawColls The amount of collateral tokens to redeemed.\n  function redeem(uint256 rawDebts) external returns (uint256 actualRawDebts, uint256 rawColls);\n\n  /// @notice Rebalance all positions in the given tick.\n  /// @param tick The id of tick to rebalance.\n  /// @param maxRawDebts The maximum amount of debt tokens to rebalance.\n  /// @return result The result of rebalance.\n  function rebalance(int16 tick, uint256 maxRawDebts) external returns (RebalanceResult memory result);\n\n  /// @notice Rebalance all ticks in the decreasing order of LTV.\n  /// @param maxRawDebts The maximum amount of debt tokens to rebalance.\n  /// @return result The result of rebalance.\n  function rebalance(uint256 maxRawDebts) external returns (RebalanceResult memory result);\n\n  /// @notice Liquidate all ticks in the decreasing order of LTV.\n  /// @param maxRawDebts The maximum amount of debt tokens to liquidate.\n  /// @param reservedRawColls The amount of collateral tokens in reserve pool.\n  /// @return result The result of liquidate.\n  function liquidate(uint256 maxRawDebts, uint256 reservedRawColls) external returns (LiquidateResult memory result);\n\n  /// @notice Reduce debt.\n  /// @param rawAmount The amount of debt tokens to reduce.\n  function reduceDebt(uint256 rawAmount) external;\n}\n"},"contracts/interfaces/IPoolConfiguration.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\ninterface IPoolConfiguration {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the oracle is updated.\n  /// @param oldOracle The old oracle address.\n  /// @param newOracle The new oracle address.\n  event UpdateOracle(address indexed oldOracle, address indexed newOracle);\n\n  /// @notice Emitted when the pool fee ratio is updated.\n  /// @param pool The address of pool.\n  /// @param recipient The address of recipient.\n  /// @param supplyRatio The supply ratio, multiplied by 1e9.\n  /// @param supplyRatioStep The supply ratio step, multiplied by 1e18.\n  /// @param withdrawFeeRatio The withdraw fee ratio, multiplied by 1e9.\n  /// @param borrowFeeRatio The borrow fee ratio, multiplied by 1e9.\n  /// @param repayFeeRatio The repay fee ratio, multiplied by 1e9.\n  event UpdatePoolFeeRatio(\n    address indexed pool,\n    address indexed recipient,\n    uint256 supplyRatio,\n    uint256 supplyRatioStep,\n    uint256 withdrawFeeRatio,\n    uint256 borrowFeeRatio,\n    uint256 repayFeeRatio\n  );\n\n  /// @notice Emitted when the long funding ratio parameter is updated.\n  /// @param scalarA The scalar A.\n  /// @param scalarB The scalar B.\n  /// @param maxFxUSDRatio The max fxUSD ratio.\n  event UpdateLongFundingRatioParameter(uint64 scalarA, uint64 scalarB, uint64 maxFxUSDRatio);\n\n  /// @notice Emitted when the short funding ratio parameter is updated.\n  /// @param scalarC The scalar C.\n  /// @param maxBorrowRatio The max borrow ratio.\n  event UpdateShortFundingRatioParameter(uint64 scalarC, uint64 maxBorrowRatio);\n\n  /// @notice Emitted when the snapshot is taken.\n  /// @param borrowIndex The borrow index.\n  /// @param lastInterestRate The last interest rate.\n  /// @param timestamp The timestamp of the snapshot.\n  event Snapshot(uint256 borrowIndex, uint256 lastInterestRate, uint256 timestamp);\n\n  /// @notice Emitted when the stable depeg price is updated.\n  /// @param oldStableDepegPrice The old stable depeg price.\n  /// @param newStableDepegPrice The new stable depeg price.\n  event UpdateStableDepegPrice(uint256 oldStableDepegPrice, uint256 newStableDepegPrice);\n\n  /// @notice Emitted when an address is registered.\n  /// @param key The key of the registered address.\n  /// @param addr The registered address.\n  event Register(bytes32 key, address addr);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return whether borrow for fxUSD is allowed.\n  function isBorrowAllowed() external view returns (bool);\n\n  /// @notice Return whether redeem for fxUSD is allowed.\n  function isRedeemAllowed() external view returns (bool);\n\n  /// @notice Return whether funding costs is enabled.\n  function isFundingEnabled() external view returns (bool);\n\n  /// @notice Return whether repay with stable coin is allowed.\n  function isStableRepayAllowed() external view returns (bool);\n\n  /// @notice Get the pool fee ratio.\n  /// @param pool The address of pool.\n  /// @param recipient The address of recipient.\n  /// @return supplyFeeRatio The supply fee ratio, multiplied by 1e9.\n  /// @return withdrawFeeRatio The withdraw fee ratio, multiplied by 1e9.\n  /// @return borrowFeeRatio The borrow fee ratio, multiplied by 1e9.\n  /// @return repayFeeRatio The repay fee ratio, multiplied by 1e9.\n  function getPoolFeeRatio(\n    address pool,\n    address recipient\n  )\n    external\n    view\n    returns (uint256 supplyFeeRatio, uint256 withdrawFeeRatio, uint256 borrowFeeRatio, uint256 repayFeeRatio);\n\n  /// @notice Get the long pool funding ratio.\n  /// @param pool The address of pool.\n  /// @return fundingRatio The funding ratio, multiplied by 1e18.\n  function getLongPoolFundingRatio(address pool) external view returns (uint256 fundingRatio);\n\n  /// @notice Get the short pool funding ratio.\n  /// @param pool The address of pool.\n  /// @return fundingRatio The funding ratio, multiplied by 1e18.\n  function getShortPoolFundingRatio(address pool) external view returns (uint256 fundingRatio);\n\n  /// @notice Get the registered address.\n  /// @param key The key of the registered address.\n  /// @return address The registered address.\n  function registry(bytes32 key) external view returns (address);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Checkpoint the lending pool snapshot.\n  /// @param pool The address of pool.\n  function checkpoint(address pool) external;\n}\n"},"contracts/interfaces/IPoolManager.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPoolManager {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Register a new pool.\n  /// @param pool The address of fx pool.\n  event RegisterPool(address indexed pool);\n\n  /// @notice Emitted when the reward splitter contract is updated.\n  /// @param pool The address of fx pool.\n  /// @param oldSplitter The address of previous reward splitter contract.\n  /// @param newSplitter The address of current reward splitter contract.\n  event UpdateRewardSplitter(address indexed pool, address indexed oldSplitter, address indexed newSplitter);\n\n  /// @notice Emitted when token rate is updated.\n  /// @param scalar The token scalar to reach 18 decimals.\n  /// @param provider The address of token rate provider.\n  event UpdateTokenRate(address indexed token, uint256 scalar, address provider);\n\n  /// @notice Emitted when pool capacity is updated.\n  /// @param pool The address of fx pool.\n  /// @param collateralCapacity The capacity for collateral token.\n  /// @param debtCapacity The capacity for debt token.\n  event UpdatePoolCapacity(address indexed pool, uint256 collateralCapacity, uint256 debtCapacity);\n\n  /// @notice Emitted when position is updated.\n  /// @param pool The address of pool where the position belongs to.\n  /// @param position The id of the position.\n  /// @param deltaColls The amount of collateral token changes.\n  /// @param deltaDebts The amount of debt token changes.\n  /// @param protocolFees The amount of protocol fees charges.\n  event Operate(\n    address indexed pool,\n    uint256 indexed position,\n    int256 deltaColls,\n    int256 deltaDebts,\n    uint256 protocolFees\n  );\n\n  /// @notice Emitted when redeem happened.\n  /// @param pool The address of pool redeemed.\n  /// @param colls The amount of collateral tokens redeemed.\n  /// @param debts The amount of debt tokens redeemed.\n  /// @param protocolFees The amount of protocol fees charges.\n  event Redeem(address indexed pool, uint256 colls, uint256 debts, uint256 protocolFees);\n\n  /// @notice Emitted when someone harvest pending rewards.\n  /// @param caller The address of caller.\n  /// @param amountRewards The amount of total harvested rewards.\n  /// @param amountFunding The amount of total harvested funding.\n  /// @param performanceFee The amount of harvested rewards distributed to protocol revenue.\n  /// @param harvestBounty The amount of harvested rewards distributed to caller as harvest bounty.\n  event Harvest(\n    address indexed caller,\n    address indexed pool,\n    uint256 amountRewards,\n    uint256 amountFunding,\n    uint256 performanceFee,\n    uint256 harvestBounty\n  );\n\n  /// @notice Emitted when debt is reduced by someone.\n  /// @param pool The address of pool reduced.\n  /// @param amount The amount of debt token reduced.\n  event ReduceDebt(address indexed pool, uint256 amount);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of fxUSD.\n  function fxUSD() external view returns (address);\n\n  /// @notice The address of counterparty PoolManager.\n  function counterparty() external view returns (address);\n\n  /// @notice The address of `PoolConfiguration` contract.\n  function configuration() external view returns (address);\n\n  /// @notice The address of reward splitter.\n  function rewardSplitter(address pool) external view returns (address);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Open a new position or operate on an old position.\n  /// @param pool The address of pool to operate.\n  /// @param positionId The id of the position. If `positionId=0`, it means we need to open a new position.\n  /// @param newColl The amount of collateral token to supply (positive value) or withdraw (negative value).\n  /// @param newDebt The amount of debt token to borrow (positive value) or repay (negative value).\n  /// @return actualPositionId The id of this position.\n  function operate(\n    address pool,\n    uint256 positionId,\n    int256 newColl,\n    int256 newDebt\n  ) external returns (uint256 actualPositionId);\n\n  /// @notice Redeem debt tokens to get collateral tokens.\n  /// @param pool The address of pool to redeem.\n  /// @param debts The amount of debt tokens to redeem.\n  /// @param minColls The minimum amount of collateral tokens should redeem.\n  /// @return actualDebts The actual amount of debt tokens used.\n  /// @return colls The amount of collateral tokens redeemed.\n  function redeem(address pool, uint256 debts, uint256 minColls) external returns (uint256 actualDebts, uint256 colls);\n\n  /// @notice Harvest pending rewards of the given pool.\n  /// @param pool The address of pool to harvest.\n  /// @return amountRewards The amount of rewards harvested.\n  /// @return amountFunding The amount of funding harvested.\n  function harvest(address pool) external returns (uint256 amountRewards, uint256 amountFunding);\n\n  /// @notice Reduce the debt of a pool. This function is only callable by whitelisted addresses.\n  /// @param pool The address of the pool to reduce debt for.\n  /// @param amount The amount of debt token to reduce.\n  function reduceDebt(address pool, uint256 amount) external;\n}\n"},"contracts/libraries/BitMath.sol":{"content":"// SPDX-License-Identifier: GPL-2.0-or-later\n\npragma solidity ^0.8.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\n///\n/// copy from: https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/BitMath.sol\nlibrary BitMath {\n    /// @notice Returns the index of the most significant bit of the number,\n    ///     where the least significant bit is at index 0 and the most significant bit is at index 255\n    /// @dev The function satisfies the property:\n    ///     x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n    /// @param x the value for which to compute the most significant bit, must be greater than 0\n    /// @return r the index of the most significant bit\n    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n        require(x > 0);\n\n        if (x >= 0x100000000000000000000000000000000) {\n            x >>= 128;\n            r += 128;\n        }\n        if (x >= 0x10000000000000000) {\n            x >>= 64;\n            r += 64;\n        }\n        if (x >= 0x100000000) {\n            x >>= 32;\n            r += 32;\n        }\n        if (x >= 0x10000) {\n            x >>= 16;\n            r += 16;\n        }\n        if (x >= 0x100) {\n            x >>= 8;\n            r += 8;\n        }\n        if (x >= 0x10) {\n            x >>= 4;\n            r += 4;\n        }\n        if (x >= 0x4) {\n            x >>= 2;\n            r += 2;\n        }\n        if (x >= 0x2) r += 1;\n    }\n\n    /// @notice Returns the index of the least significant bit of the number,\n    ///     where the least significant bit is at index 0 and the most significant bit is at index 255\n    /// @dev The function satisfies the property:\n    ///     (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n    /// @param x the value for which to compute the least significant bit, must be greater than 0\n    /// @return r the index of the least significant bit\n    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n        require(x > 0);\n\n        r = 255;\n        if (x & type(uint128).max > 0) {\n            r -= 128;\n        } else {\n            x >>= 128;\n        }\n        if (x & type(uint64).max > 0) {\n            r -= 64;\n        } else {\n            x >>= 64;\n        }\n        if (x & type(uint32).max > 0) {\n            r -= 32;\n        } else {\n            x >>= 32;\n        }\n        if (x & type(uint16).max > 0) {\n            r -= 16;\n        } else {\n            x >>= 16;\n        }\n        if (x & type(uint8).max > 0) {\n            r -= 8;\n        } else {\n            x >>= 8;\n        }\n        if (x & 0xf > 0) {\n            r -= 4;\n        } else {\n            x >>= 4;\n        }\n        if (x & 0x3 > 0) {\n            r -= 2;\n        } else {\n            x >>= 2;\n        }\n        if (x & 0x1 > 0) r -= 1;\n    }\n}\n"},"contracts/libraries/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nlibrary Math {\n  enum Rounding {\n    Up,\n    Down\n  }\n\n  /// @dev Internal return the value of min(a, b).\n  function min(uint256 a, uint256 b) internal pure returns (uint256) {\n    return a < b ? a : b;\n  }\n\n  /// @dev Internal return the value of max(a, b).\n  function max(uint256 a, uint256 b) internal pure returns (uint256) {\n    return a > b ? a : b;\n  }\n\n  /// @dev Internal return the value of a * b / c, with rounding.\n  function mulDiv(uint256 a, uint256 b, uint256 c, Rounding rounding) internal pure returns (uint256) {\n    return rounding == Rounding.Down ? mulDivDown(a, b, c) : mulDivUp(a, b, c);\n  }\n\n  /// @dev Internal return the value of ceil(a * b / c).\n  function mulDivUp(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {\n    return (a * b + c - 1) / c;\n  }\n\n  /// @dev Internal return the value of floor(a * b / c).\n  function mulDivDown(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {\n    return (a * b) / c;\n  }\n}\n"},"contracts/libraries/TickBitmap.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nimport { BitMath } from \"./BitMath.sol\";\n\nlibrary TickBitmap {\n  function position(int16 tick) private pure returns (int8 wordPos, uint8 bitPos) {\n    assembly {\n      wordPos := shr(8, tick)\n      bitPos := and(tick, 255)\n    }\n  }\n\n  function flipTick(mapping(int8 => uint256) storage self, int16 tick) internal {\n    (int8 wordPos, uint8 bitPos) = position(tick);\n    uint256 mask = 1 << bitPos;\n    self[wordPos] ^= mask;\n  }\n\n  function isBitSet(mapping(int8 => uint256) storage self, int16 tick) internal view returns (bool) {\n    (int8 wordPos, uint8 bitPos) = position(tick);\n    uint256 mask = 1 << bitPos;\n    return (self[wordPos] & mask) > 0;\n  }\n\n  /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is\n  /// to the left (less than or equal to).\n  function nextDebtPositionWithinOneWord(\n    mapping(int8 => uint256) storage self,\n    int16 tick\n  ) internal view returns (int16 next, bool hasDebt) {\n    unchecked {\n      // start from the word of the next tick, since the current tick state doesn't matter\n      (int8 wordPos, uint8 bitPos) = position(tick);\n      // all the 1s at or to the right of the current bitPos\n      uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n      uint256 masked = self[wordPos] & mask;\n\n      // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n      hasDebt = masked != 0;\n      // overflow/underflow is possible, but prevented externally by limiting tick\n      next = hasDebt\n        ? (tick - int16(uint16(bitPos - BitMath.mostSignificantBit(masked))))\n        : (tick - int16(uint16(bitPos)));\n    }\n  }\n}\n"},"contracts/libraries/TickMath.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nlibrary TickMath {\n  /// The minimum tick that can be passed in getRatioAtTick. 1.0015**-32767\n  int24 internal constant MIN_TICK = -32767;\n  /// The maximum tick that can be passed in getRatioAtTick. 1.0015**32767\n  int24 internal constant MAX_TICK = 32767;\n\n  uint256 internal constant NEGATIVE_MASK = 0x8000000000000000000000000000000000000000000000000000000000000000;\n\n  uint256 internal constant SCALAR00 = 0x100000000000000000000000000000000;\n  uint256 internal constant SCALAR01 = 0xff9dd7de423466c20352b1246ce4856f; // 2^128/1.0015**1 = 339772707859149738855091969477551883631\n  uint256 internal constant SCALAR02 = 0xff3bd55f4488ad277531fa1c725a66d0; // 2^128/1.0015**2 = 339263812140938331358054887146831636176\n  uint256 internal constant SCALAR03 = 0xfe78410fd6498b73cb96a6917f853259; // 2^128/1.0015**4 = 338248306163758188337119769319392490073\n  uint256 internal constant SCALAR04 = 0xfcf2d9987c9be178ad5bfeffaa123273; // 2^128/1.0015**8 = 336226404141693512316971918999264834163\n  uint256 internal constant SCALAR05 = 0xf9ef02c4529258b057769680fc6601b3; // 2^128/1.0015**16 = 332218786018727629051611634067491389875\n  uint256 internal constant SCALAR06 = 0xf402d288133a85a17784a411f7aba082; // 2^128/1.0015**32 = 324346285652234375371948336458280706178\n  uint256 internal constant SCALAR07 = 0xe895615b5beb6386553757b0352bda90; // 2^128/1.0015**64 = 309156521885964218294057947947195947664\n  uint256 internal constant SCALAR08 = 0xd34f17a00ffa00a8309940a15930391a; // 2^128/1.0015**128 = 280877777739312896540849703637713172762\n  uint256 internal constant SCALAR09 = 0xae6b7961714e20548d88ea5123f9a0ff; // 2^128/1.0015**256 = 231843708922198649176471782639349113087\n  uint256 internal constant SCALAR10 = 0x76d6461f27082d74e0feed3b388c0ca1; // 2^128/1.0015**512 = 157961477267171621126394973980180876449\n  uint256 internal constant SCALAR11 = 0x372a3bfe0745d8b6b19d985d9a8b85bb; // 2^128/1.0015**1024 = 73326833024599564193373530205717235131\n  uint256 internal constant SCALAR12 = 0x0be32cbee48979763cf7247dd7bb539d; // 2^128/1.0015**2048 = 15801066890623697521348224657638773661\n  uint256 internal constant SCALAR13 = 0x8d4f70c9ff4924dac37612d1e2921e; // 2^128/1.0015**4096 = 733725103481409245883800626999235102\n  uint256 internal constant SCALAR14 = 0x4e009ae5519380809a02ca7aec77; // 2^128/1.0015**8192 = 1582075887005588088019997442108535\n  uint256 internal constant SCALAR15 = 0x17c45e641b6e95dee056ff10; // 2^128/1.0015**16384 = 7355550435635883087458926352\n\n  /// The minimum value that can be returned from getRatioAtTick. Equivalent to getRatioAtTick(MIN_TICK). ~ Equivalent to `(1 << 96) * (1.0015**-32767)`\n  uint256 internal constant MIN_TICK_RATIO = 37075071;\n  /// The maximum value that can be returned from getRatioAtTick. Equivalent to getRatioAtTick(MAX_TICK).\n  /// ~ Equivalent to `(1 << 96) * (1.0015**32767)`, rounding etc. leading to minor difference\n  uint256 internal constant MAX_TICK_RATIO = 169307877264527972847801929085841449095838922544595;\n\n  uint256 internal constant ZERO_TICK_SCALED_RATIO = 0x1000000000000000000000000; // 1 << 96 // 79228162514264337593543950336\n  uint256 internal constant PRECISION = 1e26;\n\n  /// @notice ratioX96 = (1.0015^tick) * 2^96\n  /// @dev Throws if |tick| > max tick\n  /// @param tick The input tick for the above formula\n  /// @return ratioX96 ratio = (debt amount/collateral amount)\n  function getRatioAtTick(int tick) internal pure returns (uint256 ratioX96) {\n    assembly {\n      let tickAbs := tick\n      if and(tick, NEGATIVE_MASK) {\n        tickAbs := sub(0, tick)\n      }\n\n      if gt(tickAbs, MAX_TICK) {\n        revert(0, 0)\n      }\n      let value_ := SCALAR00\n      if and(tickAbs, 0x1) {\n        value_ := SCALAR01\n      }\n      if and(tickAbs, 0x2) {\n        value_ := shr(128, mul(value_, SCALAR02))\n      }\n      if and(tickAbs, 0x4) {\n        value_ := shr(128, mul(value_, SCALAR03))\n      }\n      if and(tickAbs, 0x8) {\n        value_ := shr(128, mul(value_, SCALAR04))\n      }\n      if and(tickAbs, 0x10) {\n        value_ := shr(128, mul(value_, SCALAR05))\n      }\n      if and(tickAbs, 0x20) {\n        value_ := shr(128, mul(value_, SCALAR06))\n      }\n      if and(tickAbs, 0x40) {\n        value_ := shr(128, mul(value_, SCALAR07))\n      }\n      if and(tickAbs, 0x80) {\n        value_ := shr(128, mul(value_, SCALAR08))\n      }\n      if and(tickAbs, 0x100) {\n        value_ := shr(128, mul(value_, SCALAR09))\n      }\n      if and(tickAbs, 0x200) {\n        value_ := shr(128, mul(value_, SCALAR10))\n      }\n      if and(tickAbs, 0x400) {\n        value_ := shr(128, mul(value_, SCALAR11))\n      }\n      if and(tickAbs, 0x800) {\n        value_ := shr(128, mul(value_, SCALAR12))\n      }\n      if and(tickAbs, 0x1000) {\n        value_ := shr(128, mul(value_, SCALAR13))\n      }\n      if and(tickAbs, 0x2000) {\n        value_ := shr(128, mul(value_, SCALAR14))\n      }\n      if and(tickAbs, 0x4000) {\n        value_ := shr(128, mul(value_, SCALAR15))\n      }\n\n      let precision_ := 0\n      if iszero(and(tick, NEGATIVE_MASK)) {\n        value_ := div(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, value_)\n        // we round up in the division so getTickAtRatio of the output price is always consistent\n        if mod(value_, 0x100000000) {\n          precision_ := 1\n        }\n      }\n      ratioX96 := add(shr(32, value_), precision_)\n    }\n  }\n\n  /// @notice ratioX96 = (1.0015^tick) * 2^96\n  /// @dev Throws if ratioX96 > max ratio || ratioX96 < min ratio\n  /// @param ratioX96 The input ratio; ratio = (debt amount/collateral amount)\n  /// @return tick The output tick for the above formula. Returns in round down form. if tick is 123.23 then 123, if tick is -123.23 then returns -124\n  /// @return perfectRatioX96 perfect ratio for the above tick\n  function getTickAtRatio(uint256 ratioX96) internal pure returns (int tick, uint perfectRatioX96) {\n    assembly {\n      if or(gt(ratioX96, MAX_TICK_RATIO), lt(ratioX96, MIN_TICK_RATIO)) {\n        revert(0, 0)\n      }\n\n      let tickIsNegative := lt(ratioX96, ZERO_TICK_SCALED_RATIO)\n      let value_\n\n      switch tickIsNegative\n      case 0 {\n        // if ratioX96 >= ZERO_TICK_SCALED_RATIO\n        value_ := div(mul(ratioX96, PRECISION), ZERO_TICK_SCALED_RATIO)\n      }\n      default {\n        // ratioX96 < ZERO_TICK_SCALED_RATIO\n        value_ := div(mul(ZERO_TICK_SCALED_RATIO, PRECISION), ratioX96)\n      }\n\n      // use `getRatioAtTick(tick)` to get `(1.0015^tick) * 2^96`\n      // and use python to get the value of `getRatioAtTick(tick) * 10^26 / 79228162514264337593543950336`\n\n      // for tick = 2^14\n      // ratioX96 = (1.0015^16384) * 2^96 = 3665252098134783297721995888541655517464\n      // 3665252098134783297721995888541655517464 * 10^26 / 79228162514264337593543950336 = \n      // 4626198540796508716348404308351034442.59912669744680855913628167\n      if iszero(lt(value_, 4626198540796508716348404308351034442)) {\n        tick := or(tick, 0x4000)\n        value_ := div(mul(value_, PRECISION), 4626198540796508716348404308351034442)\n      }\n      // for tick = 2^13\n      // ratioX96 = (1.0015^8192) * 2^96 = 17040868196391020479062776466509866\n      // 17040868196391020479062776466509866 * 10^26 / 79228162514264337593543950336 = \n      // 21508599537851153911767490449162.30388433471560772971058422\n      if iszero(lt(value_, 21508599537851153911767490449162)) {\n        tick := or(tick, 0x2000)\n        value_ := div(mul(value_, PRECISION), 21508599537851153911767490449162)\n      }\n      // for tick = 2^12\n      // ratioX96 = (1.0015^4096) * 2^96 = 36743933851015821532611831851151\n      // 36743933851015821532611831851151 * 10^26 / 79228162514264337593543950336 = \n      // 46377364670549310883002866648.97849117190913404467057871\n      if iszero(lt(value_, 46377364670549310883002866648)) {\n        tick := or(tick, 0x1000)\n        value_ := div(mul(value_, PRECISION), 46377364670549310883002866648)\n      }\n      // for tick = 2^11\n      // ratioX96 = (1.0015^2048) * 2^96 = 1706210527034005899209104452336\n      // 1706210527034005899209104452336 * 10^26 / 79228162514264337593543950336 =\n      // 2153540449365864845468344760.06441018972143364324249494\n      if iszero(lt(value_, 2153540449365864845468344760)) {\n        tick := or(tick, 0x800)\n        value_ := div(mul(value_, PRECISION), 2153540449365864845468344760)\n      }\n      // for tick = 2^10\n      // ratioX96 = (1.0015^1024) * 2^96 = 367668226692760093024536487237\n      // 367668226692760093024536487237 * 10^26 / 79228162514264337593543950336 =\n      // 464062544207767844008185024.95183649344791541594882857\n      if iszero(lt(value_, 464062544207767844008185024)) {\n        tick := or(tick, 0x400)\n        value_ := div(mul(value_, PRECISION), 464062544207767844008185024)\n      }\n      // for tick = 2^9\n      // ratioX96 = (1.0015^512) * 2^96 = 170674186729409605620119663669\n      // 170674186729409605620119663669 * 10^26 / 79228162514264337593543950336 =\n      // 215421109505955298802281577.03291187458466714140583746\n      if iszero(lt(value_, 215421109505955298802281577)) {\n        tick := or(tick, 0x200)\n        value_ := div(mul(value_, PRECISION), 215421109505955298802281577)\n      }\n      // for tick = 2^8\n      // ratioX96 = (1.0015^256) * 2^96 = 116285004205991934861656513302\n      // 116285004205991934861656513302 * 10^26 / 79228162514264337593543950336 =\n      // 146772309890508740607270614.66786113800638440233092948\n      if iszero(lt(value_, 146772309890508740607270614)) {\n        tick := or(tick, 0x100)\n        value_ := div(mul(value_, PRECISION), 146772309890508740607270614)\n      }\n      // for tick = 2^7\n      // ratioX96 = (1.0015^128) * 2^96 = 95984619659632141743747099591\n      // 95984619659632141743747099591 * 10^26 / 79228162514264337593543950336 =\n      // 121149622323187099817270416.15833126823570458129564582\n      if iszero(lt(value_, 121149622323187099817270416)) {\n        tick := or(tick, 0x80)\n        value_ := div(mul(value_, PRECISION), 121149622323187099817270416)\n      }\n      // for tick = 2^6\n      // ratioX96 = (1.0015^64) * 2^96 = 87204845308406958006717891125\n      // 87204845308406958006717891125 * 10^26 / 79228162514264337593543950336 =\n      // 110067989135437147685980801.56915296006152089117457608\n      if iszero(lt(value_, 110067989135437147685980801)) {\n        tick := or(tick, 0x40)\n        value_ := div(mul(value_, PRECISION), 110067989135437147685980801)\n      }\n      // for tick = 2^5\n      // ratioX96 = (1.0015^32) * 2^96 = 83120873769022354029916374476\n      // 83120873769022354029916374476 * 10^26 / 79228162514264337593543950336 =\n      // 104913292358707887270979599.83188521036790476918243160\n      if iszero(lt(value_, 104913292358707887270979599)) {\n        tick := or(tick, 0x20)\n        value_ := div(mul(value_, PRECISION), 104913292358707887270979599)\n      }\n      // for tick = 2^4\n      // ratioX96 = (1.0015^16) * 2^96 = 81151180492336368327184716177\n      // 81151180492336368327184716177 * 10^26 / 79228162514264337593543950336 =\n      // 102427189924701091191840927.76289018827089975214307641\n      if iszero(lt(value_, 102427189924701091191840927)) {\n        tick := or(tick, 0x10)\n        value_ := div(mul(value_, PRECISION), 102427189924701091191840927)\n      }\n      // for tick = 2^3\n      // ratioX96 = (1.0015^8) * 2^96 = 80183906840906820640659903621\n      // 80183906840906820640659903621 * 10^26 / 79228162514264337593543950336 =\n      // 101206318935480056907421312.89064558712400350960439215\n      if iszero(lt(value_, 101206318935480056907421312)) {\n        tick := or(tick, 0x8)\n        value_ := div(mul(value_, PRECISION), 101206318935480056907421312)\n      }\n      // for tick = 2^2\n      // ratioX96 = (1.0015^4) * 2^96 = 79704602139525152702959747604\n      // 79704602139525152702959747604 * 10^26 / 79228162514264337593543950336 =\n      // 100601351350506250000000000.00093883057718280672865438\n      if iszero(lt(value_, 100601351350506250000000000)) {\n        tick := or(tick, 0x4)\n        value_ := div(mul(value_, PRECISION), 100601351350506250000000000)\n      }\n      // for tick = 2^1\n      // ratioX96 = (1.0015^2) * 2^96 = 79466025265172787701084167661\n      // 79466025265172787701084167661 * 10^26 / 79228162514264337593543950336 =\n      // 100300225000000000000000000.00013094333720199783798501\n      if iszero(lt(value_, 100300225000000000000000000)) {\n        tick := or(tick, 0x2)\n        value_ := div(mul(value_, PRECISION), 100300225000000000000000000)\n      }\n      // for tick = 2^0\n      // ratioX96 = (1.0015^1) * 2^96 = 79347004758035734099934266262\n      // 79347004758035734099934266262 * 10^26 / 79228162514264337593543950336 =\n      // 100150000000000000000000000.00062604001438339496877474\n      if iszero(lt(value_, 100150000000000000000000000)) {\n        tick := or(tick, 0x1)\n        value_ := div(mul(value_, PRECISION), 100150000000000000000000000)\n      }\n\n      switch tickIsNegative\n      case 0 {\n        // if ratioX96 >= ZERO_TICK_SCALED_RATIO\n        perfectRatioX96 := div(mul(ratioX96, PRECISION), value_)\n      }\n      default {\n        // ratioX96 < ZERO_TICK_SCALED_RATIO\n        tick := not(tick)\n        perfectRatioX96 := div(mul(ratioX96, value_), 100150000000000000000000000)\n      }\n\n      // perfect ratio should always be <= ratioX96\n      // not sure if it can ever be bigger but better to have extra checks\n      if gt(perfectRatioX96, ratioX96) {\n        revert(0, 0)\n      }\n    }\n  }\n}\n"},"contracts/price-oracle/interfaces/IPriceOracle.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPriceOracle {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the value of maximum price deviation is updated.\n  /// @param oldValue The value of the previous maximum price deviation.\n  /// @param newValue The value of the current maximum price deviation.\n  event UpdateMaxPriceDeviation(uint256 oldValue, uint256 newValue);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the oracle price with 18 decimal places.\n  /// @return anchorPrice The anchor price for this asset, multiplied by 1e18. It should be hard to manipulate,\n  ///         like time-weighted average price or chainlink spot price.\n  /// @return minPrice The minimum oracle price among all available price sources (including twap), multiplied by 1e18.\n  /// @return maxPrice The maximum oracle price among all available price sources (including twap), multiplied by 1e18.\n  function getPrice() external view returns (uint256 anchorPrice, uint256 minPrice, uint256 maxPrice);\n\n  /// @notice Return the oracle price for exchange with 18 decimal places.\n  function getExchangePrice() external view returns (uint256);\n\n  /// @notice Return the oracle price for liquidation with 18 decimal places.\n  function getLiquidatePrice() external view returns (uint256);\n\n  /// @notice Return the oracle price for redemption with 18 decimal places.\n  function getRedeemPrice() external view returns (uint256);\n}\n"}},"matchId":"52385897","creationMatch":"exact_match","runtimeMatch":"exact_match","verifiedAt":"2026-09-25T19:09:13Z","match":"exact_match","chainId":"56","address":"0xa2559504975DEea4FC73BA255D28b20349c3c017"}