File size: 114,118 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
{
  "language": "Solidity",
  "sources": {
    "lib/openzeppelin-contracts/contracts/access/IAccessControl.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted signaling this.\n     *\n     * _Available since v3.1._\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call, an admin role\n     * bearer except when using {AccessControl-_setupRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) external view returns (bool);\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function grantRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function revokeRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     */\n    function renounceRole(bytes32 role, address account) external;\n}\n"
    },
    "lib/openzeppelin-contracts/contracts/access/IAccessControlEnumerable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.\n */\ninterface IAccessControlEnumerable is IAccessControl {\n    /**\n     * @dev Returns one of the accounts that have `role`. `index` must be a\n     * value between 0 and {getRoleMemberCount}, non-inclusive.\n     *\n     * Role bearers are not sorted in any particular way, and their ordering may\n     * change at any point.\n     *\n     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n     * you perform all queries on the same block. See the following\n     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n     * for more information.\n     */\n    function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n    /**\n     * @dev Returns the number of accounts that have `role`. Can be used\n     * together with {getRoleMember} to enumerate all bearers of a role.\n     */\n    function getRoleMemberCount(bytes32 role) external view returns (uint256);\n}\n"
    },
    "lib/openzeppelin-contracts/contracts/proxy/Clones.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/Clones.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for\n * deploying minimal proxy contracts, also known as \"clones\".\n *\n * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies\n * > a minimal bytecode implementation that delegates all calls to a known, fixed address.\n *\n * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`\n * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the\n * deterministic method.\n *\n * _Available since v3.4._\n */\nlibrary Clones {\n    /**\n     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.\n     *\n     * This function uses the create opcode, which should never revert.\n     */\n    function clone(address implementation) internal returns (address instance) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes\n            // of the `implementation` address with the bytecode before the address.\n            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))\n            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.\n            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))\n            instance := create(0, 0x09, 0x37)\n        }\n        require(instance != address(0), \"ERC1167: create failed\");\n    }\n\n    /**\n     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.\n     *\n     * This function uses the create2 opcode and a `salt` to deterministically deploy\n     * the clone. Using the same `implementation` and `salt` multiple time will revert, since\n     * the clones cannot be deployed twice at the same address.\n     */\n    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes\n            // of the `implementation` address with the bytecode before the address.\n            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))\n            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.\n            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))\n            instance := create2(0, 0x09, 0x37, salt)\n        }\n        require(instance != address(0), \"ERC1167: create2 failed\");\n    }\n\n    /**\n     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n     */\n    function predictDeterministicAddress(\n        address implementation,\n        bytes32 salt,\n        address deployer\n    ) internal pure returns (address predicted) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let ptr := mload(0x40)\n            mstore(add(ptr, 0x38), deployer)\n            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)\n            mstore(add(ptr, 0x14), implementation)\n            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)\n            mstore(add(ptr, 0x58), salt)\n            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))\n            predicted := keccak256(add(ptr, 0x43), 0x55)\n        }\n    }\n\n    /**\n     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n     */\n    function predictDeterministicAddress(address implementation, bytes32 salt)\n        internal\n        view\n        returns (address predicted)\n    {\n        return predictDeterministicAddress(implementation, salt, address(this));\n    }\n}\n"
    },
    "lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _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"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
    },
    "lib/openzeppelin-contracts/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"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    function safeTransfer(\n        IERC20 token,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        uint256 newAllowance = token.allowance(address(this), spender) + value;\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            uint256 newAllowance = oldAllowance - value;\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n        }\n    }\n\n    function safePermit(\n        IERC20Permit token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        if (returndata.length > 0) {\n            // Return data is optional\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n    /**\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n     */\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n     */\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n    /**\n     * @dev Returns the number of tokens in ``owner``'s account.\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @dev Returns the owner of the `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes calldata data\n    ) external;\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: 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(\n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the caller.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function setApprovalForAll(address operator, bool _approved) external;\n\n    /**\n     * @dev Returns the account approved for `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function getApproved(uint256 tokenId) external view returns (address operator);\n\n    /**\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n     *\n     * See {setApprovalForAll}\n     */\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
    },
    "lib/openzeppelin-contracts/contracts/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return 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(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (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"
    },
    "lib/openzeppelin-contracts/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"
    },
    "lib/openzeppelin-contracts/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"
    },
    "src/interfaces/IProtocolGovernance.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport \"./utils/IDefaultAccessControl.sol\";\nimport \"./IUnitPricesGovernance.sol\";\n\ninterface IProtocolGovernance is IDefaultAccessControl, IUnitPricesGovernance {\n    /// @notice CommonLibrary protocol params.\n    /// @param maxTokensPerVault Max different token addresses that could be managed by the vault\n    /// @param governanceDelay The delay (in secs) that must pass before setting new pending params to commiting them\n    /// @param protocolTreasury The address that collects protocolFees, if protocolFee is not zero\n    /// @param forceAllowMask If a permission bit is set in this mask it forces all addresses to have this permission as true\n    /// @param withdrawLimit Withdraw limit (in unit prices, i.e. usd)\n    struct Params {\n        uint256 maxTokensPerVault;\n        uint256 governanceDelay;\n        address protocolTreasury;\n        uint256 forceAllowMask;\n        uint256 withdrawLimit;\n    }\n\n    // -------------------  EXTERNAL, VIEW  -------------------\n\n    /// @notice Timestamp after which staged granted permissions for the given address can be committed.\n    /// @param target The given address\n    /// @return Zero if there are no staged permission grants, timestamp otherwise\n    function stagedPermissionGrantsTimestamps(address target) external view returns (uint256);\n\n    /// @notice Staged granted permission bitmask for the given address.\n    /// @param target The given address\n    /// @return Bitmask\n    function stagedPermissionGrantsMasks(address target) external view returns (uint256);\n\n    /// @notice Permission bitmask for the given address.\n    /// @param target The given address\n    /// @return Bitmask\n    function permissionMasks(address target) external view returns (uint256);\n\n    /// @notice Timestamp after which staged pending protocol parameters can be committed\n    /// @return Zero if there are no staged parameters, timestamp otherwise.\n    function stagedParamsTimestamp() external view returns (uint256);\n\n    /// @notice Staged pending protocol parameters.\n    function stagedParams() external view returns (Params memory);\n\n    /// @notice Current protocol parameters.\n    function params() external view returns (Params memory);\n\n    /// @notice Addresses for which non-zero permissions are set.\n    function permissionAddresses() external view returns (address[] memory);\n\n    /// @notice Permission addresses staged for commit.\n    function stagedPermissionGrantsAddresses() external view returns (address[] memory);\n\n    /// @notice Return all addresses where rawPermissionMask bit for permissionId is set to 1.\n    /// @param permissionId Id of the permission to check.\n    /// @return A list of dirty addresses.\n    function addressesByPermission(uint8 permissionId) external view returns (address[] memory);\n\n    /// @notice Checks if address has permission or given permission is force allowed for any address.\n    /// @param addr Address to check\n    /// @param permissionId Permission to check\n    function hasPermission(address addr, uint8 permissionId) external view returns (bool);\n\n    /// @notice Checks if address has all permissions.\n    /// @param target Address to check\n    /// @param permissionIds A list of permissions to check\n    function hasAllPermissions(address target, uint8[] calldata permissionIds) external view returns (bool);\n\n    /// @notice Max different ERC20 token addresses that could be managed by the protocol.\n    function maxTokensPerVault() external view returns (uint256);\n\n    /// @notice The delay for committing any governance params.\n    function governanceDelay() external view returns (uint256);\n\n    /// @notice The address of the protocol treasury.\n    function protocolTreasury() external view returns (address);\n\n    /// @notice Permissions mask which defines if ordinary permission should be reverted.\n    /// This bitmask is xored with ordinary mask.\n    function forceAllowMask() external view returns (uint256);\n\n    /// @notice Withdraw limit per token per block.\n    /// @param token Address of the token\n    /// @return Withdraw limit per token per block\n    function withdrawLimit(address token) external view returns (uint256);\n\n    /// @notice Addresses that has staged validators.\n    function stagedValidatorsAddresses() external view returns (address[] memory);\n\n    /// @notice Timestamp after which staged granted permissions for the given address can be committed.\n    /// @param target The given address\n    /// @return Zero if there are no staged permission grants, timestamp otherwise\n    function stagedValidatorsTimestamps(address target) external view returns (uint256);\n\n    /// @notice Staged validator for the given address.\n    /// @param target The given address\n    /// @return Validator\n    function stagedValidators(address target) external view returns (address);\n\n    /// @notice Addresses that has validators.\n    function validatorsAddresses() external view returns (address[] memory);\n\n    /// @notice Address that has validators.\n    /// @param i The number of address\n    /// @return Validator address\n    function validatorsAddress(uint256 i) external view returns (address);\n\n    /// @notice Validator for the given address.\n    /// @param target The given address\n    /// @return Validator\n    function validators(address target) external view returns (address);\n\n    // -------------------  EXTERNAL, MUTATING, GOVERNANCE, IMMEDIATE  -------------------\n\n    /// @notice Rollback all staged validators.\n    function rollbackStagedValidators() external;\n\n    /// @notice Revoke validator instantly from the given address.\n    /// @param target The given address\n    function revokeValidator(address target) external;\n\n    /// @notice Stages a new validator for the given address\n    /// @param target The given address\n    /// @param validator The validator for the given address\n    function stageValidator(address target, address validator) external;\n\n    /// @notice Commits validator for the given address.\n    /// @dev Reverts if governance delay has not passed yet.\n    /// @param target The given address.\n    function commitValidator(address target) external;\n\n    /// @notice Commites all staged validators for which governance delay passed\n    /// @return Addresses for which validators were committed\n    function commitAllValidatorsSurpassedDelay() external returns (address[] memory);\n\n    /// @notice Rollback all staged granted permission grant.\n    function rollbackStagedPermissionGrants() external;\n\n    /// @notice Commits permission grants for the given address.\n    /// @dev Reverts if governance delay has not passed yet.\n    /// @param target The given address.\n    function commitPermissionGrants(address target) external;\n\n    /// @notice Commites all staged permission grants for which governance delay passed.\n    /// @return An array of addresses for which permission grants were committed.\n    function commitAllPermissionGrantsSurpassedDelay() external returns (address[] memory);\n\n    /// @notice Revoke permission instantly from the given address.\n    /// @param target The given address.\n    /// @param permissionIds A list of permission ids to revoke.\n    function revokePermissions(address target, uint8[] memory permissionIds) external;\n\n    /// @notice Commits staged protocol params.\n    /// Reverts if governance delay has not passed yet.\n    function commitParams() external;\n\n    // -------------------  EXTERNAL, MUTATING, GOVERNANCE, DELAY  -------------------\n\n    /// @notice Sets new pending params that could have been committed after governance delay expires.\n    /// @param newParams New protocol parameters to set.\n    function stageParams(Params memory newParams) external;\n\n    /// @notice Stage granted permissions that could have been committed after governance delay expires.\n    /// Resets commit delay and permissions if there are already staged permissions for this address.\n    /// @param target Target address\n    /// @param permissionIds A list of permission ids to grant\n    function stagePermissionGrants(address target, uint8[] memory permissionIds) external;\n}\n"
    },
    "src/interfaces/IUnitPricesGovernance.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport \"./utils/IDefaultAccessControl.sol\";\n\ninterface IUnitPricesGovernance is IDefaultAccessControl, IERC165 {\n    // -------------------  EXTERNAL, VIEW  -------------------\n\n    /// @notice Estimated amount of token worth 1 USD staged for commit.\n    /// @param token Address of the token\n    /// @return The amount of token\n    function stagedUnitPrices(address token) external view returns (uint256);\n\n    /// @notice Timestamp after which staged unit prices for the given token can be committed.\n    /// @param token Address of the token\n    /// @return Timestamp\n    function stagedUnitPricesTimestamps(address token) external view returns (uint256);\n\n    /// @notice Estimated amount of token worth 1 USD.\n    /// @param token Address of the token\n    /// @return The amount of token\n    function unitPrices(address token) external view returns (uint256);\n\n    // -------------------  EXTERNAL, MUTATING  -------------------\n\n    /// @notice Stage estimated amount of token worth 1 USD staged for commit.\n    /// @param token Address of the token\n    /// @param value The amount of token\n    function stageUnitPrice(address token, uint256 value) external;\n\n    /// @notice Reset staged value\n    /// @param token Address of the token\n    function rollbackUnitPrice(address token) external;\n\n    /// @notice Commit staged unit price\n    /// @param token Address of the token\n    function commitUnitPrice(address token) external;\n}\n"
    },
    "src/interfaces/IVaultRegistry.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.9;\n\nimport \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport \"./IProtocolGovernance.sol\";\n\ninterface IVaultRegistry is IERC721 {\n    /// @notice Get Vault for the giver NFT ID.\n    /// @param nftId NFT ID\n    /// @return vault Address of the Vault contract\n    function vaultForNft(uint256 nftId) external view returns (address vault);\n\n    /// @notice Get NFT ID for given Vault contract address.\n    /// @param vault Address of the Vault contract\n    /// @return nftId NFT ID\n    function nftForVault(address vault) external view returns (uint256 nftId);\n\n    /// @notice Checks if the nft is locked for all transfers\n    /// @param nft NFT to check for lock\n    /// @return `true` if locked, false otherwise\n    function isLocked(uint256 nft) external view returns (bool);\n\n    /// @notice Register new Vault and mint NFT.\n    /// @param vault address of the vault\n    /// @param owner owner of the NFT\n    /// @return nft Nft minted for the given Vault\n    function registerVault(address vault, address owner) external returns (uint256 nft);\n\n    /// @notice Number of Vaults registered.\n    function vaultsCount() external view returns (uint256);\n\n    /// @notice All Vaults registered.\n    function vaults() external view returns (address[] memory);\n\n    /// @notice Address of the ProtocolGovernance.\n    function protocolGovernance() external view returns (IProtocolGovernance);\n\n    /// @notice Address of the staged ProtocolGovernance.\n    function stagedProtocolGovernance() external view returns (IProtocolGovernance);\n\n    /// @notice Minimal timestamp when staged ProtocolGovernance can be applied.\n    function stagedProtocolGovernanceTimestamp() external view returns (uint256);\n\n    /// @notice Stage new ProtocolGovernance.\n    /// @param newProtocolGovernance new ProtocolGovernance\n    function stageProtocolGovernance(IProtocolGovernance newProtocolGovernance) external;\n\n    /// @notice Commit new ProtocolGovernance.\n    function commitStagedProtocolGovernance() external;\n\n    /// @notice Lock NFT for transfers\n    /// @dev Use this method when vault structure is set up and should become immutable. Can be called by owner.\n    /// @param nft - NFT to lock\n    function lockNft(uint256 nft) external;\n}\n"
    },
    "src/interfaces/external/erc/IERC1271.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\ninterface IERC1271 {\n    /// @notice Verifies offchain signature.\n    /// @dev Should return whether the signature provided is valid for the provided hash\n    ///\n    /// MUST return the bytes4 magic value 0x1626ba7e when function passes.\n    ///\n    /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)\n    ///\n    /// MUST allow external calls\n    /// @param _hash Hash of the data to be signed\n    /// @param _signature Signature byte array associated with _hash\n    /// @return magicValue 0x1626ba7e if valid, 0xffffffff otherwise\n    function isValidSignature(bytes32 _hash, bytes memory _signature) external view returns (bytes4 magicValue);\n}\n"
    },
    "src/interfaces/utils/IDefaultAccessControl.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport \"@openzeppelin/contracts/access/IAccessControlEnumerable.sol\";\n\ninterface IDefaultAccessControl is IAccessControlEnumerable {\n    /// @notice Checks that the address is contract admin.\n    /// @param who Address to check\n    /// @return `true` if who is admin, `false` otherwise\n    function isAdmin(address who) external view returns (bool);\n\n    /// @notice Checks that the address is contract admin.\n    /// @param who Address to check\n    /// @return `true` if who is operator, `false` otherwise\n    function isOperator(address who) external view returns (bool);\n}\n"
    },
    "src/interfaces/validators/IBaseValidator.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport \"../IProtocolGovernance.sol\";\n\ninterface IBaseValidator {\n    /// @notice Validator parameters\n    /// @param protocolGovernance Reference to Protocol Governance\n    struct ValidatorParams {\n        IProtocolGovernance protocolGovernance;\n    }\n\n    /// @notice Validator params staged to commit.\n    function stagedValidatorParams() external view returns (ValidatorParams memory);\n\n    /// @notice Timestamp after which validator params can be committed.\n    function stagedValidatorParamsTimestamp() external view returns (uint256);\n\n    /// @notice Current validator params.\n    function validatorParams() external view returns (ValidatorParams memory);\n\n    /// @notice Stage new validator params for commit.\n    /// @param newParams New params for commit\n    function stageValidatorParams(ValidatorParams calldata newParams) external;\n\n    /// @notice Commit new validator params.\n    function commitValidatorParams() external;\n}\n"
    },
    "src/interfaces/validators/IValidator.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport \"./IBaseValidator.sol\";\n\ninterface IValidator is IBaseValidator, IERC165 {\n    // @notice Validate if call can be made to external contract.\n    // @dev Reverts if validation failed. Returns nothing if validation is ok\n    // @param sender Sender of the externalCall method\n    // @param addr Address of the called contract\n    // @param value Ether value for the call\n    // @param selector Selector of the called method\n    // @param data Call data after selector\n    function validate(\n        address sender,\n        address addr,\n        uint256 value,\n        bytes4 selector,\n        bytes calldata data\n    ) external view;\n}\n"
    },
    "src/interfaces/vaults/IERC20Vault.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport \"./IIntegrationVault.sol\";\n\ninterface IERC20Vault is IIntegrationVault {\n    /// @notice Initialized a new contract.\n    /// @dev Can only be initialized by vault governance\n    /// @param nft_ NFT of the vault in the VaultRegistry\n    /// @param vaultTokens_ ERC20 tokens that will be managed by this Vault\n    function initialize(uint256 nft_, address[] memory vaultTokens_) external;\n}\n"
    },
    "src/interfaces/vaults/IIntegrationVault.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport \"../external/erc/IERC1271.sol\";\nimport \"./IVault.sol\";\n\ninterface IIntegrationVault is IVault, IERC1271 {\n    /// @notice Pushes tokens on the vault balance to the underlying protocol. For example, for Yearn this operation will take USDC from\n    /// the contract balance and convert it to yUSDC.\n    /// @dev Tokens **must** be a subset of Vault Tokens. However, the convention is that if tokenAmount == 0 it is the same as token is missing.\n    ///\n    /// Also notice that this operation doesn't guarantee that tokenAmounts will be invested in full.\n    /// @param tokens Tokens to push\n    /// @param tokenAmounts Amounts of tokens to push\n    /// @param options Additional options that could be needed for some vaults. E.g. for Uniswap this could be `deadline` param. For the exact bytes structure see concrete vault descriptions\n    /// @return actualTokenAmounts The amounts actually invested. It could be less than tokenAmounts (but not higher)\n    function push(\n        address[] memory tokens,\n        uint256[] memory tokenAmounts,\n        bytes memory options\n    ) external returns (uint256[] memory actualTokenAmounts);\n\n    /// @notice The same as `push` method above but transfers tokens to vault balance prior to calling push.\n    /// After the `push` it returns all the leftover tokens back (`push` method doesn't guarantee that tokenAmounts will be invested in full).\n    /// @param tokens Tokens to push\n    /// @param tokenAmounts Amounts of tokens to push\n    /// @param options Additional options that could be needed for some vaults. E.g. for Uniswap this could be `deadline` param. For the exact bytes structure see concrete vault descriptions\n    /// @return actualTokenAmounts The amounts actually invested. It could be less than tokenAmounts (but not higher)\n    function transferAndPush(\n        address from,\n        address[] memory tokens,\n        uint256[] memory tokenAmounts,\n        bytes memory options\n    ) external returns (uint256[] memory actualTokenAmounts);\n\n    /// @notice Pulls tokens from the underlying protocol to the `to` address.\n    /// @dev Can only be called but Vault Owner or Strategy. Vault owner is the owner of NFT for this vault in VaultManager.\n    /// Strategy is approved address for the vault NFT.\n    /// When called by vault owner this method just pulls the tokens from the protocol to the `to` address\n    /// When called by strategy on vault other than zero vault it pulls the tokens to zero vault (required `to` == zero vault)\n    /// When called by strategy on zero vault it pulls the tokens to zero vault, pushes tokens on the `to` vault, and reclaims everything that's left.\n    /// Thus any vault other than zero vault cannot have any tokens on it\n    ///\n    /// Tokens **must** be a subset of Vault Tokens. However, the convention is that if tokenAmount == 0 it is the same as token is missing.\n    ///\n    /// Pull is fulfilled on the best effort basis, i.e. if the tokenAmounts overflows available funds it withdraws all the funds.\n    /// @param to Address to receive the tokens\n    /// @param tokens Tokens to pull\n    /// @param tokenAmounts Amounts of tokens to pull\n    /// @param options Additional options that could be needed for some vaults. E.g. for Uniswap this could be `deadline` param. For the exact bytes structure see concrete vault descriptions\n    /// @return actualTokenAmounts The amounts actually withdrawn. It could be less than tokenAmounts (but not higher)\n    function pull(\n        address to,\n        address[] memory tokens,\n        uint256[] memory tokenAmounts,\n        bytes memory options\n    ) external returns (uint256[] memory actualTokenAmounts);\n\n    /// @notice Claim ERC20 tokens from vault balance to zero vault.\n    /// @dev Cannot be called from zero vault.\n    /// @param tokens Tokens to claim\n    /// @return actualTokenAmounts Amounts reclaimed\n    function reclaimTokens(address[] memory tokens) external returns (uint256[] memory actualTokenAmounts);\n\n    /// @notice Execute one of whitelisted calls.\n    /// @dev Can only be called by Vault Owner or Strategy. Vault owner is the owner of NFT for this vault in VaultManager.\n    /// Strategy is approved address for the vault NFT.\n    ///\n    /// Since this method allows sending arbitrary transactions, the destinations of the calls\n    /// are whitelisted by Protocol Governance.\n    /// @param to Address of the reward pool\n    /// @param selector Selector of the call\n    /// @param data Abi encoded parameters to `to::selector`\n    /// @return result Result of execution of the call\n    function externalCall(\n        address to,\n        bytes4 selector,\n        bytes memory data\n    ) external payable returns (bytes memory result);\n}\n"
    },
    "src/interfaces/vaults/IVault.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport \"./IVaultGovernance.sol\";\n\ninterface IVault is IERC165 {\n    /// @notice Checks if the vault is initialized\n\n    function initialized() external view returns (bool);\n\n    /// @notice VaultRegistry NFT for this vault\n    function nft() external view returns (uint256);\n\n    /// @notice Address of the Vault Governance for this contract.\n    function vaultGovernance() external view returns (IVaultGovernance);\n\n    /// @notice ERC20 tokens under Vault management.\n    function vaultTokens() external view returns (address[] memory);\n\n    /// @notice Checks if a token is vault token\n    /// @param token Address of the token to check\n    /// @return `true` if this token is managed by Vault\n    function isVaultToken(address token) external view returns (bool);\n\n    /// @notice Total value locked for this contract.\n    /// @dev Generally it is the underlying token value of this contract in some\n    /// other DeFi protocol. For example, for USDC Yearn Vault this would be total USDC balance that could be withdrawn for Yearn to this contract.\n    /// The tvl itself is estimated in some range. Sometimes the range is exact, sometimes it's not\n    /// @return minTokenAmounts Lower bound for total available balances estimation (nth tokenAmount corresponds to nth token in vaultTokens)\n    /// @return maxTokenAmounts Upper bound for total available balances estimation (nth tokenAmount corresponds to nth token in vaultTokens)\n    function tvl() external view returns (uint256[] memory minTokenAmounts, uint256[] memory maxTokenAmounts);\n\n    /// @notice Existential amounts for each token\n    function pullExistentials() external view returns (uint256[] memory);\n}\n"
    },
    "src/interfaces/vaults/IVaultGovernance.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport \"../IProtocolGovernance.sol\";\nimport \"../IVaultRegistry.sol\";\nimport \"./IVault.sol\";\n\ninterface IVaultGovernance {\n    /// @notice Internal references of the contract.\n    /// @param protocolGovernance Reference to Protocol Governance\n    /// @param registry Reference to Vault Registry\n    struct InternalParams {\n        IProtocolGovernance protocolGovernance;\n        IVaultRegistry registry;\n        IVault singleton;\n    }\n\n    // -------------------  EXTERNAL, VIEW  -------------------\n\n    /// @notice Timestamp in unix time seconds after which staged Delayed Strategy Params could be committed.\n    /// @param nft Nft of the vault\n    function delayedStrategyParamsTimestamp(uint256 nft) external view returns (uint256);\n\n    /// @notice Timestamp in unix time seconds after which staged Delayed Protocol Params could be committed.\n    function delayedProtocolParamsTimestamp() external view returns (uint256);\n\n    /// @notice Timestamp in unix time seconds after which staged Delayed Protocol Params Per Vault could be committed.\n    /// @param nft Nft of the vault\n    function delayedProtocolPerVaultParamsTimestamp(uint256 nft) external view returns (uint256);\n\n    /// @notice Timestamp in unix time seconds after which staged Internal Params could be committed.\n    function internalParamsTimestamp() external view returns (uint256);\n\n    /// @notice Internal Params of the contract.\n    function internalParams() external view returns (InternalParams memory);\n\n    /// @notice Staged new Internal Params.\n    /// @dev The Internal Params could be committed after internalParamsTimestamp\n    function stagedInternalParams() external view returns (InternalParams memory);\n\n    // -------------------  EXTERNAL, MUTATING  -------------------\n\n    /// @notice Stage new Internal Params.\n    /// @param newParams New Internal Params\n    function stageInternalParams(InternalParams memory newParams) external;\n\n    /// @notice Commit staged Internal Params.\n    function commitInternalParams() external;\n}\n"
    },
    "src/interfaces/vaults/IVaultRoot.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\ninterface IVaultRoot {\n    /// @notice Checks if subvault is present\n    /// @param nft_ index of subvault for check\n    /// @return `true` if subvault present, `false` otherwise\n    function hasSubvault(uint256 nft_) external view returns (bool);\n\n    /// @notice Get subvault by index\n    /// @param index Index of subvault\n    /// @return address Address of the contract\n    function subvaultAt(uint256 index) external view returns (address);\n\n    /// @notice Get index of subvault by nft\n    /// @param nft_ Nft for getting subvault\n    /// @return index Index of subvault\n    function subvaultOneBasedIndex(uint256 nft_) external view returns (uint256);\n\n    /// @notice Get all subvalutNfts in the current Vault\n    /// @return subvaultNfts Subvaults of NTFs\n    function subvaultNfts() external view returns (uint256[] memory);\n}\n"
    },
    "src/libraries/CommonLibrary.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport \"./external/FullMath.sol\";\nimport \"./ExceptionsLibrary.sol\";\n\n/// @notice CommonLibrary shared utilities\nlibrary CommonLibrary {\n    uint256 constant DENOMINATOR = 10**9;\n    uint256 constant D18 = 10**18;\n    uint256 constant YEAR = 365 * 24 * 3600;\n    uint256 constant Q128 = 2**128;\n    uint256 constant Q96 = 2**96;\n    uint256 constant Q48 = 2**48;\n    uint256 constant Q160 = 2**160;\n    uint256 constant UNI_FEE_DENOMINATOR = 10**6;\n\n    /// @notice Sort uint256 using bubble sort. The sorting is done in-place.\n    /// @param arr Array of uint256\n    function sortUint(uint256[] memory arr) internal pure {\n        uint256 l = arr.length;\n        for (uint256 i = 0; i < l; ++i) {\n            for (uint256 j = i + 1; j < l; ++j) {\n                if (arr[i] > arr[j]) {\n                    uint256 temp = arr[i];\n                    arr[i] = arr[j];\n                    arr[j] = temp;\n                }\n            }\n        }\n    }\n\n    /// @notice Checks if array of addresses is sorted and all adresses are unique\n    /// @param tokens A set of addresses to check\n    /// @return `true` if all addresses are sorted and unique, `false` otherwise\n    function isSortedAndUnique(address[] memory tokens) internal pure returns (bool) {\n        if (tokens.length < 2) {\n            return true;\n        }\n        for (uint256 i = 0; i < tokens.length - 1; ++i) {\n            if (tokens[i] >= tokens[i + 1]) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /// @notice Projects tokenAmounts onto subset or superset of tokens\n    /// @dev\n    /// Requires both sets of tokens to be sorted. When tokens are not sorted, it's undefined behavior.\n    /// If there is a token in tokensToProject that is not part of tokens and corresponding tokenAmountsToProject > 0, reverts.\n    /// Zero token amount is eqiuvalent to missing token\n    function projectTokenAmounts(\n        address[] memory tokens,\n        address[] memory tokensToProject,\n        uint256[] memory tokenAmountsToProject\n    ) internal pure returns (uint256[] memory) {\n        uint256[] memory res = new uint256[](tokens.length);\n        uint256 t = 0;\n        uint256 tp = 0;\n        while ((t < tokens.length) && (tp < tokensToProject.length)) {\n            if (tokens[t] < tokensToProject[tp]) {\n                res[t] = 0;\n                t++;\n            } else if (tokens[t] > tokensToProject[tp]) {\n                if (tokenAmountsToProject[tp] == 0) {\n                    tp++;\n                } else {\n                    revert(\"TPS\");\n                }\n            } else {\n                res[t] = tokenAmountsToProject[tp];\n                t++;\n                tp++;\n            }\n        }\n        while (t < tokens.length) {\n            res[t] = 0;\n            t++;\n        }\n        return res;\n    }\n\n    /// @notice Calculated sqrt of uint in X96 format\n    /// @param xX96 input number in X96 format\n    /// @return sqrt of xX96 in X96 format\n    function sqrtX96(uint256 xX96) internal pure returns (uint256) {\n        uint256 sqX96 = sqrt(xX96);\n        return sqX96 << 48;\n    }\n\n    /// @notice Calculated sqrt of uint\n    /// @param x input number\n    /// @return sqrt of x\n    function sqrt(uint256 x) internal pure returns (uint256) {\n        if (x == 0) return 0;\n        uint256 xx = x;\n        uint256 r = 1;\n        if (xx >= 0x100000000000000000000000000000000) {\n            xx >>= 128;\n            r <<= 64;\n        }\n        if (xx >= 0x10000000000000000) {\n            xx >>= 64;\n            r <<= 32;\n        }\n        if (xx >= 0x100000000) {\n            xx >>= 32;\n            r <<= 16;\n        }\n        if (xx >= 0x10000) {\n            xx >>= 16;\n            r <<= 8;\n        }\n        if (xx >= 0x100) {\n            xx >>= 8;\n            r <<= 4;\n        }\n        if (xx >= 0x10) {\n            xx >>= 4;\n            r <<= 2;\n        }\n        if (xx >= 0x8) {\n            r <<= 1;\n        }\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        uint256 r1 = x / r;\n        return (r < r1 ? r : r1);\n    }\n\n    /// @notice Recovers signer address from signed message hash\n    /// @param _ethSignedMessageHash signed message\n    /// @param _signature contatenated ECDSA r, s, v (65 bytes)\n    /// @return Recovered address if the signature is valid, address(0) otherwise\n    function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) internal pure returns (address) {\n        (bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);\n\n        return ecrecover(_ethSignedMessageHash, v, r, s);\n    }\n\n    /// @notice Get ECDSA r, s, v from signature\n    /// @param sig signature (65 bytes)\n    /// @return r ECDSA r\n    /// @return s ECDSA s\n    /// @return v ECDSA v\n    function splitSignature(bytes memory sig)\n        internal\n        pure\n        returns (\n            bytes32 r,\n            bytes32 s,\n            uint8 v\n        )\n    {\n        require(sig.length == 65, ExceptionsLibrary.INVALID_LENGTH);\n\n        assembly {\n            r := mload(add(sig, 32))\n            s := mload(add(sig, 64))\n            v := byte(0, mload(add(sig, 96)))\n        }\n    }\n}\n"
    },
    "src/libraries/ExceptionsLibrary.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\n/// @notice Exceptions stores project`s smart-contracts exceptions\nlibrary ExceptionsLibrary {\n    string constant ADDRESS_ZERO = \"AZ\";\n    string constant VALUE_ZERO = \"VZ\";\n    string constant EMPTY_LIST = \"EMPL\";\n    string constant NOT_FOUND = \"NF\";\n    string constant INIT = \"INIT\";\n    string constant DUPLICATE = \"DUP\";\n    string constant NULL = \"NULL\";\n    string constant TIMESTAMP = \"TS\";\n    string constant FORBIDDEN = \"FRB\";\n    string constant ALLOWLIST = \"ALL\";\n    string constant LIMIT_OVERFLOW = \"LIMO\";\n    string constant LIMIT_UNDERFLOW = \"LIMU\";\n    string constant INVALID_VALUE = \"INV\";\n    string constant INVARIANT = \"INVA\";\n    string constant INVALID_TARGET = \"INVTR\";\n    string constant INVALID_TOKEN = \"INVTO\";\n    string constant INVALID_INTERFACE = \"INVI\";\n    string constant INVALID_SELECTOR = \"INVS\";\n    string constant INVALID_STATE = \"INVST\";\n    string constant INVALID_LENGTH = \"INVL\";\n    string constant LOCK = \"LCKD\";\n    string constant DISABLED = \"DIS\";\n}\n"
    },
    "src/libraries/PermissionIdsLibrary.sol": {
      "content": "//SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\n/// @notice Stores permission ids for addresses\nlibrary PermissionIdsLibrary {\n    // The msg.sender is allowed to register vault\n    uint8 constant REGISTER_VAULT = 0;\n    // The msg.sender is allowed to create vaults\n    uint8 constant CREATE_VAULT = 1;\n    // The token is allowed to be transfered by vault\n    uint8 constant ERC20_TRANSFER = 2;\n    // The token is allowed to be added to vault\n    uint8 constant ERC20_VAULT_TOKEN = 3;\n    // Trusted protocols that are allowed to be approved of vault ERC20 tokens by any strategy\n    uint8 constant ERC20_APPROVE = 4;\n    // Trusted protocols that are allowed to be approved of vault ERC20 tokens by trusted strategy\n    uint8 constant ERC20_APPROVE_RESTRICTED = 5;\n    // Strategy allowed using restricted API\n    uint8 constant TRUSTED_STRATEGY = 6;\n}\n"
    },
    "src/libraries/external/FullMath.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity =0.8.9;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n    function mulDiv(\n        uint256 a,\n        uint256 b,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        // diff: original lib works under 0.7.6 with overflows enabled\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = a * b\n            // Compute the product mod 2**256 and mod 2**256 - 1\n            // then use the Chinese Remainder Theorem to reconstruct\n            // 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(a, b, not(0))\n                prod0 := mul(a, b)\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                require(denominator > 0);\n                assembly {\n                    result := div(prod0, denominator)\n                }\n                return result;\n            }\n\n            // Make sure the result is less than 2**256.\n            // Also prevents denominator == 0\n            require(denominator > prod1);\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0]\n            // Compute remainder using mulmod\n            uint256 remainder;\n            assembly {\n                remainder := mulmod(a, b, denominator)\n            }\n            // Subtract 256 bit number from 512 bit number\n            assembly {\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator\n            // Compute largest power of two divisor of denominator.\n            // Always >= 1.\n            // diff: original uint256 twos = -denominator & denominator;\n            uint256 twos = uint256(-int256(denominator)) & denominator;\n            // Divide denominator by power of two\n            assembly {\n                denominator := div(denominator, twos)\n            }\n\n            // Divide [prod1 prod0] by the factors of two\n            assembly {\n                prod0 := div(prod0, twos)\n            }\n            // Shift in bits from prod1 into prod0. For this we need\n            // to flip `twos` such that it is 2**256 / twos.\n            // If twos is zero, then it becomes one\n            assembly {\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2**256\n            // Now that denominator is an odd number, it has an inverse\n            // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n            // Compute the inverse by starting with a seed that is correct\n            // correct for four bits. That is, denominator * inv = 1 mod 2**4\n            uint256 inv = (3 * denominator) ^ 2;\n            // Now use Newton-Raphson iteration to improve the precision.\n            // Thanks to Hensel's lifting lemma, this also works in modular\n            // arithmetic, doubling the correct bits in each step.\n            inv *= 2 - denominator * inv; // inverse mod 2**8\n            inv *= 2 - denominator * inv; // inverse mod 2**16\n            inv *= 2 - denominator * inv; // inverse mod 2**32\n            inv *= 2 - denominator * inv; // inverse mod 2**64\n            inv *= 2 - denominator * inv; // inverse mod 2**128\n            inv *= 2 - denominator * inv; // inverse mod 2**256\n\n            // Because the division is now exact we can divide by multiplying\n            // with the modular inverse of denominator. This will give us the\n            // correct result modulo 2**256. Since the precoditions guarantee\n            // that the outcome is less than 2**256, this is the final result.\n            // We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inv;\n            return result;\n        }\n    }\n\n    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    function mulDivRoundingUp(\n        uint256 a,\n        uint256 b,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        // diff: original lib works under 0.7.6 with overflows enabled\n        unchecked {\n            result = mulDiv(a, b, denominator);\n            if (mulmod(a, b, denominator) > 0) {\n                require(result < type(uint256).max);\n                result++;\n            }\n        }\n    }\n}\n"
    },
    "src/vaults/ERC20Vault.sol": {
      "content": "// SPDX-License-Identifier: BSL-1.1\npragma solidity =0.8.9;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport \"../interfaces/IProtocolGovernance.sol\";\nimport \"../interfaces/vaults/IERC20Vault.sol\";\nimport \"../libraries/ExceptionsLibrary.sol\";\nimport \"./IntegrationVault.sol\";\n\n/// @notice Vault that stores ERC20 tokens.\ncontract ERC20Vault is IERC20Vault, IntegrationVault {\n    using SafeERC20 for IERC20;\n\n    // -------------------  EXTERNAL, VIEW  -------------------\n\n    /// @inheritdoc IVault\n    function tvl() public view returns (uint256[] memory minTokenAmounts, uint256[] memory maxTokenAmounts) {\n        address[] memory tokens = _vaultTokens;\n        uint256 len = tokens.length;\n        minTokenAmounts = new uint256[](len);\n        for (uint256 i = 0; i < len; ++i) {\n            minTokenAmounts[i] = IERC20(tokens[i]).balanceOf(address(this));\n        }\n        maxTokenAmounts = minTokenAmounts;\n    }\n\n    // -------------------  EXTERNAL, MUTATING  -------------------\n    /// @inheritdoc IERC20Vault\n    function initialize(uint256 nft_, address[] memory vaultTokens_) external {\n        _initialize(vaultTokens_, nft_);\n    }\n\n    // -------------------  INTERNAL, VIEW  -----------------------\n    function _isReclaimForbidden(address token) internal view override returns (bool) {\n        uint256 len = _vaultTokens.length;\n        for (uint256 i = 0; i < len; ++i) {\n            if (token == _vaultTokens[i]) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    // -------------------  INTERNAL, MUTATING  -------------------\n\n    function _push(uint256[] memory tokenAmounts, bytes memory)\n        internal\n        pure\n        override\n        returns (uint256[] memory actualTokenAmounts)\n    {\n        // no-op, tokens are already on balance\n        return tokenAmounts;\n    }\n\n    function _pull(\n        address to,\n        uint256[] memory tokenAmounts,\n        bytes memory options\n    ) internal override returns (uint256[] memory actualTokenAmounts) {\n        actualTokenAmounts = new uint256[](tokenAmounts.length);\n        uint256[] memory pushTokenAmounts = new uint256[](tokenAmounts.length);\n        address[] memory tokens = _vaultTokens;\n        IVaultRegistry registry = _vaultGovernance.internalParams().registry;\n        address owner = registry.ownerOf(_nft);\n\n        for (uint256 i = 0; i < tokenAmounts.length; ++i) {\n            IERC20 vaultToken = IERC20(tokens[i]);\n            uint256 balance = vaultToken.balanceOf(address(this));\n            uint256 amount = tokenAmounts[i] < balance ? tokenAmounts[i] : balance;\n            IERC20(tokens[i]).safeTransfer(to, amount);\n            actualTokenAmounts[i] = amount;\n            if (owner != to) {\n                // this will equal to amounts pulled + any accidental prior balances on `to`;\n                pushTokenAmounts[i] = IERC20(tokens[i]).balanceOf(to);\n            }\n        }\n        if (owner != to) {\n            // if we pull as a strategy, make sure everything is pushed\n            IIntegrationVault(to).push(tokens, pushTokenAmounts, options);\n            // any accidental prior balances + push leftovers\n            uint256[] memory reclaimed = IIntegrationVault(to).reclaimTokens(tokens);\n            for (uint256 i = 0; i < tokenAmounts.length; i++) {\n                // equals to exactly how much is pushed\n                actualTokenAmounts[i] = actualTokenAmounts[i] >= reclaimed[i]\n                    ? actualTokenAmounts[i] - reclaimed[i]\n                    : 0;\n            }\n        }\n    }\n\n    /// @inheritdoc IntegrationVault\n    function supportsInterface(bytes4 interfaceId) public view override(IERC165, IntegrationVault) returns (bool) {\n        return super.supportsInterface(interfaceId) || (interfaceId == type(IERC20Vault).interfaceId);\n    }\n}\n"
    },
    "src/vaults/IntegrationVault.sol": {
      "content": "// SPDX-License-Identifier: BSL-1.1\npragma solidity 0.8.9;\n\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/utils/introspection/ERC165.sol\";\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\nimport \"../interfaces/external/erc/IERC1271.sol\";\nimport \"../interfaces/vaults/IVaultRoot.sol\";\nimport \"../interfaces/vaults/IIntegrationVault.sol\";\nimport \"../interfaces/validators/IValidator.sol\";\nimport \"../libraries/CommonLibrary.sol\";\nimport \"../libraries/ExceptionsLibrary.sol\";\nimport \"../libraries/PermissionIdsLibrary.sol\";\nimport \"./VaultGovernance.sol\";\nimport \"./Vault.sol\";\n\n/// @notice Abstract contract that has logic common for every Vault.\n/// @dev Notes:\n/// ### ERC-721\n///\n/// Each Vault should be registered in VaultRegistry and get corresponding VaultRegistry NFT.\n///\n/// ### Access control\n///\n/// `push` and `pull` methods are only allowed for owner / approved person of the NFT. However,\n/// `pull` for approved person also checks that pull destination is another vault of the Vault System.\n///\n/// The semantics is: NFT owner owns all Vault liquidity, Approved person is liquidity manager.\n/// ApprovedForAll person cannot do anything except ERC-721 token transfers.\n///\n/// Both NFT owner and approved person can call externalCall method which claims liquidity mining rewards (if any)\n///\n/// `reclaimTokens` for claiming rewards given by an underlying protocol to erc20Vault in order to sell them there\nabstract contract IntegrationVault is IIntegrationVault, ReentrancyGuard, Vault {\n    using SafeERC20 for IERC20;\n\n    // -------------------  EXTERNAL, VIEW  -------------------\n\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Vault) returns (bool) {\n        return\n            super.supportsInterface(interfaceId) ||\n            (interfaceId == type(IIntegrationVault).interfaceId) ||\n            (interfaceId == type(IERC1271).interfaceId);\n    }\n\n    // -------------------  EXTERNAL, MUTATING  -------------------\n\n    /// @inheritdoc IIntegrationVault\n    function push(\n        address[] memory tokens,\n        uint256[] memory tokenAmounts,\n        bytes memory options\n    ) public nonReentrant returns (uint256[] memory actualTokenAmounts) {\n        uint256 nft_ = _nft;\n        require(nft_ != 0, ExceptionsLibrary.INIT);\n        IVaultRegistry vaultRegistry = _vaultGovernance.internalParams().registry;\n        IVault ownerVault = IVault(vaultRegistry.ownerOf(nft_)); // Also checks that the token exists\n        uint256 ownerNft = vaultRegistry.nftForVault(address(ownerVault));\n        require(ownerNft != 0, ExceptionsLibrary.NOT_FOUND); // require deposits only through Vault\n        uint256[] memory pTokenAmounts = _validateAndProjectTokens(tokens, tokenAmounts);\n        uint256[] memory pActualTokenAmounts = _push(pTokenAmounts, options);\n        actualTokenAmounts = CommonLibrary.projectTokenAmounts(tokens, _vaultTokens, pActualTokenAmounts);\n        emit Push(pActualTokenAmounts);\n    }\n\n    /// @inheritdoc IIntegrationVault\n    function transferAndPush(\n        address from,\n        address[] memory tokens,\n        uint256[] memory tokenAmounts,\n        bytes memory options\n    ) external returns (uint256[] memory actualTokenAmounts) {\n        uint256 len = tokens.length;\n        for (uint256 i = 0; i < len; ++i)\n            if (tokenAmounts[i] != 0) {\n                IERC20(tokens[i]).safeTransferFrom(from, address(this), tokenAmounts[i]);\n            }\n\n        actualTokenAmounts = push(tokens, tokenAmounts, options);\n        for (uint256 i = 0; i < tokens.length; ++i) {\n            uint256 leftover = actualTokenAmounts[i] < tokenAmounts[i] ? tokenAmounts[i] - actualTokenAmounts[i] : 0;\n            if (leftover != 0) IERC20(tokens[i]).safeTransfer(from, leftover);\n        }\n    }\n\n    /// @inheritdoc IIntegrationVault\n    function pull(\n        address to,\n        address[] memory tokens,\n        uint256[] memory tokenAmounts,\n        bytes memory options\n    ) external nonReentrant returns (uint256[] memory actualTokenAmounts) {\n        uint256 nft_ = _nft;\n        require(nft_ != 0, ExceptionsLibrary.INIT);\n        require(_isApprovedOrOwner(msg.sender), ExceptionsLibrary.FORBIDDEN); // Also checks that the token exists\n        IVaultRegistry registry = _vaultGovernance.internalParams().registry;\n        address owner = registry.ownerOf(nft_);\n        IVaultRoot root = _root(registry, nft_, owner);\n        if (owner != msg.sender) {\n            address zeroVault = root.subvaultAt(0);\n            if (zeroVault == address(this)) {\n                // If we pull from zero vault\n                require(\n                    root.hasSubvault(registry.nftForVault(to)) && to != address(this),\n                    ExceptionsLibrary.INVALID_TARGET\n                );\n            } else {\n                // If we pull from other vault\n                require(zeroVault == to, ExceptionsLibrary.INVALID_TARGET);\n            }\n        }\n        uint256[] memory pTokenAmounts = _validateAndProjectTokens(tokens, tokenAmounts);\n        uint256[] memory pActualTokenAmounts = _pull(to, pTokenAmounts, options);\n        actualTokenAmounts = CommonLibrary.projectTokenAmounts(tokens, _vaultTokens, pActualTokenAmounts);\n        emit Pull(to, actualTokenAmounts);\n    }\n\n    /// @inheritdoc IIntegrationVault\n    function reclaimTokens(address[] memory tokens)\n        external\n        virtual\n        nonReentrant\n        returns (uint256[] memory actualTokenAmounts)\n    {\n        uint256 nft_ = _nft;\n        require(nft_ != 0, ExceptionsLibrary.INIT);\n        IVaultGovernance.InternalParams memory params = _vaultGovernance.internalParams();\n        IProtocolGovernance governance = params.protocolGovernance;\n        IVaultRegistry registry = params.registry;\n        address owner = registry.ownerOf(nft_);\n        address to = _root(registry, nft_, owner).subvaultAt(0);\n        actualTokenAmounts = new uint256[](tokens.length);\n        if (to == address(this)) {\n            return actualTokenAmounts;\n        }\n        for (uint256 i = 0; i < tokens.length; ++i) {\n            if (\n                _isReclaimForbidden(tokens[i]) ||\n                !governance.hasPermission(tokens[i], PermissionIdsLibrary.ERC20_TRANSFER)\n            ) {\n                continue;\n            }\n            IERC20 token = IERC20(tokens[i]);\n            actualTokenAmounts[i] = token.balanceOf(address(this));\n\n            token.safeTransfer(to, actualTokenAmounts[i]);\n        }\n        emit ReclaimTokens(to, tokens, actualTokenAmounts);\n    }\n\n    /// @inheritdoc IERC1271\n    function isValidSignature(bytes32 _hash, bytes memory _signature) external view returns (bytes4 magicValue) {\n        IVaultGovernance.InternalParams memory params = _vaultGovernance.internalParams();\n        IVaultRegistry registry = params.registry;\n        IProtocolGovernance protocolGovernance = params.protocolGovernance;\n        uint256 nft_ = _nft;\n        if (nft_ == 0) {\n            return 0xffffffff;\n        }\n        address strategy = registry.getApproved(nft_);\n        if (!protocolGovernance.hasPermission(strategy, PermissionIdsLibrary.TRUSTED_STRATEGY)) {\n            return 0xffffffff;\n        }\n        uint32 size;\n        assembly {\n            size := extcodesize(strategy)\n        }\n        if (size > 0) {\n            if (IERC165(strategy).supportsInterface(type(IERC1271).interfaceId)) {\n                return IERC1271(strategy).isValidSignature(_hash, _signature);\n            } else {\n                return 0xffffffff;\n            }\n        }\n        if (CommonLibrary.recoverSigner(_hash, _signature) == strategy) {\n            return 0x1626ba7e;\n        }\n        return 0xffffffff;\n    }\n\n    /// @inheritdoc IIntegrationVault\n    function externalCall(\n        address to,\n        bytes4 selector,\n        bytes calldata data\n    ) external payable nonReentrant returns (bytes memory result) {\n        require(_nft != 0, ExceptionsLibrary.INIT);\n        require(_isApprovedOrOwner(msg.sender), ExceptionsLibrary.FORBIDDEN);\n        IProtocolGovernance protocolGovernance = _vaultGovernance.internalParams().protocolGovernance;\n        IValidator validator = IValidator(protocolGovernance.validators(to));\n        require(address(validator) != address(0), ExceptionsLibrary.FORBIDDEN);\n        validator.validate(msg.sender, to, msg.value, selector, data);\n        (bool res, bytes memory returndata) = to.call{value: msg.value}(abi.encodePacked(selector, data));\n        if (!res) {\n            assembly {\n                let returndata_size := mload(returndata)\n                // Bubble up revert reason\n                revert(add(32, returndata), returndata_size)\n            }\n        }\n        result = returndata;\n    }\n\n    // -------------------  INTERNAL, VIEW  -------------------\n\n    function _validateAndProjectTokens(address[] memory tokens, uint256[] memory tokenAmounts)\n        internal\n        view\n        returns (uint256[] memory pTokenAmounts)\n    {\n        require(CommonLibrary.isSortedAndUnique(tokens), ExceptionsLibrary.INVARIANT);\n        require(tokens.length == tokenAmounts.length, ExceptionsLibrary.INVALID_VALUE);\n        pTokenAmounts = CommonLibrary.projectTokenAmounts(_vaultTokens, tokens, tokenAmounts);\n    }\n\n    function _root(\n        IVaultRegistry registry,\n        uint256 thisNft,\n        address thisOwner\n    ) internal view returns (IVaultRoot) {\n        uint256 thisOwnerNft = registry.nftForVault(thisOwner);\n        require((thisNft != 0) && (thisOwnerNft != 0), ExceptionsLibrary.INIT);\n\n        return IVaultRoot(thisOwner);\n    }\n\n    function _isApprovedOrOwner(address sender) internal view returns (bool) {\n        IVaultRegistry registry = _vaultGovernance.internalParams().registry;\n        uint256 nft_ = _nft;\n        if (nft_ == 0) {\n            return false;\n        }\n        return registry.getApproved(nft_) == sender || registry.ownerOf(nft_) == sender;\n    }\n\n    /// @notice check if token is forbidden to transfer under reclaim\n    /// @dev it is done in order to prevent reclaiming internal protocol tokens\n    ///      for example to prevent YEarn tokens to reclaimed\n    ///      if our vault is managing tokens, depositing it in YEarn\n    /// @param token The address of token to check\n    /// @return if token is forbidden\n    function _isReclaimForbidden(address token) internal view virtual returns (bool);\n\n    // -------------------  INTERNAL, MUTATING  -------------------\n\n    /// Guaranteed to have exact signature matchinn vault tokens\n    function _push(uint256[] memory tokenAmounts, bytes memory options)\n        internal\n        virtual\n        returns (uint256[] memory actualTokenAmounts);\n\n    /// Guaranteed to have exact signature matchinn vault tokens\n    function _pull(\n        address to,\n        uint256[] memory tokenAmounts,\n        bytes memory options\n    ) internal virtual returns (uint256[] memory actualTokenAmounts);\n\n    // --------------------------  EVENTS  --------------------------\n\n    /// @notice Emitted on successful push\n    /// @param tokenAmounts The amounts of tokens to pushed\n    event Push(uint256[] tokenAmounts);\n\n    /// @notice Emitted on successful pull\n    /// @param to The target address for pulled tokens\n    /// @param tokenAmounts The amounts of tokens to pull\n    event Pull(address to, uint256[] tokenAmounts);\n\n    /// @notice Emitted when tokens are reclaimed\n    /// @param to The target address for pulled tokens\n    /// @param tokens ERC20 tokens to be reclaimed\n    /// @param tokenAmounts The amounts of reclaims\n    event ReclaimTokens(address to, address[] tokens, uint256[] tokenAmounts);\n}\n"
    },
    "src/vaults/Vault.sol": {
      "content": "// SPDX-License-Identifier: BSL-1.1\npragma solidity 0.8.9;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/utils/introspection/ERC165.sol\";\nimport \"../libraries/CommonLibrary.sol\";\nimport \"../libraries/ExceptionsLibrary.sol\";\nimport \"../interfaces/vaults/IVault.sol\";\nimport \"./VaultGovernance.sol\";\n\n/// @notice Abstract contract that has logic common for every Vault.\n/// @dev Notes:\n/// ### ERC-721\n///\n/// Each Vault should be registered in VaultRegistry and get corresponding VaultRegistry NFT.\n///\n/// ### Access control\n///\n/// `push` and `pull` methods are only allowed for owner / approved person of the NFT. However,\n/// `pull` for approved person also checks that pull destination is another vault of the Vault System.\n///\n/// The semantics is: NFT owner owns all Vault liquidity, Approved person is liquidity manager.\n/// ApprovedForAll person cannot do anything except ERC-721 token transfers.\n///\n/// Both NFT owner and approved person can call externalCall method which claims liquidity mining rewards (if any)\n///\n/// `reclaimTokens` for mistakenly transfered tokens (not included into vaultTokens) additionally can be withdrawn by\n/// the protocol admin\nabstract contract Vault is IVault, ERC165 {\n    using SafeERC20 for IERC20;\n\n    IVaultGovernance internal _vaultGovernance;\n    address[] internal _vaultTokens;\n    mapping(address => int256) internal _vaultTokensIndex;\n    uint256 internal _nft;\n    uint256[] internal _pullExistentials;\n\n    constructor() {\n        // lock initialization and thus all mutations for any deployed Vault\n        _nft = type(uint256).max;\n    }\n\n    // -------------------  EXTERNAL, VIEW  -------------------\n\n    /// @inheritdoc IVault\n    function initialized() external view returns (bool) {\n        return _nft != 0;\n    }\n\n    /// @inheritdoc IVault\n    function isVaultToken(address token) public view returns (bool) {\n        return _vaultTokensIndex[token] != 0;\n    }\n\n    /// @inheritdoc IVault\n    function vaultGovernance() external view returns (IVaultGovernance) {\n        return _vaultGovernance;\n    }\n\n    /// @inheritdoc IVault\n    function vaultTokens() external view returns (address[] memory) {\n        return _vaultTokens;\n    }\n\n    /// @inheritdoc IVault\n    function nft() external view returns (uint256) {\n        return _nft;\n    }\n\n    /// @inheritdoc IVault\n    function tvl() public view virtual returns (uint256[] memory minTokenAmounts, uint256[] memory maxTokenAmounts);\n\n    /// @inheritdoc IVault\n    function pullExistentials() external view returns (uint256[] memory) {\n        return _pullExistentials;\n    }\n\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {\n        return super.supportsInterface(interfaceId) || (interfaceId == type(IVault).interfaceId);\n    }\n\n    // -------------------  INTERNAL, MUTATING  -------------------\n\n    function _initialize(address[] memory vaultTokens_, uint256 nft_) internal virtual {\n        require(_nft == 0, ExceptionsLibrary.INIT);\n        require(CommonLibrary.isSortedAndUnique(vaultTokens_), ExceptionsLibrary.INVARIANT);\n        require(nft_ != 0, ExceptionsLibrary.VALUE_ZERO); // guarantees that this method can only be called once\n        IProtocolGovernance governance = IVaultGovernance(msg.sender).internalParams().protocolGovernance;\n        require(\n            vaultTokens_.length > 0 && vaultTokens_.length <= governance.maxTokensPerVault(),\n            ExceptionsLibrary.INVALID_VALUE\n        );\n        for (uint256 i = 0; i < vaultTokens_.length; i++) {\n            require(\n                governance.hasPermission(vaultTokens_[i], PermissionIdsLibrary.ERC20_VAULT_TOKEN),\n                ExceptionsLibrary.FORBIDDEN\n            );\n        }\n        _vaultGovernance = IVaultGovernance(msg.sender);\n        _vaultTokens = vaultTokens_;\n        _nft = nft_;\n        uint256 len = _vaultTokens.length;\n        for (uint256 i = 0; i < len; ++i) {\n            _vaultTokensIndex[vaultTokens_[i]] = int256(i + 1);\n\n            IERC20Metadata token = IERC20Metadata(vaultTokens_[i]);\n            _pullExistentials.push(10**(token.decimals() / 2));\n        }\n        emit Initialized(tx.origin, msg.sender, vaultTokens_, nft_);\n    }\n\n    // --------------------------  EVENTS  --------------------------\n\n    /// @notice Emitted when Vault is intialized\n    /// @param origin Origin of the transaction (tx.origin)\n    /// @param sender Sender of the call (msg.sender)\n    /// @param vaultTokens_ ERC20 tokens under the vault management\n    /// @param nft_ VaultRegistry NFT assigned to the vault\n    event Initialized(address indexed origin, address indexed sender, address[] vaultTokens_, uint256 nft_);\n}\n"
    },
    "src/vaults/VaultGovernance.sol": {
      "content": "// SPDX-License-Identifier: BSL-1.1\npragma solidity 0.8.9;\n\nimport \"@openzeppelin/contracts/proxy/Clones.sol\";\nimport \"@openzeppelin/contracts/utils/introspection/ERC165.sol\";\nimport \"../interfaces/IProtocolGovernance.sol\";\nimport \"../interfaces/vaults/IVaultGovernance.sol\";\nimport \"../libraries/ExceptionsLibrary.sol\";\nimport \"../libraries/PermissionIdsLibrary.sol\";\n\n/// @notice Internal contract for managing different params.\n/// @dev The contract should be overriden by the concrete VaultGovernance,\n/// define different params structs and use abi.decode / abi.encode to serialize\n/// to bytes in this contract. It also should emit events on params change.\nabstract contract VaultGovernance is IVaultGovernance, ERC165 {\n    InternalParams internal _internalParams;\n    InternalParams private _stagedInternalParams;\n    uint256 internal _internalParamsTimestamp;\n\n    mapping(uint256 => bytes) internal _delayedStrategyParams;\n    mapping(uint256 => bytes) internal _stagedDelayedStrategyParams;\n    mapping(uint256 => uint256) internal _delayedStrategyParamsTimestamp;\n\n    mapping(uint256 => bytes) internal _delayedProtocolPerVaultParams;\n    mapping(uint256 => bytes) internal _stagedDelayedProtocolPerVaultParams;\n    mapping(uint256 => uint256) internal _delayedProtocolPerVaultParamsTimestamp;\n\n    bytes internal _delayedProtocolParams;\n    bytes internal _stagedDelayedProtocolParams;\n    uint256 internal _delayedProtocolParamsTimestamp;\n\n    mapping(uint256 => bytes) internal _strategyParams;\n    bytes internal _protocolParams;\n    bytes internal _operatorParams;\n\n    /// @notice Creates a new contract.\n    /// @param internalParams_ Initial Internal Params\n    constructor(InternalParams memory internalParams_) {\n        require(address(internalParams_.protocolGovernance) != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n        require(address(internalParams_.registry) != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n        require(address(internalParams_.singleton) != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n        _internalParams = internalParams_;\n    }\n\n    // -------------------  EXTERNAL, VIEW  -------------------\n\n    /// @inheritdoc IVaultGovernance\n    function delayedStrategyParamsTimestamp(uint256 nft) external view returns (uint256) {\n        return _delayedStrategyParamsTimestamp[nft];\n    }\n\n    /// @inheritdoc IVaultGovernance\n    function delayedProtocolPerVaultParamsTimestamp(uint256 nft) external view returns (uint256) {\n        return _delayedProtocolPerVaultParamsTimestamp[nft];\n    }\n\n    /// @inheritdoc IVaultGovernance\n    function delayedProtocolParamsTimestamp() external view returns (uint256) {\n        return _delayedProtocolParamsTimestamp;\n    }\n\n    /// @inheritdoc IVaultGovernance\n    function internalParamsTimestamp() external view returns (uint256) {\n        return _internalParamsTimestamp;\n    }\n\n    /// @inheritdoc IVaultGovernance\n    function internalParams() external view returns (InternalParams memory) {\n        return _internalParams;\n    }\n\n    /// @inheritdoc IVaultGovernance\n    function stagedInternalParams() external view returns (InternalParams memory) {\n        return _stagedInternalParams;\n    }\n\n    function supportsInterface(bytes4 interfaceID) public view virtual override(ERC165) returns (bool) {\n        return super.supportsInterface(interfaceID) || interfaceID == type(IVaultGovernance).interfaceId;\n    }\n\n    // -------------------  EXTERNAL, MUTATING  -------------------\n\n    /// @inheritdoc IVaultGovernance\n    function stageInternalParams(InternalParams memory newParams) external {\n        _requireProtocolAdmin();\n        require(address(newParams.protocolGovernance) != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n        require(address(newParams.registry) != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n        require(address(newParams.singleton) != address(0), ExceptionsLibrary.ADDRESS_ZERO);\n        _stagedInternalParams = newParams;\n        _internalParamsTimestamp = block.timestamp + _internalParams.protocolGovernance.governanceDelay();\n        emit StagedInternalParams(tx.origin, msg.sender, newParams, _internalParamsTimestamp);\n    }\n\n    /// @inheritdoc IVaultGovernance\n    function commitInternalParams() external {\n        _requireProtocolAdmin();\n        require(_internalParamsTimestamp != 0, ExceptionsLibrary.NULL);\n        require(block.timestamp >= _internalParamsTimestamp, ExceptionsLibrary.TIMESTAMP);\n        _internalParams = _stagedInternalParams;\n        delete _internalParamsTimestamp;\n        delete _stagedInternalParams;\n        emit CommitedInternalParams(tx.origin, msg.sender, _internalParams);\n    }\n\n    // -------------------  INTERNAL, VIEW  -------------------\n\n    function _requireAtLeastStrategy(uint256 nft) internal view {\n        require(\n            (_internalParams.protocolGovernance.isAdmin(msg.sender) ||\n                _internalParams.registry.getApproved(nft) == msg.sender ||\n                (_internalParams.registry.ownerOf(nft) == msg.sender)),\n            ExceptionsLibrary.FORBIDDEN\n        );\n    }\n\n    function _requireProtocolAdmin() internal view {\n        require(_internalParams.protocolGovernance.isAdmin(msg.sender), ExceptionsLibrary.FORBIDDEN);\n    }\n\n    function _requireAtLeastOperator() internal view {\n        IProtocolGovernance governance = _internalParams.protocolGovernance;\n        require(governance.isAdmin(msg.sender) || governance.isOperator(msg.sender), ExceptionsLibrary.FORBIDDEN);\n    }\n\n    // -------------------  INTERNAL, MUTATING  -------------------\n\n    function _createVault(address owner) internal returns (address vault, uint256 nft) {\n        IProtocolGovernance protocolGovernance = IProtocolGovernance(_internalParams.protocolGovernance);\n        require(\n            protocolGovernance.hasPermission(msg.sender, PermissionIdsLibrary.CREATE_VAULT),\n            ExceptionsLibrary.FORBIDDEN\n        );\n        IVaultRegistry vaultRegistry = _internalParams.registry;\n        nft = vaultRegistry.vaultsCount() + 1;\n        vault = Clones.cloneDeterministic(address(_internalParams.singleton), bytes32(nft));\n        vaultRegistry.registerVault(address(vault), owner);\n    }\n\n    /// @notice Set Delayed Strategy Params\n    /// @param nft Nft of the vault\n    /// @param params New params\n    function _stageDelayedStrategyParams(uint256 nft, bytes memory params) internal {\n        _requireAtLeastStrategy(nft);\n        _stagedDelayedStrategyParams[nft] = params;\n        uint256 delayFactor = _delayedStrategyParams[nft].length == 0 ? 0 : 1;\n        _delayedStrategyParamsTimestamp[nft] =\n            block.timestamp +\n            _internalParams.protocolGovernance.governanceDelay() *\n            delayFactor;\n    }\n\n    /// @notice Commit Delayed Strategy Params\n    function _commitDelayedStrategyParams(uint256 nft) internal {\n        _requireAtLeastStrategy(nft);\n        uint256 thisDelayedStrategyParamsTimestamp = _delayedStrategyParamsTimestamp[nft];\n        require(thisDelayedStrategyParamsTimestamp != 0, ExceptionsLibrary.NULL);\n        require(block.timestamp >= thisDelayedStrategyParamsTimestamp, ExceptionsLibrary.TIMESTAMP);\n        _delayedStrategyParams[nft] = _stagedDelayedStrategyParams[nft];\n        delete _stagedDelayedStrategyParams[nft];\n        delete _delayedStrategyParamsTimestamp[nft];\n    }\n\n    /// @notice Set Delayed Protocol Per Vault Params\n    /// @param nft Nft of the vault\n    /// @param params New params\n    function _stageDelayedProtocolPerVaultParams(uint256 nft, bytes memory params) internal {\n        _requireProtocolAdmin();\n        _stagedDelayedProtocolPerVaultParams[nft] = params;\n        uint256 delayFactor = _delayedProtocolPerVaultParams[nft].length == 0 ? 0 : 1;\n        _delayedProtocolPerVaultParamsTimestamp[nft] =\n            block.timestamp +\n            _internalParams.protocolGovernance.governanceDelay() *\n            delayFactor;\n    }\n\n    /// @notice Commit Delayed Protocol Per Vault Params\n    function _commitDelayedProtocolPerVaultParams(uint256 nft) internal {\n        _requireProtocolAdmin();\n        uint256 thisDelayedProtocolPerVaultParamsTimestamp = _delayedProtocolPerVaultParamsTimestamp[nft];\n        require(thisDelayedProtocolPerVaultParamsTimestamp != 0, ExceptionsLibrary.NULL);\n        require(block.timestamp >= thisDelayedProtocolPerVaultParamsTimestamp, ExceptionsLibrary.TIMESTAMP);\n        _delayedProtocolPerVaultParams[nft] = _stagedDelayedProtocolPerVaultParams[nft];\n        delete _stagedDelayedProtocolPerVaultParams[nft];\n        delete _delayedProtocolPerVaultParamsTimestamp[nft];\n    }\n\n    /// @notice Set Delayed Protocol Params\n    /// @param params New params\n    function _stageDelayedProtocolParams(bytes memory params) internal {\n        _requireProtocolAdmin();\n        uint256 delayFactor = _delayedProtocolParams.length == 0 ? 0 : 1;\n        _stagedDelayedProtocolParams = params;\n        _delayedProtocolParamsTimestamp =\n            block.timestamp +\n            _internalParams.protocolGovernance.governanceDelay() *\n            delayFactor;\n    }\n\n    /// @notice Commit Delayed Protocol Params\n    function _commitDelayedProtocolParams() internal {\n        _requireProtocolAdmin();\n        require(_delayedProtocolParamsTimestamp != 0, ExceptionsLibrary.NULL);\n        require(block.timestamp >= _delayedProtocolParamsTimestamp, ExceptionsLibrary.TIMESTAMP);\n        _delayedProtocolParams = _stagedDelayedProtocolParams;\n        delete _stagedDelayedProtocolParams;\n        delete _delayedProtocolParamsTimestamp;\n    }\n\n    /// @notice Set immediate strategy params\n    /// @dev Should require nft > 0\n    /// @param nft Nft of the vault\n    /// @param params New params\n    function _setStrategyParams(uint256 nft, bytes memory params) internal {\n        _requireAtLeastStrategy(nft);\n        _strategyParams[nft] = params;\n    }\n\n    /// @notice Set immediate operator params\n    /// @param params New params\n    function _setOperatorParams(bytes memory params) internal {\n        _requireAtLeastOperator();\n        _operatorParams = params;\n    }\n\n    /// @notice Set immediate protocol params\n    /// @param params New params\n    function _setProtocolParams(bytes memory params) internal {\n        _requireProtocolAdmin();\n        _protocolParams = params;\n    }\n\n    // --------------------------  EVENTS  --------------------------\n\n    /// @notice Emitted when InternalParams are staged for commit\n    /// @param origin Origin of the transaction (tx.origin)\n    /// @param sender Sender of the call (msg.sender)\n    /// @param params New params that were staged for commit\n    /// @param when When the params could be committed\n    event StagedInternalParams(address indexed origin, address indexed sender, InternalParams params, uint256 when);\n\n    /// @notice Emitted when InternalParams are staged for commit\n    /// @param origin Origin of the transaction (tx.origin)\n    /// @param sender Sender of the call (msg.sender)\n    /// @param params New params that were staged for commit\n    event CommitedInternalParams(address indexed origin, address indexed sender, InternalParams params);\n\n    /// @notice Emitted when New Vault is deployed\n    /// @param origin Origin of the transaction (tx.origin)\n    /// @param sender Sender of the call (msg.sender)\n    /// @param vaultTokens Vault tokens for this vault\n    /// @param options Options for deploy. The details of the options structure are specified in subcontracts\n    /// @param owner Owner of the VaultRegistry NFT for this vault\n    /// @param vaultAddress Address of the new Vault\n    /// @param vaultNft VaultRegistry NFT for the new Vault\n    event DeployedVault(\n        address indexed origin,\n        address indexed sender,\n        address[] vaultTokens,\n        bytes options,\n        address owner,\n        address vaultAddress,\n        uint256 vaultNft\n    );\n}\n"
    }
  },
  "settings": {
    "remappings": [
      "@openzeppelin/=lib/openzeppelin-contracts/",
      "@solmate/=lib/solmate/",
      "ds-test/=lib/forge-std/lib/ds-test/src/",
      "forge-std/=lib/forge-std/src/"
    ],
    "optimizer": {
      "enabled": true,
      "runs": 200,
      "details": {
        "yul": true,
        "yulDetails": {
          "stackAllocation": true
        }
      }
    },
    "metadata": {
      "bytecodeHash": "ipfs"
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "evmVersion": "london",
    "libraries": {}
  }
}