creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts/interfaces/IERC20Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/extensions/IERC20Metadata.sol\";\n"
      },
      "@openzeppelin/contracts/interfaces/IERC721Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC721/extensions/IERC721Metadata.sol\";\n"
      },
      "@openzeppelin/contracts/proxy/Proxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n    /**\n     * @dev Delegates the current call to `implementation`.\n     *\n     * This function does not return to its internal call site, it will return directly to the external caller.\n     */\n    function _delegate(address implementation) internal virtual {\n        assembly {\n            // Copy msg.data. We take full control of memory in this inline assembly\n            // block because it will not return to Solidity code. We overwrite the\n            // Solidity scratch pad at memory position 0.\n            calldatacopy(0, 0, calldatasize())\n\n            // Call the implementation.\n            // out and outsize are 0 because we don't know the size yet.\n            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n            // Copy the returned data.\n            returndatacopy(0, 0, returndatasize())\n\n            switch result\n            // delegatecall returns 0 on error.\n            case 0 {\n                revert(0, returndatasize())\n            }\n            default {\n                return(0, returndatasize())\n            }\n        }\n    }\n\n    /**\n     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n     * and {_fallback} should delegate.\n     */\n    function _implementation() internal view virtual returns (address);\n\n    /**\n     * @dev Delegates the current call to the address returned by `_implementation()`.\n     *\n     * This function does not return to its internal call site, it will return directly to the external caller.\n     */\n    function _fallback() internal virtual {\n        _beforeFallback();\n        _delegate(_implementation());\n    }\n\n    /**\n     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n     * function in the contract matches the call data.\n     */\n    fallback() external payable virtual {\n        _fallback();\n    }\n\n    /**\n     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n     * is empty.\n     */\n    receive() external payable virtual {\n        _fallback();\n    }\n\n    /**\n     * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n     * call, or as part of the Solidity `fallback` or `receive` functions.\n     *\n     * If overridden should call `super._beforeFallback()`.\n     */\n    function _beforeFallback() internal virtual {}\n}\n"
      },
      "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (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        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\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    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == _ENTERED;\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/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/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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(address from, address to, uint256 amount) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/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    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) 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(IERC20 token, address spender, uint256 value) 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    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n     * Revert on invalid signature.\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        require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation 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     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\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 cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return\n            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n    /**\n     * @dev Returns the token collection name.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the token collection symbol.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n     */\n    function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC721/IERC721.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {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(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n     * understand this adds an external call which potentially creates a reentrancy vulnerability.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the 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/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\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://consensys.net/diligence/blog/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.8.0/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 functionCallWithValue(target, data, 0, \"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(address target, bytes memory data, uint256 value) 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        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, 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        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, 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        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or 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            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\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"
      },
      "@openzeppelin/contracts/utils/Create2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Create2.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.\n * `CREATE2` can be used to compute in advance the address where a smart\n * contract will be deployed, which allows for interesting new mechanisms known\n * as 'counterfactual interactions'.\n *\n * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more\n * information.\n */\nlibrary Create2 {\n    /**\n     * @dev Deploys a contract using `CREATE2`. The address where the contract\n     * will be deployed can be known in advance via {computeAddress}.\n     *\n     * The bytecode for a contract can be obtained from Solidity with\n     * `type(contractName).creationCode`.\n     *\n     * Requirements:\n     *\n     * - `bytecode` must not be empty.\n     * - `salt` must have not been used for `bytecode` already.\n     * - the factory must have a balance of at least `amount`.\n     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.\n     */\n    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {\n        require(address(this).balance >= amount, \"Create2: insufficient balance\");\n        require(bytecode.length != 0, \"Create2: bytecode length is zero\");\n        /// @solidity memory-safe-assembly\n        assembly {\n            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)\n        }\n        require(addr != address(0), \"Create2: Failed on deploy\");\n    }\n\n    /**\n     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the\n     * `bytecodeHash` or `salt` will result in a new destination address.\n     */\n    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {\n        return computeAddress(salt, bytecodeHash, address(this));\n    }\n\n    /**\n     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n     */\n    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let ptr := mload(0x40) // Get free memory pointer\n\n            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |\n            // |-------------------|---------------------------------------------------------------------------|\n            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |\n            // | salt              |                                      BBBBBBBBBBBBB...BB                   |\n            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |\n            // | 0xFF              |            FF                                                             |\n            // |-------------------|---------------------------------------------------------------------------|\n            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |\n            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |\n\n            mstore(add(ptr, 0x40), bytecodeHash)\n            mstore(add(ptr, 0x20), salt)\n            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes\n            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff\n            mstore8(start, 0xff)\n            addr := keccak256(start, 85)\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/introspection/ERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"
      },
      "@openzeppelin/contracts/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"
      },
      "@openzeppelin/contracts/utils/math/Math.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Down, // Toward negative infinity\n        Up, // Toward infinity\n        Zero // Toward zero\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds up instead\n     * of rounding down.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n     * with further edits by Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            require(denominator > prod1, \"Math: mulDiv overflow\");\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n            // See https://cs.stackexchange.com/q/138556/92363.\n\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/math/SafeCast.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 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 *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\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     * _Available since v4.7._\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        require(value <= type(uint248).max, \"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     * _Available since v4.7._\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        require(value <= type(uint240).max, \"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     * _Available since v4.7._\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        require(value <= type(uint232).max, \"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     * _Available since v4.2._\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        require(value <= type(uint224).max, \"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     * _Available since v4.7._\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        require(value <= type(uint216).max, \"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     * _Available since v4.7._\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        require(value <= type(uint208).max, \"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     * _Available since v4.7._\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        require(value <= type(uint200).max, \"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     * _Available since v4.7._\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        require(value <= type(uint192).max, \"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     * _Available since v4.7._\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        require(value <= type(uint184).max, \"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     * _Available since v4.7._\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        require(value <= type(uint176).max, \"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     * _Available since v4.7._\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        require(value <= type(uint168).max, \"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     * _Available since v4.7._\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        require(value <= type(uint160).max, \"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     * _Available since v4.7._\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        require(value <= type(uint152).max, \"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     * _Available since v4.7._\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        require(value <= type(uint144).max, \"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     * _Available since v4.7._\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        require(value <= type(uint136).max, \"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     * _Available since v2.5._\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        require(value <= type(uint128).max, \"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     * _Available since v4.7._\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        require(value <= type(uint120).max, \"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     * _Available since v4.7._\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        require(value <= type(uint112).max, \"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     * _Available since v4.7._\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        require(value <= type(uint104).max, \"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 `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        require(value <= type(uint96).max, \"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 `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        require(value <= type(uint88).max, \"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 `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n        return uint72(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     * _Available since v2.5._\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        require(value <= type(uint64).max, \"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     * _Available since v4.7._\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        require(value <= type(uint56).max, \"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     * _Available since v4.7._\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        require(value <= type(uint48).max, \"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     * _Available since v4.7._\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        require(value <= type(uint40).max, \"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     * _Available since v2.5._\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        require(value <= type(uint32).max, \"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     * _Available since v4.7._\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        require(value <= type(uint24).max, \"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     * _Available since v2.5._\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        require(value <= type(uint16).max, \"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     * _Available since v2.5._\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     *\n     * _Available since v3.0._\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        require(value >= 0, \"SafeCast: value must be positive\");\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     *\n     * _Available since v3.0._\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/math/SignedMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // must be unchecked in order to support `n = type(int256).min`\n            return uint256(n >= 0 ? n : -n);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Multicall.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Multicall.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./Address.sol\";\n\n/**\n * @dev Provides a function to batch together multiple calls in a single external call.\n *\n * _Available since v4.1._\n */\nabstract contract Multicall {\n    /**\n     * @dev Receives and executes a batch of function calls on this contract.\n     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n     */\n    function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {\n        results = new bytes[](data.length);\n        for (uint256 i = 0; i < data.length; i++) {\n            results[i] = Address.functionDelegateCall(address(this), data[i]);\n        }\n        return results;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Strings.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\nimport \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            /// @solidity memory-safe-assembly\n            assembly {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                /// @solidity memory-safe-assembly\n                assembly {\n                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toString(int256 value) internal pure returns (string memory) {\n        return string(abi.encodePacked(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value))));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/structs/EnumerableSet.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping(bytes32 => uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value's index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (lastIndex != toDeleteIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the last value to the index where the value to delete is\n                set._values[toDeleteIndex] = lastValue;\n                // Update the index for the moved value\n                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"
      },
      "contracts/BorrowLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport \"./Pool.sol\";\nimport \"./LoanReceipt.sol\";\nimport \"./LiquidityLogic.sol\";\n\nimport \"./interfaces/IPool.sol\";\nimport \"./integrations/DelegateCash/IDelegateRegistryV1.sol\";\nimport \"./integrations/DelegateCash/IDelegateRegistryV2.sol\";\n\n/**\n * @title Borrow Logic\n * @author MetaStreet Labs\n */\nlibrary BorrowLogic {\n    using SafeCast for uint256;\n    using LiquidityLogic for LiquidityLogic.Liquidity;\n\n    /**************************************************************************/\n    /* Constants */\n    /**************************************************************************/\n\n    /**\n     * @notice Borrow options tag size in bytes\n     */\n    uint256 internal constant BORROW_OPTIONS_TAG_SIZE = 2;\n\n    /**\n     * @notice Borrow options length size in bytes\n     */\n    uint256 internal constant BORROW_OPTIONS_LENGTH_SIZE = 2;\n\n    /**************************************************************************/\n    /* Helpers */\n    /**************************************************************************/\n\n    /**\n     * @notice Helper function to extract specified option tag from options\n     * data\n     *\n     * @dev Options are encoded as:\n     *   2 byte uint16 tag\n     *   2 byte uint16 length\n     *   n byte bytes  data\n     * The first matching tag is returned.\n     *\n     * @param options Encoded options\n     * @param tag Tag to find\n     * @return Options data\n     */\n    function _getOptionsData(bytes calldata options, Pool.BorrowOptions tag) internal pure returns (bytes calldata) {\n        /* Scan the options for the tag */\n        for (uint256 offsetTag; offsetTag < options.length; ) {\n            /* Compute offsets with for tag length and data */\n            uint256 offsetLength = offsetTag + BORROW_OPTIONS_TAG_SIZE;\n            uint256 offsetData = offsetTag + BORROW_OPTIONS_TAG_SIZE + BORROW_OPTIONS_LENGTH_SIZE;\n\n            /* The tag is in the first 2 bytes of each options item */\n            uint256 currentTag = uint16(bytes2(options[offsetTag:offsetLength]));\n\n            /* The length of the options data is in the second 2 bytes of each options item, after the tag */\n            uint256 dataLength = uint16(bytes2(options[offsetLength:offsetData]));\n\n            /* Return the offset and length if the tag is found */\n            if (currentTag == uint256(tag)) {\n                return options[offsetData:offsetData + dataLength];\n            }\n\n            /* Increment to next options item */\n            offsetTag = offsetData + dataLength;\n        }\n\n        /* Return empty slice if no tag is found */\n        return options[0:0];\n    }\n\n    /**\n     * @notice Helper function that calls delegate.cash registry to delegate token\n     *\n     * @param delegations Delegate storage\n     * @param collateralToken Collateral token\n     * @param collateralTokenId Collateral token ID\n     * @param delegateRegistryV1 Delegate registry v1 address\n     * @param delegateRegistryV2 Delegate registry v2 address\n     * @param options Options data\n     */\n    function _optionDelegateCash(\n        Pool.DelegateStorage storage delegations,\n        address collateralToken,\n        uint256 collateralTokenId,\n        address delegateRegistryV1,\n        address delegateRegistryV2,\n        bytes calldata options\n    ) internal {\n        /* Find delegate.cash v2 tagged data in options */\n        bytes calldata delegateDataV2 = _getOptionsData(options, Pool.BorrowOptions.DelegateCashV2);\n\n        if (delegateDataV2.length != 0) {\n            if (delegateRegistryV2 == address(0)) revert IPool.InvalidBorrowOptions();\n            if (delegateDataV2.length != 20) revert IPool.InvalidBorrowOptions();\n\n            /* Store delegate in mapping */\n            delegations.delegates[collateralToken][collateralTokenId] = Pool.Delegate({\n                version: Pool.DelegateVersion.DelegateCashV2,\n                to: address(uint160(bytes20(delegateDataV2)))\n            });\n\n            /* Delegate token */\n            IDelegateRegistryV2(delegateRegistryV2).delegateERC721(\n                address(uint160(bytes20(delegateDataV2))),\n                collateralToken,\n                collateralTokenId,\n                \"\",\n                true\n            );\n\n            /* Return if found, skip additional search */\n            return;\n        }\n\n        /* Find delegate.cash v1 tagged data in options, if v2 data is empty */\n        bytes calldata delegateDataV1 = _getOptionsData(options, Pool.BorrowOptions.DelegateCashV1);\n\n        if (delegateDataV1.length != 0) {\n            if (delegateRegistryV1 == address(0)) revert IPool.InvalidBorrowOptions();\n            if (delegateDataV1.length != 20) revert IPool.InvalidBorrowOptions();\n\n            /* Store delegate in mapping */\n            delegations.delegates[collateralToken][collateralTokenId] = Pool.Delegate({\n                version: Pool.DelegateVersion.DelegateCashV1,\n                to: address(uint160(bytes20(delegateDataV1)))\n            });\n\n            /* Delegate token */\n            IDelegateRegistryV1(delegateRegistryV1).delegateForToken(\n                address(uint160(bytes20(delegateDataV1))),\n                collateralToken,\n                collateralTokenId,\n                true\n            );\n        }\n    }\n\n    /**\n     * @notice Helper function to revoke token delegate\n     *\n     * @param delegations Delegate storage\n     * @param collateralToken Contract address of token that delegation is being removed from\n     * @param collateralTokenId Token id of token that delegation is being removed from\n     * @param delegateRegistryV1 Delegate registry v1 address\n     * @param delegateRegistryV2 Delegate registry v2 address\n     */\n    function _revokeDelegates(\n        Pool.DelegateStorage storage delegations,\n        address collateralToken,\n        uint256 collateralTokenId,\n        address delegateRegistryV1,\n        address delegateRegistryV2\n    ) internal {\n        Pool.Delegate memory delegate = delegations.delegates[collateralToken][collateralTokenId];\n\n        if (delegate.version == Pool.DelegateVersion.None) {\n            return;\n        } else if (delegate.version == Pool.DelegateVersion.DelegateCashV2) {\n            IDelegateRegistryV2(delegateRegistryV2).delegateERC721(\n                delegate.to,\n                collateralToken,\n                collateralTokenId,\n                \"\",\n                false\n            );\n        } else if (delegate.version == Pool.DelegateVersion.DelegateCashV1) {\n            IDelegateRegistryV1(delegateRegistryV1).delegateForToken(\n                delegate.to,\n                collateralToken,\n                collateralTokenId,\n                false\n            );\n        }\n\n        /* Remove delegate from mapping */\n        delete delegations.delegates[collateralToken][collateralTokenId];\n    }\n\n    /**\n     * @dev Helper function to calculated prorated repayment\n     * @param loanReceipt Decoded loan receipt\n     * @return repayment amount in currency tokens\n     * @return proration based on elapsed duration\n     */\n    function _prorateRepayment(\n        LoanReceipt.LoanReceiptV2 memory loanReceipt\n    ) internal view returns (uint256 repayment, uint256 proration) {\n        /* Minimum of proration and 1.0 */\n        proration = Math.min(\n            ((block.timestamp - (loanReceipt.maturity - loanReceipt.duration)) * LiquidityLogic.FIXED_POINT_SCALE) /\n                loanReceipt.duration,\n            LiquidityLogic.FIXED_POINT_SCALE\n        );\n\n        /* Compute repayment using prorated interest */\n        repayment =\n            loanReceipt.principal +\n            (((loanReceipt.repayment - loanReceipt.principal) * proration) / LiquidityLogic.FIXED_POINT_SCALE);\n    }\n\n    /**\n     * @dev Helper function to decode a loan receipt\n     * @param loanReceipt Loan receipt\n     * @return Decoded loan receipt\n     */\n    function _decodeLoanReceipt(bytes calldata loanReceipt) external pure returns (LoanReceipt.LoanReceiptV2 memory) {\n        return LoanReceipt.decode(loanReceipt);\n    }\n\n    /**\n     * @dev Helper function to handle borrow accounting\n     * @param self Pool storage\n     * @param principal Principal amount in currency tokens\n     * @param duration Duration in seconds\n     * @param collateralToken Collateral token address\n     * @param collateralTokenId Collateral token ID\n     * @param repayment Repayment amount in currency tokens\n     * @param maxRepayment Maximum repayment amount in currency tokens\n     * @param adminFee Admin fee\n     * @param nodes Liquidity nodes\n     * @param count Liquidity nodes count\n     * @param collateralWrapperContext Collateral wrapper context data\n     * @return Encoded loan receipt, loan receipt hash\n     */\n    function _borrow(\n        Pool.PoolStorage storage self,\n        uint256 principal,\n        uint64 duration,\n        address collateralToken,\n        uint256 collateralTokenId,\n        uint256 repayment,\n        uint256 maxRepayment,\n        uint256 adminFee,\n        LiquidityLogic.NodeSource[] memory nodes,\n        uint16 count,\n        bytes memory collateralWrapperContext\n    ) external returns (bytes memory, bytes32) {\n        /* Validate principal is non-zero */\n        if (principal == 0) revert IPool.InvalidParameters();\n\n        /* Validate duration is non-zero */\n        if (duration == 0) revert IPool.UnsupportedLoanDuration();\n\n        /* Validate repayment */\n        if (repayment > maxRepayment) revert IPool.RepaymentTooHigh();\n\n        /* Build the loan receipt */\n        LoanReceipt.LoanReceiptV2 memory receipt = LoanReceipt.LoanReceiptV2({\n            version: 2,\n            principal: principal,\n            repayment: repayment,\n            adminFee: adminFee,\n            borrower: msg.sender,\n            maturity: (block.timestamp + duration).toUint64(),\n            duration: duration,\n            collateralToken: collateralToken,\n            collateralTokenId: collateralTokenId,\n            collateralWrapperContextLen: collateralWrapperContext.length.toUint16(),\n            collateralWrapperContext: collateralWrapperContext,\n            nodeReceipts: new LoanReceipt.NodeReceipt[](count)\n        });\n\n        /* Use liquidity nodes */\n        for (uint256 i; i < count; i++) {\n            /* Use node */\n            self.liquidity.use(nodes[i].tick, nodes[i].used, nodes[i].pending, duration);\n\n            /* Construct node receipt */\n            receipt.nodeReceipts[i] = LoanReceipt.NodeReceipt({\n                tick: nodes[i].tick,\n                used: nodes[i].used,\n                pending: nodes[i].pending\n            });\n        }\n\n        /* Encode and hash the loan receipt */\n        bytes memory encodedLoanReceipt = LoanReceipt.encode(receipt);\n        bytes32 loanReceiptHash = LoanReceipt.hash(encodedLoanReceipt);\n\n        /* Validate no loan receipt hash collision */\n        if (self.loans[loanReceiptHash] != Pool.LoanStatus.Uninitialized) revert IPool.InvalidLoanReceipt();\n\n        /* Store loan status */\n        self.loans[loanReceiptHash] = Pool.LoanStatus.Active;\n\n        return (encodedLoanReceipt, loanReceiptHash);\n    }\n\n    /**\n     * @dev Helper function to handle repay accounting\n     * @param self Pool storage\n     * @param encodedLoanReceipt Encoded loan receipt\n     * @return Repayment amount in currency tokens, decoded loan receipt, loan\n     * receipt hash\n     */\n    function _repay(\n        Pool.PoolStorage storage self,\n        bytes calldata encodedLoanReceipt\n    ) external returns (uint256, LoanReceipt.LoanReceiptV2 memory, bytes32) {\n        /* Compute loan receipt hash */\n        bytes32 loanReceiptHash = LoanReceipt.hash(encodedLoanReceipt);\n\n        /* Validate loan receipt */\n        if (self.loans[loanReceiptHash] != Pool.LoanStatus.Active) revert IPool.InvalidLoanReceipt();\n\n        /* Decode loan receipt */\n        LoanReceipt.LoanReceiptV2 memory loanReceipt = LoanReceipt.decode(encodedLoanReceipt);\n\n        /* Validate borrow and repay is not in same block */\n        if (loanReceipt.maturity - loanReceipt.duration == block.timestamp) revert IPool.InvalidLoanReceipt();\n\n        /* Validate caller is borrower */\n        if (msg.sender != loanReceipt.borrower) revert IPool.InvalidCaller();\n\n        /* Compute proration and repayment using prorated interest */\n        (uint256 repayment, uint256 proration) = _prorateRepayment(loanReceipt);\n\n        /* Compute elapsed time since loan origination */\n        uint64 elapsed = uint64(block.timestamp + loanReceipt.duration - loanReceipt.maturity);\n\n        /* Restore liquidity nodes */\n        for (uint256 i; i < loanReceipt.nodeReceipts.length; i++) {\n            /* Restore node */\n            self.liquidity.restore(\n                loanReceipt.nodeReceipts[i].tick,\n                loanReceipt.nodeReceipts[i].used,\n                loanReceipt.nodeReceipts[i].pending,\n                loanReceipt.nodeReceipts[i].used +\n                    uint128(\n                        ((loanReceipt.nodeReceipts[i].pending - loanReceipt.nodeReceipts[i].used) * proration) /\n                            LiquidityLogic.FIXED_POINT_SCALE\n                    ),\n                loanReceipt.duration,\n                elapsed\n            );\n        }\n\n        /* Update admin fee total balance with prorated admin fee */\n        self.adminFeeBalance += (loanReceipt.adminFee * proration) / LiquidityLogic.FIXED_POINT_SCALE;\n\n        /* Mark loan status repaid */\n        self.loans[loanReceiptHash] = Pool.LoanStatus.Repaid;\n\n        return (repayment, loanReceipt, loanReceiptHash);\n    }\n\n    /**\n     * @dev Helper function to handle liquidate accounting\n     * @param self Pool storage\n     * @param encodedLoanReceipt Encoded loan receipt\n     * @return Decoded loan receipt, loan receipt hash\n     */\n    function _liquidate(\n        Pool.PoolStorage storage self,\n        bytes calldata encodedLoanReceipt\n    ) external returns (LoanReceipt.LoanReceiptV2 memory, bytes32) {\n        /* Compute loan receipt hash */\n        bytes32 loanReceiptHash = LoanReceipt.hash(encodedLoanReceipt);\n\n        /* Validate loan status is active */\n        if (self.loans[loanReceiptHash] != Pool.LoanStatus.Active) revert IPool.InvalidLoanReceipt();\n\n        /* Decode loan receipt */\n        LoanReceipt.LoanReceiptV2 memory loanReceipt = LoanReceipt.decode(encodedLoanReceipt);\n\n        /* Validate loan is expired */\n        if (block.timestamp <= loanReceipt.maturity) revert IPool.LoanNotExpired();\n\n        /* Mark loan status liquidated */\n        self.loans[loanReceiptHash] = Pool.LoanStatus.Liquidated;\n\n        return (loanReceipt, loanReceiptHash);\n    }\n\n    /**\n     * @dev Helper function to handle collateral liquidation accounting\n     * @param self Pool storage\n     * @param encodedLoanReceipt Encoded loan receipt\n     * @param proceeds Proceeds amount in currency tokens\n     * @return Borrower surplus, decoded loan receipt, loan receipt hash\n     */\n    function _onCollateralLiquidated(\n        Pool.PoolStorage storage self,\n        bytes calldata encodedLoanReceipt,\n        uint256 proceeds\n    ) external returns (uint256, LoanReceipt.LoanReceiptV2 memory, bytes32) {\n        /* Compute loan receipt hash */\n        bytes32 loanReceiptHash = LoanReceipt.hash(encodedLoanReceipt);\n\n        /* Validate loan status is liquidated */\n        if (self.loans[loanReceiptHash] != Pool.LoanStatus.Liquidated) revert IPool.InvalidLoanReceipt();\n\n        /* Decode loan receipt */\n        LoanReceipt.LoanReceiptV2 memory loanReceipt = LoanReceipt.decode(encodedLoanReceipt);\n\n        /* Compute borrower's share of liquidation surplus */\n        uint256 borrowerSurplus = proceeds > loanReceipt.repayment ? proceeds - loanReceipt.repayment : 0;\n\n        /* Compute elapsed time since loan origination */\n        uint64 elapsed = uint64(block.timestamp + loanReceipt.duration - loanReceipt.maturity);\n\n        /* Restore liquidity nodes */\n        uint256 proceedsRemaining = proceeds - borrowerSurplus;\n        uint256 lastIndex = loanReceipt.nodeReceipts.length - 1;\n        for (uint256 i; i < loanReceipt.nodeReceipts.length; i++) {\n            /* Compute amount to restore depending on whether there is a surplus */\n            uint256 restored = (i == lastIndex)\n                ? proceedsRemaining\n                : Math.min(loanReceipt.nodeReceipts[i].pending, proceedsRemaining);\n\n            /* Restore node */\n            self.liquidity.restore(\n                loanReceipt.nodeReceipts[i].tick,\n                loanReceipt.nodeReceipts[i].used,\n                loanReceipt.nodeReceipts[i].pending,\n                restored.toUint128(),\n                loanReceipt.duration,\n                elapsed\n            );\n\n            /* Update proceeds remaining */\n            proceedsRemaining -= restored;\n        }\n\n        /* Mark loan status collateral liquidated */\n        self.loans[loanReceiptHash] = Pool.LoanStatus.CollateralLiquidated;\n\n        return (borrowerSurplus, loanReceipt, loanReceiptHash);\n    }\n}\n"
      },
      "contracts/configurations/WeightedRateSetCollectionPool.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport \"../Pool.sol\";\nimport \"../rates/WeightedInterestRateModel.sol\";\nimport \"../filters/SetCollectionCollateralFilter.sol\";\nimport \"../tokenization/ERC20DepositToken.sol\";\n\n/**\n * @title Pool Configuration with a Weighted Interest Rate Model and Set Collection\n * Collateral Filter\n * @author MetaStreet Labs\n */\ncontract WeightedRateSetCollectionPool is\n    Pool,\n    WeightedInterestRateModel,\n    SetCollectionCollateralFilter,\n    ERC20DepositToken\n{\n    /**************************************************************************/\n    /* Constructor */\n    /**************************************************************************/\n\n    /**\n     * @notice Pool constructor\n     * @param collateralLiquidator Collateral liquidator\n     * @param delegateRegistryV1 Delegation registry v1 contract\n     * @param delegateRegistryV2 Delegation registry v2 contract\n     * @param erc20DepositTokenImplementation ERC20 Deposit Token implementation address\n     * @param collateralWrappers Collateral wrappers\n     */\n    constructor(\n        address collateralLiquidator,\n        address delegateRegistryV1,\n        address delegateRegistryV2,\n        address erc20DepositTokenImplementation,\n        address[] memory collateralWrappers\n    )\n        Pool(collateralLiquidator, delegateRegistryV1, delegateRegistryV2, collateralWrappers)\n        WeightedInterestRateModel()\n        ERC20DepositToken(erc20DepositTokenImplementation)\n    {\n        /* Disable initialization of implementation contract */\n        _storage.currencyToken = IERC20(address(1));\n    }\n\n    /**************************************************************************/\n    /* Initializer */\n    /**************************************************************************/\n\n    /**\n     * @notice Initializer\n     * @dev Fee-on-transfer currency tokens are not supported\n     * @param params ABI-encoded parameters\n     */\n    function initialize(bytes memory params) external {\n        require(address(_storage.currencyToken) == address(0), \"Already initialized\");\n\n        /* Decode parameters */\n        (\n            address collateralToken_,\n            uint256[] memory tokenIds_,\n            address currencyToken_,\n            uint64[] memory durations_,\n            uint64[] memory rates_\n        ) = abi.decode(params, (address, uint256[], address, uint64[], uint64[]));\n\n        /* Initialize Collateral Filter */\n        SetCollectionCollateralFilter._initialize(collateralToken_, tokenIds_);\n\n        /* Initialize Pool */\n        Pool._initialize(currencyToken_, durations_, rates_);\n    }\n\n    /**************************************************************************/\n    /* Name */\n    /**************************************************************************/\n\n    /**\n     * @inheritdoc Pool\n     */\n    function IMPLEMENTATION_NAME() external pure override returns (string memory) {\n        return \"WeightedRateSetCollectionPool\";\n    }\n}\n"
      },
      "contracts/DepositLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"./Pool.sol\";\nimport \"./Tick.sol\";\nimport \"./LiquidityLogic.sol\";\n\nimport \"./interfaces/IPool.sol\";\n\n/**\n * @title Deposit Logic\n * @author MetaStreet Labs\n */\nlibrary DepositLogic {\n    using LiquidityLogic for LiquidityLogic.Liquidity;\n\n    /**\n     * @dev Helper function to handle deposit accounting\n     * @param self Pool storage\n     * @param tick Tick\n     * @param amount Amount\n     * @param minShares Minimum shares\n     * @return Deposit shares\n     */\n    function _deposit(\n        Pool.PoolStorage storage self,\n        uint128 tick,\n        uint128 amount,\n        uint128 minShares\n    ) external returns (uint128) {\n        /* Validate tick */\n        Tick.validate(tick, 0, 0, self.durations.length - 1, 0, self.rates.length - 1);\n\n        /* Deposit into liquidity node */\n        uint128 shares = self.liquidity.deposit(tick, amount);\n\n        /* Validate shares received is sufficient */\n        if (shares == 0 || shares < minShares) revert IPool.InsufficientShares();\n\n        /* Add to deposit */\n        self.deposits[msg.sender][tick].shares += shares;\n\n        return shares;\n    }\n\n    /**\n     * @dev Helper function to handle redeem accounting\n     * @param self Pool storage\n     * @param tick Tick\n     * @param shares Shares\n     * @return redemptionId Redemption ID\n     */\n    function _redeem(Pool.PoolStorage storage self, uint128 tick, uint128 shares) external returns (uint128) {\n        /* Look up deposit */\n        Pool.Deposit storage dep = self.deposits[msg.sender][tick];\n\n        /* Assign redemption ID */\n        uint128 redemptionId = dep.redemptionId++;\n\n        /* Look up redemption */\n        Pool.Redemption storage redemption = dep.redemptions[redemptionId];\n\n        /* Validate shares */\n        if (shares == 0 || shares > dep.shares) revert IPool.InsufficientShares();\n\n        /* Redeem shares in tick with liquidity manager */\n        (uint128 index, uint128 target) = self.liquidity.redeem(tick, shares);\n\n        /* Update deposit state */\n        redemption.pending = shares;\n        redemption.index = index;\n        redemption.target = target;\n\n        /* Decrement deposit shares */\n        dep.shares -= shares;\n\n        return redemptionId;\n    }\n\n    /**\n     * @dev Helper function to handle withdraw accounting\n     * @param self Pool storage\n     * @param tick Tick\n     * @param redemptionId Redemption ID\n     * @return Withdrawn shares and withdrawn amount\n     */\n    function _withdraw(\n        Pool.PoolStorage storage self,\n        uint128 tick,\n        uint128 redemptionId\n    ) external returns (uint128, uint128) {\n        /* Look up redemption */\n        Pool.Redemption storage redemption = self.deposits[msg.sender][tick].redemptions[redemptionId];\n\n        /* If no redemption is pending */\n        if (redemption.pending == 0) revert IPool.InvalidRedemptionStatus();\n\n        /* Look up redemption available */\n        (uint128 shares, uint128 amount, uint128 processedIndices, uint128 processedShares) = self\n            .liquidity\n            .redemptionAvailable(tick, redemption.pending, redemption.index, redemption.target);\n\n        /* If the entire redemption is ready */\n        if (shares == redemption.pending) {\n            delete self.deposits[msg.sender][tick].redemptions[redemptionId];\n        } else {\n            redemption.pending -= shares;\n            redemption.index += processedIndices;\n            redemption.target = (processedShares < redemption.target) ? redemption.target - processedShares : 0;\n        }\n\n        return (shares, amount);\n    }\n\n    /**\n     * @dev Helper function to handle transfer accounting\n     * @param self Pool storage\n     * @param from From\n     * @param to To\n     * @param tick Tick\n     * @param shares Shares\n     */\n    function _transfer(Pool.PoolStorage storage self, address from, address to, uint128 tick, uint128 shares) external {\n        if (self.deposits[from][tick].shares < shares) revert IPool.InsufficientShares();\n\n        self.deposits[from][tick].shares -= shares;\n        self.deposits[to][tick].shares += shares;\n    }\n\n    /**\n     * Helper function to look up redemption available\n     * @param self Pool storage\n     * @param account Account\n     * @param tick Tick\n     * @param redemptionId Redemption ID\n     * @return shares Amount of deposit shares available for redemption\n     * @return amount Amount of currency tokens available for withdrawal\n     * @return sharesAhead Amount of pending shares ahead in queue\n     */\n    function _redemptionAvailable(\n        Pool.PoolStorage storage self,\n        address account,\n        uint128 tick,\n        uint128 redemptionId\n    ) external view returns (uint256 shares, uint256 amount, uint256 sharesAhead) {\n        /* Look up redemption */\n        Pool.Redemption storage redemption = self.deposits[account][tick].redemptions[redemptionId];\n\n        /* If no redemption is pending */\n        if (redemption.pending == 0) return (0, 0, 0);\n\n        uint128 processedShares;\n        (shares, amount, , processedShares) = self.liquidity.redemptionAvailable(\n            tick,\n            redemption.pending,\n            redemption.index,\n            redemption.target\n        );\n\n        /* Compute pending shares ahead in queue */\n        sharesAhead = redemption.target > processedShares ? redemption.target - processedShares : 0;\n    }\n}\n"
      },
      "contracts/filters/CollateralFilter.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Collateral Filter API\n * @author MetaStreet Labs\n */\nabstract contract CollateralFilter {\n    /**************************************************************************/\n    /* Errors */\n    /**************************************************************************/\n\n    /**\n     * @notice Invalid parameters\n     */\n    error InvalidCollateralFilterParameters();\n\n    /**************************************************************************/\n    /* API */\n    /**************************************************************************/\n\n    /**\n     * @notice Get collateral filter name\n     * @return Collateral filter name\n     */\n    function COLLATERAL_FILTER_NAME() external view virtual returns (string memory);\n\n    /**\n     * @notice Get collateral filter version\n     * @return Collateral filter version\n     */\n    function COLLATERAL_FILTER_VERSION() external view virtual returns (string memory);\n\n    /**\n     * @notice Get collateral token\n     * @return Collateral token contract\n     */\n    function collateralToken() external view virtual returns (address);\n\n    /**\n     * @notice Get collateral tokens\n     * @return Collateral token contract\n     */\n    function collateralTokens() external view virtual returns (address[] memory);\n\n    /**\n     * Query if collateral token is supported\n     * @param token Collateral token contract\n     * @param tokenId Collateral Token ID\n     * @param index Collateral Token ID index\n     * @param context ABI-encoded context\n     * @return True if supported, otherwise false\n     */\n    function _collateralSupported(\n        address token,\n        uint256 tokenId,\n        uint256 index,\n        bytes calldata context\n    ) internal view virtual returns (bool);\n}\n"
      },
      "contracts/filters/SetCollectionCollateralFilter.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\nimport \"./CollateralFilter.sol\";\n\n/**\n * @title Set Collection Collateral Filter\n * @author MetaStreet Labs\n */\ncontract SetCollectionCollateralFilter is CollateralFilter {\n    using EnumerableSet for EnumerableSet.UintSet;\n\n    /**************************************************************************/\n    /* State */\n    /**************************************************************************/\n\n    /**\n     * @notice Supported token\n     */\n    address private _token;\n\n    /**\n     * @notice Set of supported token IDs\n     */\n    EnumerableSet.UintSet private _tokenIds;\n\n    /**\n     * @notice Requires migration boolean\n     */\n    bool private _requiresMigration;\n\n    /**************************************************************************/\n    /* Initializer */\n    /**************************************************************************/\n\n    /**\n     * @notice SetCollectionCollateralFilter initializer\n     */\n    function _initialize(address token, uint256[] memory tokenIds_) internal {\n        /* Validate root and node count */\n        if (tokenIds_.length == 0) revert InvalidCollateralFilterParameters();\n\n        /* Set supported token */\n        _token = token;\n\n        /* Add each token ID to set of token IDs */\n        for (uint256 i; i < tokenIds_.length; i++) {\n            _tokenIds.add(tokenIds_[i]);\n        }\n    }\n\n    /**************************************************************************/\n    /* Getters */\n    /**************************************************************************/\n\n    /**\n     * @inheritdoc CollateralFilter\n     */\n    function COLLATERAL_FILTER_NAME() external pure override returns (string memory) {\n        return \"SetCollectionCollateralFilter\";\n    }\n\n    /**\n     * @inheritdoc CollateralFilter\n     */\n    function COLLATERAL_FILTER_VERSION() external pure override returns (string memory) {\n        return \"1.0\";\n    }\n\n    /**\n     * @notice Get collateral token\n     * @return Collateral token contract\n     */\n    function collateralToken() external view override returns (address) {\n        return _token;\n    }\n\n    /**\n     * @inheritdoc CollateralFilter\n     */\n    function collateralTokens() external view override returns (address[] memory) {\n        address[] memory tokens = new address[](1);\n        tokens[0] = _token;\n\n        return tokens;\n    }\n\n    /**\n     * @notice Get collateral token IDs\n     * @return Collateral token IDs\n     */\n    function collateralTokenIds() external view returns (uint256[] memory) {\n        return _tokenIds.values();\n    }\n\n    /**************************************************************************/\n    /* Implementation */\n    /**************************************************************************/\n\n    /**\n     * @inheritdoc CollateralFilter\n     */\n    function _collateralSupported(\n        address token,\n        uint256 tokenId,\n        uint256,\n        bytes calldata\n    ) internal view override returns (bool) {\n        /* Validate token supported */\n        if (token != _token) return false;\n\n        /* Validate token ID is in set of token IDs */\n        return _tokenIds.contains(tokenId);\n    }\n\n    /**************************************************************************/\n    /* Migration */\n    /**************************************************************************/\n\n    /**\n     * @notice Set _requiresMigration, previously _initialized, to false\n     * @dev This function is to be removed after migration\n     */\n    function migrate() external {\n        require(_requiresMigration, \"Already migrated\");\n\n        _requiresMigration = false;\n    }\n}\n"
      },
      "contracts/integrations/DelegateCash/IDelegateRegistryV1.sol": {
        "content": "// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.19;\n\n/**\n * @title IDelegateRegistryV1\n *\n * @dev Subset of full interface\n */\ninterface IDelegateRegistryV1 {\n    /// @notice Delegation type\n    enum DelegationType {\n        NONE,\n        ALL,\n        CONTRACT,\n        TOKEN\n    }\n\n    /// @notice Info about a single delegation, used for onchain enumeration\n    struct DelegationInfo {\n        DelegationType type_;\n        address vault;\n        address delegate;\n        address contract_;\n        uint256 tokenId;\n    }\n\n    /// @notice Info about a single contract-level delegation\n    struct ContractDelegation {\n        address contract_;\n        address delegate;\n    }\n\n    /// @notice Info about a single token-level delegation\n    struct TokenDelegation {\n        address contract_;\n        uint256 tokenId;\n        address delegate;\n    }\n\n    /// @notice Emitted when a user delegates a specific token\n    event DelegateForToken(address vault, address delegate, address contract_, uint256 tokenId, bool value);\n\n    /**\n     * -----------  WRITE -----------\n     */\n\n    /**\n     * @notice Allow the delegate to act on your behalf for a specific token\n     * @param delegate The hotwallet to act on your behalf\n     * @param contract_ The address for the contract you're delegating\n     * @param tokenId The token id for the token you're delegating\n     * @param value Whether to enable or disable delegation for this address, true for setting and false for revoking\n     */\n    function delegateForToken(address delegate, address contract_, uint256 tokenId, bool value) external;\n\n    /**\n     * -----------  READ -----------\n     */\n\n    /**\n     * @notice Returns an array of contract-level delegates for a given vault's token\n     * @param vault The cold wallet who issued the delegation\n     * @param contract_ The address for the contract holding the token\n     * @param tokenId The token id for the token you're delegating\n     * @return addresses Array of contract-level delegates for a given vault's token\n     */\n    function getDelegatesForToken(\n        address vault,\n        address contract_,\n        uint256 tokenId\n    ) external view returns (address[] memory);\n\n    /**\n     * @notice Returns true if the address is delegated to act on the entire vault\n     * @param delegate The hotwallet to act on your behalf\n     * @param vault The cold wallet who issued the delegation\n     */\n    function checkDelegateForAll(address delegate, address vault) external view returns (bool);\n\n    /**\n     * @notice Returns true if the address is delegated to act on your behalf for a token contract or an entire vault\n     * @param delegate The hotwallet to act on your behalf\n     * @param contract_ The address for the contract you're delegating\n     * @param vault The cold wallet who issued the delegation\n     */\n    function checkDelegateForContract(address delegate, address vault, address contract_) external view returns (bool);\n\n    /**\n     * @notice Returns true if the address is delegated to act on your behalf for a specific token, the token's contract or an entire vault\n     * @param delegate The hotwallet to act on your behalf\n     * @param contract_ The address for the contract you're delegating\n     * @param tokenId The token id for the token you're delegating\n     * @param vault The cold wallet who issued the delegation\n     */\n    function checkDelegateForToken(\n        address delegate,\n        address vault,\n        address contract_,\n        uint256 tokenId\n    ) external view returns (bool);\n}\n"
      },
      "contracts/integrations/DelegateCash/IDelegateRegistryV2.sol": {
        "content": "// SPDX-License-Identifier: CC0-1.0\npragma solidity >=0.8.13;\n\n/**\n * @title IDelegateRegistryV2\n *\n * @dev Subset of full interface\n *\n * @author foobar (0xfoobar)\n */\ninterface IDelegateRegistryV2 {\n    /// @notice Delegation type, NONE is used when a delegation does not exist or is revoked\n    enum DelegationType {\n        NONE,\n        ALL,\n        CONTRACT,\n        ERC721,\n        ERC20,\n        ERC1155\n    }\n\n    /// @notice Struct for returning delegations\n    struct Delegation {\n        DelegationType type_;\n        address to;\n        address from;\n        bytes32 rights;\n        address contract_;\n        uint256 tokenId;\n        uint256 amount;\n    }\n\n    /// @notice Emitted when an address delegates or revokes rights for an ERC721 tokenId\n    event DelegateERC721(\n        address indexed from,\n        address indexed to,\n        address indexed contract_,\n        uint256 tokenId,\n        bytes32 rights,\n        bool enable\n    );\n\n    /**\n     * -----------  WRITE -----------\n     */\n\n    /**\n     * @notice Allow the delegate to act on behalf of `msg.sender` for a specific ERC721 token\n     * @param to The address to act as delegate\n     * @param contract_ The contract whose rights are being delegated\n     * @param tokenId The token id to delegate\n     * @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring to encompass all rights\n     * @param enable Whether to enable or disable this delegation, true delegates and false revokes\n     * @return delegationHash The unique identifier of the delegation\n     */\n    function delegateERC721(\n        address to,\n        address contract_,\n        uint256 tokenId,\n        bytes32 rights,\n        bool enable\n    ) external payable returns (bytes32 delegationHash);\n\n    /**\n     * @notice Check if `to` is a delegate of `from` for the specific `contract` and `tokenId`, the entire `contract_`, or the entire wallet\n     * @param to The delegated address to check\n     * @param contract_ The specific contract address being checked\n     * @param tokenId The token id for the token to delegating\n     * @param from The wallet that issued the delegation\n     * @param rights Specific rights to check for, pass the zero value to ignore subdelegations and check full delegations only\n     * @return valid Whether delegate is granted to act on from's behalf for entire wallet, that contract, or that specific tokenId\n     */\n    function checkDelegateForERC721(\n        address to,\n        address from,\n        address contract_,\n        uint256 tokenId,\n        bytes32 rights\n    ) external view returns (bool);\n\n    /**\n     * ----------- ENUMERATIONS -----------\n     */\n\n    /**\n     * @notice Returns all enabled delegations an address has given out\n     * @param from The address to retrieve delegations for\n     * @return delegations Array of Delegation structs\n     */\n    function getOutgoingDelegations(address from) external view returns (Delegation[] memory delegations);\n}\n"
      },
      "contracts/interfaces/ICollateralLiquidationReceiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Interface to a Collateral Liquidation Receiver\n */\ninterface ICollateralLiquidationReceiver {\n    /**\n     * @notice Callback on collateral liquidated\n     * @dev Pre-conditions: 1) proceeds were transferred, and 2) transferred amount >= proceeds\n     * @param liquidationContext Liquidation context\n     * @param proceeds Liquidation proceeds in currency tokens\n     */\n    function onCollateralLiquidated(bytes calldata liquidationContext, uint256 proceeds) external;\n}\n"
      },
      "contracts/interfaces/ICollateralLiquidator.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Interface to a Collateral Liquidator\n */\ninterface ICollateralLiquidator {\n    /**\n     * @notice Get collateral liquidator name\n     * @return Collateral liquidator name\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @notice Liquidate collateral\n     * @param currencyToken Currency token\n     * @param collateralToken Collateral token, either underlying token or collateral wrapper\n     * @param collateralTokenId Collateral token ID\n     * @param collateralWrapperContext Collateral wrapper context\n     * @param liquidationContext Liquidation callback context\n     */\n    function liquidate(\n        address currencyToken,\n        address collateralToken,\n        uint256 collateralTokenId,\n        bytes calldata collateralWrapperContext,\n        bytes calldata liquidationContext\n    ) external;\n}\n"
      },
      "contracts/interfaces/ICollateralWrapper.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Interface to a Collateral Wrapper\n */\ninterface ICollateralWrapper {\n    /**************************************************************************/\n    /* API */\n    /**************************************************************************/\n\n    /**\n     * @notice Get collateral wrapper name\n     * @return Collateral wrapper name\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @notice Enumerate wrapped collateral\n     * @param tokenId Collateral wrapper token ID\n     * @param context Implementation-specific context\n     * @return token Token address\n     * @return tokenIds List of unique token ids\n     */\n    function enumerate(\n        uint256 tokenId,\n        bytes calldata context\n    ) external view returns (address token, uint256[] memory tokenIds);\n\n    /**\n     * @notice Enumerate wrapped collateral with quantities of each token id\n     * @param tokenId Collateral wrapper token ID\n     * @param context Implementation-specific context\n     * @return token Token address\n     * @return tokenIds List of unique token ids\n     * @return quantities List of quantities of each token id\n     */\n    function enumerateWithQuantities(\n        uint256 tokenId,\n        bytes calldata context\n    ) external view returns (address token, uint256[] memory tokenIds, uint256[] memory quantities);\n\n    /**\n     * @notice Get total token count represented by wrapped collateral\n     * @param tokenId Collateral wrapper token ID\n     * @param context Implementation-specific context\n     * @return tokenCount Total token count\n     */\n    function count(uint256 tokenId, bytes calldata context) external view returns (uint256 tokenCount);\n\n    /*\n     * Transfer collateral calldata\n     * @param token Collateral token\n     * @param from From address\n     * @param to To address\n     * @param tokenId Collateral wrapper token ID\n     * @param quantity Quantity of token ID\n     * @return target Transfer target\n     * @return data Transfer calldata\n     */\n    function transferCalldata(\n        address token,\n        address from,\n        address to,\n        uint256 tokenId,\n        uint256 quantity\n    ) external returns (address target, bytes memory data);\n\n    /*\n     * Unwrap collateral\n     * @param tokenId Collateral wrapper token ID\n     * @param context Implementation-specific context\n     */\n    function unwrap(uint256 tokenId, bytes calldata context) external;\n}\n"
      },
      "contracts/interfaces/ILiquidity.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Interface to Liquidity state\n */\ninterface ILiquidity {\n    /**************************************************************************/\n    /* Errors */\n    /**************************************************************************/\n\n    /**\n     * @notice Insufficient liquidity\n     */\n    error InsufficientLiquidity();\n\n    /**\n     * @notice Inactive liquidity\n     */\n    error InactiveLiquidity();\n\n    /**\n     * @notice Insufficient tick spacing\n     */\n    error InsufficientTickSpacing();\n\n    /**************************************************************************/\n    /* Structures */\n    /**************************************************************************/\n\n    /**\n     * @notice Flattened liquidity node returned by getter\n     * @param tick Tick\n     * @param value Liquidity value\n     * @param shares Liquidity shares outstanding\n     * @param available Liquidity available\n     * @param pending Liquidity pending (with interest)\n     * @param redemptions Total pending redemptions\n     * @param prev Previous liquidity node\n     * @param next Next liquidity node\n     */\n    struct NodeInfo {\n        uint128 tick;\n        uint128 value;\n        uint128 shares;\n        uint128 available;\n        uint128 pending;\n        uint128 redemptions;\n        uint128 prev;\n        uint128 next;\n    }\n\n    /**\n     * @notice Accrual info returned by getter\n     * @param accrued Accrued interest\n     * @param rate Accrual rate\n     * @param timestamp Accrual timestamp\n     */\n    struct AccrualInfo {\n        uint128 accrued;\n        uint64 rate;\n        uint64 timestamp;\n    }\n\n    /**************************************************************************/\n    /* API */\n    /**************************************************************************/\n\n    /**\n     * Get liquidity nodes spanning [startTick, endTick] range\n     * @param startTick Start tick\n     * @param endTick End tick\n     * @return Liquidity nodes\n     */\n    function liquidityNodes(uint128 startTick, uint128 endTick) external view returns (NodeInfo[] memory);\n\n    /**\n     * Get liquidity node at tick\n     * @param tick Tick\n     * @return Liquidity node\n     */\n    function liquidityNode(uint128 tick) external view returns (NodeInfo memory);\n\n    /**\n     * Get liquidity node with accrual info at tick\n     * @param tick Tick\n     * @return Liquidity node, Accrual info\n     */\n    function liquidityNodeWithAccrual(uint128 tick) external view returns (NodeInfo memory, AccrualInfo memory);\n\n    /**\n     * @notice Get deposit share price\n     * @param tick Tick\n     * @return Deposit share price\n     */\n    function depositSharePrice(uint128 tick) external view returns (uint256);\n\n    /**\n     * @notice Get redemption share price\n     * @param tick Tick\n     * @return Redemption share price\n     */\n    function redemptionSharePrice(uint128 tick) external view returns (uint256);\n}\n"
      },
      "contracts/interfaces/IPool.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Interface to a Pool\n */\ninterface IPool {\n    /**************************************************************************/\n    /* Errors */\n    /**************************************************************************/\n\n    /**\n     * @notice Invalid caller\n     */\n    error InvalidCaller();\n\n    /**\n     * @notice Insufficient shares\n     */\n    error InsufficientShares();\n\n    /**\n     * @notice Invalid redemption status\n     */\n    error InvalidRedemptionStatus();\n\n    /**\n     * @notice Invalid loan receipt\n     */\n    error InvalidLoanReceipt();\n\n    /**\n     * @notice Invalid borrow options\n     */\n    error InvalidBorrowOptions();\n\n    /**\n     * @notice Unsupported collateral\n     * @param index Index of unsupported asset\n     */\n    error UnsupportedCollateral(uint256 index);\n\n    /**\n     * @notice Unsupported loan duration\n     */\n    error UnsupportedLoanDuration();\n\n    /**\n     * @notice Repayment too high\n     */\n    error RepaymentTooHigh();\n\n    /**\n     * @notice Loan not expired\n     */\n    error LoanNotExpired();\n\n    /**\n     * @notice Invalid parameters\n     */\n    error InvalidParameters();\n\n    /**************************************************************************/\n    /* Events */\n    /**************************************************************************/\n\n    /**\n     * @notice Emitted when currency is deposited\n     * @param account Account\n     * @param tick Tick\n     * @param amount Amount of currency tokens\n     * @param shares Amount of shares allocated\n     */\n    event Deposited(address indexed account, uint128 indexed tick, uint256 amount, uint256 shares);\n\n    /**\n     * @notice Emitted when deposit shares are redeemed\n     * @param account Account\n     * @param tick Tick\n     * @param redemptionId Redemption ID\n     * @param shares Amount of shares to be redeemed\n     */\n    event Redeemed(address indexed account, uint128 indexed tick, uint128 indexed redemptionId, uint256 shares);\n\n    /**\n     * @notice Emitted when redeemed currency tokens are withdrawn\n     * @param account Account\n     * @param tick Tick\n     * @param redemptionId Redemption ID\n     * @param shares Amount of shares redeemed\n     * @param amount Amount of currency tokens withdrawn\n     */\n    event Withdrawn(\n        address indexed account,\n        uint128 indexed tick,\n        uint128 indexed redemptionId,\n        uint256 shares,\n        uint256 amount\n    );\n\n    /**\n     * @notice Emitted when deposit shares are transferred\n     * @param from Source account\n     * @param to Destination account\n     * @param tick Tick\n     * @param shares Amount of shares transferred\n     */\n    event Transferred(address indexed from, address indexed to, uint128 indexed tick, uint256 shares);\n\n    /**\n     * @notice Emitted when a loan is originated\n     * @param loanReceiptHash Loan receipt hash\n     * @param loanReceipt Loan receipt\n     */\n    event LoanOriginated(bytes32 indexed loanReceiptHash, bytes loanReceipt);\n\n    /**\n     * @notice Emitted when a loan is repaid\n     * @param loanReceiptHash Loan receipt hash\n     * @param repayment Repayment amount in currency tokens\n     */\n    event LoanRepaid(bytes32 indexed loanReceiptHash, uint256 repayment);\n\n    /**\n     * @notice Emitted when a loan is liquidated\n     * @param loanReceiptHash Loan receipt hash\n     */\n    event LoanLiquidated(bytes32 indexed loanReceiptHash);\n\n    /**\n     * @notice Emitted when loan collateral is liquidated\n     * @param loanReceiptHash Loan receipt hash\n     * @param proceeds Total liquidation proceeds in currency tokens\n     * @param borrowerProceeds Borrower's share of liquidation proceeds in\n     * currency tokens\n     */\n    event CollateralLiquidated(bytes32 indexed loanReceiptHash, uint256 proceeds, uint256 borrowerProceeds);\n\n    /**\n     * @notice Emitted when admin fee rate is updated\n     * @param rate New admin fee rate in basis points\n     */\n    event AdminFeeRateUpdated(uint256 rate);\n\n    /**\n     * @notice Emitted when admin fees are withdrawn\n     * @param account Recipient account\n     * @param amount Amount of currency tokens withdrawn\n     */\n    event AdminFeesWithdrawn(address indexed account, uint256 amount);\n\n    /**************************************************************************/\n    /* Getters */\n    /**************************************************************************/\n\n    /**\n     * @notice Get currency token\n     * @return Currency token contract\n     */\n    function currencyToken() external view returns (address);\n\n    /**\n     * @notice Get supported durations\n     * @return List of loan durations in second\n     */\n    function durations() external view returns (uint64[] memory);\n\n    /**\n     * @notice Get supported rates\n     * @return List of rates in interest per second\n     */\n    function rates() external view returns (uint64[] memory);\n\n    /**\n     * @notice Get admin\n     * @return Admin\n     */\n    function admin() external view returns (address);\n\n    /**\n     * @notice Get admin fee rate\n     * @return Admin fee rate in basis points\n     */\n    function adminFeeRate() external view returns (uint32);\n\n    /**\n     * @notice Get admin fee balance\n     * @return Admin fee balance in currency tokens\n     */\n    function adminFeeBalance() external view returns (uint256);\n\n    /**\n     * @notice Get list of supported collateral wrappers\n     * @return Collateral wrappers\n     */\n    function collateralWrappers() external view returns (address[] memory);\n\n    /**\n     * @notice Get collateral liquidator contract\n     * @return Collateral liquidator contract\n     */\n    function collateralLiquidator() external view returns (address);\n\n    /**\n     * @notice Get delegation registry v1 contract\n     * @return Delegation registry contract\n     */\n    function delegationRegistry() external view returns (address);\n\n    /**\n     * @notice Get delegation registry v2 contract\n     * @return Delegation registry contract\n     */\n    function delegationRegistryV2() external view returns (address);\n\n    /**************************************************************************/\n    /* Deposit API */\n    /**************************************************************************/\n\n    /**\n     * @notice Deposit amount at tick\n     *\n     * Emits a {Deposited} event.\n     *\n     * @param tick Tick\n     * @param amount Amount of currency tokens\n     * @param minShares Minimum amount of shares to receive\n     * @return shares Amount of shares minted\n     */\n    function deposit(uint128 tick, uint256 amount, uint256 minShares) external returns (uint256 shares);\n\n    /**\n     * @notice Redeem deposit shares for currency tokens. Currency tokens can\n     * be withdrawn with the `withdraw()` method once the redemption is\n     * processed.\n     *\n     * Emits a {Redeemed} event.\n     *\n     * @param tick Tick\n     * @param shares Amount of deposit shares to redeem\n     * @return redemptionId Redemption ID\n     */\n    function redeem(uint128 tick, uint256 shares) external returns (uint128 redemptionId);\n\n    /**\n     * @notice Get redemption available\n     *\n     * @param account Account\n     * @param tick Tick\n     * @param redemptionId Redemption ID\n     * @return shares Amount of deposit shares available for redemption\n     * @return amount Amount of currency tokens available for withdrawal\n     * @return sharesAhead Amount of pending shares ahead in queue\n     */\n    function redemptionAvailable(\n        address account,\n        uint128 tick,\n        uint128 redemptionId\n    ) external view returns (uint256 shares, uint256 amount, uint256 sharesAhead);\n\n    /**\n     * @notice Withdraw a redemption that is available\n     *\n     * Emits a {Withdrawn} event.\n     *\n     * @param tick Tick\n     * @param redemptionId Redemption ID\n     * @return shares Amount of deposit shares burned\n     * @return amount Amount of currency tokens withdrawn\n     */\n    function withdraw(uint128 tick, uint128 redemptionId) external returns (uint256 shares, uint256 amount);\n\n    /**\n     * @notice Rebalance a redemption that is available to a new tick\n     *\n     * Emits {Withdrawn} and {Deposited} events.\n     *\n     * @param srcTick Source tick\n     * @param dstTick Destination Tick\n     * @param redemptionId Redemption ID\n     * @param minShares Minimum amount of destination shares to receive\n     * @return oldShares Amount of source deposit shares burned\n     * @return newShares Amount of destination deposit shares minted\n     * @return amount Amount of currency tokens redeposited\n     */\n    function rebalance(\n        uint128 srcTick,\n        uint128 dstTick,\n        uint128 redemptionId,\n        uint256 minShares\n    ) external returns (uint256 oldShares, uint256 newShares, uint256 amount);\n\n    /**************************************************************************/\n    /* Lend API */\n    /**************************************************************************/\n\n    /**\n     * @notice Quote repayment for a loan\n     * @param principal Principal amount in currency tokens\n     * @param duration Duration in seconds\n     * @param collateralToken Collateral token address\n     * @param collateralTokenId Collateral token ID\n     * @param ticks Liquidity ticks\n     * @param options Encoded options\n     * @return repayment Repayment amount in currency tokens\n     */\n    function quote(\n        uint256 principal,\n        uint64 duration,\n        address collateralToken,\n        uint256 collateralTokenId,\n        uint128[] calldata ticks,\n        bytes calldata options\n    ) external view returns (uint256 repayment);\n\n    /**\n     * @notice Originate a loan\n     *\n     * Emits a {LoanOriginated} event.\n     *\n     * @param principal Principal amount in currency tokens\n     * @param duration Duration in seconds\n     * @param collateralToken Collateral token address\n     * @param collateralTokenId Collateral token ID\n     * @param maxRepayment Maximum repayment amount in currency tokens\n     * @param ticks Liquidity ticks\n     * @param options Encoded options\n     * @return repayment Repayment amount in currency tokens\n     */\n    function borrow(\n        uint256 principal,\n        uint64 duration,\n        address collateralToken,\n        uint256 collateralTokenId,\n        uint256 maxRepayment,\n        uint128[] calldata ticks,\n        bytes calldata options\n    ) external returns (uint256 repayment);\n\n    /**\n     * @notice Repay a loan\n     *\n     * Emits a {LoanRepaid} event.\n     *\n     * @param encodedLoanReceipt Encoded loan receipt\n     * @return repayment Repayment amount in currency tokens\n     */\n    function repay(bytes calldata encodedLoanReceipt) external returns (uint256 repayment);\n\n    /**\n     * @notice Refinance a loan\n     *\n     * Emits a {LoanRepaid} event and a {LoanOriginated} event.\n     *\n     * @param encodedLoanReceipt Encoded loan receipt\n     * @param principal Principal amount in currency tokens\n     * @param duration Duration in seconds\n     * @param maxRepayment Maximum repayment amount in currency tokens\n     * @param ticks Liquidity ticks\n     * @return repayment Repayment amount in currency tokens\n     */\n    function refinance(\n        bytes calldata encodedLoanReceipt,\n        uint256 principal,\n        uint64 duration,\n        uint256 maxRepayment,\n        uint128[] calldata ticks\n    ) external returns (uint256 repayment);\n\n    /**\n     * @notice Liquidate an expired loan\n     *\n     * Emits a {LoanLiquidated} event.\n     *\n     * @param loanReceipt Loan receipt\n     */\n    function liquidate(bytes calldata loanReceipt) external;\n}\n"
      },
      "contracts/LiquidityLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport \"./interfaces/ILiquidity.sol\";\nimport \"./Tick.sol\";\n\n/**\n * @title Liquidity Logic\n * @author MetaStreet Labs\n */\nlibrary LiquidityLogic {\n    using SafeCast for uint256;\n\n    /**************************************************************************/\n    /* Constants */\n    /**************************************************************************/\n\n    /**\n     * @notice Tick limit spacing basis points (10%)\n     */\n    uint256 internal constant TICK_LIMIT_SPACING_BASIS_POINTS = 1000;\n\n    /**\n     * @notice Fixed point scale\n     */\n    uint256 internal constant FIXED_POINT_SCALE = 1e18;\n\n    /**\n     * @notice Basis points scale\n     */\n    uint256 internal constant BASIS_POINTS_SCALE = 10_000;\n\n    /**\n     * @notice Impaired price threshold (5%)\n     */\n    uint256 internal constant IMPAIRED_PRICE_THRESHOLD = 0.05 * 1e18;\n\n    /**\n     * @notice Max ticks used count\n     */\n    uint256 private constant MAX_TICKS_USED_COUNT = 32;\n\n    /**\n     * @notice Max redemption queue scan count\n     */\n    uint256 private constant MAX_REDEMPTION_QUEUE_SCAN_COUNT = 150;\n\n    /**************************************************************************/\n    /* Structures */\n    /**************************************************************************/\n\n    /**\n     * @notice Node source\n     * @param tick Tick\n     * @param used Amount used\n     * @param pending Amount pending\n     */\n    struct NodeSource {\n        uint128 tick;\n        uint128 used;\n        uint128 pending;\n    }\n\n    /**\n     * @notice Fulfilled redemption\n     * @param shares Shares redeemed\n     * @param amount Amount redeemed\n     */\n    struct FulfilledRedemption {\n        uint128 shares;\n        uint128 amount;\n    }\n\n    /**\n     * @notice Redemption state\n     * @param pending Pending shares\n     * @param index Current index\n     * @param fulfilled Fulfilled redemptions\n     */\n    struct Redemptions {\n        uint128 pending;\n        uint128 index;\n        mapping(uint128 => FulfilledRedemption) fulfilled;\n    }\n\n    /**\n     * @notice Accrual state\n     * @param accrued Accrued interest\n     * @param rate Accrual rate\n     * @param timestamp Last accrual timestamp\n     */\n    struct Accrual {\n        uint128 accrued;\n        uint64 rate;\n        uint64 timestamp;\n    }\n\n    /**\n     * @notice Liquidity node\n     * @param value Liquidity value\n     * @param shares Liquidity shares outstanding\n     * @param available Liquidity available\n     * @param pending Liquidity pending (with interest)\n     * @param prev Previous liquidity node\n     * @param next Next liquidity node\n     * @param redemption Redemption state\n     * @param accrual Accrual state\n     */\n    struct Node {\n        uint128 value;\n        uint128 shares;\n        uint128 available;\n        uint128 pending;\n        uint128 prev;\n        uint128 next;\n        Redemptions redemptions;\n        Accrual accrual;\n    }\n\n    /**\n     * @notice Liquidity state\n     * @param nodes Liquidity nodes\n     */\n    struct Liquidity {\n        mapping(uint256 => Node) nodes;\n    }\n\n    /**************************************************************************/\n    /* Getters */\n    /**************************************************************************/\n\n    /**\n     * Get liquidity node at tick\n     * @param liquidity Liquidity state\n     * @param tick Tick\n     * @return Liquidity node\n     */\n    function liquidityNode(Liquidity storage liquidity, uint128 tick) public view returns (ILiquidity.NodeInfo memory) {\n        Node storage node = liquidity.nodes[tick];\n\n        return\n            ILiquidity.NodeInfo({\n                tick: tick,\n                value: node.value,\n                shares: node.shares,\n                available: node.available,\n                pending: node.pending,\n                redemptions: node.redemptions.pending,\n                prev: node.prev,\n                next: node.next\n            });\n    }\n\n    /**\n     * @notice Count liquidity nodes spanning [startTick, endTick] range, where\n     * startTick is 0 or an instantiated tick\n     * @param liquidity Liquidity state\n     * @param startTick Start tick\n     * @param endTick End tick\n     * @return count Liquidity nodes count\n     */\n    function liquidityNodesCount(\n        Liquidity storage liquidity,\n        uint128 startTick,\n        uint128 endTick\n    ) public view returns (uint256 count) {\n        /* Validate start tick has active liquidity */\n        if (liquidity.nodes[startTick].next == 0) revert ILiquidity.InactiveLiquidity();\n\n        /* Count nodes */\n        uint256 t = startTick;\n        while (t != type(uint128).max && t <= endTick) {\n            t = liquidity.nodes[t].next;\n            count++;\n        }\n    }\n\n    /**\n     * @notice Get liquidity nodes spanning [startTick, endTick] range, where\n     * startTick is 0 or an instantiated tick\n     * @param liquidity Liquidity state\n     * @param startTick Start tick\n     * @param endTick End tick\n     * @return Liquidity nodes\n     */\n    function liquidityNodes(\n        Liquidity storage liquidity,\n        uint128 startTick,\n        uint128 endTick\n    ) external view returns (ILiquidity.NodeInfo[] memory) {\n        ILiquidity.NodeInfo[] memory nodes = new ILiquidity.NodeInfo[](\n            liquidityNodesCount(liquidity, startTick, endTick)\n        );\n\n        /* Populate nodes */\n        uint256 i;\n        uint128 t = startTick;\n        while (t != type(uint128).max && t <= endTick) {\n            nodes[i] = liquidityNode(liquidity, t);\n            t = nodes[i++].next;\n        }\n\n        return nodes;\n    }\n\n    /**\n     * @notice Get liquidity node with accrual info at tick\n     * @param liquidity Liquidity state\n     * @param tick Tick\n     * @return Liquidity node, Accrual info\n     */\n    function liquidityNodeWithAccrual(\n        Liquidity storage liquidity,\n        uint128 tick\n    ) external view returns (ILiquidity.NodeInfo memory, ILiquidity.AccrualInfo memory) {\n        Node storage node = liquidity.nodes[tick];\n\n        return (\n            ILiquidity.NodeInfo({\n                tick: tick,\n                value: node.value,\n                shares: node.shares,\n                available: node.available,\n                pending: node.pending,\n                redemptions: node.redemptions.pending,\n                prev: node.prev,\n                next: node.next\n            }),\n            ILiquidity.AccrualInfo({\n                accrued: node.accrual.accrued,\n                rate: node.accrual.rate,\n                timestamp: node.accrual.timestamp\n            })\n        );\n    }\n\n    /**\n     * @notice Get redemption available amount\n     * @param liquidity Liquidity state\n     * @param tick Tick\n     * @param pending Redemption pending\n     * @param index Redemption index\n     * @param target Redemption target\n     * @return redeemedShares Redeemed shares\n     * @return redeemedAmount Redeemed amount\n     * @return processedIndices Processed indices\n     * @return processedShares Processed shares\n     */\n    function redemptionAvailable(\n        Liquidity storage liquidity,\n        uint128 tick,\n        uint128 pending,\n        uint128 index,\n        uint128 target\n    )\n        internal\n        view\n        returns (uint128 redeemedShares, uint128 redeemedAmount, uint128 processedIndices, uint128 processedShares)\n    {\n        Node storage node = liquidity.nodes[tick];\n\n        uint256 stopIndex = index + MAX_REDEMPTION_QUEUE_SCAN_COUNT;\n\n        for (; processedShares < target + pending && index < stopIndex; index++) {\n            if (index == node.redemptions.index) {\n                /* Reached pending unfulfilled redemption */\n                break;\n            }\n\n            /* Look up the next fulfilled redemption */\n            FulfilledRedemption storage redemption = node.redemptions.fulfilled[index];\n\n            /* Update processed count */\n            processedIndices += 1;\n            processedShares += redemption.shares;\n\n            if (processedShares <= target) {\n                /* Have not reached the redemption queue position yet */\n                continue;\n            } else {\n                /* Compute number of shares to redeem in range of this\n                 * redemption batch */\n                uint128 shares = (((processedShares > target + pending) ? pending : (processedShares - target))) -\n                    redeemedShares;\n                /* Compute price of shares in this redemption batch */\n                uint256 price = (redemption.amount * FIXED_POINT_SCALE) / redemption.shares;\n\n                /* Accumulate redeemed shares and corresponding amount */\n                redeemedShares += shares;\n                redeemedAmount += Math.mulDiv(shares, price, FIXED_POINT_SCALE).toUint128();\n            }\n        }\n    }\n\n    /**\n     * @notice Get deposit share price\n     * @param liquidity Liquidity state\n     * @param tick Tick\n     * @return Deposit share price\n     */\n    function depositSharePrice(Liquidity storage liquidity, uint128 tick) external view returns (uint256) {\n        Node storage node = liquidity.nodes[tick];\n\n        /* Simulate accrual */\n        uint128 accrued = node.accrual.accrued + node.accrual.rate * uint128(block.timestamp - node.accrual.timestamp);\n\n        /* Return deposit price */\n        return\n            node.shares == 0\n                ? FIXED_POINT_SCALE\n                : (Math.min(node.value + accrued, node.available + node.pending) * FIXED_POINT_SCALE) / node.shares;\n    }\n\n    /**\n     * @notice Get redemption share price\n     * @param liquidity Liquidity state\n     * @param tick Tick\n     * @return Redemption share price\n     */\n    function redemptionSharePrice(Liquidity storage liquidity, uint128 tick) external view returns (uint256) {\n        Node storage node = liquidity.nodes[tick];\n\n        /* Revert if node is empty */\n        if (node.value == 0 || node.shares == 0) revert ILiquidity.InactiveLiquidity();\n\n        /* Return redemption price */\n        return (node.value * FIXED_POINT_SCALE) / node.shares;\n    }\n\n    /**************************************************************************/\n    /* Internal Helpers */\n    /**************************************************************************/\n\n    /**\n     * @dev Check if tick is reserved\n     * @param tick Tick\n     * @return True if reserved, otherwise false\n     */\n    function _isReserved(uint128 tick) internal pure returns (bool) {\n        return tick == 0 || tick == type(uint128).max;\n    }\n\n    /**\n     * @dev Check if liquidity node is empty\n     * @param node Liquidity node\n     * @return True if empty, otherwise false\n     */\n    function _isEmpty(Node storage node) internal view returns (bool) {\n        return node.shares == 0 && node.pending == 0;\n    }\n\n    /**\n     * @dev Check if liquidity node is active\n     * @param node Liquidity node\n     * @return True if active, otherwise false\n     */\n    function _isActive(Node storage node) internal view returns (bool) {\n        return node.prev != 0 || node.next != 0;\n    }\n\n    /**\n     * @dev Check if liquidity node is impaired\n     * @param node Liquidity node\n     * @return True if impaired, otherwise false\n     */\n    function _isImpaired(Node storage node) internal view returns (bool) {\n        /* If there's shares, but insufficient value for a stable share price */\n        return node.shares != 0 && node.value * FIXED_POINT_SCALE < node.shares * IMPAIRED_PRICE_THRESHOLD;\n    }\n\n    /**\n     * @notice Instantiate liquidity\n     * @param liquidity Liquidity state\n     * @param tick Tick\n     */\n    function _instantiate(Liquidity storage liquidity, Node storage node, uint128 tick) internal {\n        /* If node is active, do nothing */\n        if (_isActive(node)) return;\n        /* If node is inactive and not empty, revert */\n        if (!_isEmpty(node)) revert ILiquidity.InactiveLiquidity();\n\n        /* Find prior node to new tick */\n        uint128 prevTick;\n        Node storage prevNode = liquidity.nodes[prevTick];\n        while (prevNode.next < tick) {\n            prevTick = prevNode.next;\n            prevNode = liquidity.nodes[prevTick];\n        }\n\n        /* Decode limits from previous tick, new tick, and next tick */\n        (uint256 prevLimit, , , ) = Tick.decode(prevTick);\n        (uint256 newLimit, , , ) = Tick.decode(tick);\n        (uint256 nextLimit, , , ) = Tick.decode(prevNode.next);\n\n        /* Validate tick limit spacing */\n        if (\n            newLimit != prevLimit &&\n            newLimit < (prevLimit * (BASIS_POINTS_SCALE + TICK_LIMIT_SPACING_BASIS_POINTS)) / BASIS_POINTS_SCALE\n        ) revert ILiquidity.InsufficientTickSpacing();\n        if (\n            newLimit != nextLimit &&\n            nextLimit < (newLimit * (BASIS_POINTS_SCALE + TICK_LIMIT_SPACING_BASIS_POINTS)) / BASIS_POINTS_SCALE\n        ) revert ILiquidity.InsufficientTickSpacing();\n\n        /* Link new node */\n        node.prev = prevTick;\n        node.next = prevNode.next;\n        liquidity.nodes[prevNode.next].prev = tick;\n        prevNode.next = tick;\n    }\n\n    /**\n     * @dev Garbage collect an impaired or empty node, unlinking it from active\n     * liquidity\n     * @param liquidity Liquidity state\n     * @param node Liquidity node\n     */\n    function _garbageCollect(Liquidity storage liquidity, Node storage node) internal {\n        /* If node is not impaired and not empty, or already inactive, do nothing */\n        if ((!_isImpaired(node) && !_isEmpty(node)) || !_isActive(node)) return;\n\n        /* Make node inactive by unlinking it */\n        liquidity.nodes[node.prev].next = node.next;\n        liquidity.nodes[node.next].prev = node.prev;\n        node.next = 0;\n        node.prev = 0;\n    }\n\n    /**\n     * @notice Process redemptions from available liquidity\n     * @param liquidity Liquidity state\n     * @param node Liquidity node\n     */\n    function _processRedemptions(Liquidity storage liquidity, Node storage node) internal {\n        /* If there's no pending shares to redeem */\n        if (node.redemptions.pending == 0) return;\n\n        /* Compute redemption price */\n        uint256 price = (node.value * FIXED_POINT_SCALE) / node.shares;\n\n        if (price == 0) {\n            /* If node has pending interest */\n            if (node.pending != 0) return;\n\n            /* If node is insolvent, redeem all shares for zero amount */\n            uint128 shares = node.redemptions.pending;\n\n            /* Record fulfilled redemption */\n            node.redemptions.fulfilled[node.redemptions.index++] = FulfilledRedemption({shares: shares, amount: 0});\n\n            /* Update node state */\n            node.shares -= shares;\n            node.value = 0;\n            node.available = 0;\n            node.redemptions.pending = 0;\n\n            return;\n        } else {\n            /* Node is solvent */\n\n            /* If there's no cash to redeem from */\n            if (node.available == 0) return;\n\n            /* Redeem as many shares as possible and pending from available cash */\n            uint128 shares = uint128(Math.min((node.available * FIXED_POINT_SCALE) / price, node.redemptions.pending));\n            uint128 amount = Math.mulDiv(shares, price, FIXED_POINT_SCALE).toUint128();\n\n            /* If there's insufficient cash to redeem non-zero pending shares\n             * at current price */\n            if (shares == 0) return;\n\n            /* Record fulfilled redemption */\n            node.redemptions.fulfilled[node.redemptions.index++] = FulfilledRedemption({\n                shares: shares,\n                amount: amount\n            });\n\n            /* Update node state */\n            node.shares -= shares;\n            node.value -= amount;\n            node.available -= amount;\n            node.redemptions.pending -= shares;\n\n            /* Garbage collect node if it is now empty */\n            _garbageCollect(liquidity, node);\n\n            return;\n        }\n    }\n\n    /**\n     * @notice Process accrued value from accrual rate and timestamp\n     * @param node Liquidity node\n     */\n    function _accrue(Node storage node) internal {\n        node.accrual.accrued += node.accrual.rate * uint128(block.timestamp - node.accrual.timestamp);\n        node.accrual.timestamp = uint64(block.timestamp);\n    }\n\n    /**************************************************************************/\n    /* Primary API */\n    /**************************************************************************/\n\n    /**\n     * @notice Initialize liquidity state\n     * @param liquidity Liquidity state\n     */\n    function initialize(Liquidity storage liquidity) internal {\n        /* Liquidity state defaults to zero, but need to make head and tail nodes */\n        liquidity.nodes[0].next = type(uint128).max;\n        /* liquidity.nodes[type(uint128).max].prev = 0 by default */\n    }\n\n    /**\n     * @notice Deposit liquidity\n     * @param liquidity Liquidity state\n     * @param tick Tick\n     * @param amount Amount\n     * @return Number of shares\n     */\n    function deposit(Liquidity storage liquidity, uint128 tick, uint128 amount) internal returns (uint128) {\n        Node storage node = liquidity.nodes[tick];\n\n        /* If tick is reserved */\n        if (_isReserved(tick)) revert ILiquidity.InactiveLiquidity();\n\n        /* Instantiate node, if necessary */\n        _instantiate(liquidity, node, tick);\n\n        /* Process accrual */\n        _accrue(node);\n\n        /* Compute deposit price */\n        uint256 price = node.shares == 0\n            ? FIXED_POINT_SCALE\n            : (Math.min(node.value + node.accrual.accrued, node.available + node.pending) * FIXED_POINT_SCALE) /\n                node.shares;\n\n        /* Compute shares */\n        uint128 shares = ((amount * FIXED_POINT_SCALE) / price).toUint128();\n\n        node.value += amount;\n        node.shares += shares;\n        node.available += amount;\n\n        /* Process any pending redemptions from available cash */\n        _processRedemptions(liquidity, node);\n\n        return shares;\n    }\n\n    /**\n     * @notice Use liquidity from node\n     * @param liquidity Liquidity state\n     * @param tick Tick\n     * @param used Used amount\n     * @param pending Pending amount\n     * @param duration Duration\n     */\n    function use(Liquidity storage liquidity, uint128 tick, uint128 used, uint128 pending, uint64 duration) internal {\n        Node storage node = liquidity.nodes[tick];\n\n        node.available -= used;\n        node.pending += pending;\n\n        /* Process accrual */\n        _accrue(node);\n        /* Increment accrual rate */\n        uint256 rate = uint256(pending - used) / duration;\n        node.accrual.rate += rate.toUint64();\n    }\n\n    /**\n     * @notice Restore liquidity and process pending redemptions\n     * @param liquidity Liquidity state\n     * @param tick Tick\n     * @param used Used amount\n     * @param pending Pending amount\n     * @param restored Restored amount\n     * @param duration Duration\n     * @param elapsed Elapsed time since loan origination\n     */\n    function restore(\n        Liquidity storage liquidity,\n        uint128 tick,\n        uint128 used,\n        uint128 pending,\n        uint128 restored,\n        uint64 duration,\n        uint64 elapsed\n    ) internal {\n        Node storage node = liquidity.nodes[tick];\n\n        node.value = node.value - used + restored;\n        node.available += restored;\n        node.pending -= pending;\n\n        /* Garbage collect node if it is now impaired */\n        _garbageCollect(liquidity, node);\n\n        /* Process any pending redemptions */\n        _processRedemptions(liquidity, node);\n\n        /* Process accrual */\n        _accrue(node);\n        /* Decrement accrual rate and accrued */\n        uint256 rate = uint256(pending - used) / duration;\n        node.accrual.rate -= rate.toUint64();\n        node.accrual.accrued -= uint128(rate * elapsed);\n    }\n\n    /**\n     * @notice Redeem liquidity\n     * @param liquidity Liquidity state\n     * @param tick Tick\n     * @param shares Shares\n     * @return Redemption index, Redemption target\n     */\n    function redeem(Liquidity storage liquidity, uint128 tick, uint128 shares) internal returns (uint128, uint128) {\n        Node storage node = liquidity.nodes[tick];\n\n        /* Redemption from inactive liquidity nodes is allowed to facilitate\n         * restoring garbage collected nodes */\n\n        /* Snapshot redemption target */\n        uint128 redemptionIndex = node.redemptions.index;\n        uint128 redemptionTarget = node.redemptions.pending;\n\n        /* Add shares to pending redemptions */\n        node.redemptions.pending += shares;\n\n        /* Initialize redemption record to save gas in loan callbacks */\n        if (node.redemptions.fulfilled[redemptionIndex].shares != type(uint128).max) {\n            node.redemptions.fulfilled[redemptionIndex] = FulfilledRedemption({shares: type(uint128).max, amount: 0});\n        }\n\n        /* Process any pending redemptions from available cash */\n        _processRedemptions(liquidity, node);\n\n        return (redemptionIndex, redemptionTarget);\n    }\n\n    /**\n     * @notice Source liquidity from nodes\n     * @param liquidity Liquidity state\n     * @param amount Amount\n     * @param ticks Ticks to source from\n     * @param multiplier Multiplier for amount\n     * @param durationIndex Duration index for amount\n     * @return Sourced liquidity nodes, count of nodes\n     */\n    function source(\n        Liquidity storage liquidity,\n        uint256 amount,\n        uint128[] calldata ticks,\n        uint256 multiplier,\n        uint256 durationIndex\n    ) internal view returns (NodeSource[] memory, uint16) {\n        NodeSource[] memory sources = new NodeSource[](ticks.length);\n\n        uint256 prevTick;\n        uint256 taken;\n        uint256 count;\n        for (; count < ticks.length && taken != amount; count++) {\n            uint128 tick = ticks[count];\n\n            /* Validate tick and decode limit */\n            uint256 limit = Tick.validate(tick, prevTick, durationIndex);\n\n            /* Look up liquidity node */\n            Node storage node = liquidity.nodes[tick];\n\n            /* Consume as much as possible up to the tick limit, amount available, and amount remaining */\n            uint128 take = uint128(Math.min(Math.min(limit * multiplier - taken, node.available), amount - taken));\n\n            /* Record the liquidity allocation in our sources list */\n            sources[count] = NodeSource({tick: tick, used: take, pending: 0});\n\n            taken += take;\n            prevTick = tick;\n        }\n\n        /* If unable to source required liquidity amount from provided ticks */\n        if (taken < amount) revert ILiquidity.InsufficientLiquidity();\n\n        /* If count exceeds max number of ticks */\n        if (count > MAX_TICKS_USED_COUNT) revert ILiquidity.InsufficientLiquidity();\n\n        return (sources, count.toUint16());\n    }\n}\n"
      },
      "contracts/LoanReceipt.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\n/**\n * @title LoanReceipt\n * @author MetaStreet Labs\n */\nlibrary LoanReceipt {\n    /**************************************************************************/\n    /* Errors */\n    /**************************************************************************/\n\n    /**\n     * @notice Invalid receipt encoding\n     */\n    error InvalidReceiptEncoding();\n\n    /**************************************************************************/\n    /* Constants */\n    /**************************************************************************/\n\n    /**\n     * @notice Loan receipt version\n     */\n    uint8 internal constant LOAN_RECEIPT_VERSION = 2;\n\n    /**\n     * @notice Loan receipt header size in bytes\n     * @dev Header excludes borrow options byte array\n     */\n    uint256 internal constant LOAN_RECEIPT_HEADER_SIZE = 187;\n\n    /**\n     * @notice Loan receipt node receipt size in bytes\n     */\n    uint256 internal constant LOAN_RECEIPT_NODE_RECEIPT_SIZE = 48;\n\n    /**************************************************************************/\n    /* Structures */\n    /**************************************************************************/\n\n    /**\n     * @notice LoanReceiptV2\n     * @param version Version (2)\n     * @param principal Principal amount in currency tokens\n     * @param repayment Repayment amount in currency tokens\n     * @param adminFee Admin fee amount in currency tokens\n     * @param borrower Borrower\n     * @param maturity Loan maturity timestamp\n     * @param duration Loan duration\n     * @param collateralToken Collateral token\n     * @param collateralTokenId Collateral token ID\n     * @param collateralWrapperContextLen Collateral wrapper context length\n     * @param collateralWrapperContext Collateral wrapper context data\n     * @param nodeReceipts Node receipts\n     */\n    struct LoanReceiptV2 {\n        uint8 version;\n        uint256 principal;\n        uint256 repayment;\n        uint256 adminFee;\n        address borrower;\n        uint64 maturity;\n        uint64 duration;\n        address collateralToken;\n        uint256 collateralTokenId;\n        uint16 collateralWrapperContextLen;\n        bytes collateralWrapperContext;\n        NodeReceipt[] nodeReceipts;\n    }\n\n    /**\n     * @notice Node receipt\n     * @param tick Tick\n     * @param used Used amount\n     * @param pending Pending amount\n     */\n    struct NodeReceipt {\n        uint128 tick;\n        uint128 used;\n        uint128 pending;\n    }\n\n    /**************************************************************************/\n    /* Tightly packed format */\n    /**************************************************************************/\n\n    /*\n      Header (187 bytes)\n          1   uint8   version                        0:1\n          32  uint256 principal                      1:33\n          32  uint256 repayment                      33:65\n          32  uint256 adminFee                       65:97\n          20  address borrower                       97:117\n          8   uint64  maturity                       117:125\n          8   uint64  duration                       125:133\n          20  address collateralToken                133:153\n          32  uint256 collateralTokenId              153:185\n          2   uint16  collateralWrapperContextLen    185:187\n\n      Collateral Wrapper Context Data (M bytes)      187:---\n\n      Node Receipts (48 * N bytes)\n          N   NodeReceipts[] nodeReceipts\n              16  uint128 tick\n              16  uint128 used\n              16  uint128 pending\n    */\n\n    /**************************************************************************/\n    /* API */\n    /**************************************************************************/\n\n    /**\n     * @dev Compute loan receipt hash\n     * @param encodedReceipt Encoded loan receipt\n     * @return Loan Receipt hash\n     */\n    function hash(bytes memory encodedReceipt) internal view returns (bytes32) {\n        /* Take hash of chain ID (32 bytes) concatenated with encoded loan receipt */\n        return keccak256(abi.encodePacked(block.chainid, encodedReceipt));\n    }\n\n    /**\n     * @dev Encode a loan receipt into bytes\n     * @param receipt Loan Receipt\n     * @return Encoded loan receipt\n     */\n    function encode(LoanReceiptV2 memory receipt) internal pure returns (bytes memory) {\n        /* Encode header */\n        bytes memory header = abi.encodePacked(\n            receipt.version,\n            receipt.principal,\n            receipt.repayment,\n            receipt.adminFee,\n            receipt.borrower,\n            receipt.maturity,\n            receipt.duration,\n            receipt.collateralToken,\n            receipt.collateralTokenId,\n            receipt.collateralWrapperContextLen,\n            receipt.collateralWrapperContext\n        );\n\n        /* Encode node receipts */\n        bytes memory nodeReceipts;\n        for (uint256 i; i < receipt.nodeReceipts.length; i++) {\n            nodeReceipts = abi.encodePacked(\n                nodeReceipts,\n                receipt.nodeReceipts[i].tick,\n                receipt.nodeReceipts[i].used,\n                receipt.nodeReceipts[i].pending\n            );\n        }\n\n        return abi.encodePacked(header, nodeReceipts);\n    }\n\n    /**\n     * @dev Decode a loan receipt from bytes\n     * @param encodedReceipt Encoded loan Receipt\n     * @return Decoded loan receipt\n     */\n    function decode(bytes calldata encodedReceipt) internal pure returns (LoanReceiptV2 memory) {\n        /* Validate encoded receipt length */\n        if (encodedReceipt.length < LOAN_RECEIPT_HEADER_SIZE) revert InvalidReceiptEncoding();\n\n        uint256 collateralWrapperContextLen = uint16(bytes2(encodedReceipt[185:187]));\n\n        /* Validate length with collateral wrapper context */\n        if (encodedReceipt.length < LOAN_RECEIPT_HEADER_SIZE + collateralWrapperContextLen)\n            revert InvalidReceiptEncoding();\n\n        /* Validate length with node receipts */\n        if (\n            (encodedReceipt.length - LOAN_RECEIPT_HEADER_SIZE - collateralWrapperContextLen) %\n                LOAN_RECEIPT_NODE_RECEIPT_SIZE !=\n            0\n        ) revert InvalidReceiptEncoding();\n\n        /* Validate encoded receipt version */\n        if (uint8(encodedReceipt[0]) != LOAN_RECEIPT_VERSION) revert InvalidReceiptEncoding();\n\n        LoanReceiptV2 memory receipt;\n\n        /* Decode header */\n        receipt.version = uint8(encodedReceipt[0]);\n        receipt.principal = uint256(bytes32(encodedReceipt[1:33]));\n        receipt.repayment = uint256(bytes32(encodedReceipt[33:65]));\n        receipt.adminFee = uint256(bytes32(encodedReceipt[65:97]));\n        receipt.borrower = address(uint160(bytes20(encodedReceipt[97:117])));\n        receipt.maturity = uint64(bytes8(encodedReceipt[117:125]));\n        receipt.duration = uint64(bytes8(encodedReceipt[125:133]));\n        receipt.collateralToken = address(uint160(bytes20(encodedReceipt[133:153])));\n        receipt.collateralTokenId = uint256(bytes32(encodedReceipt[153:185]));\n        receipt.collateralWrapperContextLen = uint16(collateralWrapperContextLen);\n        receipt.collateralWrapperContext = encodedReceipt[187:187 + collateralWrapperContextLen];\n\n        /* Decode node receipts */\n        uint256 numNodeReceipts = (encodedReceipt.length - LOAN_RECEIPT_HEADER_SIZE - collateralWrapperContextLen) /\n            LOAN_RECEIPT_NODE_RECEIPT_SIZE;\n        receipt.nodeReceipts = new NodeReceipt[](numNodeReceipts);\n        uint256 offset = LOAN_RECEIPT_HEADER_SIZE + collateralWrapperContextLen;\n        for (uint256 i; i < numNodeReceipts; i++) {\n            receipt.nodeReceipts[i].tick = uint128(bytes16(encodedReceipt[offset:offset + 16]));\n            receipt.nodeReceipts[i].used = uint128(bytes16(encodedReceipt[offset + 16:offset + 32]));\n            receipt.nodeReceipts[i].pending = uint128(bytes16(encodedReceipt[offset + 32:offset + 48]));\n            offset += LOAN_RECEIPT_NODE_RECEIPT_SIZE;\n        }\n\n        return receipt;\n    }\n}\n"
      },
      "contracts/Pool.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\nimport \"@openzeppelin/contracts/utils/introspection/ERC165.sol\";\nimport \"@openzeppelin/contracts/utils/Multicall.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport \"./filters/CollateralFilter.sol\";\nimport \"./rates/InterestRateModel.sol\";\nimport \"./tokenization/DepositToken.sol\";\n\nimport \"./LoanReceipt.sol\";\nimport \"./LiquidityLogic.sol\";\nimport \"./DepositLogic.sol\";\nimport \"./BorrowLogic.sol\";\n\nimport \"./interfaces/IPool.sol\";\nimport \"./interfaces/ILiquidity.sol\";\nimport \"./interfaces/ICollateralWrapper.sol\";\nimport \"./interfaces/ICollateralLiquidator.sol\";\nimport \"./interfaces/ICollateralLiquidationReceiver.sol\";\n\n/**\n * @title Pool\n * @author MetaStreet Labs\n */\nabstract contract Pool is\n    ERC165,\n    ReentrancyGuard,\n    Multicall,\n    CollateralFilter,\n    InterestRateModel,\n    DepositToken,\n    IPool,\n    ILiquidity,\n    ICollateralLiquidationReceiver\n{\n    using SafeCast for uint256;\n    using SafeERC20 for IERC20;\n    using LiquidityLogic for LiquidityLogic.Liquidity;\n\n    /**************************************************************************/\n    /* Constants */\n    /**************************************************************************/\n\n    /**\n     * @notice Tick spacing basis points\n     */\n    uint256 public constant TICK_LIMIT_SPACING_BASIS_POINTS = LiquidityLogic.TICK_LIMIT_SPACING_BASIS_POINTS;\n\n    /**************************************************************************/\n    /* Structures */\n    /**************************************************************************/\n\n    /**\n     * @notice Redemption\n     * @param pending Redemption shares pending\n     * @param index Redemption queue index\n     * @param target Redemption queue target\n     */\n    struct Redemption {\n        uint128 pending;\n        uint128 index;\n        uint128 target;\n    }\n\n    /**\n     * @notice Deposit\n     * @param shares Shares\n     * @param redemptionId Next Redemption ID\n     * @param redemptions Mapping of redemption ID to redemption\n     */\n    struct Deposit {\n        uint128 shares;\n        uint128 redemptionId;\n        mapping(uint128 => Redemption) redemptions;\n    }\n\n    /**\n     * @notice Delegate\n     * @param version Delegate version\n     * @param to Delegate address\n     */\n    struct Delegate {\n        DelegateVersion version;\n        address to;\n    }\n\n    /**\n     * @custom:storage-location erc7201:pool.delegateStorage\n     */\n    struct DelegateStorage {\n        /* Mapping of collateralToken to token ID to Delegate */\n        mapping(address => mapping(uint256 => Delegate)) delegates;\n    }\n\n    /**\n     * @notice Loan status\n     */\n    enum LoanStatus {\n        Uninitialized,\n        Active,\n        Repaid,\n        Liquidated,\n        CollateralLiquidated\n    }\n\n    /**\n     * @notice Borrow function options\n     */\n    enum BorrowOptions {\n        None,\n        CollateralWrapperContext,\n        CollateralFilterContext,\n        DelegateCashV1,\n        DelegateCashV2\n    }\n\n    /**\n     * @notice Delegate version\n     */\n    enum DelegateVersion {\n        None,\n        DelegateCashV1,\n        DelegateCashV2\n    }\n\n    /**************************************************************************/\n    /* Immutable State */\n    /**************************************************************************/\n\n    /**\n     * @notice Collateral wrappers (max 3)\n     */\n    address internal immutable _collateralWrapper1;\n    address internal immutable _collateralWrapper2;\n    address internal immutable _collateralWrapper3;\n\n    /**\n     * @notice Collateral liquidator\n     */\n    ICollateralLiquidator internal immutable _collateralLiquidator;\n\n    /**\n     * @notice Delegate registry v1 contract\n     */\n    address internal immutable _delegateRegistryV1;\n\n    /**\n     * @notice Delegate registry v2 contract\n     */\n    address internal immutable _delegateRegistryV2;\n\n    /**\n     * @notice Delegate cash storage slot\n     * @dev keccak256(abi.encode(uint256(keccak256(\"erc7201:pool.delegateStorage\")) - 1)) & ~bytes32(uint256(0xff));\n     */\n    bytes32 internal constant DELEGATE_STORAGE_LOCATION =\n        0xf0e5094ebd597f2042580340ce53d1b15e5b64e0d8be717ecde51dd37c619300;\n\n    /**************************************************************************/\n    /* State */\n    /**************************************************************************/\n\n    /**\n     * @notice Pool Storage\n     * @param currencyToken Currency token contract\n     * @param adminFeeRate Admin free rate in basis points\n     * @param durations Durations\n     * @param rates Rates\n     * @param admin Admin\n     * @param adminFeeBalance Admin fee balance\n     * @param liquidity Liquidity\n     * @param deposits Mapping of account to tick to deposit\n     * @param loans Mapping of loan receipt hash to loan status\n     */\n    struct PoolStorage {\n        IERC20 currencyToken;\n        uint32 adminFeeRate;\n        uint64[] durations;\n        uint64[] rates;\n        address admin;\n        uint256 adminFeeBalance;\n        LiquidityLogic.Liquidity liquidity;\n        mapping(address => mapping(uint128 => Deposit)) deposits;\n        mapping(bytes32 => LoanStatus) loans;\n    }\n\n    /**\n     * @notice Pool state\n     */\n    PoolStorage internal _storage;\n\n    /**************************************************************************/\n    /* Constructor */\n    /**************************************************************************/\n\n    /**\n     * @notice Pool constructor\n     * @param collateralLiquidator_ Collateral liquidator\n     * @param delegateRegistryV1_ Delegate registry v1 contract\n     * @param delegateRegistryV2_ Delegate registry v2 contract\n     * @param collateralWrappers_ Collateral wrappers\n     */\n    constructor(\n        address collateralLiquidator_,\n        address delegateRegistryV1_,\n        address delegateRegistryV2_,\n        address[] memory collateralWrappers_\n    ) {\n        if (collateralWrappers_.length > 3) revert InvalidParameters();\n\n        _collateralLiquidator = ICollateralLiquidator(collateralLiquidator_);\n        _delegateRegistryV1 = delegateRegistryV1_;\n        _delegateRegistryV2 = delegateRegistryV2_;\n        _collateralWrapper1 = (collateralWrappers_.length > 0) ? collateralWrappers_[0] : address(0);\n        _collateralWrapper2 = (collateralWrappers_.length > 1) ? collateralWrappers_[1] : address(0);\n        _collateralWrapper3 = (collateralWrappers_.length > 2) ? collateralWrappers_[2] : address(0);\n    }\n\n    /**************************************************************************/\n    /* Initializer */\n    /**************************************************************************/\n\n    /**\n     * @notice Pool initializer\n     * @dev Fee-on-transfer currency tokens are not supported\n     * @param currencyToken_ Currency token contract\n     * @param durations_ Duration tiers\n     * @param rates_ Interest rate tiers\n     */\n    function _initialize(address currencyToken_, uint64[] memory durations_, uint64[] memory rates_) internal {\n        if (IERC20Metadata(currencyToken_).decimals() != 18) revert InvalidParameters();\n\n        _storage.currencyToken = IERC20(currencyToken_);\n        _storage.admin = msg.sender;\n\n        /* Assign durations */\n        if (durations_.length > Tick.MAX_NUM_DURATIONS) revert InvalidParameters();\n        for (uint256 i; i < durations_.length; i++) {\n            /* Check duration is monotonic */\n            if (i != 0 && durations_[i] >= durations_[i - 1]) revert InvalidParameters();\n            _storage.durations.push(durations_[i]);\n        }\n\n        /* Assign rates */\n        if (rates_.length > Tick.MAX_NUM_RATES) revert InvalidParameters();\n        for (uint256 i; i < rates_.length; i++) {\n            /* Check rate is monotonic */\n            if (i != 0 && rates_[i] <= rates_[i - 1]) revert InvalidParameters();\n            _storage.rates.push(rates_[i]);\n        }\n\n        /* Initialize liquidity */\n        _storage.liquidity.initialize();\n    }\n\n    /**************************************************************************/\n    /* Getters */\n    /**************************************************************************/\n\n    /**\n     * @notice Get implementation name\n     * @return Implementation name\n     */\n    function IMPLEMENTATION_NAME() external pure virtual returns (string memory);\n\n    /**\n     * @notice Get implementation version\n     * @return Implementation version\n     */\n    function IMPLEMENTATION_VERSION() external pure returns (string memory) {\n        return \"2.7.1\";\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function currencyToken() external view returns (address) {\n        return address(_storage.currencyToken);\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function durations() external view returns (uint64[] memory) {\n        return _storage.durations;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function rates() external view returns (uint64[] memory) {\n        return _storage.rates;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function admin() external view returns (address) {\n        return _storage.admin;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function adminFeeRate() external view returns (uint32) {\n        return _storage.adminFeeRate;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function adminFeeBalance() external view returns (uint256) {\n        return _storage.adminFeeBalance;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function collateralWrappers() external view returns (address[] memory) {\n        address[] memory collateralWrappers_ = new address[](3);\n        collateralWrappers_[0] = _collateralWrapper1;\n        collateralWrappers_[1] = _collateralWrapper2;\n        collateralWrappers_[2] = _collateralWrapper3;\n        return collateralWrappers_;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function collateralLiquidator() external view returns (address) {\n        return address(_collateralLiquidator);\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function delegationRegistry() external view returns (address) {\n        return address(_delegateRegistryV1);\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function delegationRegistryV2() external view returns (address) {\n        return address(_delegateRegistryV2);\n    }\n\n    /**\n     * @notice Get deposit\n     * @param account Account\n     * @param tick Tick\n     * @return shares Shares\n     * @return redemptionId Redemption ID\n     */\n    function deposits(address account, uint128 tick) external view returns (uint128 shares, uint128 redemptionId) {\n        shares = _storage.deposits[account][tick].shares;\n        redemptionId = _storage.deposits[account][tick].redemptionId;\n    }\n\n    /**\n     * @notice Get redemption\n     * @param account Account\n     * @param tick Tick\n     * @param redemptionId Redemption ID\n     * @return Redemption\n     */\n    function redemptions(\n        address account,\n        uint128 tick,\n        uint128 redemptionId\n    ) external view returns (Redemption memory) {\n        return _storage.deposits[account][tick].redemptions[redemptionId];\n    }\n\n    /**\n     * @notice Get loan status\n     * @param receiptHash Loan receipt hash\n     * @return Loan status\n     */\n    function loans(bytes32 receiptHash) external view returns (LoanStatus) {\n        return _storage.loans[receiptHash];\n    }\n\n    /**\n     * @inheritdoc ILiquidity\n     */\n    function liquidityNodes(uint128 startTick, uint128 endTick) external view returns (NodeInfo[] memory) {\n        return _storage.liquidity.liquidityNodes(startTick, endTick);\n    }\n\n    /**\n     * @inheritdoc ILiquidity\n     */\n    function liquidityNode(uint128 tick) external view returns (NodeInfo memory) {\n        return _storage.liquidity.liquidityNode(tick);\n    }\n\n    /**\n     * @inheritdoc ILiquidity\n     */\n    function liquidityNodeWithAccrual(uint128 tick) external view returns (NodeInfo memory, AccrualInfo memory) {\n        return _storage.liquidity.liquidityNodeWithAccrual(tick);\n    }\n\n    /**\n     * @inheritdoc ILiquidity\n     */\n    function depositSharePrice(uint128 tick) external view returns (uint256) {\n        return _storage.liquidity.depositSharePrice(tick);\n    }\n\n    /**\n     * @inheritdoc ILiquidity\n     */\n    function redemptionSharePrice(uint128 tick) external view returns (uint256) {\n        return _storage.liquidity.redemptionSharePrice(tick);\n    }\n\n    /**************************************************************************/\n    /* Loan Receipt External Helpers */\n    /**************************************************************************/\n\n    /**\n     * @notice Decode loan receipt\n     * @param loanReceipt Loan receipt\n     * @return Decoded loan receipt\n     */\n    function decodeLoanReceipt(bytes calldata loanReceipt) external pure returns (LoanReceipt.LoanReceiptV2 memory) {\n        return BorrowLogic._decodeLoanReceipt(loanReceipt);\n    }\n\n    /**************************************************************************/\n    /* Helper Functions */\n    /**************************************************************************/\n\n    /**\n     * @notice Helper function that returns underlying collateral in (address,\n     * uint256[], uint256) shape\n     * @param collateralToken Collateral token, either underlying token or collateral wrapper\n     * @param collateralTokenId Collateral token ID\n     * @param collateralWrapperContext Collateral wrapper context\n     * @return token Underlying collateral token\n     * @return tokenIds Underlying collateral token IDs (unique)\n     * @return tokenCount Underlying total token count\n     */\n    function _getUnderlyingCollateral(\n        address collateralToken,\n        uint256 collateralTokenId,\n        bytes memory collateralWrapperContext\n    ) internal view returns (address token, uint256[] memory tokenIds, uint256 tokenCount) {\n        /* Enumerate if collateral token is a collateral wrapper */\n        if (\n            collateralToken == _collateralWrapper1 ||\n            collateralToken == _collateralWrapper2 ||\n            collateralToken == _collateralWrapper3\n        ) {\n            (token, tokenIds) = ICollateralWrapper(collateralToken).enumerate(\n                collateralTokenId,\n                collateralWrapperContext\n            );\n            tokenCount = ICollateralWrapper(collateralToken).count(collateralTokenId, collateralWrapperContext);\n            return (token, tokenIds, tokenCount);\n        }\n\n        /* If single asset, convert to length one token ID array */\n        token = collateralToken;\n        tokenIds = new uint256[](1);\n        tokenIds[0] = collateralTokenId;\n        tokenCount = 1;\n    }\n\n    /**\n     * @notice Get reference to ERC-7201 delegate storage\n     * @return $ Reference to delegate storage\n     */\n    function _getDelegateStorage() private pure returns (DelegateStorage storage $) {\n        assembly {\n            $.slot := DELEGATE_STORAGE_LOCATION\n        }\n    }\n\n    /**\n     * @dev Helper function to quote a loan\n     * @param principal Principal amount in currency tokens\n     * @param duration Duration in seconds\n     * @param collateralToken Collateral token address\n     * @param collateralTokenId Collateral token ID\n     * @param ticks Liquidity node ticks\n     * @param collateralWrapperContext Collateral wrapper context\n     * @param collateralFilterContext Collateral filter context\n     * @param isRefinance True if called by refinance()\n     * @return Repayment amount in currency tokens, admin fee in currency\n     * tokens, liquidity nodes, liquidity node count\n     */\n    function _quote(\n        uint256 principal,\n        uint64 duration,\n        address collateralToken,\n        uint256 collateralTokenId,\n        uint128[] calldata ticks,\n        bytes memory collateralWrapperContext,\n        bytes calldata collateralFilterContext,\n        bool isRefinance\n    ) internal view returns (uint256, uint256, LiquidityLogic.NodeSource[] memory, uint16) {\n        /* Get underlying collateral */\n        (\n            address underlyingCollateralToken,\n            uint256[] memory underlyingCollateralTokenIds,\n            uint256 underlyingCollateralTokenCount\n        ) = _getUnderlyingCollateral(collateralToken, collateralTokenId, collateralWrapperContext);\n\n        /* Verify collateral is supported */\n        if (!isRefinance) {\n            for (uint256 i; i < underlyingCollateralTokenIds.length; i++) {\n                if (\n                    !_collateralSupported(\n                        underlyingCollateralToken,\n                        underlyingCollateralTokenIds[i],\n                        i,\n                        collateralFilterContext\n                    )\n                ) revert UnsupportedCollateral(i);\n            }\n        }\n\n        /* Cache durations */\n        uint64[] memory durations_ = _storage.durations;\n\n        /* Validate duration */\n        if (duration > durations_[0]) revert UnsupportedLoanDuration();\n\n        /* Lookup duration index */\n        uint256 durationIndex = durations_.length - 1;\n        for (; durationIndex > 0; durationIndex--) {\n            if (duration <= durations_[durationIndex]) break;\n        }\n\n        /* Source liquidity nodes */\n        (LiquidityLogic.NodeSource[] memory nodes, uint16 count) = _storage.liquidity.source(\n            principal,\n            ticks,\n            underlyingCollateralTokenCount,\n            durationIndex\n        );\n\n        /* Price interest for liquidity nodes */\n        (uint256 repayment, uint256 adminFee) = _price(\n            principal,\n            duration,\n            nodes,\n            count,\n            _storage.rates,\n            _storage.adminFeeRate\n        );\n\n        return (repayment, adminFee, nodes, count);\n    }\n\n    /**************************************************************************/\n    /* Lend API */\n    /**************************************************************************/\n\n    /**\n     * @inheritdoc IPool\n     */\n    function quote(\n        uint256 principal,\n        uint64 duration,\n        address collateralToken,\n        uint256 collateralTokenId,\n        uint128[] calldata ticks,\n        bytes calldata options\n    ) external view returns (uint256) {\n        /* Quote repayment */\n        (uint256 repayment, , , ) = _quote(\n            principal,\n            duration,\n            collateralToken,\n            collateralTokenId,\n            ticks,\n            BorrowLogic._getOptionsData(options, BorrowOptions.CollateralWrapperContext),\n            BorrowLogic._getOptionsData(options, BorrowOptions.CollateralFilterContext),\n            false\n        );\n\n        return repayment;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function borrow(\n        uint256 principal,\n        uint64 duration,\n        address collateralToken,\n        uint256 collateralTokenId,\n        uint256 maxRepayment,\n        uint128[] calldata ticks,\n        bytes calldata options\n    ) external nonReentrant returns (uint256) {\n        /* Quote repayment, admin fee, and liquidity nodes */\n        (uint256 repayment, uint256 adminFee, LiquidityLogic.NodeSource[] memory nodes, uint16 count) = _quote(\n            principal,\n            duration,\n            collateralToken,\n            collateralTokenId,\n            ticks,\n            BorrowLogic._getOptionsData(options, BorrowOptions.CollateralWrapperContext),\n            BorrowLogic._getOptionsData(options, BorrowOptions.CollateralFilterContext),\n            false\n        );\n\n        /* Handle borrow accounting */\n        (bytes memory encodedLoanReceipt, bytes32 loanReceiptHash) = BorrowLogic._borrow(\n            _storage,\n            principal,\n            duration,\n            collateralToken,\n            collateralTokenId,\n            repayment,\n            maxRepayment,\n            adminFee,\n            nodes,\n            count,\n            BorrowLogic._getOptionsData(options, BorrowOptions.CollateralWrapperContext)\n        );\n\n        /* Handle delegate.cash option */\n        BorrowLogic._optionDelegateCash(\n            _getDelegateStorage(),\n            collateralToken,\n            collateralTokenId,\n            _delegateRegistryV1,\n            _delegateRegistryV2,\n            options\n        );\n\n        /* Transfer collateral from borrower to pool */\n        IERC721(collateralToken).transferFrom(msg.sender, address(this), collateralTokenId);\n\n        /* Transfer principal from pool to borrower */\n        _storage.currencyToken.safeTransfer(msg.sender, principal);\n\n        /* Emit LoanOriginated */\n        emit LoanOriginated(loanReceiptHash, encodedLoanReceipt);\n\n        return repayment;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function repay(bytes calldata encodedLoanReceipt) external nonReentrant returns (uint256) {\n        /* Handle repay accounting */\n        (uint256 repayment, LoanReceipt.LoanReceiptV2 memory loanReceipt, bytes32 loanReceiptHash) = BorrowLogic._repay(\n            _storage,\n            encodedLoanReceipt\n        );\n\n        /* Revoke delegates */\n        BorrowLogic._revokeDelegates(\n            _getDelegateStorage(),\n            loanReceipt.collateralToken,\n            loanReceipt.collateralTokenId,\n            _delegateRegistryV1,\n            _delegateRegistryV2\n        );\n\n        /* Transfer repayment from borrower to pool */\n        _storage.currencyToken.safeTransferFrom(loanReceipt.borrower, address(this), repayment);\n\n        /* Transfer collateral from pool to borrower */\n        IERC721(loanReceipt.collateralToken).transferFrom(\n            address(this),\n            loanReceipt.borrower,\n            loanReceipt.collateralTokenId\n        );\n\n        /* Emit Loan Repaid */\n        emit LoanRepaid(loanReceiptHash, repayment);\n\n        return repayment;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function refinance(\n        bytes calldata encodedLoanReceipt,\n        uint256 principal,\n        uint64 duration,\n        uint256 maxRepayment,\n        uint128[] calldata ticks\n    ) external nonReentrant returns (uint256) {\n        /* Handle repay accounting */\n        (uint256 repayment, LoanReceipt.LoanReceiptV2 memory loanReceipt, bytes32 loanReceiptHash) = BorrowLogic._repay(\n            _storage,\n            encodedLoanReceipt\n        );\n\n        /* Quote new repayment, admin fee, and liquidity nodes */\n        (uint256 newRepayment, uint256 adminFee, LiquidityLogic.NodeSource[] memory nodes, uint16 count) = _quote(\n            principal,\n            duration,\n            loanReceipt.collateralToken,\n            loanReceipt.collateralTokenId,\n            ticks,\n            loanReceipt.collateralWrapperContext,\n            encodedLoanReceipt[0:0],\n            true\n        );\n\n        /* Handle borrow accounting */\n        (bytes memory newEncodedLoanReceipt, bytes32 newLoanReceiptHash) = BorrowLogic._borrow(\n            _storage,\n            principal,\n            duration,\n            loanReceipt.collateralToken,\n            loanReceipt.collateralTokenId,\n            newRepayment,\n            maxRepayment,\n            adminFee,\n            nodes,\n            count,\n            loanReceipt.collateralWrapperContext\n        );\n\n        /* Determine transfer direction */\n        if (principal < repayment) {\n            /* Transfer prorated repayment less principal from borrower to pool */\n            _storage.currencyToken.safeTransferFrom(loanReceipt.borrower, address(this), repayment - principal);\n        } else {\n            /* Transfer principal less prorated repayment from pool to borrower */\n            _storage.currencyToken.safeTransfer(msg.sender, principal - repayment);\n        }\n\n        /* Emit Loan Repaid */\n        emit LoanRepaid(loanReceiptHash, repayment);\n\n        /* Emit LoanOriginated */\n        emit LoanOriginated(newLoanReceiptHash, newEncodedLoanReceipt);\n\n        return newRepayment;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function liquidate(bytes calldata encodedLoanReceipt) external nonReentrant {\n        /* Handle liquidate accounting */\n        (LoanReceipt.LoanReceiptV2 memory loanReceipt, bytes32 loanReceiptHash) = BorrowLogic._liquidate(\n            _storage,\n            encodedLoanReceipt\n        );\n\n        /* Revoke delegates */\n        BorrowLogic._revokeDelegates(\n            _getDelegateStorage(),\n            loanReceipt.collateralToken,\n            loanReceipt.collateralTokenId,\n            _delegateRegistryV1,\n            _delegateRegistryV2\n        );\n\n        /* Approve collateral for transfer to _collateralLiquidator */\n        IERC721(loanReceipt.collateralToken).approve(address(_collateralLiquidator), loanReceipt.collateralTokenId);\n\n        /* Start liquidation with collateral liquidator */\n        _collateralLiquidator.liquidate(\n            address(_storage.currencyToken),\n            loanReceipt.collateralToken,\n            loanReceipt.collateralTokenId,\n            loanReceipt.collateralWrapperContext,\n            encodedLoanReceipt\n        );\n\n        /* Emit Loan Liquidated */\n        emit LoanLiquidated(loanReceiptHash);\n    }\n\n    /**************************************************************************/\n    /* Callbacks */\n    /**************************************************************************/\n\n    /**\n     * @inheritdoc ICollateralLiquidationReceiver\n     */\n    function onCollateralLiquidated(bytes calldata encodedLoanReceipt, uint256 proceeds) external nonReentrant {\n        /* Validate caller is collateral liquidator */\n        if (msg.sender != address(_collateralLiquidator)) revert InvalidCaller();\n\n        /* Handle collateral liquidation accounting */\n        (uint256 borrowerSurplus, LoanReceipt.LoanReceiptV2 memory loanReceipt, bytes32 loanReceiptHash) = BorrowLogic\n            ._onCollateralLiquidated(_storage, encodedLoanReceipt, proceeds);\n\n        /* Transfer surplus to borrower */\n        if (borrowerSurplus != 0) IERC20(_storage.currencyToken).safeTransfer(loanReceipt.borrower, borrowerSurplus);\n\n        /* Emit Collateral Liquidated */\n        emit CollateralLiquidated(loanReceiptHash, proceeds, borrowerSurplus);\n    }\n\n    /**************************************************************************/\n    /* Deposit API */\n    /**************************************************************************/\n\n    /**\n     * @inheritdoc IPool\n     */\n    function deposit(uint128 tick, uint256 amount, uint256 minShares) external nonReentrant returns (uint256) {\n        /* Handle deposit accounting and compute shares */\n        uint128 shares = DepositLogic._deposit(_storage, tick, amount.toUint128(), minShares.toUint128());\n\n        /* Call token hook */\n        _onExternalTransfer(address(0), msg.sender, tick, shares);\n\n        /* Transfer deposit amount */\n        _storage.currencyToken.safeTransferFrom(msg.sender, address(this), amount);\n\n        /* Emit Deposited */\n        emit Deposited(msg.sender, tick, amount, shares);\n\n        return shares;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function redeem(uint128 tick, uint256 shares) external nonReentrant returns (uint128) {\n        /* Handle redeem accounting */\n        uint128 redemptionId = DepositLogic._redeem(_storage, tick, shares.toUint128());\n\n        /* Call token hook */\n        _onExternalTransfer(msg.sender, address(0), tick, shares);\n\n        /* Emit Redeemed event */\n        emit Redeemed(msg.sender, tick, redemptionId, shares);\n\n        return redemptionId;\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function redemptionAvailable(\n        address account,\n        uint128 tick,\n        uint128 redemptionId\n    ) external view returns (uint256 shares, uint256 amount, uint256 sharesAhead) {\n        /* Handle redemption available accounting */\n        return DepositLogic._redemptionAvailable(_storage, account, tick, redemptionId);\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function withdraw(uint128 tick, uint128 redemptionId) external nonReentrant returns (uint256, uint256) {\n        /* Handle withdraw accounting and compute both shares and amount */\n        (uint128 shares, uint128 amount) = DepositLogic._withdraw(_storage, tick, redemptionId);\n\n        /* Transfer withdrawal amount */\n        if (amount != 0) _storage.currencyToken.safeTransfer(msg.sender, amount);\n\n        /* Emit Withdrawn */\n        emit Withdrawn(msg.sender, tick, redemptionId, shares, amount);\n\n        return (shares, amount);\n    }\n\n    /**\n     * @inheritdoc IPool\n     */\n    function rebalance(\n        uint128 srcTick,\n        uint128 dstTick,\n        uint128 redemptionId,\n        uint256 minShares\n    ) external nonReentrant returns (uint256, uint256, uint256) {\n        /* Handle withdraw accounting and compute both shares and amount */\n        (uint128 oldShares, uint128 amount) = DepositLogic._withdraw(_storage, srcTick, redemptionId);\n\n        /* Handle deposit accounting and compute new shares */\n        uint128 newShares = DepositLogic._deposit(_storage, dstTick, amount, minShares.toUint128());\n\n        /* Call token hook */\n        _onExternalTransfer(address(0), msg.sender, dstTick, newShares);\n\n        /* Emit Withdrawn */\n        emit Withdrawn(msg.sender, srcTick, redemptionId, oldShares, amount);\n\n        /* Emit Deposited */\n        emit Deposited(msg.sender, dstTick, amount, newShares);\n\n        return (oldShares, newShares, amount);\n    }\n\n    /**\n     * @notice Transfer shares between accounts by operator\n     *\n     * @dev Only callable by deposit token contract\n     *\n     * @param from From\n     * @param to To\n     * @param tick Tick\n     * @param shares Shares\n     */\n    function transfer(address from, address to, uint128 tick, uint256 shares) external nonReentrant {\n        /* Validate caller is deposit token created by Pool */\n        if (msg.sender != depositToken(tick)) revert InvalidCaller();\n\n        /* Handle transfer accounting */\n        DepositLogic._transfer(_storage, from, to, tick, shares.toUint128());\n\n        /* Emit Transferred */\n        emit Transferred(from, to, tick, shares);\n    }\n\n    /**\n     * @notice Tokenize a tick\n     *\n     * @param tick Tick\n     * @return Deposit token address\n     */\n    function tokenize(uint128 tick) external returns (address) {\n        /* Validate tick */\n        Tick.validate(tick, 0, 0, _storage.durations.length - 1, 0, _storage.rates.length - 1);\n\n        return _tokenize(tick);\n    }\n\n    /**************************************************************************/\n    /* Admin Fees API */\n    /**************************************************************************/\n\n    /**\n     * @notice Set the admin fee rate\n     *\n     * Emits a {AdminFeeRateUpdated} event.\n     *\n     * @param rate Rate is the admin fee in basis points\n     */\n    function setAdminFeeRate(uint32 rate) external {\n        if (msg.sender != _storage.admin) revert InvalidCaller();\n        if (rate >= LiquidityLogic.BASIS_POINTS_SCALE) revert InvalidParameters();\n\n        _storage.adminFeeRate = rate;\n\n        emit AdminFeeRateUpdated(rate);\n    }\n\n    /**\n     * @notice Withdraw admin fees\n     *\n     * Emits a {AdminFeesWithdrawn} event.\n     *\n     * @param recipient Recipient account\n     * @param amount Amount to withdraw\n     */\n    function withdrawAdminFees(address recipient, uint256 amount) external nonReentrant {\n        if (msg.sender != _storage.admin) revert InvalidCaller();\n        if (recipient == address(0) || amount > _storage.adminFeeBalance) revert InvalidParameters();\n\n        /* Update admin fees balance */\n        _storage.adminFeeBalance -= amount;\n\n        /* Transfer cash from Pool to recipient */\n        _storage.currencyToken.safeTransfer(recipient, amount);\n\n        emit AdminFeesWithdrawn(recipient, amount);\n    }\n\n    /******************************************************/\n    /* ERC165 interface */\n    /******************************************************/\n\n    /**\n     * @inheritdoc IERC165\n     */\n    function supportsInterface(bytes4 interfaceId) public view override returns (bool) {\n        return interfaceId == type(ICollateralLiquidationReceiver).interfaceId || super.supportsInterface(interfaceId);\n    }\n}\n"
      },
      "contracts/rates/InterestRateModel.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../LiquidityLogic.sol\";\n\n/**\n * @title Interest Rate Model API\n * @author MetaStreet Labs\n */\nabstract contract InterestRateModel {\n    /**************************************************************************/\n    /* Errors */\n    /**************************************************************************/\n\n    /**\n     * @notice Invalid parameters\n     */\n    error InvalidInterestRateModelParameters();\n\n    /**************************************************************************/\n    /* API */\n    /**************************************************************************/\n\n    /**\n     * @notice Get interest rate model name\n     * @return Interest rate model name\n     */\n    function INTEREST_RATE_MODEL_NAME() external view virtual returns (string memory);\n\n    /**\n     * @notice Get interest rate model version\n     * @return Interest rate model version\n     */\n    function INTEREST_RATE_MODEL_VERSION() external view virtual returns (string memory);\n\n    /**\n     * @notice Price interest for liquidity\n     * @param principal Principal\n     * @param duration Duration\n     * @param nodes Liquidity nodes\n     * @param count Liquidity node count\n     * @param rates Interest rates\n     * @param adminFeeRate Admin fee rate\n     * @return repayment Repayment\n     * @return adminFee Admin fee\n     */\n    function _price(\n        uint256 principal,\n        uint64 duration,\n        LiquidityLogic.NodeSource[] memory nodes,\n        uint16 count,\n        uint64[] memory rates,\n        uint32 adminFeeRate\n    ) internal view virtual returns (uint256 repayment, uint256 adminFee);\n}\n"
      },
      "contracts/rates/WeightedInterestRateModel.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport \"./InterestRateModel.sol\";\nimport \"../Tick.sol\";\n\n/**\n * @title Weighted Interest Rate Model\n * @author MetaStreet Labs\n */\ncontract WeightedInterestRateModel is InterestRateModel {\n    using SafeCast for uint256;\n\n    /**************************************************************************/\n    /* Constructor */\n    /**************************************************************************/\n\n    /**\n     * @notice WeightedInterestRateModel constructor\n     */\n    constructor() {}\n\n    /**************************************************************************/\n    /* Implementation */\n    /**************************************************************************/\n\n    /**\n     * @inheritdoc InterestRateModel\n     */\n    function INTEREST_RATE_MODEL_NAME() external pure override returns (string memory) {\n        return \"WeightedInterestRateModel\";\n    }\n\n    /**\n     * @inheritdoc InterestRateModel\n     */\n    function INTEREST_RATE_MODEL_VERSION() external pure override returns (string memory) {\n        return \"2.0\";\n    }\n\n    /**\n     * @inheritdoc InterestRateModel\n     */\n    function _price(\n        uint256 principal,\n        uint64 duration,\n        LiquidityLogic.NodeSource[] memory nodes,\n        uint16 count,\n        uint64[] memory rates,\n        uint32 adminFeeRate\n    ) internal pure override returns (uint256, uint256) {\n        /* First pass to compute repayment and weights */\n        uint256[] memory weights = new uint256[](count);\n        uint256 repayment;\n        uint256 normalization;\n        for (uint256 i; i < count; i++) {\n            /* Compute tick repayment */\n            (, , uint256 rateIndex, ) = Tick.decode(nodes[i].tick);\n            uint256 pending = nodes[i].used +\n                Math.mulDiv(nodes[i].used, rates[rateIndex] * duration, LiquidityLogic.FIXED_POINT_SCALE);\n\n            /* Update cumulative repayment */\n            repayment += pending;\n\n            /* Compute tick weight */\n            weights[i] = Math.mulDiv(repayment, pending, principal);\n\n            /* Accumulate weight for normalization */\n            normalization += weights[i];\n        }\n\n        /* Compute interest and admin fee */\n        uint256 interest = repayment - principal;\n        uint256 adminFee = (interest * adminFeeRate) / LiquidityLogic.BASIS_POINTS_SCALE;\n\n        /* Deduct admin fee from interest */\n        interest -= adminFee;\n\n        /* Second pass to assign weighted interest to ticks */\n        uint256 interestRemaining = interest;\n        for (uint256 i; i < count; i++) {\n            /* Compute weighted interest to tick */\n            uint256 weightedInterest = Math.mulDiv(interest, weights[i], normalization);\n\n            /* Assign node pending amount */\n            nodes[i].pending = nodes[i].used + weightedInterest.toUint128();\n\n            /* Track remaining interest */\n            interestRemaining -= weightedInterest;\n        }\n\n        /* Drop off remaining interest dust at lowest node */\n        if (interestRemaining != 0) nodes[0].pending += interestRemaining.toUint128();\n\n        return (repayment, adminFee);\n    }\n}\n"
      },
      "contracts/Tick.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\n/**\n * @title Tick\n * @author MetaStreet Labs\n */\nlibrary Tick {\n    /*\n     * A tick encodes three conditions on liquidity: limit, duration, and rate.\n     * Limit is the maximum depth that liquidity sourced from the node can be\n     * used in. Duration is the maximum allowed duration for that liquidity.\n     * Rate is the interest rate associated with that liquidity. Duration and\n     * rates are encoded as indexes into predetermined, discrete tiers.\n     *\n     * +-----------------------------------------------------------------------+\n     * |                                 128                                   |\n     * +--------------------------------------|----------|----------|----------+\n     * |                  120                 |    3     |     3    |     2    |\n     * |                 Limit                | Dur. Idx | Rate Idx | Reserved |\n     * +-----------------------------------------------------------------------+\n     *\n     * Duration Index is ordered from longest duration to shortest, e.g. 30\n     * days, 14 days, 7 days.\n     *\n     * Rate Index is ordered from lowest rate to highest rate, e.g. 10%, 30%,\n     * 50%.\n     */\n\n    /**************************************************************************/\n    /* Constants */\n    /**************************************************************************/\n\n    /**\n     * @notice Tick limit mask\n     */\n    uint256 internal constant TICK_LIMIT_MASK = 0xffffffffffffffffffffffffffffff;\n\n    /**\n     * @notice Tick limit shift\n     */\n    uint256 internal constant TICK_LIMIT_SHIFT = 8;\n\n    /**\n     * @notice Tick duration index mask\n     */\n    uint256 internal constant TICK_DURATION_MASK = 0x7;\n\n    /**\n     * @notice Tick duration index shift\n     */\n    uint256 internal constant TICK_DURATION_SHIFT = 5;\n\n    /**\n     * @notice Tick rate index mask\n     */\n    uint256 internal constant TICK_RATE_MASK = 0x7;\n\n    /**\n     * @notice Tick rate index shift\n     */\n    uint256 internal constant TICK_RATE_SHIFT = 2;\n\n    /**\n     * @notice Tick reserved mask\n     */\n    uint256 internal constant TICK_RESERVED_MASK = 0x3;\n\n    /**\n     * @notice Tick reserved shift\n     */\n    uint256 internal constant TICK_RESERVED_SHIFT = 0;\n\n    /**\n     * @notice Maximum number of durations supported\n     */\n    uint256 internal constant MAX_NUM_DURATIONS = TICK_DURATION_MASK + 1;\n\n    /**\n     * @notice Maximum number of rates supported\n     */\n    uint256 internal constant MAX_NUM_RATES = TICK_RATE_MASK + 1;\n\n    /**************************************************************************/\n    /* Errors */\n    /**************************************************************************/\n\n    /**\n     * @notice Invalid tick\n     */\n    error InvalidTick();\n\n    /**************************************************************************/\n    /* Helper Functions */\n    /**************************************************************************/\n\n    /**\n     * @dev Decode a Tick\n     * @param tick Tick\n     * @return limit Limit field\n     * @return duration Duration field\n     * @return rate Rate field\n     * @return reserved Reserved field\n     */\n    function decode(\n        uint128 tick\n    ) internal pure returns (uint256 limit, uint256 duration, uint256 rate, uint256 reserved) {\n        limit = ((tick >> TICK_LIMIT_SHIFT) & TICK_LIMIT_MASK);\n        duration = ((tick >> TICK_DURATION_SHIFT) & TICK_DURATION_MASK);\n        rate = ((tick >> TICK_RATE_SHIFT) & TICK_RATE_MASK);\n        reserved = ((tick >> TICK_RESERVED_SHIFT) & TICK_RESERVED_MASK);\n    }\n\n    /**\n     * @dev Validate a Tick (fast)\n     * @param tick Tick\n     * @param prevTick Previous tick\n     * @param maxDurationIndex Maximum Duration Index (inclusive)\n     * @return Limit field\n     */\n    function validate(uint128 tick, uint256 prevTick, uint256 maxDurationIndex) internal pure returns (uint256) {\n        (uint256 limit, uint256 duration, , ) = decode(tick);\n        if (tick <= prevTick) revert InvalidTick();\n        if (duration > maxDurationIndex) revert InvalidTick();\n        return limit;\n    }\n\n    /**\n     * @dev Validate a Tick (slow)\n     * @param tick Tick\n     * @param minLimit Minimum Limit (exclusive)\n     * @param minDurationIndex Minimum Duration Index (inclusive)\n     * @param maxDurationIndex Maximum Duration Index (inclusive)\n     * @param minRateIndex Minimum Rate Index (inclusive)\n     * @param maxRateIndex Maximum Rate Index (inclusive)\n     */\n    function validate(\n        uint128 tick,\n        uint256 minLimit,\n        uint256 minDurationIndex,\n        uint256 maxDurationIndex,\n        uint256 minRateIndex,\n        uint256 maxRateIndex\n    ) internal pure {\n        (uint256 limit, uint256 duration, uint256 rate, uint256 reserved) = decode(tick);\n        if (limit <= minLimit) revert InvalidTick();\n        if (duration < minDurationIndex) revert InvalidTick();\n        if (duration > maxDurationIndex) revert InvalidTick();\n        if (rate < minRateIndex) revert InvalidTick();\n        if (rate > maxRateIndex) revert InvalidTick();\n        if (reserved != 0) revert InvalidTick();\n    }\n}\n"
      },
      "contracts/tokenization/DepositToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Deposit Token API\n * @author MetaStreet Labs\n */\nabstract contract DepositToken {\n    /**************************************************************************/\n    /* Events */\n    /**************************************************************************/\n\n    /**\n     * @notice Emitted when deposit token created\n     * @param instance Instance address\n     * @param implementation Implementation address\n     * @param tick Tick\n     */\n    event TokenCreated(address indexed instance, address indexed implementation, uint128 indexed tick);\n\n    /**************************************************************************/\n    /* API */\n    /**************************************************************************/\n\n    /**\n     * @notice Get the deposit token address for tick\n     *\n     * @param tick Tick\n     * @return Deposit token address\n     */\n    function depositToken(uint128 tick) public view virtual returns (address);\n\n    /**\n     * @notice Tokenize a tick\n     *\n     * @param tick Tick\n     * @return Deposit token address\n     */\n    function _tokenize(uint128 tick) internal virtual returns (address);\n\n    /**\n     * @notice Hook called by Pool on token transfers\n     *\n     * @param from From\n     * @param to To\n     * @param tick Tick\n     * @param shares Shares\n     */\n    function _onExternalTransfer(address from, address to, uint128 tick, uint256 shares) internal virtual;\n}\n"
      },
      "contracts/tokenization/ERC20DepositToken.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"./DepositToken.sol\";\n\nimport \"./ERC20DepositTokenFactory.sol\";\nimport \"./ERC20DepositTokenImplementation.sol\";\n\n/**\n * @title ERC20 Deposit Token\n * @author MetaStreet Labs\n */\ncontract ERC20DepositToken is DepositToken {\n    /**************************************************************************/\n    /* Structures */\n    /**************************************************************************/\n\n    /**\n     * @custom:storage-location erc7201:erc20DepositToken.depositTokenStorage\n     */\n    struct DepositTokenStorage {\n        /* Mapping of tick to token address */\n        mapping(uint128 => address) tokens;\n    }\n\n    /**************************************************************************/\n    /* State */\n    /**************************************************************************/\n\n    /**\n     * @notice Current ERC20 deposit token implementation\n     */\n    address internal immutable _implementation;\n\n    /**\n     * @notice Deposit token storage slot\n     * @dev keccak256(abi.encode(uint256(keccak256(\"erc20DepositToken.depositTokenStorage\")) - 1)) & ~bytes32(uint256(0xff));\n     */\n    bytes32 private constant DEPOSIT_TOKEN_STORAGE_LOCATION =\n        0xc61d9ab4916a5eab6b572dc8707662b99e55e17ecdc61af8ff79465ad64ded00;\n\n    /**************************************************************************/\n    /* Constructor */\n    /**************************************************************************/\n\n    /**\n     * @notice ERC20DepositToken constructor\n     *\n     * @param implementation_ ERC20 deposit token implementation address\n     */\n    constructor(address implementation_) {\n        _implementation = implementation_;\n    }\n\n    /**************************************************************************/\n    /* Internal Helpers */\n    /**************************************************************************/\n\n    /**\n     * @notice Get reference to ERC-7201 deposit token storage\n     *\n     * @return $ Reference to deposit token storage\n     */\n    function _getDepositTokenStorage() private pure returns (DepositTokenStorage storage $) {\n        assembly {\n            $.slot := DEPOSIT_TOKEN_STORAGE_LOCATION\n        }\n    }\n\n    /**************************************************************************/\n    /* API */\n    /**************************************************************************/\n\n    /**\n     * @notice Get ERC20 Deposit Token implementation address\n     *\n     * @return ERC20 Deposit Token implementation address\n     */\n    function getERC20DepositTokenImplementation() external view returns (address) {\n        return _implementation;\n    }\n\n    /**\n     * @notice Tokenize a tick\n     *\n     * @param tick Tick\n     */\n    function _tokenize(uint128 tick) internal override returns (address) {\n        /* Return token if it already exists */\n        address tokenInstance = depositToken(tick);\n        if (tokenInstance != address(0)) {\n            emit TokenCreated(tokenInstance, _implementation, tick);\n\n            return tokenInstance;\n        }\n\n        /* Create proxied token */\n        tokenInstance = ERC20DepositTokenFactory.deploy(tick);\n\n        /* Store token instance in mapping */\n        _getDepositTokenStorage().tokens[tick] = tokenInstance;\n\n        emit TokenCreated(tokenInstance, _implementation, tick);\n\n        return tokenInstance;\n    }\n\n    /**\n     * @inheritdoc DepositToken\n     */\n    function depositToken(uint128 tick) public view override returns (address) {\n        return _getDepositTokenStorage().tokens[tick];\n    }\n\n    /**\n     * @inheritdoc DepositToken\n     */\n    function _onExternalTransfer(address from, address to, uint128 tick, uint256 shares) internal override {\n        /* No operation if token does not exist */\n        if (depositToken(tick) == address(0)) return;\n\n        /* Call external transfer hook */\n        ERC20DepositTokenImplementation(depositToken(tick)).onExternalTransfer(from, to, shares);\n    }\n}\n"
      },
      "contracts/tokenization/ERC20DepositTokenFactory.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/Create2.sol\";\n\nimport \"./ERC20DepositTokenProxy.sol\";\n\n/**\n * @title ERC20 Deposit Token Factory\n * @author MetaStreet Labs\n */\nlibrary ERC20DepositTokenFactory {\n    /**\n     * @notice Deploy a proxied ERC20 deposit token\n     * @param tick Tick\n     * @return Proxy address\n     */\n    function deploy(uint128 tick) external returns (address) {\n        /* Create init data */\n        bytes memory initData = abi.encode(\n            address(this),\n            abi.encodeWithSignature(\"initialize(bytes)\", abi.encode(tick))\n        );\n\n        /* Create token instance */\n        return\n            Create2.deploy(\n                0,\n                bytes32(uint256(tick)),\n                abi.encodePacked(type(ERC20DepositTokenProxy).creationCode, initData)\n            );\n    }\n}\n"
      },
      "contracts/tokenization/ERC20DepositTokenImplementation.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/interfaces/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC721Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\n\nimport \"../Pool.sol\";\nimport \"../interfaces/ILiquidity.sol\";\n\n/**\n * @title ERC20 Deposit Token Implementation\n * @author MetaStreet Labs\n */\ncontract ERC20DepositTokenImplementation is IERC20Metadata {\n    using Tick for uint128;\n    using SafeCast for uint256;\n\n    /**************************************************************************/\n    /* Errors */\n    /**************************************************************************/\n\n    /**\n     * @notice ERC20 Errors from OpenZeppelin implementation:\n     *         https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v5.0.0/contracts/interfaces/draft-IERC6093.sol\n     */\n\n    /**\n     * @notice Insufficient balance\n     *\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @notice Insufficient allowance\n     *\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @notice Invalid spender\n     *\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSpender(address sender);\n\n    /**\n     * @notice Invalid Sender\n     *\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @notice Invalid Receiver\n     *\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @notice Invalid caller\n     */\n    error InvalidCaller();\n\n    /**************************************************************************/\n    /* Constants */\n    /**************************************************************************/\n\n    /**\n     * @notice Implementation version\n     */\n    string public constant IMPLEMENTATION_VERSION = \"1.0\";\n\n    /**\n     * @notice Fixed point scale\n     */\n    uint256 internal constant FIXED_POINT_SCALE = 1e18;\n\n    /**************************************************************************/\n    /* State */\n    /**************************************************************************/\n\n    /**\n     * @notice Initialized boolean\n     */\n    bool internal _initialized;\n\n    /**\n     * @notice MetaStreet V2 Pool\n     */\n    Pool internal _pool;\n\n    /**\n     * @notice Deposit tick\n     */\n    uint128 internal _tick;\n\n    /**\n     * @notice Owner => operator => allowance\n     */\n    mapping(address => mapping(address => uint256)) private _allowances;\n\n    /**************************************************************************/\n    /* Constructor */\n    /**************************************************************************/\n\n    /**\n     * @notice ERC20 Deposit Token Implementation constructor\n     */\n    constructor() {\n        /* Disable initialization of implementation contract */\n        _initialized = true;\n    }\n\n    /**************************************************************************/\n    /* Initializer */\n    /**************************************************************************/\n\n    /**\n     * @notice Initializer\n     * @param params ABI-encoded parameters\n     */\n    function initialize(bytes memory params) external {\n        require(!_initialized, \"Already initialized\");\n        _initialized = true;\n\n        /* Decode parameters */\n        uint128 tick_ = abi.decode(params, (uint128));\n\n        _pool = Pool(msg.sender);\n        _tick = tick_;\n    }\n\n    /**************************************************************************/\n    /* Internal Helpers */\n    /**************************************************************************/\n\n    /**\n     * @notice Helper function to get rounded loan limit for name() and symbol()\n     *\n     * @dev Solely utilized to generate rounded number in name() and symbol() getters.\n     *      Loan limits > 1 ETH are rounded to the nearest whole number. Under 1 ETH\n     *      are rounded to the nearest hundredth place.\n     *\n     * @param loanLimit_ Loan limit as uint256\n     *\n     * @return Loan limit as string\n     */\n    function _getLoanLimit(uint256 loanLimit_) internal pure returns (string memory) {\n        /* Handle loan limits > 1 ETH */\n        if (loanLimit_ >= FIXED_POINT_SCALE) {\n            return Strings.toString((loanLimit_ + (FIXED_POINT_SCALE / 2)) / FIXED_POINT_SCALE);\n        } else {\n            /* Handle loan limits < 1 ETH */\n            uint256 scaledValue = loanLimit_ * 100;\n            uint256 integer = scaledValue / FIXED_POINT_SCALE;\n            if (scaledValue % FIXED_POINT_SCALE >= FIXED_POINT_SCALE / 2) {\n                integer += 1;\n            }\n            uint256 hundredthPlaces = integer % 100;\n            string memory decimalStr = hundredthPlaces < 10\n                ? string.concat(\"0\", Strings.toString(hundredthPlaces))\n                : Strings.toString(hundredthPlaces);\n\n            return string.concat(\"0.\", decimalStr);\n        }\n    }\n\n    /**************************************************************************/\n    /* Getters */\n    /**************************************************************************/\n\n    /**\n     * @inheritdoc IERC20Metadata\n     */\n    function name() public view returns (string memory) {\n        (uint256 limit_, , , ) = _tick.decode();\n        return\n            string.concat(\n                \"MetaStreet V2 Deposit: \",\n                IERC721Metadata(_pool.collateralToken()).symbol(),\n                \"-\",\n                IERC20Metadata(_pool.currencyToken()).symbol(),\n                \":\",\n                _getLoanLimit(limit_)\n            );\n    }\n\n    /**\n     * @inheritdoc IERC20Metadata\n     */\n    function symbol() public view returns (string memory) {\n        (uint256 limit_, , , ) = _tick.decode();\n        return\n            string.concat(\n                \"m\",\n                IERC20Metadata(_pool.currencyToken()).symbol(),\n                \"-\",\n                IERC721Metadata(_pool.collateralToken()).symbol(),\n                \":\",\n                _getLoanLimit(limit_)\n            );\n    }\n\n    /**\n     * @inheritdoc IERC20Metadata\n     */\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @notice Pool\n     * @return Pool address\n     */\n    function pool() external view returns (Pool) {\n        return _pool;\n    }\n\n    /**\n     * @notice Tick\n     * @return Encoded tick\n     */\n    function tick() external view returns (uint128) {\n        return _tick;\n    }\n\n    /**\n     * @notice Tick loan limit\n     * @return Loan limit in currency tokens\n     */\n    function limit() external view returns (uint128) {\n        (uint256 limit_, , , ) = _tick.decode();\n        return limit_.toUint128();\n    }\n\n    /**\n     * @notice Tick duration\n     * @return Duration in seconds\n     */\n    function duration() external view returns (uint64) {\n        (, uint256 durationIndex, , ) = _tick.decode();\n        return _pool.durations()[durationIndex];\n    }\n\n    /**\n     * @notice Tick rate\n     * @return Rate in interest per second\n     */\n    function rate() external view returns (uint64) {\n        (, , uint256 rateIndex, ) = _tick.decode();\n        return _pool.rates()[rateIndex];\n    }\n\n    /**\n     * @notice Currency token\n     * @return Address of currency token\n     */\n    function currencyToken() external view returns (address) {\n        return _pool.currencyToken();\n    }\n\n    /**\n     * @notice Deposit share price\n     * @return Deposit share price\n     */\n    function depositSharePrice() external view returns (uint256) {\n        return _pool.depositSharePrice(_tick);\n    }\n\n    /**\n     * @notice Redemption share price\n     * @return Redemption share price\n     */\n    function redemptionSharePrice() external view returns (uint256) {\n        return _pool.redemptionSharePrice(_tick);\n    }\n\n    /**************************************************************************/\n    /* Internal Helpers */\n    /**************************************************************************/\n\n    /**\n     * @notice Helper function to transfer tokens\n     *\n     * @param from From\n     * @param to To\n     * @param value Value\n     */\n    function _transfer(address from, address to, uint256 value) internal {\n        /* No transfer to zero address */\n        if (to == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n\n        /* Validate balance */\n        uint256 fromBalance = balanceOf(from);\n        if (fromBalance < value) {\n            revert ERC20InsufficientBalance(from, fromBalance, value);\n        }\n\n        /* Call transfer on pool */\n        _pool.transfer(from, to, _tick, value);\n\n        emit Transfer(from, to, value);\n    }\n\n    /**************************************************************************/\n    /* Hooks */\n    /**************************************************************************/\n\n    /**\n     * @notice External transfer hook\n     *\n     * @param from From\n     * @param to To\n     * @param value Value\n     */\n    function onExternalTransfer(address from, address to, uint256 value) external {\n        if (msg.sender != address(_pool)) revert InvalidCaller();\n\n        emit Transfer(from, to, value);\n    }\n\n    /**************************************************************************/\n    /* IERC20 API */\n    /**************************************************************************/\n\n    /**\n     * @inheritdoc IERC20\n     */\n    function totalSupply() public view returns (uint256) {\n        /* Get Pool node */\n        ILiquidity.NodeInfo memory node = _pool.liquidityNode(_tick);\n\n        /* Calculate total supply */\n        return node.shares - node.redemptions;\n    }\n\n    /**\n     * @inheritdoc IERC20\n     */\n    function balanceOf(address account) public view returns (uint256) {\n        /* Get shares from deposits */\n        (uint128 shares, ) = _pool.deposits(account, _tick);\n\n        return shares;\n    }\n\n    /**\n     * @inheritdoc IERC20\n     */\n    function allowance(address owner, address spender) public view returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @inheritdoc IERC20\n     */\n    function approve(address spender, uint256 value) public returns (bool) {\n        if (spender == address(0)) {\n            revert ERC20InvalidSpender(address(0));\n        }\n\n        _allowances[msg.sender][spender] = value;\n\n        emit Approval(msg.sender, spender, value);\n\n        return true;\n    }\n\n    /**\n     * @inheritdoc IERC20\n     */\n    function transfer(address to, uint256 value) public returns (bool) {\n        _transfer(msg.sender, to, value);\n\n        return true;\n    }\n\n    /**\n     * @inheritdoc IERC20\n     */\n    function transferFrom(address from, address to, uint256 value) public returns (bool) {\n        /* No transfer from zero address */\n        if (from == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n\n        /* Check + update allowance */\n        uint256 currentAllowance = allowance(from, msg.sender);\n        if (currentAllowance != type(uint256).max) {\n            if (currentAllowance < value) {\n                revert ERC20InsufficientAllowance(msg.sender, currentAllowance, value);\n            }\n            unchecked {\n                _allowances[from][msg.sender] = currentAllowance - value;\n            }\n        }\n\n        _transfer(from, to, value);\n\n        return true;\n    }\n}\n"
      },
      "contracts/tokenization/ERC20DepositTokenProxy.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/proxy/Proxy.sol\";\nimport \"@openzeppelin/contracts/utils/Address.sol\";\n\nimport \"./ERC20DepositToken.sol\";\n\n/**\n * @title ERC20 Deposit Token Proxy\n * @author MetaStreet Labs\n */\ncontract ERC20DepositTokenProxy is Proxy {\n    /**************************************************************************/\n    /* Constants */\n    /**************************************************************************/\n\n    /**\n     * @notice Beacon address (ERC20DepositToken)\n     */\n    address internal immutable _beacon;\n\n    /**************************************************************************/\n    /* Constructor */\n    /**************************************************************************/\n\n    /**\n     * @notice ERC20DepositTokenProxy constructor\n     *\n     * @dev Set the ERC20DepositToken address as beacon\n     *      and initializes the storage of the Proxy\n     *\n     * @param beacon Beacon address\n     * @param data Initialization data\n     */\n    constructor(address beacon, bytes memory data) {\n        _beacon = beacon;\n        Address.functionDelegateCall(ERC20DepositToken(beacon).getERC20DepositTokenImplementation(), data);\n    }\n\n    /**************************************************************************/\n    /* Getters */\n    /**************************************************************************/\n\n    /**\n     * @notice Get implementation address\n     *\n     * @dev Overrides Proxy._implementation()\n     *\n     * @return Implementation address\n     */\n    function _implementation() internal view virtual override returns (address) {\n        return ERC20DepositToken(_beacon).getERC20DepositTokenImplementation();\n    }\n}\n"
      }
    },
    "settings": {
      "viaIR": true,
      "optimizer": {
        "enabled": true,
        "runs": 400
      },
      "evmVersion": "shanghai",
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {
        "contracts/BorrowLogic.sol": {
          "BorrowLogic": "0x267c9554dc352545e8b28a4b0749d489d1ec5f0b"
        },
        "contracts/DepositLogic.sol": {
          "DepositLogic": "0xab4df303e49deda51e2d7be92a2ff5a30c10f0e1"
        },
        "contracts/LiquidityLogic.sol": {
          "LiquidityLogic": "0xfd41fd6de89e372fd720da1dbb55e72960a2d53d"
        },
        "contracts/tokenization/ERC20DepositTokenFactory.sol": {
          "ERC20DepositTokenFactory": "0x87fb4c61c0f48d781c8da926122accbfa1ee8d25"
        }
      }
    }
  }}