creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts-v4/security/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}\n"
      },
      "@openzeppelin/contracts-v4/token/ERC20/extensions/draft-IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "@openzeppelin/contracts-v4/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts-v4/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    function safeTransfer(\n        IERC20 token,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        uint256 newAllowance = token.allowance(address(this), spender) + value;\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            uint256 newAllowance = oldAllowance - value;\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n        }\n    }\n\n    function safePermit(\n        IERC20Permit token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        if (returndata.length > 0) {\n            // Return data is optional\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-v4/token/ERC721/IERC721.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../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 a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes calldata data\n    ) 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 {setApprovalForAll}.\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 safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\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(\n        address from,\n        address to,\n        uint256 tokenId\n    ) 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 caller.\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-v4/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(isContract(target), \"Address: delegate call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length > 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n                /// @solidity memory-safe-assembly\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-v4/utils/introspection/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\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"
      },
      "contracts/abstract/MasterAwareV2.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity ^0.8.18;\n\nimport \"../interfaces/INXMMaster.sol\";\nimport \"../interfaces/IMasterAwareV2.sol\";\nimport \"../interfaces/IMemberRoles.sol\";\n\nabstract contract MasterAwareV2 is IMasterAwareV2 {\n\n  INXMMaster public master;\n\n  mapping(uint => address payable) public internalContracts;\n\n  modifier onlyMember {\n    require(\n      IMemberRoles(internalContracts[uint(ID.MR)]).checkRole(\n        msg.sender,\n        uint(IMemberRoles.Role.Member)\n      ),\n      \"Caller is not a member\"\n    );\n    _;\n  }\n\n  modifier onlyAdvisoryBoard {\n    require(\n      IMemberRoles(internalContracts[uint(ID.MR)]).checkRole(\n        msg.sender,\n        uint(IMemberRoles.Role.AdvisoryBoard)\n      ),\n      \"Caller is not an advisory board member\"\n    );\n    _;\n  }\n\n  modifier onlyInternal {\n    require(master.isInternal(msg.sender), \"Caller is not an internal contract\");\n    _;\n  }\n\n  modifier onlyMaster {\n    if (address(master) != address(0)) {\n      require(address(master) == msg.sender, \"Not master\");\n    }\n    _;\n  }\n\n  modifier onlyGovernance {\n    require(\n      master.checkIsAuthToGoverned(msg.sender),\n      \"Caller is not authorized to govern\"\n    );\n    _;\n  }\n\n  modifier onlyEmergencyAdmin {\n    require(\n      msg.sender == master.emergencyAdmin(),\n      \"Caller is not emergency admin\"\n    );\n    _;\n  }\n\n  modifier whenPaused {\n    require(master.isPause(), \"System is not paused\");\n    _;\n  }\n\n  modifier whenNotPaused {\n    require(!master.isPause(), \"System is paused\");\n    _;\n  }\n\n  function getInternalContractAddress(ID id) internal view returns (address payable) {\n    return internalContracts[uint(id)];\n  }\n\n  function changeMasterAddress(address masterAddress) public onlyMaster {\n    master = INXMMaster(masterAddress);\n  }\n\n}\n"
      },
      "contracts/abstract/Multicall.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity ^0.8.18;\n\nabstract contract Multicall {\n\n  error RevertedWithoutReason(uint index);\n\n  // WARNING: Do not set this function as payable\n  function multicall(bytes[] calldata data) external returns (bytes[] memory results) {\n\n    uint callCount = data.length;\n    results = new bytes[](callCount);\n\n    for (uint i = 0; i < callCount; i++) {\n      (bool ok, bytes memory result) = address(this).delegatecall(data[i]);\n\n      if (!ok) {\n\n        uint length = result.length;\n\n        // 0 length returned from empty revert() / require(false)\n        if (length == 0) {\n          revert RevertedWithoutReason(i);\n        }\n\n        assembly {\n          revert(add(result, 0x20), length)\n        }\n      }\n\n      results[i] = result;\n    }\n  }\n}\n"
      },
      "contracts/interfaces/ICover.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\nimport \"./ICoverNFT.sol\";\nimport \"./IStakingNFT.sol\";\nimport \"./IStakingPool.sol\";\nimport \"./IStakingPoolFactory.sol\";\n\n/* ========== DATA STRUCTURES ========== */\n\nenum ClaimMethod {\n  IndividualClaims,\n  YieldTokenIncidents\n}\n\n// Basically CoverStatus from QuotationData.sol but with the extra Migrated status to avoid\n// polluting Cover.sol state layout with new status variables.\nenum LegacyCoverStatus {\n  Active,\n  ClaimAccepted,\n  ClaimDenied,\n  CoverExpired,\n  ClaimSubmitted,\n  Requested,\n  Migrated\n}\n\n/* io structs */\n\nstruct PoolAllocationRequest {\n  uint40 poolId;\n  bool skip;\n  uint coverAmountInAsset;\n}\n\nstruct RequestAllocationVariables {\n  uint previousPoolAllocationsLength;\n  uint previousPremiumInNXM;\n  uint refund;\n  uint coverAmountInNXM;\n}\n\nstruct BuyCoverParams {\n  uint coverId;\n  address owner;\n  uint24 productId;\n  uint8 coverAsset;\n  uint96 amount;\n  uint32 period;\n  uint maxPremiumInAsset;\n  uint8 paymentAsset;\n  uint16 commissionRatio;\n  address commissionDestination;\n  string ipfsData;\n}\n\nstruct ProductParam {\n  string productName;\n  uint productId;\n  string ipfsMetadata;\n  Product product;\n  uint[] allowedPools;\n}\n\nstruct ProductTypeParam {\n  string productTypeName;\n  uint productTypeId;\n  string ipfsMetadata;\n  ProductType productType;\n}\n\nstruct ProductInitializationParams {\n  uint productId;\n  uint8 weight;\n  uint96 initialPrice;\n  uint96 targetPrice;\n}\n\n/* storage structs */\n\nstruct PoolAllocation {\n  uint40 poolId;\n  uint96 coverAmountInNXM;\n  uint96 premiumInNXM;\n  uint24 allocationId;\n}\n\nstruct CoverData {\n  uint24 productId;\n  uint8 coverAsset;\n  uint96 amountPaidOut;\n}\n\nstruct CoverSegment {\n  uint96 amount;\n  uint32 start;\n  uint32 period; // seconds\n  uint32 gracePeriod; // seconds\n  uint24 globalRewardsRatio;\n  uint24 globalCapacityRatio;\n}\n\nstruct Product {\n  uint16 productType;\n  address yieldTokenAddress;\n  // cover assets bitmap. each bit represents whether the asset with\n  // the index of that bit is enabled as a cover asset for this product\n  uint32 coverAssets;\n  uint16 initialPriceRatio;\n  uint16 capacityReductionRatio;\n  bool isDeprecated;\n  bool useFixedPrice;\n}\n\nstruct ProductType {\n  uint8 claimMethod;\n  uint32 gracePeriod;\n}\n\nstruct ActiveCover {\n  // Global active cover amount per asset.\n  uint192 totalActiveCoverInAsset;\n  // The last time activeCoverExpirationBuckets was updated\n  uint64 lastBucketUpdateId;\n}\n\ninterface ICover {\n\n  /* ========== VIEWS ========== */\n\n  function coverData(uint coverId) external view returns (CoverData memory);\n\n  function coverDataCount() external view returns (uint);\n\n  function coverSegmentsCount(uint coverId) external view returns (uint);\n\n  function coverSegments(uint coverId) external view returns (CoverSegment[] memory);\n\n  function coverSegmentWithRemainingAmount(\n    uint coverId,\n    uint segmentId\n  ) external view returns (CoverSegment memory);\n\n  function products(uint id) external view returns (Product memory);\n\n  function productTypes(uint id) external view returns (ProductType memory);\n\n  function stakingPool(uint index) external view returns (IStakingPool);\n\n  function productNames(uint productId) external view returns (string memory);\n\n  function productsCount() external view returns (uint);\n\n  function productTypesCount() external view returns (uint);\n\n  function totalActiveCoverInAsset(uint coverAsset) external view returns (uint);\n\n  function globalCapacityRatio() external view returns (uint);\n\n  function globalRewardsRatio() external view returns (uint);\n\n  function getPriceAndCapacityRatios(uint[] calldata productIds) external view returns (\n    uint _globalCapacityRatio,\n    uint _globalMinPriceRatio,\n    uint[] memory _initialPriceRatios,\n    uint[] memory _capacityReductionRatios\n  );\n\n  /* === MUTATIVE FUNCTIONS ==== */\n\n  function addLegacyCover(\n    uint productId,\n    uint coverAsset,\n    uint amount,\n    uint start,\n    uint period,\n    address newOwner\n  ) external returns (uint coverId);\n\n  function buyCover(\n    BuyCoverParams calldata params,\n    PoolAllocationRequest[] calldata coverChunkRequests\n  ) external payable returns (uint coverId);\n\n  function setProductTypes(ProductTypeParam[] calldata productTypes) external;\n\n  function setProducts(ProductParam[] calldata params) external;\n\n  function burnStake(\n    uint coverId,\n    uint segmentId,\n    uint amount\n  ) external returns (address coverOwner);\n\n  function coverNFT() external returns (ICoverNFT);\n\n  function stakingNFT() external returns (IStakingNFT);\n\n  function stakingPoolFactory() external returns (IStakingPoolFactory);\n\n  function createStakingPool(\n    bool isPrivatePool,\n    uint initialPoolFee,\n    uint maxPoolFee,\n    ProductInitializationParams[] calldata productInitParams,\n    string calldata ipfsDescriptionHash\n  ) external returns (uint poolId, address stakingPoolAddress);\n\n  function isPoolAllowed(uint productId, uint poolId) external returns (bool);\n  function requirePoolIsAllowed(uint[] calldata productIds, uint poolId) external view;\n\n  /* ========== EVENTS ========== */\n\n  event ProductSet(uint id, string ipfsMetadata);\n  event ProductTypeSet(uint id, string ipfsMetadata);\n  event CoverEdited(uint indexed coverId, uint indexed productId, uint indexed segmentId, address buyer, string ipfsMetadata);\n\n  // Auth\n  error OnlyMemberRolesCanOperateTransfer();\n  error OnlyOwnerOrApproved();\n\n  // Cover details\n  error CoverPeriodTooShort();\n  error CoverPeriodTooLong();\n  error CoverOutsideOfTheGracePeriod();\n  error CoverAmountIsZero();\n\n  // Products\n  error ProductDoesntExist();\n  error ProductTypeNotFound();\n  error ProductDoesntExistOrIsDeprecated();\n  error InvalidProductType();\n  error UnexpectedProductId();\n  error PoolNotAllowedForThisProduct(uint productId);\n\n  // Cover and payment assets\n  error CoverAssetNotSupported();\n  error InvalidPaymentAsset();\n  error UnexpectedCoverAsset();\n  error UnsupportedCoverAssets();\n  error UnexpectedEthSent();\n  error EditNotSupported();\n\n  // Price & Commission\n  error PriceExceedsMaxPremiumInAsset();\n  error TargetPriceBelowGlobalMinPriceRatio();\n  error InitialPriceRatioBelowGlobalMinPriceRatio();\n  error InitialPriceRatioAbove100Percent();\n  error CommissionRateTooHigh();\n\n  // ETH transfers\n  error InsufficientEthSent();\n  error SendingEthToPoolFailed();\n  error SendingEthToCommissionDestinationFailed();\n  error ReturningEthRemainderToSenderFailed();\n\n  // Misc\n  error AlreadyInitialized();\n  error ExpiredCoversCannotBeEdited();\n  error CoverNotYetExpired(uint coverId);\n  error CoverAlreadyExpired(uint coverId);\n  error InsufficientCoverAmountAllocated();\n  error UnexpectedPoolId();\n  error CapacityReductionRatioAbove100Percent();\n}\n"
      },
      "contracts/interfaces/ICoverNFT.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\nimport \"@openzeppelin/contracts-v4/token/ERC721/IERC721.sol\";\n\ninterface ICoverNFT is IERC721 {\n\n  function isApprovedOrOwner(address spender, uint tokenId) external returns (bool);\n\n  function mint(address to) external returns (uint tokenId);\n\n  function changeOperator(address newOperator) external;\n\n  function totalSupply() external view returns (uint);\n\n  function name() external view returns (string memory);\n\n  error NotOperator();\n  error NotMinted();\n  error WrongFrom();\n  error InvalidRecipient();\n  error InvalidNewOperatorAddress();\n  error InvalidNewNFTDescriptorAddress();\n  error NotAuthorized();\n  error UnsafeRecipient();\n  error AlreadyMinted();\n\n}\n"
      },
      "contracts/interfaces/IMasterAwareV2.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\ninterface IMasterAwareV2 {\n\n  // TODO: if you update this enum, update lib/constants.js as well\n  enum ID {\n    TC, // TokenController.sol\n    P1, // Pool.sol\n    MR, // MemberRoles.sol\n    MC, // MCR.sol\n    CO, // Cover.sol\n    SP, // StakingProducts.sol\n    PS, // LegacyPooledStaking.sol\n    GV, // Governance.sol\n    GW, // LegacyGateway.sol\n    CL, // CoverMigrator.sol\n    AS, // Assessment.sol\n    CI, // IndividualClaims.sol - Claims for Individuals\n    CG, // YieldTokenIncidents.sol - Claims for Groups\n    RA, // Ramm.sol\n    ST  // SafeTracker.sol\n  }\n\n  function changeMasterAddress(address masterAddress) external;\n\n  function changeDependentContractAddress() external;\n\n  function internalContracts(uint) external view returns (address payable);\n}\n"
      },
      "contracts/interfaces/IMemberRoles.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\ninterface IMemberRoles {\n\n  enum Role {Unassigned, AdvisoryBoard, Member, Owner}\n\n  function join(address _userAddress, uint nonce, bytes calldata signature) external payable;\n\n  function switchMembership(address _newAddress) external;\n\n  function switchMembershipAndAssets(\n    address newAddress,\n    uint[] calldata coverIds,\n    uint[] calldata stakingTokenIds\n  ) external;\n\n  function switchMembershipOf(address member, address _newAddress) external;\n\n  function totalRoles() external view returns (uint256);\n\n  function changeAuthorized(uint _roleId, address _newAuthorized) external;\n\n  function setKycAuthAddress(address _add) external;\n\n  function members(uint _memberRoleId) external view returns (uint, address[] memory memberArray);\n\n  function numberOfMembers(uint _memberRoleId) external view returns (uint);\n\n  function authorized(uint _memberRoleId) external view returns (address);\n\n  function roles(address _memberAddress) external view returns (uint[] memory);\n\n  function checkRole(address _memberAddress, uint _roleId) external view returns (bool);\n\n  function getMemberLengthForAllRoles() external view returns (uint[] memory totalMembers);\n\n  function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool);\n\n  function membersLength(uint _memberRoleId) external view returns (uint);\n\n  event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);\n\n  event MemberJoined(address indexed newMember, uint indexed nonce);\n\n  event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);\n  \n  event MembershipWithdrawn(address indexed member, uint timestamp);\n}\n"
      },
      "contracts/interfaces/INXMMaster.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\ninterface INXMMaster {\n\n  function tokenAddress() external view returns (address);\n\n  function owner() external view returns (address);\n\n  function emergencyAdmin() external view returns (address);\n\n  function masterInitialized() external view returns (bool);\n\n  function isInternal(address _add) external view returns (bool);\n\n  function isPause() external view returns (bool check);\n\n  function isMember(address _add) external view returns (bool);\n\n  function checkIsAuthToGoverned(address _add) external view returns (bool);\n\n  function getLatestAddress(bytes2 _contractName) external view returns (address payable contractAddress);\n\n  function contractAddresses(bytes2 code) external view returns (address payable);\n\n  function upgradeMultipleContracts(\n    bytes2[] calldata _contractCodes,\n    address payable[] calldata newAddresses\n  ) external;\n\n  function removeContracts(bytes2[] calldata contractCodesToRemove) external;\n\n  function addNewInternalContracts(\n    bytes2[] calldata _contractCodes,\n    address payable[] calldata newAddresses,\n    uint[] calldata _types\n  ) external;\n\n  function updateOwnerParameters(bytes8 code, address payable val) external;\n}\n"
      },
      "contracts/interfaces/INXMToken.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\ninterface INXMToken {\n\n  function burn(uint256 amount) external returns (bool);\n\n  function burnFrom(address from, uint256 value) external returns (bool);\n\n  function operatorTransfer(address from, uint256 value) external returns (bool);\n\n  function mint(address account, uint256 amount) external;\n\n  function isLockedForMV(address member) external view returns (uint);\n\n  function whiteListed(address member) external view returns (bool);\n\n  function addToWhiteList(address _member) external returns (bool);\n\n  function removeFromWhiteList(address _member) external returns (bool);\n\n  function changeOperator(address _newOperator) external returns (bool);\n\n  function lockForMemberVote(address _of, uint _days) external;\n\n  /**\n * @dev Returns the amount of tokens in existence.\n */\n  function totalSupply() external view returns (uint256);\n\n  /**\n   * @dev Returns the amount of tokens owned by `account`.\n   */\n  function balanceOf(address account) external view returns (uint256);\n\n  /**\n   * @dev Moves `amount` tokens from the caller's account to `recipient`.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * Emits a {Transfer} event.\n   */\n  function transfer(address recipient, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Returns the remaining number of tokens that `spender` will be\n   * allowed to spend on behalf of `owner` through {transferFrom}. This is\n   * zero by default.\n   *\n   * This value changes when {approve} or {transferFrom} are called.\n   */\n  function allowance(address owner, address spender) external view returns (uint256);\n\n  /**\n   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * IMPORTANT: Beware that changing an allowance with this method brings the risk\n   * that someone may use both the old and the new allowance by unfortunate\n   * transaction ordering. One possible solution to mitigate this race\n   * condition is to first reduce the spender's allowance to 0 and set the\n   * desired value afterwards:\n   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n   *\n   * Emits an {Approval} event.\n   */\n  function approve(address spender, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Moves `amount` tokens from `sender` to `recipient` using the\n   * allowance mechanism. `amount` is then deducted from the caller's\n   * allowance.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * Emits a {Transfer} event.\n   */\n  function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Emitted when `value` tokens are moved from one account (`from`) to\n   * another (`to`).\n   *\n   * Note that `value` may be zero.\n   */\n  event Transfer(address indexed from, address indexed to, uint256 value);\n\n  /**\n   * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n   * a call to {approve}. `value` is the new allowance.\n   */\n  event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
      },
      "contracts/interfaces/IPool.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\nimport \"./IPriceFeedOracle.sol\";\n\nstruct SwapDetails {\n  uint104 minAmount;\n  uint104 maxAmount;\n  uint32 lastSwapTime;\n  // 2 decimals of precision. 0.01% -> 0.0001 -> 1e14\n  uint16 maxSlippageRatio;\n}\n\nstruct Asset {\n  address assetAddress;\n  bool isCoverAsset;\n  bool isAbandoned;\n}\n\ninterface IPool {\n\n  function swapOperator() external view returns (address);\n\n  function getAsset(uint assetId) external view returns (Asset memory);\n\n  function getAssets() external view returns (Asset[] memory);\n\n  function transferAssetToSwapOperator(address asset, uint amount) external;\n\n  function setSwapDetailsLastSwapTime(address asset, uint32 lastSwapTime) external;\n\n  function getAssetSwapDetails(address assetAddress) external view returns (SwapDetails memory);\n\n  function sendPayout(uint assetIndex, address payable payoutAddress, uint amount, uint ethDepositAmount) external;\n\n  function sendEth(address payoutAddress, uint amount) external;\n\n  function upgradeCapitalPool(address payable newPoolAddress) external;\n\n  function priceFeedOracle() external view returns (IPriceFeedOracle);\n\n  function getPoolValueInEth() external view returns (uint);\n\n  function calculateMCRRatio(uint totalAssetValue, uint mcrEth) external pure returns (uint);\n\n  function getInternalTokenPriceInAsset(uint assetId) external view returns (uint tokenPrice);\n\n  function getInternalTokenPriceInAssetAndUpdateTwap(uint assetId) external returns (uint tokenPrice);\n\n  function getTokenPrice() external view returns (uint tokenPrice);\n\n  function getMCRRatio() external view returns (uint);\n\n  function setSwapValue(uint value) external;\n}\n"
      },
      "contracts/interfaces/IPriceFeedOracle.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\ninterface Aggregator {\n  function latestAnswer() external view returns (int);\n}\n\nstruct OracleAsset {\n  Aggregator aggregator;\n  uint8 decimals;\n}\n\ninterface IPriceFeedOracle {\n\n  function ETH() external view returns (address);\n  function assets(address) external view returns (Aggregator, uint8);\n\n  function getAssetToEthRate(address asset) external view returns (uint);\n  function getAssetForEth(address asset, uint ethIn) external view returns (uint);\n  function getEthForAsset(address asset, uint amount) external view returns (uint);\n\n}\n"
      },
      "contracts/interfaces/IStakingNFT.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\nimport \"@openzeppelin/contracts-v4/token/ERC721/IERC721.sol\";\n\ninterface IStakingNFT is IERC721 {\n\n  function isApprovedOrOwner(address spender, uint tokenId) external returns (bool);\n\n  function mint(uint poolId, address to) external returns (uint tokenId);\n\n  function changeOperator(address newOperator) external;\n\n  function totalSupply() external returns (uint);\n\n  function tokenInfo(uint tokenId) external view returns (uint poolId, address owner);\n\n  function stakingPoolOf(uint tokenId) external view returns (uint poolId);\n\n  function stakingPoolFactory() external view returns (address);\n\n  function name() external view returns (string memory);\n\n  error NotOperator();\n  error NotMinted();\n  error WrongFrom();\n  error InvalidRecipient();\n  error InvalidNewOperatorAddress();\n  error InvalidNewNFTDescriptorAddress();\n  error NotAuthorized();\n  error UnsafeRecipient();\n  error AlreadyMinted();\n  error NotStakingPool();\n\n}\n"
      },
      "contracts/interfaces/IStakingPool.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\n/* structs for io */\n\nstruct AllocationRequest {\n  uint productId;\n  uint coverId;\n  uint allocationId;\n  uint period;\n  uint gracePeriod;\n  bool useFixedPrice;\n  uint previousStart;\n  uint previousExpiration;\n  uint previousRewardsRatio;\n  uint globalCapacityRatio;\n  uint capacityReductionRatio;\n  uint rewardRatio;\n  uint globalMinPrice;\n}\n\nstruct StakedProductParam {\n  uint productId;\n  bool recalculateEffectiveWeight;\n  bool setTargetWeight;\n  uint8 targetWeight;\n  bool setTargetPrice;\n  uint96 targetPrice;\n}\n\n  struct BurnStakeParams {\n    uint allocationId;\n    uint productId;\n    uint start;\n    uint period;\n    uint deallocationAmount;\n  }\n\ninterface IStakingPool {\n\n  /* structs for storage */\n\n  // stakers are grouped in tranches based on the timelock expiration\n  // tranche index is calculated based on the expiration date\n  // the initial proposal is to have 4 tranches per year (1 tranche per quarter)\n  struct Tranche {\n    uint128 stakeShares;\n    uint128 rewardsShares;\n  }\n\n  struct ExpiredTranche {\n    uint96 accNxmPerRewardShareAtExpiry;\n    uint96 stakeAmountAtExpiry; // nxm total supply is 6.7e24 and uint96.max is 7.9e28\n    uint128 stakeSharesSupplyAtExpiry;\n  }\n\n  struct Deposit {\n    uint96 lastAccNxmPerRewardShare;\n    uint96 pendingRewards;\n    uint128 stakeShares;\n    uint128 rewardsShares;\n  }\n\n  function initialize(\n    bool isPrivatePool,\n    uint initialPoolFee,\n    uint maxPoolFee,\n    uint _poolId,\n    string memory ipfsDescriptionHash\n  ) external;\n\n  function processExpirations(bool updateUntilCurrentTimestamp) external;\n\n  function requestAllocation(\n    uint amount,\n    uint previousPremium,\n    AllocationRequest calldata request\n  ) external returns (uint premium, uint allocationId);\n\n  function burnStake(uint amount, BurnStakeParams calldata params) external;\n\n  function depositTo(\n    uint amount,\n    uint trancheId,\n    uint requestTokenId,\n    address destination\n  ) external returns (uint tokenId);\n\n  function withdraw(\n    uint tokenId,\n    bool withdrawStake,\n    bool withdrawRewards,\n    uint[] memory trancheIds\n  ) external returns (uint withdrawnStake, uint withdrawnRewards);\n\n  function isPrivatePool() external view returns (bool);\n\n  function isHalted() external view returns (bool);\n\n  function manager() external view returns (address);\n\n  function getPoolId() external view returns (uint);\n\n  function getPoolFee() external view returns (uint);\n\n  function getMaxPoolFee() external view returns (uint);\n\n  function getActiveStake() external view returns (uint);\n\n  function getStakeSharesSupply() external view returns (uint);\n\n  function getRewardsSharesSupply() external view returns (uint);\n\n  function getRewardPerSecond() external view returns (uint);\n\n  function getAccNxmPerRewardsShare() external view returns (uint);\n\n  function getLastAccNxmUpdate() external view returns (uint);\n\n  function getFirstActiveTrancheId() external view returns (uint);\n\n  function getFirstActiveBucketId() external view returns (uint);\n\n  function getNextAllocationId() external view returns (uint);\n\n  function getDeposit(uint tokenId, uint trancheId) external view returns (\n    uint lastAccNxmPerRewardShare,\n    uint pendingRewards,\n    uint stakeShares,\n    uint rewardsShares\n  );\n\n  function getTranche(uint trancheId) external view returns (\n    uint stakeShares,\n    uint rewardsShares\n  );\n\n  function getExpiredTranche(uint trancheId) external view returns (\n    uint accNxmPerRewardShareAtExpiry,\n    uint stakeAmountAtExpiry,\n    uint stakeShareSupplyAtExpiry\n  );\n\n  function setPoolFee(uint newFee) external;\n\n  function setPoolPrivacy(bool isPrivatePool) external;\n\n  function getActiveAllocations(\n    uint productId\n  ) external view returns (uint[] memory trancheAllocations);\n\n  function getTrancheCapacities(\n    uint productId,\n    uint firstTrancheId,\n    uint trancheCount,\n    uint capacityRatio,\n    uint reductionRatio\n  ) external view returns (uint[] memory trancheCapacities);\n\n  /* ========== EVENTS ========== */\n\n  event StakeDeposited(address indexed user, uint256 amount, uint256 trancheId, uint256 tokenId);\n\n  event DepositExtended(address indexed user, uint256 tokenId, uint256 initialTrancheId, uint256 newTrancheId, uint256 topUpAmount);\n\n  event PoolPrivacyChanged(address indexed manager, bool isPrivate);\n\n  event PoolFeeChanged(address indexed manager, uint newFee);\n\n  event PoolDescriptionSet(string ipfsDescriptionHash);\n\n  event Withdraw(address indexed user, uint indexed tokenId, uint tranche, uint amountStakeWithdrawn, uint amountRewardsWithdrawn);\n\n  event StakeBurned(uint amount);\n\n  event Deallocated(uint productId);\n\n  event BucketExpired(uint bucketId);\n\n  event TrancheExpired(uint trancheId);\n\n  // Auth\n  error OnlyCoverContract();\n  error OnlyManager();\n  error PrivatePool();\n  error SystemPaused();\n  error PoolHalted();\n\n  // Fees\n  error PoolFeeExceedsMax();\n  error MaxPoolFeeAbove100();\n\n  // Voting\n  error NxmIsLockedForGovernanceVote();\n  error ManagerNxmIsLockedForGovernanceVote();\n\n  // Deposit\n  error InsufficientDepositAmount();\n  error RewardRatioTooHigh();\n\n  // Staking NFTs\n  error InvalidTokenId();\n  error NotTokenOwnerOrApproved();\n  error InvalidStakingPoolForToken();\n\n  // Tranche & capacity\n  error NewTrancheEndsBeforeInitialTranche();\n  error RequestedTrancheIsNotYetActive();\n  error RequestedTrancheIsExpired();\n  error InsufficientCapacity();\n\n  // Allocation\n  error AlreadyDeallocated(uint allocationId);\n}\n"
      },
      "contracts/interfaces/IStakingPoolBeacon.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.5.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IStakingPoolBeacon {\n  /**\n   * @dev Must return an address that can be used as a delegate call target.\n   *\n   * {BeaconProxy} will check that this address is a contract.\n   */\n  function stakingPoolImplementation() external view returns (address);\n}\n"
      },
      "contracts/interfaces/IStakingPoolFactory.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\ninterface IStakingPoolFactory {\n\n  function stakingPoolCount() external view returns (uint);\n\n  function beacon() external view returns (address);\n\n  function create(address beacon) external returns (uint poolId, address stakingPoolAddress);\n\n  event StakingPoolCreated(uint indexed poolId, address indexed stakingPoolAddress);\n}\n"
      },
      "contracts/interfaces/IStakingProducts.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\nimport \"./ICover.sol\";\nimport \"./IStakingPool.sol\";\n\ninterface IStakingProducts {\n\n  // TODO: resize values?\n  struct Weights {\n    uint32 totalEffectiveWeight;\n    uint32 totalTargetWeight;\n  }\n\n  struct StakedProduct {\n    uint16 lastEffectiveWeight;\n    uint8 targetWeight;\n    uint96 targetPrice;\n    uint96 bumpedPrice;\n    uint32 bumpedPriceUpdateTime;\n  }\n\n  /* ============= PRODUCT FUNCTIONS ============= */\n\n  function setProducts(uint poolId, StakedProductParam[] memory params) external;\n\n  function setInitialProducts(uint poolId, ProductInitializationParams[] memory params) external;\n\n  function getProductTargetWeight(uint poolId, uint productId) external view returns (uint);\n\n  function getTotalTargetWeight(uint poolId) external view returns (uint);\n\n  function getTotalEffectiveWeight(uint poolId) external view returns (uint);\n\n  function getProduct(uint poolId, uint productId) external view returns (\n    uint lastEffectiveWeight,\n    uint targetWeight,\n    uint targetPrice,\n    uint bumpedPrice,\n    uint bumpedPriceUpdateTime\n  );\n\n  /* ============= PRICING FUNCTIONS ============= */\n\n  function getPremium(\n    uint poolId,\n    uint productId,\n    uint period,\n    uint coverAmount,\n    uint initialCapacityUsed,\n    uint totalCapacity,\n    uint globalMinPrice,\n    bool useFixedPrice,\n    uint nxmPerAllocationUnit,\n    uint allocationUnitsPerNxm\n  ) external returns (uint premium);\n\n  function calculateFixedPricePremium(\n    uint coverAmount,\n    uint period,\n    uint fixedPrice,\n    uint nxmPerAllocationUnit,\n    uint targetPriceDenominator\n  ) external pure returns (uint);\n\n\n  function calculatePremium(\n    StakedProduct memory product,\n    uint period,\n    uint coverAmount,\n    uint initialCapacityUsed,\n    uint totalCapacity,\n    uint targetPrice,\n    uint currentBlockTimestamp,\n    uint nxmPerAllocationUnit,\n    uint allocationUnitsPerNxm,\n    uint targetPriceDenominator\n  ) external pure returns (uint premium, StakedProduct memory);\n\n  function calculatePremiumPerYear(\n    uint basePrice,\n    uint coverAmount,\n    uint initialCapacityUsed,\n    uint totalCapacity,\n    uint nxmPerAllocationUnit,\n    uint allocationUnitsPerNxm,\n    uint targetPriceDenominator\n  ) external pure returns (uint);\n\n  // Calculates the premium for a given cover amount starting with the surge point\n  function calculateSurgePremium(\n    uint amountOnSurge,\n    uint totalCapacity,\n    uint allocationUnitsPerNxm\n  ) external pure returns (uint);\n\n  /* ============= EVENTS ============= */\n\n  event ProductUpdated(uint productId, uint8 targetWeight, uint96 targetPrice);\n\n  /* ============= ERRORS ============= */\n\n  // Auth\n  error OnlyStakingPool();\n  error OnlyCoverContract();\n  error OnlyManager();\n\n  // Products & weights\n  error MustSetPriceForNewProducts();\n  error MustSetWeightForNewProducts();\n  error TargetPriceTooHigh();\n  error TargetPriceBelowMin();\n  error TargetWeightTooHigh();\n  error MustRecalculateEffectiveWeight();\n  error TotalTargetWeightExceeded();\n  error TotalEffectiveWeightExceeded();\n\n}\n"
      },
      "contracts/interfaces/ITokenController.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.5.0;\n\nimport \"./INXMToken.sol\";\n\ninterface ITokenController {\n\n  struct StakingPoolNXMBalances {\n    uint128 rewards;\n    uint128 deposits;\n  }\n\n  struct CoverInfo {\n    uint16 claimCount;\n    bool hasOpenClaim;\n    bool hasAcceptedClaim;\n    uint96 requestedPayoutAmount;\n    // note: still 128 bits available here, can be used later\n  }\n\n  struct StakingPoolOwnershipOffer {\n    address proposedManager;\n    uint96 deadline;\n  }\n\n  function coverInfo(uint id) external view returns (\n    uint16 claimCount,\n    bool hasOpenClaim,\n    bool hasAcceptedClaim,\n    uint96 requestedPayoutAmount\n  );\n\n  function withdrawCoverNote(\n    address _of,\n    uint[] calldata _coverIds,\n    uint[] calldata _indexes\n  ) external;\n\n  function changeOperator(address _newOperator) external;\n\n  function operatorTransfer(address _from, address _to, uint _value) external returns (bool);\n\n  function burnFrom(address _of, uint amount) external returns (bool);\n\n  function addToWhitelist(address _member) external;\n\n  function removeFromWhitelist(address _member) external;\n\n  function mint(address _member, uint _amount) external;\n\n  function lockForMemberVote(address _of, uint _days) external;\n\n  function withdrawClaimAssessmentTokens(address[] calldata users) external;\n\n  function getLockReasons(address _of) external view returns (bytes32[] memory reasons);\n\n  function totalSupply() external view returns (uint);\n\n  function totalBalanceOf(address _of) external view returns (uint amount);\n\n  function totalBalanceOfWithoutDelegations(address _of) external view returns (uint amount);\n\n  function getTokenPrice() external view returns (uint tokenPrice);\n\n  function token() external view returns (INXMToken);\n\n  function getStakingPoolManager(uint poolId) external view returns (address manager);\n\n  function getManagerStakingPools(address manager) external view returns (uint[] memory poolIds);\n\n  function isStakingPoolManager(address member) external view returns (bool);\n\n  function getStakingPoolOwnershipOffer(uint poolId) external view returns (address proposedManager, uint deadline);\n\n  function transferStakingPoolsOwnership(address from, address to) external;\n\n  function assignStakingPoolManager(uint poolId, address manager) external;\n\n  function createStakingPoolOwnershipOffer(uint poolId, address proposedManager, uint deadline) external;\n\n  function acceptStakingPoolOwnershipOffer(uint poolId) external;\n\n  function cancelStakingPoolOwnershipOffer(uint poolId) external;\n\n  function mintStakingPoolNXMRewards(uint amount, uint poolId) external;\n\n  function burnStakingPoolNXMRewards(uint amount, uint poolId) external;\n\n  function depositStakedNXM(address from, uint amount, uint poolId) external;\n\n  function withdrawNXMStakeAndRewards(address to, uint stakeToWithdraw, uint rewardsToWithdraw, uint poolId) external;\n\n  function burnStakedNXM(uint amount, uint poolId) external;\n\n  function stakingPoolNXMBalances(uint poolId) external view returns(uint128 rewards, uint128 deposits);\n\n  function tokensLocked(address _of, bytes32 _reason) external view returns (uint256 amount);\n\n  function getWithdrawableCoverNotes(\n    address coverOwner\n  ) external view returns (\n    uint[] memory coverIds,\n    bytes32[] memory lockReasons,\n    uint withdrawableAmount\n  );\n\n  function getPendingRewards(address member) external view returns (uint);\n}\n"
      },
      "contracts/libraries/Math.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity ^0.8.18;\n\n/**\n * @dev Simple library that defines min, max and babylonian sqrt functions\n */\nlibrary Math {\n\n  function min(uint a, uint b) internal pure returns (uint) {\n    return a < b ? a : b;\n  }\n\n  function max(uint a, uint b) internal pure returns (uint) {\n    return a > b ? a : b;\n  }\n\n  function sum(uint[] memory items) internal pure returns (uint) {\n    uint count = items.length;\n    uint total;\n\n    for (uint i = 0; i < count; i++) {\n      total += items[i];\n    }\n\n    return total;\n  }\n\n  function divRound(uint a, uint b) internal pure returns (uint) {\n    return (a + b / 2) / b;\n  }\n\n  function divCeil(uint a, uint b) internal pure returns (uint) {\n    return (a + b - 1) / b;\n  }\n\n  function roundUp(uint a, uint b) internal pure returns (uint) {\n    return divCeil(a, b) * b;\n  }\n\n  // babylonian method\n  function sqrt(uint y) internal pure returns (uint) {\n\n    if (y > 3) {\n      uint z = y;\n      uint x = y / 2 + 1;\n      while (x < z) {\n        z = x;\n        x = (y / x + x) / 2;\n      }\n      return z;\n    }\n\n    if (y != 0) {\n      return 1;\n    }\n\n    return 0;\n  }\n\n}\n"
      },
      "contracts/libraries/SafeUintCast.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.18;\n\n/**\n * @dev Wrappers over Solidity's uintXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeUintCast {\n  /**\n   * @dev Returns the downcasted uint248 from uint256, reverting on\n   * overflow (when the input is greater than largest uint248).\n   *\n   * Counterpart to Solidity's `uint248` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 248 bits\n   */\n  function toUint248(uint256 value) internal pure returns (uint248) {\n    require(value < 2**248, \"SafeCast: value doesn\\'t fit in 248 bits\");\n    return uint248(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint240 from uint256, reverting on\n   * overflow (when the input is greater than largest uint240).\n   *\n   * Counterpart to Solidity's `uint240` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 240 bits\n   */\n  function toUint240(uint256 value) internal pure returns (uint240) {\n    require(value < 2**240, \"SafeCast: value doesn\\'t fit in 240 bits\");\n    return uint240(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint232 from uint256, reverting on\n   * overflow (when the input is greater than largest uint232).\n   *\n   * Counterpart to Solidity's `uint232` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 232 bits\n   */\n  function toUint232(uint256 value) internal pure returns (uint232) {\n    require(value < 2**232, \"SafeCast: value doesn\\'t fit in 232 bits\");\n    return uint232(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint224 from uint256, reverting on\n   * overflow (when the input is greater than largest uint224).\n   *\n   * Counterpart to Solidity's `uint224` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 224 bits\n   */\n  function toUint224(uint256 value) internal pure returns (uint224) {\n    require(value < 2**224, \"SafeCast: value doesn\\'t fit in 224 bits\");\n    return uint224(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint216 from uint256, reverting on\n   * overflow (when the input is greater than largest uint216).\n   *\n   * Counterpart to Solidity's `uint216` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 216 bits\n   */\n  function toUint216(uint256 value) internal pure returns (uint216) {\n    require(value < 2**216, \"SafeCast: value doesn\\'t fit in 216 bits\");\n    return uint216(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint208 from uint256, reverting on\n   * overflow (when the input is greater than largest uint208).\n   *\n   * Counterpart to Solidity's `uint208` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 208 bits\n   */\n  function toUint208(uint256 value) internal pure returns (uint208) {\n    require(value < 2**208, \"SafeCast: value doesn\\'t fit in 208 bits\");\n    return uint208(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint200 from uint256, reverting on\n   * overflow (when the input is greater than largest uint200).\n   *\n   * Counterpart to Solidity's `uint200` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 200 bits\n   */\n  function toUint200(uint256 value) internal pure returns (uint200) {\n    require(value < 2**200, \"SafeCast: value doesn\\'t fit in 200 bits\");\n    return uint200(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint192 from uint256, reverting on\n   * overflow (when the input is greater than largest uint192).\n   *\n   * Counterpart to Solidity's `uint192` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 192 bits\n   */\n  function toUint192(uint256 value) internal pure returns (uint192) {\n    require(value < 2**192, \"SafeCast: value doesn\\'t fit in 192 bits\");\n    return uint192(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint184 from uint256, reverting on\n   * overflow (when the input is greater than largest uint184).\n   *\n   * Counterpart to Solidity's `uint184` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 184 bits\n   */\n  function toUint184(uint256 value) internal pure returns (uint184) {\n    require(value < 2**184, \"SafeCast: value doesn\\'t fit in 184 bits\");\n    return uint184(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint176 from uint256, reverting on\n   * overflow (when the input is greater than largest uint176).\n   *\n   * Counterpart to Solidity's `uint176` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 176 bits\n   */\n  function toUint176(uint256 value) internal pure returns (uint176) {\n    require(value < 2**176, \"SafeCast: value doesn\\'t fit in 176 bits\");\n    return uint176(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint168 from uint256, reverting on\n   * overflow (when the input is greater than largest uint168).\n   *\n   * Counterpart to Solidity's `uint168` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 168 bits\n   */\n  function toUint168(uint256 value) internal pure returns (uint168) {\n    require(value < 2**168, \"SafeCast: value doesn\\'t fit in 168 bits\");\n    return uint168(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint160 from uint256, reverting on\n   * overflow (when the input is greater than largest uint160).\n   *\n   * Counterpart to Solidity's `uint160` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 160 bits\n   */\n  function toUint160(uint256 value) internal pure returns (uint160) {\n    require(value < 2**160, \"SafeCast: value doesn\\'t fit in 160 bits\");\n    return uint160(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint152 from uint256, reverting on\n   * overflow (when the input is greater than largest uint152).\n   *\n   * Counterpart to Solidity's `uint152` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 152 bits\n   */\n  function toUint152(uint256 value) internal pure returns (uint152) {\n    require(value < 2**152, \"SafeCast: value doesn\\'t fit in 152 bits\");\n    return uint152(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint144 from uint256, reverting on\n   * overflow (when the input is greater than largest uint144).\n   *\n   * Counterpart to Solidity's `uint144` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 144 bits\n   */\n  function toUint144(uint256 value) internal pure returns (uint144) {\n    require(value < 2**144, \"SafeCast: value doesn\\'t fit in 144 bits\");\n    return uint144(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint136 from uint256, reverting on\n   * overflow (when the input is greater than largest uint136).\n   *\n   * Counterpart to Solidity's `uint136` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 136 bits\n   */\n  function toUint136(uint256 value) internal pure returns (uint136) {\n    require(value < 2**136, \"SafeCast: value doesn\\'t fit in 136 bits\");\n    return uint136(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint128 from uint256, reverting on\n   * overflow (when the input is greater than largest uint128).\n   *\n   * Counterpart to Solidity's `uint128` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 128 bits\n   */\n  function toUint128(uint256 value) internal pure returns (uint128) {\n    require(value < 2**128, \"SafeCast: value doesn\\'t fit in 128 bits\");\n    return uint128(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint120 from uint256, reverting on\n   * overflow (when the input is greater than largest uint120).\n   *\n   * Counterpart to Solidity's `uint120` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 120 bits\n   */\n  function toUint120(uint256 value) internal pure returns (uint120) {\n    require(value < 2**120, \"SafeCast: value doesn\\'t fit in 120 bits\");\n    return uint120(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint112 from uint256, reverting on\n   * overflow (when the input is greater than largest uint112).\n   *\n   * Counterpart to Solidity's `uint112` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 112 bits\n   */\n  function toUint112(uint256 value) internal pure returns (uint112) {\n    require(value < 2**112, \"SafeCast: value doesn\\'t fit in 112 bits\");\n    return uint112(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint104 from uint256, reverting on\n   * overflow (when the input is greater than largest uint104).\n   *\n   * Counterpart to Solidity's `uint104` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 104 bits\n   */\n  function toUint104(uint256 value) internal pure returns (uint104) {\n    require(value < 2**104, \"SafeCast: value doesn\\'t fit in 104 bits\");\n    return uint104(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint96 from uint256, reverting on\n   * overflow (when the input is greater than largest uint96).\n   *\n   * Counterpart to Solidity's `uint104` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 96 bits\n   */\n  function toUint96(uint256 value) internal pure returns (uint96) {\n    require(value < 2**96, \"SafeCast: value doesn\\'t fit in 96 bits\");\n    return uint96(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint88 from uint256, reverting on\n   * overflow (when the input is greater than largest uint88).\n   *\n   * Counterpart to Solidity's `uint104` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 88 bits\n   */\n  function toUint88(uint256 value) internal pure returns (uint88) {\n    require(value < 2**88, \"SafeCast: value doesn\\'t fit in 88 bits\");\n    return uint88(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint80 from uint256, reverting on\n   * overflow (when the input is greater than largest uint80).\n   *\n   * Counterpart to Solidity's `uint104` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 80 bits\n   */\n  function toUint80(uint256 value) internal pure returns (uint80) {\n    require(value < 2**80, \"SafeCast: value doesn\\'t fit in 80 bits\");\n    return uint80(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint64 from uint256, reverting on\n   * overflow (when the input is greater than largest uint64).\n   *\n   * Counterpart to Solidity's `uint64` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 64 bits\n   */\n  function toUint64(uint256 value) internal pure returns (uint64) {\n    require(value < 2**64, \"SafeCast: value doesn\\'t fit in 64 bits\");\n    return uint64(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint56 from uint256, reverting on\n   * overflow (when the input is greater than largest uint56).\n   *\n   * Counterpart to Solidity's `uint56` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 56 bits\n   */\n  function toUint56(uint256 value) internal pure returns (uint56) {\n    require(value < 2**56, \"SafeCast: value doesn\\'t fit in 56 bits\");\n    return uint56(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint48 from uint256, reverting on\n   * overflow (when the input is greater than largest uint48).\n   *\n   * Counterpart to Solidity's `uint48` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 48 bits\n   */\n  function toUint48(uint256 value) internal pure returns (uint48) {\n    require(value < 2**48, \"SafeCast: value doesn\\'t fit in 48 bits\");\n    return uint48(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint40 from uint256, reverting on\n   * overflow (when the input is greater than largest uint40).\n   *\n   * Counterpart to Solidity's `uint40` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 40 bits\n   */\n  function toUint40(uint256 value) internal pure returns (uint40) {\n    require(value < 2**40, \"SafeCast: value doesn\\'t fit in 40 bits\");\n    return uint40(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint32 from uint256, reverting on\n   * overflow (when the input is greater than largest uint32).\n   *\n   * Counterpart to Solidity's `uint32` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 32 bits\n   */\n  function toUint32(uint256 value) internal pure returns (uint32) {\n    require(value < 2**32, \"SafeCast: value doesn\\'t fit in 32 bits\");\n    return uint32(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint24 from uint256, reverting on\n   * overflow (when the input is greater than largest uint24).\n   *\n   * Counterpart to Solidity's `uint24` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 24 bits\n   */\n  function toUint24(uint256 value) internal pure returns (uint24) {\n    require(value < 2**24, \"SafeCast: value doesn\\'t fit in 24 bits\");\n    return uint24(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint16 from uint256, reverting on\n   * overflow (when the input is greater than largest uint16).\n   *\n   * Counterpart to Solidity's `uint16` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 16 bits\n   */\n  function toUint16(uint256 value) internal pure returns (uint16) {\n    require(value < 2**16, \"SafeCast: value doesn\\'t fit in 16 bits\");\n    return uint16(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint8 from uint256, reverting on\n   * overflow (when the input is greater than largest uint8).\n   *\n   * Counterpart to Solidity's `uint8` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 8 bits.\n   */\n  function toUint8(uint256 value) internal pure returns (uint8) {\n    require(value < 2**8, \"SafeCast: value doesn\\'t fit in 8 bits\");\n    return uint8(value);\n  }\n}\n"
      },
      "contracts/libraries/StakingPoolLibrary.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity ^0.8.18;\n\n/**\n * @dev Simple library to derive the staking pool address from the pool id without external calls\n */\nlibrary StakingPoolLibrary {\n\n  function getAddress(address factory, uint poolId) internal pure returns (address) {\n\n    bytes32 hash = keccak256(\n      abi.encodePacked(\n        hex'ff',\n        factory,\n        poolId, // salt\n        // init code hash of the MinimalBeaconProxy\n        // updated using patch-staking-pool-library.js script\n        hex'1eb804b66941a2e8465fa0951be9c8b855b7794ee05b0789ab22a02ee1298ebe' // init code hash\n      )\n    );\n\n    // cast last 20 bytes of hash to address\n    return address(uint160(uint(hash)));\n  }\n\n}\n"
      },
      "contracts/modules/cover/Cover.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-v4/security/ReentrancyGuard.sol\";\nimport \"@openzeppelin/contracts-v4/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts-v4/token/ERC20/utils/SafeERC20.sol\";\n\nimport \"../../abstract/MasterAwareV2.sol\";\nimport \"../../abstract/Multicall.sol\";\nimport \"../../interfaces/ICover.sol\";\nimport \"../../interfaces/ICoverNFT.sol\";\nimport \"../../interfaces/IPool.sol\";\nimport \"../../interfaces/IStakingNFT.sol\";\nimport \"../../interfaces/IStakingPool.sol\";\nimport \"../../interfaces/IStakingPoolBeacon.sol\";\nimport \"../../interfaces/IStakingPoolFactory.sol\";\nimport \"../../interfaces/ITokenController.sol\";\nimport \"../../interfaces/IStakingProducts.sol\";\nimport \"../../libraries/Math.sol\";\nimport \"../../libraries/SafeUintCast.sol\";\nimport \"../../libraries/StakingPoolLibrary.sol\";\n\ncontract Cover is ICover, MasterAwareV2, IStakingPoolBeacon, ReentrancyGuard, Multicall {\n  using SafeERC20 for IERC20;\n  using SafeUintCast for uint;\n\n  /* ========== STATE VARIABLES ========== */\n\n  Product[] internal _products;\n  ProductType[] internal _productTypes;\n\n  mapping(uint => CoverData) private _coverData;\n\n  // cover id => segment id => pool allocations array\n  mapping(uint => mapping(uint => PoolAllocation[])) public coverSegmentAllocations;\n\n  // product id => allowed pool ids\n  mapping(uint => uint[]) public allowedPools;\n\n  // Each cover has an array of segments. A new segment is created\n  // every time a cover is edited to deliniate the different cover periods.\n  mapping(uint => CoverSegment[]) private _coverSegments;\n\n  // assetId => { lastBucketUpdateId, totalActiveCoverInAsset }\n  mapping(uint => ActiveCover) public activeCover;\n  // assetId => bucketId => amount\n  mapping(uint => mapping(uint => uint)) internal activeCoverExpirationBuckets;\n\n  // productId => product name\n  mapping(uint => string) public productNames;\n  // productTypeId => productType name\n  mapping(uint => string) public productTypeNames;\n\n  /* ========== CONSTANTS ========== */\n\n  uint private constant GLOBAL_CAPACITY_RATIO = 20000; // 2\n  uint private constant GLOBAL_REWARDS_RATIO = 5000; // 50%\n\n  uint private constant PRICE_DENOMINATOR = 10000;\n  uint private constant COMMISSION_DENOMINATOR = 10000;\n  uint private constant CAPACITY_REDUCTION_DENOMINATOR = 10000;\n  uint private constant GLOBAL_CAPACITY_DENOMINATOR = 10_000;\n  uint private constant REWARD_DENOMINATOR = 10_000;\n\n  uint private constant MAX_COVER_PERIOD = 365 days;\n  uint private constant MIN_COVER_PERIOD = 28 days;\n  uint private constant BUCKET_SIZE = 7 days;\n  // this constant is used for calculating the normalized yearly percentage cost of cover\n  uint private constant ONE_YEAR = 365 days;\n\n  uint public constant MAX_COMMISSION_RATIO = 3000; // 30%\n\n  uint public constant GLOBAL_MIN_PRICE_RATIO = 100; // 1%\n\n  uint private constant ONE_NXM = 1e18;\n\n  uint private constant ETH_ASSET_ID = 0;\n  uint private constant NXM_ASSET_ID = type(uint8).max;\n\n  // internally we store capacity using 2 decimals\n  // 1 nxm of capacity is stored as 100\n  uint private constant ALLOCATION_UNITS_PER_NXM = 100;\n\n  // given capacities have 2 decimals\n  // smallest unit we can allocate is 1e18 / 100 = 1e16 = 0.01 NXM\n  uint public constant NXM_PER_ALLOCATION_UNIT = ONE_NXM / ALLOCATION_UNITS_PER_NXM;\n\n  ICoverNFT public immutable override coverNFT;\n  IStakingNFT public immutable override stakingNFT;\n  IStakingPoolFactory public immutable override stakingPoolFactory;\n  address public immutable stakingPoolImplementation;\n\n  /* ========== CONSTRUCTOR ========== */\n\n  constructor(\n    ICoverNFT _coverNFT,\n    IStakingNFT _stakingNFT,\n    IStakingPoolFactory _stakingPoolFactory,\n    address _stakingPoolImplementation\n  ) {\n    // in constructor we only initialize immutable fields\n    coverNFT = _coverNFT;\n    stakingNFT = _stakingNFT;\n    stakingPoolFactory = _stakingPoolFactory;\n    stakingPoolImplementation = _stakingPoolImplementation;\n  }\n\n  /* === MUTATIVE FUNCTIONS ==== */\n\n  function buyCover(\n    BuyCoverParams memory params,\n    PoolAllocationRequest[] memory poolAllocationRequests\n  ) external payable onlyMember nonReentrant whenNotPaused returns (uint coverId) {\n\n    if (params.period < MIN_COVER_PERIOD) {\n      revert CoverPeriodTooShort();\n    }\n\n    if (params.period > MAX_COVER_PERIOD) {\n      revert CoverPeriodTooLong();\n    }\n\n    if (params.commissionRatio > MAX_COMMISSION_RATIO) {\n      revert CommissionRateTooHigh();\n    }\n\n    if (params.amount == 0) {\n      revert CoverAmountIsZero();\n    }\n\n    uint segmentId;\n\n    AllocationRequest memory allocationRequest;\n    {\n\n      if (_products.length <= params.productId) {\n        revert ProductDoesntExist();\n      }\n\n      Product memory product = _products[params.productId];\n\n      if (product.isDeprecated) {\n        revert ProductDoesntExistOrIsDeprecated();\n      }\n\n      if (!isCoverAssetSupported(params.coverAsset, product.coverAssets)) {\n        revert CoverAssetNotSupported();\n      }\n\n      allocationRequest.productId = params.productId;\n      allocationRequest.coverId = coverId;\n      allocationRequest.period = params.period;\n      allocationRequest.gracePeriod = _productTypes[product.productType].gracePeriod;\n      allocationRequest.useFixedPrice = product.useFixedPrice;\n      allocationRequest.globalCapacityRatio = GLOBAL_CAPACITY_RATIO;\n      allocationRequest.capacityReductionRatio = product.capacityReductionRatio;\n      allocationRequest.rewardRatio = GLOBAL_REWARDS_RATIO;\n      allocationRequest.globalMinPrice = GLOBAL_MIN_PRICE_RATIO;\n    }\n\n    uint previousSegmentAmount;\n\n    if (params.coverId == 0) {\n\n      // new cover\n      coverId = coverNFT.mint(params.owner);\n      _coverData[coverId] = CoverData(params.productId, params.coverAsset, 0 /* amountPaidOut */);\n\n    } else {\n      revert EditNotSupported();\n\n      /*\n      // existing cover\n      coverId = params.coverId;\n\n      if (!coverNFT.isApprovedOrOwner(msg.sender, coverId)) {\n        revert OnlyOwnerOrApproved();\n      }\n\n      CoverData memory cover = _coverData[coverId];\n\n      if (params.coverAsset != cover.coverAsset) {\n        revert UnexpectedCoverAsset();\n      }\n\n      if (params.productId != cover.productId) {\n        revert UnexpectedProductId();\n      }\n\n      segmentId = _coverSegments[coverId].length;\n      CoverSegment memory lastSegment = coverSegmentWithRemainingAmount(coverId, segmentId - 1);\n\n      // require last segment not to be expired\n      if (lastSegment.start + lastSegment.period <= block.timestamp) {\n        revert ExpiredCoversCannotBeEdited();\n      }\n\n      allocationRequest.previousStart = lastSegment.start;\n      allocationRequest.previousExpiration = lastSegment.start + lastSegment.period;\n      allocationRequest.previousRewardsRatio = lastSegment.globalRewardsRatio;\n\n      // mark previous cover as ending now\n      _coverSegments[coverId][segmentId - 1].period = (block.timestamp - lastSegment.start).toUint32();\n\n      // remove cover amount from from expiration buckets\n      uint bucketAtExpiry = Math.divCeil(lastSegment.start + lastSegment.period, BUCKET_SIZE);\n      activeCoverExpirationBuckets[params.coverAsset][bucketAtExpiry] -= lastSegment.amount;\n      previousSegmentAmount += lastSegment.amount;\n      */\n    }\n\n    uint nxmPriceInCoverAsset = pool().getInternalTokenPriceInAssetAndUpdateTwap(params.coverAsset);\n    allocationRequest.coverId = coverId;\n\n    (uint coverAmountInCoverAsset, uint amountDueInNXM) = requestAllocation(\n      allocationRequest,\n      poolAllocationRequests,\n      nxmPriceInCoverAsset,\n      segmentId\n    );\n\n    if (coverAmountInCoverAsset < params.amount) {\n      revert InsufficientCoverAmountAllocated();\n    }\n\n    _coverSegments[coverId].push(\n      CoverSegment(\n        coverAmountInCoverAsset.toUint96(), // cover amount in cover asset\n        block.timestamp.toUint32(), // start\n        params.period, // period\n        allocationRequest.gracePeriod.toUint32(),\n        GLOBAL_REWARDS_RATIO.toUint24(),\n        GLOBAL_CAPACITY_RATIO.toUint24()\n      )\n    );\n\n    // can pay with cover asset or nxm only\n    if (params.paymentAsset != params.coverAsset && params.paymentAsset != NXM_ASSET_ID) {\n      revert InvalidPaymentAsset();\n    }\n    _updateTotalActiveCoverAmount(params.coverAsset, coverAmountInCoverAsset, params.period, previousSegmentAmount);\n\n    retrievePayment(\n      amountDueInNXM,\n      params.paymentAsset,\n      nxmPriceInCoverAsset,\n      params.maxPremiumInAsset,\n      params.commissionRatio,\n      params.commissionDestination\n    );\n\n    emit CoverEdited(coverId, params.productId, segmentId, msg.sender, params.ipfsData);\n  }\n\n  function expireCover(uint coverId) external {\n\n    uint segmentId = _coverSegments[coverId].length - 1;\n    CoverSegment memory lastSegment = coverSegmentWithRemainingAmount(coverId, segmentId);\n    CoverData memory cover = _coverData[coverId];\n    uint expiration = lastSegment.start + lastSegment.period;\n\n    if (expiration > block.timestamp) {\n      revert CoverNotYetExpired(coverId);\n    }\n\n    for (\n      uint allocationIndex = 0;\n      allocationIndex < coverSegmentAllocations[coverId][segmentId].length;\n      allocationIndex++\n    ) {\n      PoolAllocation memory allocation =  coverSegmentAllocations[coverId][segmentId][allocationIndex];\n      AllocationRequest memory allocationRequest;\n      // editing just the needed props for deallocation\n      allocationRequest.productId = cover.productId;\n      allocationRequest.allocationId = allocation.allocationId;\n      allocationRequest.previousStart = lastSegment.start;\n      allocationRequest.previousExpiration = expiration;\n\n      stakingPool(allocation.poolId).requestAllocation(\n        0, // amount\n        0, // previous premium\n        allocationRequest\n      );\n    }\n  }\n\n  function requestAllocation(\n    AllocationRequest memory allocationRequest,\n    PoolAllocationRequest[] memory poolAllocationRequests,\n    uint nxmPriceInCoverAsset,\n    uint segmentId\n  ) internal returns (\n    uint totalCoverAmountInCoverAsset,\n    uint totalAmountDueInNXM\n  ) {\n\n    RequestAllocationVariables memory vars = RequestAllocationVariables(0, 0, 0, 0);\n    uint totalCoverAmountInNXM;\n\n    vars.previousPoolAllocationsLength = segmentId > 0\n      ? coverSegmentAllocations[allocationRequest.coverId][segmentId - 1].length\n      : 0;\n\n    for (uint i = 0; i < poolAllocationRequests.length; i++) {\n\n      // if there is a previous segment and this index is present on it\n      if (vars.previousPoolAllocationsLength > i) {\n\n        PoolAllocation memory previousPoolAllocation =\n          coverSegmentAllocations[allocationRequest.coverId][segmentId - 1][i];\n\n        // poolAllocationRequests must match the pools in the previous segment\n        if (previousPoolAllocation.poolId != poolAllocationRequests[i].poolId) {\n          revert UnexpectedPoolId();\n        }\n\n        // check if this request should be skipped, keeping the previous allocation\n        if (poolAllocationRequests[i].skip) {\n          coverSegmentAllocations[allocationRequest.coverId][segmentId].push(previousPoolAllocation);\n          totalCoverAmountInNXM += previousPoolAllocation.coverAmountInNXM;\n          continue;\n        }\n\n        vars.previousPremiumInNXM = previousPoolAllocation.premiumInNXM;\n        vars.refund =\n          previousPoolAllocation.premiumInNXM\n          * (allocationRequest.previousExpiration - block.timestamp) // remaining period\n          / (allocationRequest.previousExpiration - allocationRequest.previousStart); // previous period\n\n        // get stored allocation id\n        allocationRequest.allocationId = previousPoolAllocation.allocationId;\n      } else {\n        // request new allocation id\n        allocationRequest.allocationId = 0;\n      }\n\n      // converting asset amount to nxm and rounding up to the nearest NXM_PER_ALLOCATION_UNIT\n      uint coverAmountInNXM = Math.roundUp(\n        Math.divCeil(poolAllocationRequests[i].coverAmountInAsset * ONE_NXM, nxmPriceInCoverAsset),\n        NXM_PER_ALLOCATION_UNIT\n      );\n\n      (uint premiumInNXM, uint allocationId) = stakingPool(poolAllocationRequests[i].poolId).requestAllocation(\n        coverAmountInNXM,\n        vars.previousPremiumInNXM,\n        allocationRequest\n      );\n\n      // omit deallocated pools from the segment\n      if (coverAmountInNXM != 0) {\n        coverSegmentAllocations[allocationRequest.coverId][segmentId].push(\n          PoolAllocation(\n            poolAllocationRequests[i].poolId,\n            coverAmountInNXM.toUint96(),\n            premiumInNXM.toUint96(),\n            allocationId.toUint24()\n          )\n        );\n      }\n\n      totalAmountDueInNXM += (vars.refund >= premiumInNXM ? 0 : premiumInNXM - vars.refund);\n      totalCoverAmountInNXM += coverAmountInNXM;\n    }\n\n    totalCoverAmountInCoverAsset = totalCoverAmountInNXM * nxmPriceInCoverAsset / ONE_NXM;\n\n    return (totalCoverAmountInCoverAsset, totalAmountDueInNXM);\n  }\n\n  function retrievePayment(\n    uint premiumInNxm,\n    uint paymentAsset,\n    uint nxmPriceInCoverAsset,\n    uint maxPremiumInAsset,\n    uint16 commissionRatio,\n    address commissionDestination\n  ) internal {\n\n    if (paymentAsset != ETH_ASSET_ID && msg.value > 0) {\n      revert UnexpectedEthSent();\n    }\n\n    // NXM payment\n    if (paymentAsset == NXM_ASSET_ID) {\n      uint commissionInNxm;\n\n      if (commissionRatio > 0) {\n        commissionInNxm = (premiumInNxm * COMMISSION_DENOMINATOR / (COMMISSION_DENOMINATOR - commissionRatio)) - premiumInNxm;\n      }\n\n      if (premiumInNxm + commissionInNxm > maxPremiumInAsset) {\n        revert PriceExceedsMaxPremiumInAsset();\n      }\n\n      ITokenController _tokenController = tokenController();\n      _tokenController.burnFrom(msg.sender, premiumInNxm);\n\n      if (commissionInNxm > 0) {\n        // commission transfer reverts if the commissionDestination is not a member\n        _tokenController.operatorTransfer(msg.sender, commissionDestination, commissionInNxm);\n      }\n\n      return;\n    }\n\n    IPool _pool = pool();\n    uint premiumInPaymentAsset = nxmPriceInCoverAsset * premiumInNxm / ONE_NXM;\n    uint commission = (premiumInPaymentAsset * COMMISSION_DENOMINATOR / (COMMISSION_DENOMINATOR - commissionRatio)) - premiumInPaymentAsset;\n    uint premiumWithCommission = premiumInPaymentAsset + commission;\n\n    if (premiumWithCommission > maxPremiumInAsset) {\n      revert PriceExceedsMaxPremiumInAsset();\n    }\n\n    // ETH payment\n    if (paymentAsset == ETH_ASSET_ID) {\n\n      if (msg.value < premiumWithCommission) {\n        revert InsufficientEthSent();\n      }\n\n      uint remainder = msg.value - premiumWithCommission;\n\n      {\n        // send premium in eth to the pool\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool ok, /* data */) = address(_pool).call{value: premiumInPaymentAsset}(\"\");\n        if (!ok) {\n          revert SendingEthToPoolFailed();\n        }\n      }\n\n      // send commission\n      if (commission > 0) {\n        (bool ok, /* data */) = address(commissionDestination).call{value: commission}(\"\");\n        if (!ok) {\n          revert SendingEthToCommissionDestinationFailed();\n        }\n      }\n\n      if (remainder > 0) {\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool ok, /* data */) = address(msg.sender).call{value: remainder}(\"\");\n        if (!ok) {\n          revert ReturningEthRemainderToSenderFailed();\n        }\n      }\n\n      return;\n    }\n\n    address coverAsset = _pool.getAsset(paymentAsset).assetAddress;\n    IERC20 token = IERC20(coverAsset);\n    token.safeTransferFrom(msg.sender, address(_pool), premiumInPaymentAsset);\n\n    if (commission > 0) {\n      token.safeTransferFrom(msg.sender, commissionDestination, commission);\n    }\n  }\n\n  function updateTotalActiveCoverAmount(uint coverAsset) public {\n    _updateTotalActiveCoverAmount(coverAsset, 0, 0, 0);\n  }\n\n  function _updateTotalActiveCoverAmount(\n    uint coverAsset,\n    uint newCoverAmountInAsset,\n    uint coverPeriod,\n    uint previousCoverSegmentAmount\n  ) internal {\n    ActiveCover memory _activeCover = activeCover[coverAsset];\n\n    uint currentBucketId = block.timestamp / BUCKET_SIZE;\n    uint totalActiveCover = _activeCover.totalActiveCoverInAsset;\n\n    if (totalActiveCover != 0) {\n      totalActiveCover -= getExpiredCoverAmount(\n        coverAsset,\n        _activeCover.lastBucketUpdateId,\n        currentBucketId\n      );\n    }\n\n    totalActiveCover -= previousCoverSegmentAmount;\n    totalActiveCover += newCoverAmountInAsset;\n\n    _activeCover.lastBucketUpdateId = currentBucketId.toUint64();\n    _activeCover.totalActiveCoverInAsset = totalActiveCover.toUint192();\n\n    // update total active cover in storage\n    activeCover[coverAsset] = _activeCover;\n\n    // update amount to expire at the end of this cover segment\n    uint bucketAtExpiry = Math.divCeil(block.timestamp + coverPeriod, BUCKET_SIZE);\n    activeCoverExpirationBuckets[coverAsset][bucketAtExpiry] += newCoverAmountInAsset;\n  }\n\n  function addLegacyCover(\n    uint productId,\n    uint coverAsset,\n    uint amount,\n    uint start,\n    uint period,\n    address newOwner\n  ) external onlyInternal returns (uint coverId) {\n\n    ProductType memory productType = _productTypes[_products[productId].productType];\n\n    // uses the current v2 grace period\n    if (block.timestamp >= start + period + productType.gracePeriod) {\n      revert CoverOutsideOfTheGracePeriod();\n    }\n\n    coverId = coverNFT.mint(newOwner);\n    _coverData[coverId] = CoverData(productId.toUint24(), coverAsset.toUint8(), 0 /* amountPaidOut */);\n\n    uint bucketAtExpiry = Math.divCeil((start + period), BUCKET_SIZE);\n    activeCoverExpirationBuckets[coverAsset][bucketAtExpiry] += amount;\n    activeCover[coverAsset].totalActiveCoverInAsset += amount.toUint192();\n\n    _coverSegments[coverId].push(\n      CoverSegment(\n        amount.toUint96(),\n        start.toUint32(),\n        period.toUint32(),\n        productType.gracePeriod,\n        0, // global rewards ratio\n        1\n      )\n    );\n\n    emit CoverEdited(coverId, productId, 0, msg.sender, \"\");\n\n    return coverId;\n  }\n\n  function createStakingPool(\n    bool isPrivatePool,\n    uint initialPoolFee,\n    uint maxPoolFee,\n    ProductInitializationParams[] memory productInitParams,\n    string calldata ipfsDescriptionHash\n  ) external whenNotPaused onlyMember returns (uint /*poolId*/, address /*stakingPoolAddress*/) {\n\n    uint numProducts = productInitParams.length;\n\n    // override with initial price and check if pool is allowed\n    for (uint i = 0; i < numProducts; i++) {\n\n      if (productInitParams[i].targetPrice < GLOBAL_MIN_PRICE_RATIO) {\n        revert TargetPriceBelowGlobalMinPriceRatio();\n      }\n\n      uint productId = productInitParams[i].productId;\n\n      // if there is a list of allowed pools for this product - this pool didn't exist yet so it's not in it\n      if (allowedPools[productId].length > 0) {\n        revert PoolNotAllowedForThisProduct(productId);\n      }\n\n      if (productId >= _products.length || _products[productId].isDeprecated) {\n        revert ProductDoesntExistOrIsDeprecated();\n      }\n\n      productInitParams[i].initialPrice = _products[productId].initialPriceRatio;\n    }\n\n    (uint poolId, address stakingPoolAddress) = stakingPoolFactory.create(address(this));\n\n    IStakingPool(stakingPoolAddress).initialize(\n      isPrivatePool,\n      initialPoolFee,\n      maxPoolFee,\n      poolId,\n      ipfsDescriptionHash\n    );\n\n    tokenController().assignStakingPoolManager(poolId, msg.sender);\n\n    stakingProducts().setInitialProducts(poolId, productInitParams);\n\n    return (poolId, stakingPoolAddress);\n  }\n\n  // Gets the total amount of active cover that is currently expired for this asset\n  function getExpiredCoverAmount(\n    uint coverAsset,\n    uint lastUpdateId,\n    uint currentBucketId\n  ) internal view returns (uint amountExpired) {\n\n    while (lastUpdateId < currentBucketId) {\n      ++lastUpdateId;\n      amountExpired += activeCoverExpirationBuckets[coverAsset][lastUpdateId];\n    }\n\n    return amountExpired;\n  }\n\n  function burnStake(\n    uint coverId,\n    uint segmentId,\n    uint payoutAmountInAsset\n  ) external onlyInternal override returns (address /* coverOwner */) {\n\n    CoverData storage cover = _coverData[coverId];\n    ActiveCover storage _activeCover = activeCover[cover.coverAsset];\n    CoverSegment memory segment = coverSegmentWithRemainingAmount(coverId, segmentId);\n    PoolAllocation[] storage allocations = coverSegmentAllocations[coverId][segmentId];\n\n    // update expired buckets and calculate the amount of active cover that should be burned\n    {\n      uint coverAsset = cover.coverAsset;\n      uint lastUpdateBucketId = _activeCover.lastBucketUpdateId;\n      uint currentBucketId = block.timestamp / BUCKET_SIZE;\n\n      uint burnedSegmentBucketId = Math.divCeil((segment.start + segment.period), BUCKET_SIZE);\n      uint activeCoverToExpire = getExpiredCoverAmount(coverAsset, lastUpdateBucketId, currentBucketId);\n\n      // if the segment has not expired - it's still accounted for in total active cover\n      if (burnedSegmentBucketId > currentBucketId) {\n        uint amountToSubtract = Math.min(payoutAmountInAsset, segment.amount);\n        activeCoverToExpire += amountToSubtract;\n        activeCoverExpirationBuckets[coverAsset][burnedSegmentBucketId] -= amountToSubtract.toUint192();\n      }\n\n      _activeCover.totalActiveCoverInAsset -= activeCoverToExpire.toUint192();\n      _activeCover.lastBucketUpdateId = currentBucketId.toUint64();\n    }\n\n    // increase amountPaidOut only *after* you read the segment\n    cover.amountPaidOut += payoutAmountInAsset.toUint96();\n\n    for (uint i = 0; i < allocations.length; i++) {\n      PoolAllocation memory allocation = allocations[i];\n\n      uint deallocationAmountInNXM = allocation.coverAmountInNXM * payoutAmountInAsset / segment.amount;\n      uint burnAmountInNxm = deallocationAmountInNXM * GLOBAL_CAPACITY_DENOMINATOR / segment.globalCapacityRatio;\n\n      allocations[i].coverAmountInNXM -= deallocationAmountInNXM.toUint96();\n      allocations[i].premiumInNXM -= (allocation.premiumInNXM * payoutAmountInAsset / segment.amount).toUint96();\n\n      BurnStakeParams memory params = BurnStakeParams(\n        allocation.allocationId,\n        cover.productId,\n        segment.start,\n        segment.period,\n        deallocationAmountInNXM\n      );\n\n      uint poolId = allocations[i].poolId;\n      stakingPool(poolId).burnStake(burnAmountInNxm, params);\n    }\n\n    return coverNFT.ownerOf(coverId);\n  }\n\n  /* ========== VIEWS ========== */\n\n  function stakingPool(uint poolId) public view returns (IStakingPool) {\n    return IStakingPool(\n      StakingPoolLibrary.getAddress(address(stakingPoolFactory), poolId)\n    );\n  }\n\n  function coverData(uint coverId) external override view returns (CoverData memory) {\n    return _coverData[coverId];\n  }\n\n  function coverSegmentWithRemainingAmount(\n    uint coverId,\n    uint segmentId\n  ) public override view returns (CoverSegment memory) {\n    CoverSegment memory segment = _coverSegments[coverId][segmentId];\n    uint96 amountPaidOut = _coverData[coverId].amountPaidOut;\n    segment.amount = segment.amount >= amountPaidOut\n      ? segment.amount - amountPaidOut\n      : 0;\n    return segment;\n  }\n\n  function coverSegments(uint coverId) external override view returns (CoverSegment[] memory) {\n    return _coverSegments[coverId];\n  }\n\n  function coverSegmentsCount(uint coverId) external override view returns (uint) {\n    return _coverSegments[coverId].length;\n  }\n\n  function coverDataCount() external override view returns (uint) {\n    return coverNFT.totalSupply();\n  }\n\n  function products(uint id) external override view returns (Product memory) {\n    return _products[id];\n  }\n\n  function productsCount() external override view returns (uint) {\n    return _products.length;\n  }\n\n  function getProducts() external view returns (Product[] memory) {\n    return _products;\n  }\n\n  function productTypes(uint id) external override view returns (ProductType memory) {\n    return _productTypes[id];\n  }\n\n  function productTypesCount() external override view returns (uint) {\n    return _productTypes.length;\n  }\n\n  /* ========== PRODUCT CONFIGURATION ========== */\n\n  function setProducts(ProductParam[] calldata productParams) external override onlyAdvisoryBoard {\n\n    uint unsupportedCoverAssetsBitmap = type(uint).max;\n\n\n    Asset[] memory assets = pool().getAssets();\n    uint assetsLength = assets.length;\n\n    for (uint i = 0; i < assetsLength; i++) {\n      if (assets[i].isCoverAsset && !assets[i].isAbandoned) {\n        // clear the bit at index i\n        unsupportedCoverAssetsBitmap ^= 1 << i;\n      }\n    }\n\n    for (uint i = 0; i < productParams.length; i++) {\n\n      ProductParam calldata param = productParams[i];\n      Product calldata product = param.product;\n\n      if (product.productType >= _productTypes.length) {\n        revert InvalidProductType();\n      }\n\n      if (unsupportedCoverAssetsBitmap & product.coverAssets != 0) {\n        revert UnsupportedCoverAssets();\n      }\n\n      if (product.initialPriceRatio < GLOBAL_MIN_PRICE_RATIO) {\n        revert InitialPriceRatioBelowGlobalMinPriceRatio();\n      }\n\n      if (product.initialPriceRatio > PRICE_DENOMINATOR) {\n        revert InitialPriceRatioAbove100Percent();\n      }\n\n      if (product.capacityReductionRatio > CAPACITY_REDUCTION_DENOMINATOR) {\n        revert CapacityReductionRatioAbove100Percent();\n      }\n\n      // TODO: https://github.com/NexusMutual/smart-contracts/issues/859\n      if (product.useFixedPrice) {\n        uint productId = param.productId == type(uint256).max ? _products.length : param.productId;\n        allowedPools[productId] = param.allowedPools;\n      }\n\n      // New product has id == uint256.max\n      if (param.productId == type(uint256).max) {\n        emit ProductSet(_products.length, param.ipfsMetadata);\n        productNames[_products.length] = param.productName;\n        _products.push(product);\n        continue;\n      }\n\n      // Existing product\n      if (param.productId >= _products.length) {\n        revert ProductDoesntExist();\n      }\n\n      Product storage newProductValue = _products[param.productId];\n      newProductValue.isDeprecated = product.isDeprecated;\n      newProductValue.coverAssets = product.coverAssets;\n      newProductValue.initialPriceRatio = product.initialPriceRatio;\n      newProductValue.capacityReductionRatio = product.capacityReductionRatio;\n\n      if (bytes(param.productName).length > 0) {\n        productNames[param.productId] = param.productName;\n      }\n\n      if (bytes(param.ipfsMetadata).length > 0) {\n        emit ProductSet(param.productId, param.ipfsMetadata);\n      }\n    }\n  }\n\n  function setProductTypes(ProductTypeParam[] calldata productTypeParams) external onlyAdvisoryBoard {\n\n    for (uint i = 0; i < productTypeParams.length; i++) {\n      ProductTypeParam calldata param = productTypeParams[i];\n\n      // New product has id == uint256.max\n      if (param.productTypeId == type(uint256).max) {\n        emit ProductTypeSet(_productTypes.length, param.ipfsMetadata);\n        productTypeNames[_productTypes.length] = param.productTypeName;\n        _productTypes.push(param.productType);\n        continue;\n      }\n\n      if (param.productTypeId >= _productTypes.length) {\n        revert ProductTypeNotFound();\n      }\n      _productTypes[param.productTypeId].gracePeriod = param.productType.gracePeriod;\n\n      if (bytes(param.productTypeName).length > 0) {\n        productTypeNames[param.productTypeId] = param.productTypeName;\n      }\n\n      if (bytes(param.ipfsMetadata).length > 0) {\n        emit ProductTypeSet(param.productTypeId, param.ipfsMetadata);\n      }\n    }\n  }\n\n  /* ========== COVER ASSETS HELPERS ========== */\n\n  function totalActiveCoverInAsset(uint assetId) public view returns (uint) {\n    return uint(activeCover[assetId].totalActiveCoverInAsset);\n  }\n\n  // Returns true if the product exists and the pool is authorized to have the product\n  function isPoolAllowed(uint productId, uint poolId) public view returns (bool) {\n\n      uint poolCount = allowedPools[productId].length;\n\n      // If no pools are specified, every pool is allowed\n      if (poolCount == 0) {\n        return true;\n      }\n\n      for (uint i = 0; i < poolCount; i++) {\n        if (allowedPools[productId][i] == poolId) {\n          return true;\n        }\n      }\n\n      // Product has allow list and pool is not in it\n      return false;\n  }\n\n  function requirePoolIsAllowed(uint[] calldata productIds, uint poolId) external view {\n    for (uint i = 0; i < productIds.length; i++) {\n      if (!isPoolAllowed(productIds[i], poolId) ) {\n        revert PoolNotAllowedForThisProduct(productIds[i]);\n      }\n    }\n  }\n\n  function globalCapacityRatio() external pure returns (uint) {\n    return GLOBAL_CAPACITY_RATIO;\n  }\n\n  function globalRewardsRatio() external pure returns (uint) {\n    return GLOBAL_REWARDS_RATIO;\n  }\n\n  function getPriceAndCapacityRatios(uint[] calldata productIds) external view returns (\n    uint _globalCapacityRatio,\n    uint _globalMinPriceRatio,\n    uint[] memory _initialPrices,\n    uint[] memory _capacityReductionRatios\n  ) {\n    _globalMinPriceRatio = GLOBAL_MIN_PRICE_RATIO;\n    _globalCapacityRatio = GLOBAL_CAPACITY_RATIO;\n    _capacityReductionRatios = new uint[](productIds.length);\n    _initialPrices = new uint[](productIds.length);\n\n    for (uint i = 0; i < productIds.length; i++) {\n      uint productId = productIds[i];\n\n      if (productId >= _products.length) {\n        revert ProductDoesntExist();\n      }\n\n      _initialPrices[i] = uint(_products[productId].initialPriceRatio);\n      _capacityReductionRatios[i] = uint(_products[productId].capacityReductionRatio);\n    }\n  }\n\n  function isCoverAssetSupported(uint assetId, uint productCoverAssetsBitmap) internal view returns (bool) {\n\n    if (\n      // product does not use default cover assets\n      productCoverAssetsBitmap != 0 &&\n      // asset id is not in the product's cover assets bitmap\n      ((1 << assetId) & productCoverAssetsBitmap == 0)\n    ) {\n      return false;\n    }\n\n    Asset memory asset = pool().getAsset(assetId);\n\n    return asset.isCoverAsset && !asset.isAbandoned;\n  }\n\n  /* ========== DEPENDENCIES ========== */\n\n  function pool() internal view returns (IPool) {\n    return IPool(internalContracts[uint(ID.P1)]);\n  }\n\n  function tokenController() internal view returns (ITokenController) {\n    return ITokenController(internalContracts[uint(ID.TC)]);\n  }\n\n  function memberRoles() internal view returns (IMemberRoles) {\n    return IMemberRoles(internalContracts[uint(ID.MR)]);\n  }\n\n  function stakingProducts() internal view returns (IStakingProducts) {\n    return IStakingProducts(getInternalContractAddress(ID.SP));\n  }\n\n  function changeDependentContractAddress() external override {\n    internalContracts[uint(ID.P1)] = master.getLatestAddress(\"P1\");\n    internalContracts[uint(ID.TC)] = master.getLatestAddress(\"TC\");\n    internalContracts[uint(ID.MR)] = master.getLatestAddress(\"MR\");\n    internalContracts[uint(ID.SP)] = master.getLatestAddress(\"SP\");\n  }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}