Transaction Hash:
Block:
16743644 at Mar-02-2023 09:50:11 PM +UTC
Transaction Fee:
0.00659052110050642 ETH
$15.03
Gas Used:
255,241 Gas / 25.82077762 Gwei
Emitted Events:
242 |
VaultFactoryB.Transfer( from=0x00000000...000000000, to=[Sender] 0x77a210814d54b9f158e584f9ff1423adbeab02aa, tokenId=371933231351632235516339868557449567428571920265 )
|
243 |
VaultFactoryB.InstanceAdded( instance=VaultB )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x4126101a...460B17789 |
0 Eth
Nonce: 0
|
0 Eth
Nonce: 1
| |||
0x77A21081...dBeaB02aa |
0.07469554285719645 Eth
Nonce: 152
|
0.06810502175669003 Eth
Nonce: 153
| 0.00659052110050642 | ||
0xBc8A1bCc...7377c5bBc | |||||
0xeBec795c...8F299cAcf
Miner
| (Fee Recipient: 0xeBe...Acf) | 10,427.955529711661921011 Eth | 10,427.955657332161921011 Eth | 0.0001276205 |
Execution Trace
VaultFactoryB.CALL( )

-
VaultB.3d602d80( )
VaultB.CALL( )
-
VaultB.DELEGATECALL( )
-
File 1 of 3: VaultFactoryB
File 2 of 3: VaultB
File 3 of 3: VaultB
{"Address.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\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 function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size \u003e 0;\n }\n\n /**\n * @dev Replacement for Solidity\u0027s `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 \u003e= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance \u003e= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length \u003e 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"},"AddressUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\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 function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size \u003e 0;\n }\n\n /**\n * @dev Replacement for Solidity\u0027s `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 \u003e= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance \u003e= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length \u003e 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"},"Clones.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.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 * \u003e To simply and cheaply clone contract functionality in an immutable way, this standard specifies\n * \u003e 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 `master`.\n *\n * This function uses the create opcode, which should never revert.\n */\n function clone(address master) internal returns (address instance) {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(ptr, 0x14), shl(0x60, master))\n mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n instance := create(0, ptr, 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 `master`.\n *\n * This function uses the create2 opcode and a `salt` to deterministically deploy\n * the clone. Using the same `master` and `salt` multiple time will revert, since\n * the clones cannot be deployed twice at the same address.\n */\n function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(ptr, 0x14), shl(0x60, master))\n mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n instance := create2(0, ptr, 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(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(ptr, 0x14), shl(0x60, master))\n mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)\n mstore(add(ptr, 0x38), shl(0x60, deployer))\n mstore(add(ptr, 0x4c), salt)\n mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))\n predicted := keccak256(add(ptr, 0x37), 0x55)\n }\n }\n\n /**\n * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n */\n function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {\n return predictDeterministicAddress(master, salt, address(this));\n }\n}\n"},"Context.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n"},"ContextUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\nimport \"./Initializable.sol\";\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal initializer {\n __Context_init_unchained();\n }\n\n function __Context_init_unchained() internal initializer {\n }\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n uint256[50] private __gap;\n}\n"},"ECDSA.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n // Check the signature length\n if (signature.length != 65) {\n revert(\"ECDSA: invalid signature length\");\n }\n\n // Divide the signature in r, s and v variables\n bytes32 r;\n bytes32 s;\n uint8 v;\n\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n // solhint-disable-next-line no-inline-assembly\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n\n return recover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (281): 0 \u003c s \u003c secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n require(uint256(s) \u003c= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, \"ECDSA: invalid signature \u0027s\u0027 value\");\n require(v == 27 || v == 28, \"ECDSA: invalid signature \u0027v\u0027 value\");\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n require(signer != address(0), \"ECDSA: invalid signature\");\n\n return signer;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * replicates the behavior of the\n * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]\n * JSON-RPC method.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n }\n}\n"},"EIP712.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/* solhint-disable max-line-length */\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n */\nabstract contract EIP712 {\n /* solhint-disable var-name-mixedcase */\n bytes32 private immutable _HASHED_NAME;\n bytes32 private immutable _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH =\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n );\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n\n constructor(string memory name, string memory version) {\n _HASHED_NAME = keccak256(bytes(name));\n _HASHED_VERSION = keccak256(bytes(version));\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 name,\n bytes32 version\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, name, version, _getChainId(), address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", _domainSeparatorV4(), structHash));\n }\n\n function _getChainId() private view returns (uint256 chainId) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal view virtual returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal view virtual returns (bytes32) {\n return _HASHED_VERSION;\n }\n}"},"EnumerableMap.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Library for managing an enumerable variant of Solidity\u0027s\n * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]\n * type.\n *\n * Maps have the following properties:\n *\n * - Entries are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Entries are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableMap for EnumerableMap.UintToAddressMap;\n *\n * // Declare a set state variable\n * EnumerableMap.UintToAddressMap private myMap;\n * }\n * ```\n *\n * As of v3.0.0, only maps of type `uint256 -\u003e address` (`UintToAddressMap`) are\n * supported.\n */\nlibrary EnumerableMap {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Map type with\n // bytes32 keys and values.\n // The Map implementation uses private functions, and user-facing\n // implementations (such as Uint256ToAddressMap) are just wrappers around\n // the underlying Map.\n // This means that we can only create new EnumerableMaps for types that fit\n // in bytes32.\n\n struct MapEntry {\n bytes32 _key;\n bytes32 _value;\n }\n\n struct Map {\n // Storage of map keys and values\n MapEntry[] _entries;\n\n // Position of the entry defined by a key in the `entries` array, plus 1\n // because index 0 means a key is not in the map.\n mapping (bytes32 =\u003e uint256) _indexes;\n }\n\n /**\n * @dev Adds a key-value pair to a map, or updates the value for an existing\n * key. O(1).\n *\n * Returns true if the key was added to the map, that is if it was not\n * already present.\n */\n function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {\n // We read and store the key\u0027s index to prevent multiple reads from the same storage slot\n uint256 keyIndex = map._indexes[key];\n\n if (keyIndex == 0) { // Equivalent to !contains(map, key)\n map._entries.push(MapEntry({ _key: key, _value: value }));\n // The entry is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n map._indexes[key] = map._entries.length;\n return true;\n } else {\n map._entries[keyIndex - 1]._value = value;\n return false;\n }\n }\n\n /**\n * @dev Removes a key-value pair from a map. O(1).\n *\n * Returns true if the key was removed from the map, that is if it was present.\n */\n function _remove(Map storage map, bytes32 key) private returns (bool) {\n // We read and store the key\u0027s index to prevent multiple reads from the same storage slot\n uint256 keyIndex = map._indexes[key];\n\n if (keyIndex != 0) { // Equivalent to contains(map, key)\n // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one\n // in the array, and then remove the last entry (sometimes called as \u0027swap and pop\u0027).\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = keyIndex - 1;\n uint256 lastIndex = map._entries.length - 1;\n\n // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs\n // so rarely, we still do the swap anyway to avoid the gas cost of adding an \u0027if\u0027 statement.\n\n MapEntry storage lastEntry = map._entries[lastIndex];\n\n // Move the last entry to the index where the entry to delete is\n map._entries[toDeleteIndex] = lastEntry;\n // Update the index for the moved entry\n map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based\n\n // Delete the slot where the moved entry was stored\n map._entries.pop();\n\n // Delete the index for the deleted slot\n delete map._indexes[key];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the key is in the map. O(1).\n */\n function _contains(Map storage map, bytes32 key) private view returns (bool) {\n return map._indexes[key] != 0;\n }\n\n /**\n * @dev Returns the number of key-value pairs in the map. O(1).\n */\n function _length(Map storage map) private view returns (uint256) {\n return map._entries.length;\n }\n\n /**\n * @dev Returns the key-value pair stored at position `index` in the map. O(1).\n *\n * Note that there are no guarantees on the ordering of entries inside the\n * array, and it may change when more entries are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {\n require(map._entries.length \u003e index, \"EnumerableMap: index out of bounds\");\n\n MapEntry storage entry = map._entries[index];\n return (entry._key, entry._value);\n }\n\n /**\n * @dev Tries to returns the value associated with `key`. O(1).\n * Does not revert if `key` is not in the map.\n */\n function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {\n uint256 keyIndex = map._indexes[key];\n if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)\n return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based\n }\n\n /**\n * @dev Returns the value associated with `key`. O(1).\n *\n * Requirements:\n *\n * - `key` must be in the map.\n */\n function _get(Map storage map, bytes32 key) private view returns (bytes32) {\n uint256 keyIndex = map._indexes[key];\n require(keyIndex != 0, \"EnumerableMap: nonexistent key\"); // Equivalent to contains(map, key)\n return map._entries[keyIndex - 1]._value; // All indexes are 1-based\n }\n\n /**\n * @dev Same as {_get}, with a custom error message when `key` is not in the map.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {_tryGet}.\n */\n function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {\n uint256 keyIndex = map._indexes[key];\n require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)\n return map._entries[keyIndex - 1]._value; // All indexes are 1-based\n }\n\n // UintToAddressMap\n\n struct UintToAddressMap {\n Map _inner;\n }\n\n /**\n * @dev Adds a key-value pair to a map, or updates the value for an existing\n * key. O(1).\n *\n * Returns true if the key was added to the map, that is if it was not\n * already present.\n */\n function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {\n return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the key was removed from the map, that is if it was present.\n */\n function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {\n return _remove(map._inner, bytes32(key));\n }\n\n /**\n * @dev Returns true if the key is in the map. O(1).\n */\n function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {\n return _contains(map._inner, bytes32(key));\n }\n\n /**\n * @dev Returns the number of elements in the map. O(1).\n */\n function length(UintToAddressMap storage map) internal view returns (uint256) {\n return _length(map._inner);\n }\n\n /**\n * @dev Returns the element stored at position `index` in the set. O(1).\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {\n (bytes32 key, bytes32 value) = _at(map._inner, index);\n return (uint256(key), address(uint160(uint256(value))));\n }\n\n /**\n * @dev Tries to returns the value associated with `key`. O(1).\n * Does not revert if `key` is not in the map.\n *\n * _Available since v3.4._\n */\n function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {\n (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));\n return (success, address(uint160(uint256(value))));\n }\n\n /**\n * @dev Returns the value associated with `key`. O(1).\n *\n * Requirements:\n *\n * - `key` must be in the map.\n */\n function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {\n return address(uint160(uint256(_get(map._inner, bytes32(key)))));\n }\n\n /**\n * @dev Same as {get}, with a custom error message when `key` is not in the map.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryGet}.\n */\n function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {\n return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));\n }\n}\n"},"EnumerableSet.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping (bytes32 =\u003e uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value\u0027s index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) { // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as \u0027swap and pop\u0027).\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n // so rarely, we still do the swap anyway to avoid the gas cost of adding an \u0027if\u0027 statement.\n\n bytes32 lastvalue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastvalue;\n // Update the index for the moved value\n set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n require(set._values.length \u003e index, \"EnumerableSet: index out of bounds\");\n return set._values[index];\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n}\n"},"ERC1271.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {ECDSA} from \"./ECDSA.sol\";\nimport {Address} from \"./Address.sol\";\n\ninterface IERC1271 {\n function isValidSignature(bytes32 _messageHash, bytes memory _signature)\n external\n view\n returns (bytes4 magicValue);\n}\n\nlibrary SignatureChecker {\n using ECDSA for bytes32;\n\n function isValidSignature(\n address signer,\n bytes32 hash,\n bytes memory signature\n ) internal view returns (bool) {\n if (Address.isContract(signer)) {\n bytes4 selector = IERC1271.isValidSignature.selector;\n (bool success, bytes memory returndata) = signer.staticcall(\n abi.encodeWithSelector(selector, hash, signature)\n );\n return success \u0026\u0026 abi.decode(returndata, (bytes4)) == selector;\n } else {\n return hash.toEthSignedMessageHash().recover(signature) == signer;\n }\n }\n}\n\n/// @title ERC1271\n/// @notice Module for ERC1271 compatibility\nabstract contract ERC1271 is IERC1271 {\n // Valid magic value bytes4(keccak256(\"isValidSignature(bytes32,bytes)\")\n bytes4 internal constant VALID_SIG = IERC1271.isValidSignature.selector;\n // Invalid magic value\n bytes4 internal constant INVALID_SIG = bytes4(0);\n\n modifier onlyValidSignature(\n bytes32 permissionHash,\n bytes memory signature\n ) {\n require(\n isValidSignature(permissionHash, signature) == VALID_SIG,\n \"ERC1271: Invalid signature\"\n );\n _;\n }\n\n function _getOwner() internal view virtual returns (address owner);\n\n function isValidSignature(bytes32 permissionHash, bytes memory signature)\n public\n view\n override\n returns (bytes4)\n {\n return\n SignatureChecker.isValidSignature(\n _getOwner(),\n permissionHash,\n signature\n )\n ? VALID_SIG\n : INVALID_SIG;\n }\n}\n"},"ERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts may inherit from this and call {_registerInterface} to declare\n * their support of an interface.\n */\nabstract contract ERC165 is IERC165 {\n /*\n * bytes4(keccak256(\u0027supportsInterface(bytes4)\u0027)) == 0x01ffc9a7\n */\n bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;\n\n /**\n * @dev Mapping of interface ids to whether or not it\u0027s supported.\n */\n mapping(bytes4 =\u003e bool) private _supportedInterfaces;\n\n constructor () internal {\n // Derived contracts need only register support for their own interfaces,\n // we register support for ERC165 itself here\n _registerInterface(_INTERFACE_ID_ERC165);\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n *\n * Time complexity O(1), guaranteed to always use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return _supportedInterfaces[interfaceId];\n }\n\n /**\n * @dev Registers the contract as an implementer of the interface defined by\n * `interfaceId`. Support of the actual ERC165 interface is automatic and\n * registering its interface id is not required.\n *\n * See {IERC165-supportsInterface}.\n *\n * Requirements:\n *\n * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).\n */\n function _registerInterface(bytes4 interfaceId) internal virtual {\n require(interfaceId != 0xffffffff, \"ERC165: invalid interface id\");\n _supportedInterfaces[interfaceId] = true;\n }\n}\n"},"ERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\nimport \"./Context.sol\";\nimport \"./IERC721.sol\";\nimport \"./IERC721Metadata.sol\";\nimport \"./IERC721Enumerable.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./ERC165.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\nimport \"./EnumerableSet.sol\";\nimport \"./EnumerableMap.sol\";\nimport \"./Strings.sol\";\n\n/**\n * @title ERC721 Non-Fungible Token Standard basic implementation\n * @dev see https://eips.ethereum.org/EIPS/eip-721\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {\n using SafeMath for uint256;\n using Address for address;\n using EnumerableSet for EnumerableSet.UintSet;\n using EnumerableMap for EnumerableMap.UintToAddressMap;\n using Strings for uint256;\n\n // Equals to `bytes4(keccak256(\"onERC721Received(address,address,uint256,bytes)\"))`\n // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`\n bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;\n\n // Mapping from holder address to their (enumerable) set of owned tokens\n mapping (address =\u003e EnumerableSet.UintSet) private _holderTokens;\n\n // Enumerable mapping from token ids to their owners\n EnumerableMap.UintToAddressMap private _tokenOwners;\n\n // Mapping from token ID to approved address\n mapping (uint256 =\u003e address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping (address =\u003e mapping (address =\u003e bool)) private _operatorApprovals;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Optional mapping for token URIs\n mapping (uint256 =\u003e string) private _tokenURIs;\n\n // Base URI\n string private _baseURI;\n\n /*\n * bytes4(keccak256(\u0027balanceOf(address)\u0027)) == 0x70a08231\n * bytes4(keccak256(\u0027ownerOf(uint256)\u0027)) == 0x6352211e\n * bytes4(keccak256(\u0027approve(address,uint256)\u0027)) == 0x095ea7b3\n * bytes4(keccak256(\u0027getApproved(uint256)\u0027)) == 0x081812fc\n * bytes4(keccak256(\u0027setApprovalForAll(address,bool)\u0027)) == 0xa22cb465\n * bytes4(keccak256(\u0027isApprovedForAll(address,address)\u0027)) == 0xe985e9c5\n * bytes4(keccak256(\u0027transferFrom(address,address,uint256)\u0027)) == 0x23b872dd\n * bytes4(keccak256(\u0027safeTransferFrom(address,address,uint256)\u0027)) == 0x42842e0e\n * bytes4(keccak256(\u0027safeTransferFrom(address,address,uint256,bytes)\u0027)) == 0xb88d4fde\n *\n * =\u003e 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^\n * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd\n */\n bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;\n\n /*\n * bytes4(keccak256(\u0027name()\u0027)) == 0x06fdde03\n * bytes4(keccak256(\u0027symbol()\u0027)) == 0x95d89b41\n * bytes4(keccak256(\u0027tokenURI(uint256)\u0027)) == 0xc87b56dd\n *\n * =\u003e 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f\n */\n bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;\n\n /*\n * bytes4(keccak256(\u0027totalSupply()\u0027)) == 0x18160ddd\n * bytes4(keccak256(\u0027tokenOfOwnerByIndex(address,uint256)\u0027)) == 0x2f745c59\n * bytes4(keccak256(\u0027tokenByIndex(uint256)\u0027)) == 0x4f6ccce7\n *\n * =\u003e 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63\n */\n bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor (string memory name_, string memory symbol_) public {\n _name = name_;\n _symbol = symbol_;\n\n // register the supported interfaces to conform to ERC721 via ERC165\n _registerInterface(_INTERFACE_ID_ERC721);\n _registerInterface(_INTERFACE_ID_ERC721_METADATA);\n _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: balance query for the zero address\");\n return _holderTokens[owner].length();\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n return _tokenOwners.get(tokenId, \"ERC721: owner query for nonexistent token\");\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\n\n string memory _tokenURI = _tokenURIs[tokenId];\n string memory base = baseURI();\n\n // If there is no base URI, return the token URI.\n if (bytes(base).length == 0) {\n return _tokenURI;\n }\n // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).\n if (bytes(_tokenURI).length \u003e 0) {\n return string(abi.encodePacked(base, _tokenURI));\n }\n // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.\n return string(abi.encodePacked(base, tokenId.toString()));\n }\n\n /**\n * @dev Returns the base URI set via {_setBaseURI}. This will be\n * automatically added as a prefix in {tokenURI} to each token\u0027s URI, or\n * to the token ID if no specific URI is set for that token ID.\n */\n function baseURI() public view virtual returns (string memory) {\n return _baseURI;\n }\n\n /**\n * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {\n return _holderTokens[owner].at(index);\n }\n\n /**\n * @dev See {IERC721Enumerable-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds\n return _tokenOwners.length();\n }\n\n /**\n * @dev See {IERC721Enumerable-tokenByIndex}.\n */\n function tokenByIndex(uint256 index) public view virtual override returns (uint256) {\n (uint256 tokenId, ) = _tokenOwners.at(index);\n return tokenId;\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n require(_exists(tokenId), \"ERC721: approved query for nonexistent token\");\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n require(operator != _msgSender(), \"ERC721: approve to caller\");\n\n _operatorApprovals[_msgSender()][operator] = approved;\n emit ApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(address from, address to, uint256 tokenId) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: transfer caller is not owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: transfer caller is not owner nor approved\");\n _safeTransfer(from, to, tokenId, _data);\n }\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 * `_data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\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 `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, _data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _tokenOwners.contains(tokenId);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n require(_exists(tokenId), \"ERC721: operator query for nonexistent token\");\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n d*\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {\n _mint(to, tokenId);\n require(_checkOnERC721Received(address(0), to, tokenId, _data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _holderTokens[to].add(tokenId);\n\n _tokenOwners.set(tokenId, to);\n\n emit Transfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId); // internal owner\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n // Clear metadata (if any)\n if (bytes(_tokenURIs[tokenId]).length != 0) {\n delete _tokenURIs[tokenId];\n }\n\n _holderTokens[owner].remove(tokenId);\n\n _tokenOwners.remove(tokenId);\n\n emit Transfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(address from, address to, uint256 tokenId) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer of token that is not own\"); // internal owner\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _holderTokens[from].remove(tokenId);\n _holderTokens[to].add(tokenId);\n\n _tokenOwners.set(tokenId, to);\n\n emit Transfer(from, to, tokenId);\n }\n\n /**\n * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {\n require(_exists(tokenId), \"ERC721Metadata: URI set of nonexistent token\");\n _tokenURIs[tokenId] = _tokenURI;\n }\n\n /**\n * @dev Internal function to set the base URI for all token IDs. It is\n * automatically added as a prefix to the value returned in {tokenURI},\n * or to the token ID if {tokenURI} is empty.\n */\n function _setBaseURI(string memory baseURI_) internal virtual {\n _baseURI = baseURI_;\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param _data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)\n private returns (bool)\n {\n if (!to.isContract()) {\n return true;\n }\n bytes memory returndata = to.functionCall(abi.encodeWithSelector(\n IERC721Receiver(to).onERC721Received.selector,\n _msgSender(),\n from,\n tokenId,\n _data\n ), \"ERC721: transfer to non ERC721Receiver implementer\");\n bytes4 retval = abi.decode(returndata, (bytes4));\n return (retval == _ERC721_RECEIVED);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``\u0027s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``\u0027s `tokenId` will be burned.\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }\n}\n"},"IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.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"},"IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\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\u0027s account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller\u0027s 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\u0027s allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller\u0027s\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"},"IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\n\nimport \"./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``\u0027s 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`, 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 be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev 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 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 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 /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n}\n"},"IERC721Enumerable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n\n /**\n * @dev Returns the total amount of tokens stored by the contract.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n * Use along with {balanceOf} to enumerate all of ``owner``\u0027s tokens.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);\n\n /**\n * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n * Use along with {totalSupply} to enumerate all tokens.\n */\n function tokenByIndex(uint256 index) external view returns (uint256);\n}\n"},"IERC721Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"},"IERC721Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.\n */\n function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);\n}\n"},"IFactory.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\ninterface IFactory {\n function create(bytes calldata args) external returns (address instance);\n\n function create2(bytes calldata args, bytes32 salt) external returns (address instance);\n}"},"Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n\n// solhint-disable-next-line compiler-version\npragma solidity \u003e=0.4.24 \u003c0.8.0;\n\nimport \"./AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since a proxied contract can\u0027t have a constructor, it\u0027s common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n */\nabstract contract Initializable {\n\n /**\n * @dev Indicates that the contract has been initialized.\n */\n bool private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Modifier to protect an initializer function from being invoked twice.\n */\n modifier initializer() {\n require(_initializing || _isConstructor() || !_initialized, \"Initializable: contract is already initialized\");\n\n bool isTopLevelCall = !_initializing;\n if (isTopLevelCall) {\n _initializing = true;\n _initialized = true;\n }\n\n _;\n\n if (isTopLevelCall) {\n _initializing = false;\n }\n }\n\n /// @dev Returns true if and only if the function is running in the constructor\n function _isConstructor() private view returns (bool) {\n return !AddressUpgradeable.isContract(address(this));\n }\n}\n"},"InstanceRegistry.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {EnumerableSet} from \"./EnumerableSet.sol\";\n\ninterface IInstanceRegistry {\n /* events */\n\n event InstanceAdded(address instance);\n event InstanceRemoved(address instance);\n\n /* view functions */\n\n function isInstance(address instance) external view returns (bool validity);\n\n function instanceCount() external view returns (uint256 count);\n\n function instanceAt(uint256 index) external view returns (address instance);\n}\n\n/// @title InstanceRegistry\ncontract InstanceRegistry is IInstanceRegistry {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /* storage */\n\n EnumerableSet.AddressSet private _instanceSet;\n\n /* view functions */\n\n function isInstance(address instance) public view override returns (bool validity) {\n return _instanceSet.contains(instance);\n }\n\n function instanceCount() public view override returns (uint256 count) {\n return _instanceSet.length();\n }\n\n function instanceAt(uint256 index) public view override returns (address instance) {\n return _instanceSet.at(index);\n }\n\n /* admin functions */\n\n function _register(address instance) internal {\n require(_instanceSet.add(instance), \"InstanceRegistry: already registered\");\n emit InstanceAdded(instance);\n }\n}"},"IVaultFactory.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\ninterface IVaultFactory {\n function create() external returns (address vault);\n\n function createFor(address beneficiary) external returns (address vault);\n\n function create2(bytes32 salt) external returns (address vault);\n\n function getOwnerVault(address owner) external view returns (address);\n}"},"Ownable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\nimport \"./Context.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor () internal {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n"},"OwnableERC721.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {IERC721} from \"./IERC721.sol\";\n\n/// @title OwnableERC721\n/// @notice Use ERC721 ownership for access control\ncontract OwnableERC721 {\n address private _nftAddress;\n\n modifier onlyOwner() {\n require(owner() == msg.sender, \"OwnableERC721: caller is not the owner\");\n _;\n }\n\n function _setNFT(address nftAddress) internal {\n _nftAddress = nftAddress;\n }\n\n function nft() public view virtual returns (address nftAddress) {\n return _nftAddress;\n }\n\n function owner() public view virtual returns (address ownerAddress) {\n return IERC721(_nftAddress).ownerOf(uint256(address(this)));\n }\n}"},"OwnableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\nimport \"./ContextUpgradeable.sol\";\nimport \"./Initializable.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal initializer {\n __Context_init_unchained();\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal initializer {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n uint256[49] private __gap;\n}\n"},"Powered.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {IPowerSwitch} from \"./PowerSwitch.sol\";\n\ninterface IPowered {\n function isOnline() external view returns (bool status);\n\n function isOffline() external view returns (bool status);\n\n function isShutdown() external view returns (bool status);\n\n function getPowerSwitch() external view returns (address powerSwitch);\n\n function getPowerController() external view returns (address controller);\n}\n\n/// @title Powered\n/// @notice Helper for calling external PowerSwitch\ncontract Powered is IPowered {\n /* storage */\n\n address private _powerSwitch;\n\n /* modifiers */\n\n modifier onlyOnline() {\n _onlyOnline();\n _;\n }\n\n modifier onlyOffline() {\n _onlyOffline();\n _;\n }\n\n modifier notShutdown() {\n _notShutdown();\n _;\n }\n\n modifier onlyShutdown() {\n _onlyShutdown();\n _;\n }\n\n /* initializer */\n\n function _setPowerSwitch(address powerSwitch) internal {\n _powerSwitch = powerSwitch;\n }\n\n /* getter functions */\n\n function isOnline() public view override returns (bool status) {\n return IPowerSwitch(_powerSwitch).isOnline();\n }\n\n function isOffline() public view override returns (bool status) {\n return IPowerSwitch(_powerSwitch).isOffline();\n }\n\n function isShutdown() public view override returns (bool status) {\n return IPowerSwitch(_powerSwitch).isShutdown();\n }\n\n function getPowerSwitch() public view override returns (address powerSwitch) {\n return _powerSwitch;\n }\n\n function getPowerController() public view override returns (address controller) {\n return IPowerSwitch(_powerSwitch).getPowerController();\n }\n\n /* convenience functions */\n\n function _onlyOnline() private view {\n require(isOnline(), \"Powered: is not online\");\n }\n\n function _onlyOffline() private view {\n require(isOffline(), \"Powered: is not offline\");\n }\n\n function _notShutdown() private view {\n require(!isShutdown(), \"Powered: is shutdown\");\n }\n\n function _onlyShutdown() private view {\n require(isShutdown(), \"Powered: is not shutdown\");\n }\n}"},"PowerSwitch.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {Ownable} from \"./Ownable.sol\";\n\ninterface IPowerSwitch {\n /* admin events */\n\n event PowerOn();\n event PowerOff();\n event EmergencyShutdown();\n\n /* data types */\n\n enum State {Online, Offline, Shutdown}\n\n /* admin functions */\n\n function powerOn() external;\n\n function powerOff() external;\n\n function emergencyShutdown() external;\n\n /* view functions */\n\n function isOnline() external view returns (bool status);\n\n function isOffline() external view returns (bool status);\n\n function isShutdown() external view returns (bool status);\n\n function getStatus() external view returns (State status);\n\n function getPowerController() external view returns (address controller);\n}\n\n/// @title PowerSwitch\n/// @notice Standalone pausing and emergency stop functionality\ncontract PowerSwitch is IPowerSwitch, Ownable {\n /* storage */\n\n IPowerSwitch.State private _status;\n\n /* initializer */\n\n constructor(address owner) {\n // sanity check owner\n require(owner != address(0), \"PowerSwitch: invalid owner\");\n // transfer ownership\n Ownable.transferOwnership(owner);\n }\n\n /* admin functions */\n\n /// @notice Turn Power On\n /// access control: only admin\n /// state machine: only when offline\n /// state scope: only modify _status\n /// token transfer: none\n function powerOn() external override onlyOwner {\n require(_status == IPowerSwitch.State.Offline, \"PowerSwitch: cannot power on\");\n _status = IPowerSwitch.State.Online;\n emit PowerOn();\n }\n\n /// @notice Turn Power Off\n /// access control: only admin\n /// state machine: only when online\n /// state scope: only modify _status\n /// token transfer: none\n function powerOff() external override onlyOwner {\n require(_status == IPowerSwitch.State.Online, \"PowerSwitch: cannot power off\");\n _status = IPowerSwitch.State.Offline;\n emit PowerOff();\n }\n\n /// @notice Shutdown Permanently\n /// access control: only admin\n /// state machine:\n /// - when online or offline\n /// - can only be called once\n /// state scope: only modify _status\n /// token transfer: none\n function emergencyShutdown() external override onlyOwner {\n require(_status != IPowerSwitch.State.Shutdown, \"PowerSwitch: cannot shutdown\");\n _status = IPowerSwitch.State.Shutdown;\n emit EmergencyShutdown();\n }\n\n /* getter functions */\n\n function isOnline() external view override returns (bool status) {\n return _status == State.Online;\n }\n\n function isOffline() external view override returns (bool status) {\n return _status == State.Offline;\n }\n\n function isShutdown() external view override returns (bool status) {\n return _status == State.Shutdown;\n }\n\n function getStatus() external view override returns (IPowerSwitch.State status) {\n return _status;\n }\n\n function getPowerController() external view override returns (address controller) {\n return Ownable.owner();\n }\n}"},"ProxyFactory.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.7.6;\n\nimport {Clones} from \"./Clones.sol\";\n\nlibrary ProxyFactory {\n /* functions */\n\n function _create(address logic, bytes memory data) internal returns (address proxy) {\n // deploy clone\n proxy = Clones.clone(logic);\n\n // attempt initialization\n if (data.length \u003e 0) {\n (bool success, bytes memory err) = proxy.call(data);\n require(success, string(err));\n }\n\n // explicit return\n return proxy;\n }\n\n function _create2(\n address logic,\n bytes memory data,\n bytes32 salt\n ) internal returns (address proxy) {\n // deploy clone\n proxy = Clones.cloneDeterministic(logic, salt);\n\n // attempt initialization\n if (data.length \u003e 0) {\n (bool success, bytes memory err) = proxy.call(data);\n require(success, string(err));\n }\n\n // explicit return\n return proxy;\n }\n}"},"RewardPool.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {Ownable} from \"./Ownable.sol\";\nimport {TransferHelper} from \"./TransferHelper.sol\";\n\nimport {Powered} from \"./Powered.sol\";\n\ninterface IRewardPool {\n function sendERC20(\n address token,\n address to,\n uint256 value\n ) external;\n\n function rescueERC20(address[] calldata tokens, address recipient) external;\n}\n\n/// @title Reward Pool\n/// @notice Vault for isolated storage of reward tokens\ncontract RewardPool is IRewardPool, Powered, Ownable {\n constructor(address powerSwitch) {\n Powered._setPowerSwitch(powerSwitch);\n }\n\n /// @notice Send an ERC20 token\n /// access control: only owner\n /// state machine:\n /// - can be called multiple times\n /// - only online\n /// state scope: none\n /// token transfer: transfer tokens from self to recipient\n /// @param token address The token to send\n /// @param to address The recipient to send to\n /// @param value uint256 Amount of tokens to send\n function sendERC20(\n address token,\n address to,\n uint256 value\n ) external override onlyOwner onlyOnline {\n TransferHelper.safeTransfer(token, to, value);\n }\n\n /// @notice Rescue multiple ERC20 tokens\n /// access control: only power controller\n /// state machine:\n /// - can be called multiple times\n /// - only shutdown\n /// state scope: none\n /// token transfer: transfer tokens from self to recipient\n /// @param tokens address[] The tokens to rescue\n /// @param recipient address The recipient to rescue to\n function rescueERC20(address[] calldata tokens, address recipient) external override onlyShutdown {\n // only callable by controller\n require(msg.sender == Powered.getPowerController(), \"RewardPool: only controller can withdraw after shutdown\");\n\n // assert recipient is defined\n require(recipient != address(0), \"RewardPool: recipient not defined\");\n\n // transfer tokens\n for (uint256 index = 0; index \u003c tokens.length; index++) {\n // get token\n address token = tokens[index];\n // get balance\n uint256 balance = IERC20(token).balanceOf(address(this));\n // transfer token\n TransferHelper.safeTransfer(token, recipient, balance);\n }\n }\n}"},"SafeMath.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Wrappers over Solidity\u0027s arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it\u0027s recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n uint256 c = a + b;\n if (c \u003c a) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b \u003e a) return (false, 0);\n return (true, a - b);\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n // Gas optimization: this is cheaper than requiring \u0027a\u0027 not being zero, but the\n // benefit is lost if \u0027b\u0027 is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity\u0027s `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c \u003e= a, \"SafeMath: addition overflow\");\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity\u0027s `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b \u003c= a, \"SafeMath: subtraction overflow\");\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity\u0027s `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0) return 0;\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b \u003e 0, \"SafeMath: division by zero\");\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b \u003e 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity\u0027s `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b \u003c= a, errorMessage);\n return a - b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryDiv}.\n *\n * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b \u003e 0, errorMessage);\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b \u003e 0, errorMessage);\n return a % b;\n }\n}\n"},"StakingCenterHaVa.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\npragma abicoder v2;\n\nimport {SafeMath} from \"./SafeMath.sol\";\nimport {EnumerableSet} from \"./EnumerableSet.sol\";\nimport {IERC20} from \"./IERC20.sol\";\nimport {OwnableUpgradeable} from \"./OwnableUpgradeable.sol\";\nimport {TransferHelper} from \"./TransferHelper.sol\";\n\nimport {Powered} from \"./Powered.sol\";\nimport {IUniversalVaultB} from \"./VaultB.sol\";\nimport {IRewardPool} from \"./RewardPool.sol\";\nimport {IFactory} from \"./IFactory.sol\";\nimport {IVaultFactory} from \"./IVaultFactory.sol\";\nimport {IInstanceRegistry} from \"./InstanceRegistry.sol\";\n\ninterface IRageQuit {\n function rageQuit() external;\n}\n\ninterface IStakingCenterHaVa {\n event StakingCenterCreated(address rewardPool, address powerSwitch);\n event StakingCenterFunded(uint256 amount, uint256 duration);\n event BonusTokenRegistered(address token);\n event VaultFactoryRegistered(address factory);\n\n event Staked(address vault, uint256 amount);\n event Unstaked(address vault, uint256 amount);\n event RewardClaimed(address vault, address token, uint256 amount);\n\n struct StakingCenterData {\n address stakingToken;\n address rewardToken;\n address rewardPool;\n RewardScaling rewardScaling;\n uint256 rewardSharesOutstanding;\n uint256 totalStake;\n uint256 totalStakeUnits;\n uint256 lastUpdate;\n RewardSchedule[] rewardSchedules;\n }\n\n struct RewardSchedule {\n uint256 duration;\n uint256 start;\n uint256 shares;\n }\n\n struct VaultData {\n address owner;\n uint256 totalStake;\n StakeData[] stakes;\n }\n\n struct StakeData {\n uint256 amount;\n uint256 timestamp;\n }\n\n struct RewardScaling {\n uint256 floor;\n uint256 ceiling;\n uint256 time;\n }\n\n struct RewardOutput {\n uint256 lastStakeAmount;\n uint256 newStakesCount;\n uint256 reward;\n uint256 newTotalStakeUnits;\n }\n\n function stake(address vault, uint256 amount, bytes calldata permission) external;\n\n function unstakeAndClaim(address vault, uint256 amount, bytes calldata permission) external;\n\n function getStakingCenterData() external view returns (StakingCenterData memory stakingCenter);\n\n function getCurrentUnlockedRewards() external view returns (uint256 unlockedRewards);\n \n function getFutureUnlockedRewards(uint256 timestamp) external view returns (uint256 unlockedRewards);\n\n function getBonusTokenSetLength() external view returns (uint256 length);\n\n function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);\n\n function isValidAddress(address target) external view returns (bool validity);\n\n function getCurrentTotalStakeUnits() external view returns (uint256 totalStakeUnits);\n\n function getFutureTotalStakeUnits(uint256 timestamp) external view returns (uint256 totalStakeUnits);\n\n function getVaultData(address vault) external view returns (VaultData memory vaultData);\n\n function getCurrentVaultReward(address vault) external view returns (uint256 reward);\n\n function getFutureVaultReward(address vault, uint256 timestamp) external view returns (uint256 reward);\n\n function getCurrentStakeReward(address vault, uint256 stakeAmount) external view returns (uint256 reward);\n\n function getFutureStakeReward(address vault, uint256 stakeAmount, uint256 timestamp) external view returns (uint256 reward);\n\n function getCurrentVaultStakeUnits(address vault) external view returns (uint256 stakeUnits);\n\n function getFutureVaultStakeUnits(address vault, uint256 timestamp) external view returns (uint256 stakeUnits);\n\n function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp) external pure returns (uint256 totalStakeUnits);\n\n function calculateStakeUnits(uint256 amount, uint256 start, uint256 end) external pure returns (uint256 stakeUnits);\n\n function calculateRewardFromStakes(StakeData[] memory stakes, uint256 unstakeAmount, uint256 unlockedRewards,\n uint256 totalStakeUnits, uint256 timestamp, RewardScaling memory rewardScaling) external pure returns (RewardOutput memory out);\n\n function calculateReward(uint256 unlockedRewards, uint256 stakeAmount, uint256 stakeDuration,\n uint256 totalStakeUnits, RewardScaling memory rewardScaling) external pure returns (uint256 reward);\n\n function calculateUnlockedRewards(RewardSchedule[] memory rewardSchedules, uint256 rewardBalance,\n uint256 sharesOutstanding, uint256 timestamp) external pure returns (uint256 unlockedRewards);\n}\n\ncontract StakingCenterHaVa is IStakingCenterHaVa, Powered, OwnableUpgradeable {\n using SafeMath for uint256;\n using EnumerableSet for EnumerableSet.AddressSet;\n \n uint256 public constant MAX_STAKES_PER_VAULT = 30;\n uint256 public constant MAX_REWARD_TOKENS = 50;\n uint256 public constant BASE_SHARES_PER_WEI = 1000000;\n\n StakingCenterData private _stakingCenter;\n mapping(address =\u003e VaultData) private _vaults;\n mapping(address =\u003e uint256) private _rewardsEarned;\n EnumerableSet.AddressSet private _bonusTokenSet;\n address private _vaultFactory;\n\n function initializeLock() external initializer {}\n\n function initialize(\n address ownerAddress,\n address rewardPoolFactory,\n address powerSwitchFactory,\n address vaultFactory,\n address stakingToken,\n address rewardToken,\n RewardScaling calldata rewardScaling\n ) external initializer {\n // the scaling floor must be smaller than ceiling\n require(rewardScaling.floor \u003c= rewardScaling.ceiling, \"StakingCenter: floor above ceiling\");\n require(rewardScaling.floor \u003e 0, \"StakingCenter: scaling floor must be greater than 0\");\n require(rewardScaling.ceiling \u003e 0, \"StakingCenter: scaling ceiling must be greater than 0\");\n\n // setting rewardScalingTime to 0 would cause divide by zero error\n // to disable reward scaling, use rewardScalingFloor == rewardScalingCeiling\n require(rewardScaling.time != 0, \"StakingCenter: scaling time cannot be zero\");\n\n // deploy power switch\n address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(ownerAddress));\n\n // deploy reward pool\n address rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));\n\n // set internal configs\n OwnableUpgradeable.__Ownable_init();\n OwnableUpgradeable.transferOwnership(ownerAddress);\n Powered._setPowerSwitch(powerSwitch);\n\n // commit to storage\n _stakingCenter.stakingToken = stakingToken;\n _stakingCenter.rewardToken = rewardToken;\n _stakingCenter.rewardPool = rewardPool;\n _stakingCenter.rewardScaling = rewardScaling;\n\n _vaultFactory = vaultFactory;\n\n // emit event\n emit StakingCenterCreated(rewardPool, powerSwitch);\n }\n\n function getBonusTokenSetLength() external view override returns (uint256 length) {\n return _bonusTokenSet.length();\n }\n\n function getBonusTokenAtIndex(uint256 index) external view override returns (address bonusToken) {\n return _bonusTokenSet.at(index);\n }\n\n function isValidAddress(address target) public view override returns (bool validity) {\n // sanity check target for potential input errors\n return\n target != address(this) \u0026\u0026\n target != address(0) \u0026\u0026\n target != _stakingCenter.stakingToken \u0026\u0026\n target != _stakingCenter.rewardToken \u0026\u0026\n target != _stakingCenter.rewardPool \u0026\u0026\n !_bonusTokenSet.contains(target);\n }\n\n function getStakingCenterData() external view override returns (StakingCenterData memory stakingCenter) {\n return _stakingCenter;\n }\n\n function getCurrentUnlockedRewards() public view override returns (uint256 unlockedRewards) {\n // calculate reward available based on state\n return getFutureUnlockedRewards(block.timestamp);\n }\n\n function getFutureUnlockedRewards(uint256 timestamp) public view override returns (uint256 unlockedRewards) {\n // get reward amount remaining\n uint256 remainingRewards = IERC20(_stakingCenter.rewardToken).balanceOf(_stakingCenter.rewardPool);\n // calculate reward available based on state\n unlockedRewards = calculateUnlockedRewards(\n _stakingCenter.rewardSchedules,\n remainingRewards,\n _stakingCenter.rewardSharesOutstanding,\n timestamp\n );\n // explicit return\n return unlockedRewards;\n }\n\n function getCurrentTotalStakeUnits() public view override returns (uint256 totalStakeUnits) {\n // calculate new stake units\n return getFutureTotalStakeUnits(block.timestamp);\n }\n\n function getFutureTotalStakeUnits(uint256 timestamp) public view override returns (uint256 totalStakeUnits) {\n // return early if no change\n if (timestamp == _stakingCenter.lastUpdate) return _stakingCenter.totalStakeUnits;\n // calculate new stake units\n uint256 newStakeUnits = calculateStakeUnits(_stakingCenter.totalStake, _stakingCenter.lastUpdate, timestamp);\n // add to cached total\n totalStakeUnits = _stakingCenter.totalStakeUnits.add(newStakeUnits);\n // explicit return\n return totalStakeUnits;\n }\n\n function getVaultData(address vault) external view override returns (VaultData memory vaultData) {\n return _vaults[vault];\n }\n\n function getCurrentVaultReward(address vault) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n _vaults[vault]\n .totalStake,\n getCurrentUnlockedRewards(),\n getCurrentTotalStakeUnits(),\n block\n .timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getFutureVaultReward(address vault, uint256 timestamp) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n _vaults[vault]\n .totalStake,\n getFutureUnlockedRewards(timestamp),\n getFutureTotalStakeUnits(timestamp),\n timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getCurrentStakeReward(address vault, uint256 stakeAmount) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n stakeAmount,\n getCurrentUnlockedRewards(),\n getCurrentTotalStakeUnits(),\n block\n .timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getFutureStakeReward(\n address vault,\n uint256 stakeAmount,\n uint256 timestamp\n ) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n stakeAmount,\n getFutureUnlockedRewards(timestamp),\n getFutureTotalStakeUnits(timestamp),\n timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getCurrentVaultStakeUnits(address vault) public view override returns (uint256 stakeUnits) {\n // calculate stake units\n return getFutureVaultStakeUnits(vault, block.timestamp);\n }\n\n function getFutureVaultStakeUnits(address vault, uint256 timestamp)\n public\n view\n override\n returns (uint256 stakeUnits)\n {\n // calculate stake units\n return calculateTotalStakeUnits(_vaults[vault].stakes, timestamp);\n }\n\n function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)\n public\n pure\n override\n returns (uint256 totalStakeUnits)\n {\n for (uint256 index; index \u003c stakes.length; index++) {\n // reference stake\n StakeData memory stakeData = stakes[index];\n // calculate stake units\n uint256 stakeUnits = calculateStakeUnits(stakeData.amount, stakeData.timestamp, timestamp);\n // add to running total\n totalStakeUnits = totalStakeUnits.add(stakeUnits);\n }\n }\n\n function calculateStakeUnits(\n uint256 amount,\n uint256 start,\n uint256 end\n ) public pure override returns (uint256 stakeUnits) {\n // calculate duration\n uint256 duration = end.sub(start);\n // calculate stake units\n stakeUnits = duration.mul(amount);\n // explicit return\n return stakeUnits;\n }\n\n function fundStakingCenter(uint256 amount, uint256 duration) external onlyOwner onlyOnline {\n // validate duration\n require(duration != 0, \"StakingCenter: invalid duration\");\n\n // create new reward shares\n // if existing rewards on this StakingCenter\n // mint new shares proportional to % change in rewards remaining\n // newShares = remainingShares * newReward / remainingRewards\n // else\n // mint new shares with BASE_SHARES_PER_WEI initial conversion rate\n // store as fixed point number with same of decimals as reward token\n uint256 newRewardShares;\n if (_stakingCenter.rewardSharesOutstanding \u003e 0) {\n uint256 remainingRewards = IERC20(_stakingCenter.rewardToken).balanceOf(_stakingCenter.rewardPool);\n newRewardShares = _stakingCenter.rewardSharesOutstanding.mul(amount).div(remainingRewards);\n } else {\n newRewardShares = amount.mul(BASE_SHARES_PER_WEI);\n }\n\n // add reward shares to total\n _stakingCenter.rewardSharesOutstanding = _stakingCenter.rewardSharesOutstanding.add(newRewardShares);\n\n // store new reward schedule\n _stakingCenter.rewardSchedules.push(RewardSchedule(duration, block.timestamp, newRewardShares));\n\n // transfer reward tokens to reward pool\n TransferHelper.safeTransfer(_stakingCenter.rewardToken, _stakingCenter.rewardPool, amount);\n\n // emit event\n emit StakingCenterFunded(amount, duration);\n }\n\n function registerVaultFactory(address factory) external onlyOwner notShutdown {\n // add factory to set\n require(isValidAddress(factory), \"StakingCenter: vault factory already registered\");\n\n _vaultFactory = factory;\n\n // emit event\n emit VaultFactoryRegistered(factory);\n }\n\n function registerBonusToken(address bonusToken) external onlyOwner onlyOnline {\n // verify valid bonus token\n require(isValidAddress(bonusToken));\n\n // verify bonus token count\n require(_bonusTokenSet.length() \u003c MAX_REWARD_TOKENS, \"StakingCenter: max bonus tokens reached \");\n\n // add token to set\n assert(_bonusTokenSet.add(bonusToken));\n\n // emit event\n emit BonusTokenRegistered(bonusToken);\n }\n\n function calculateRewardFromStakes(\n StakeData[] memory stakes,\n uint256 unstakeAmount,\n uint256 unlockedRewards,\n uint256 totalStakeUnits,\n uint256 timestamp,\n RewardScaling memory rewardScaling\n ) public pure override returns (RewardOutput memory out) {\n uint256 stakesToDrop = 0;\n while (unstakeAmount \u003e 0) {\n // fetch vault stake storage reference\n StakeData memory lastStake = stakes[stakes.length.sub(stakesToDrop).sub(1)];\n\n // calculate stake duration\n uint256 stakeDuration = timestamp.sub(lastStake.timestamp);\n\n uint256 currentAmount;\n if (lastStake.amount \u003e unstakeAmount) {\n // set current amount to remaining unstake amount\n currentAmount = unstakeAmount;\n // amount of last stake is reduced\n out.lastStakeAmount = lastStake.amount.sub(unstakeAmount);\n } else {\n // set current amount to amount of last stake\n currentAmount = lastStake.amount;\n // add to stakes to drop\n stakesToDrop += 1;\n }\n\n // update remaining unstakeAmount\n unstakeAmount = unstakeAmount.sub(currentAmount);\n\n // calculate reward amount\n uint256 currentReward =\n calculateReward(unlockedRewards, currentAmount, stakeDuration, totalStakeUnits, rewardScaling);\n\n // update cumulative reward\n out.reward = out.reward.add(currentReward);\n\n // update cached unlockedRewards\n unlockedRewards = unlockedRewards.sub(currentReward);\n\n // calculate time weighted stake\n uint256 stakeUnits = currentAmount.mul(stakeDuration);\n\n // update cached totalStakeUnits\n totalStakeUnits = totalStakeUnits.sub(stakeUnits);\n }\n\n // explicit return\n return RewardOutput(out.lastStakeAmount, stakes.length.sub(stakesToDrop), out.reward, totalStakeUnits);\n }\n\n function calculateReward(\n uint256 unlockedRewards,\n uint256 stakeAmount,\n uint256 stakeDuration,\n uint256 totalStakeUnits,\n RewardScaling memory rewardScaling\n ) public pure override returns (uint256 reward) {\n // calculate time weighted stake\n uint256 stakeUnits = stakeAmount.mul(stakeDuration);\n\n // calculate base reward\n uint256 baseReward = 0;\n if (totalStakeUnits != 0) {\n // scale reward according to proportional weight\n baseReward = unlockedRewards.mul(stakeUnits).div(totalStakeUnits);\n }\n\n if (stakeDuration \u003e= rewardScaling.time || rewardScaling.floor == rewardScaling.ceiling) {\n // no reward scaling applied\n reward = baseReward;\n } else {\n // calculate minimum reward using scaling floor\n uint256 minReward = baseReward.mul(rewardScaling.floor).div(rewardScaling.ceiling);\n\n // calculate bonus reward with vested portion of scaling factor\n uint256 bonusReward =\n baseReward\n .mul(stakeDuration)\n .mul(rewardScaling.ceiling.sub(rewardScaling.floor))\n .div(rewardScaling.ceiling)\n .div(rewardScaling.time);\n\n // add minimum reward and bonus reward\n reward = minReward.add(bonusReward);\n }\n\n // explicit return\n return reward;\n }\n\n function calculateUnlockedRewards(\n RewardSchedule[] memory rewardSchedules,\n uint256 rewardBalance,\n uint256 sharesOutstanding,\n uint256 timestamp\n ) public pure override returns (uint256 unlockedRewards) {\n // return 0 if no registered schedules\n if (rewardSchedules.length == 0) {\n return 0;\n }\n\n // calculate reward shares locked across all reward schedules\n uint256 sharesLocked;\n for (uint256 index = 0; index \u003c rewardSchedules.length; index++) {\n // fetch reward schedule storage reference\n RewardSchedule memory schedule = rewardSchedules[index];\n\n // caculate amount of shares available on this schedule\n uint256 currentSharesLocked = 0;\n if (timestamp.sub(schedule.start) \u003c schedule.duration) {\n currentSharesLocked = schedule.shares.sub(\n schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration)\n );\n }\n\n // add to running total\n sharesLocked = sharesLocked.add(currentSharesLocked);\n }\n\n // convert shares to reward\n uint256 rewardLocked = sharesLocked.mul(rewardBalance).div(sharesOutstanding);\n\n // calculate amount available\n unlockedRewards = rewardBalance.sub(rewardLocked);\n\n // explicit return\n return unlockedRewards;\n }\n\n function stake(\n address vault,\n uint256 amount,\n bytes calldata permission\n ) external override onlyOnline {\n // verify non-zero amount\n require(amount != 0);\n\n // verify the vault is a valid vault and ONLY one of ours\n require(IInstanceRegistry(_vaultFactory).isInstance(vault), \"StakingCenter: Invalid vault\");\n\n // send tokens to vault\n IERC20(_stakingCenter.stakingToken).transferFrom(msg.sender, vault, amount);\n\n // fetch vault storage reference\n VaultData storage vaultData = _vaults[vault];\n\n // verify stakes boundary not reached\n require(vaultData.stakes.length \u003c MAX_STAKES_PER_VAULT, \"StakingCenter: MAX_STAKES_PER_VAULT reached\");\n\n // update cached sum of stake units across all vaults\n _updateTotalStakeUnits();\n\n // store amount and timestamp\n vaultData.stakes.push(StakeData(amount, block.timestamp));\n\n // update cached total vault and StakingCenter amounts\n vaultData.totalStake = vaultData.totalStake.add(amount);\n _stakingCenter.totalStake = _stakingCenter.totalStake.add(amount);\n\n // call lock on vault\n IUniversalVaultB(vault).lock(_stakingCenter.stakingToken, amount, permission);\n\n // emit event\n vaultData.owner = msg.sender;\n emit Staked(vault, amount);\n }\n\n function unstakeAndClaim(\n address vault,\n uint256 amount,\n bytes calldata permission\n ) external override onlyOnline {\n // verify the vault is a valid vault and ONLY one of ours\n require(IInstanceRegistry(_vaultFactory).isInstance(vault));\n \n // fetch vault storage reference\n VaultData storage vaultData = _vaults[vault];\n require(vaultData.owner == msg.sender, \"incorrect owner\");\n\n // check for sufficient vault stake amount\n require(vaultData.totalStake \u003e= amount);\n\n // check for sufficient StakingCenter stake amount\n // if this check fails, there is a bug in stake accounting\n assert(_stakingCenter.totalStake \u003e= amount);\n\n // update cached sum of stake units across all vaults\n _updateTotalStakeUnits();\n\n // get reward amount remaining\n uint256 remainingRewards = IERC20(_stakingCenter.rewardToken).balanceOf(_stakingCenter.rewardPool);\n\n // calculate vested portion of reward pool\n uint256 unlockedRewards =\n calculateUnlockedRewards(\n _stakingCenter.rewardSchedules,\n remainingRewards,\n _stakingCenter.rewardSharesOutstanding,\n block.timestamp\n );\n\n // calculate vault time weighted reward with scaling\n RewardOutput memory out =\n calculateRewardFromStakes(\n vaultData.stakes,\n (amount == 0 ? vaultData.totalStake : amount),\n unlockedRewards,\n _stakingCenter.totalStakeUnits,\n block.timestamp,\n _stakingCenter.rewardScaling\n );\n\n if (amount != 0) {\n // update stake data in storage\n if (out.newStakesCount == 0) {\n // all stakes have been unstaked\n delete vaultData.stakes;\n } else {\n // some stakes have been completely or partially unstaked\n // delete fully unstaked stakes\n while (vaultData.stakes.length \u003e out.newStakesCount) vaultData.stakes.pop();\n\n // only perform when lastStakeAmount is set\n if (out.lastStakeAmount \u003e 0) {\n // update partially unstaked stake\n vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount;\n }\n }\n\n // update cached stake totals\n vaultData.totalStake = vaultData.totalStake.sub(amount);\n _stakingCenter.totalStake = _stakingCenter.totalStake.sub(amount);\n _stakingCenter.totalStakeUnits = out.newTotalStakeUnits;\n\n // unlock staking tokens from vault\n IUniversalVaultB(vault).unlock(_stakingCenter.stakingToken, amount, true, permission);\n\n // emit event\n emit Unstaked(vault, amount);\n } else {\n for (uint256 index; index \u003c vaultData.stakes.length; index++) {\n // update timestamps\n vaultData.stakes[index].timestamp = block.timestamp;\n }\n }\n\n // only perform on non-zero reward\n if (out.reward \u003e 0) {\n // calculate shares to burn\n // sharesToBurn = sharesOutstanding * reward / remainingRewards\n uint256 sharesToBurn = _stakingCenter.rewardSharesOutstanding.mul(out.reward).div(remainingRewards);\n\n // burn claimed shares\n _stakingCenter.rewardSharesOutstanding = _stakingCenter.rewardSharesOutstanding.sub(sharesToBurn);\n\n // transfer bonus tokens from reward pool to recipient\n if (_bonusTokenSet.length() \u003e 0) {\n for (uint256 index = 0; index \u003c _bonusTokenSet.length(); index++) {\n // fetch bonus token address reference\n address bonusToken = _bonusTokenSet.at(index);\n\n // calculate bonus token amount\n // bonusAmount = bonusRemaining * reward / remainingRewards\n uint256 bonusAmount =\n IERC20(bonusToken).balanceOf(_stakingCenter.rewardPool).mul(out.reward).div(remainingRewards);\n\n // transfer if amount is non-zero\n if (bonusAmount \u003e 0) {\n // transfer bonus token\n IRewardPool(_stakingCenter.rewardPool).sendERC20(bonusToken, vaultData.owner, bonusAmount);\n\n // emit event\n emit RewardClaimed(vault, bonusToken, bonusAmount);\n }\n }\n }\n\n // transfer reward tokens from reward pool to recipient\n IRewardPool(_stakingCenter.rewardPool).sendERC20(_stakingCenter.rewardToken, vaultData.owner, out.reward);\n _rewardsEarned[vault] = _rewardsEarned[vault].add(out.reward);\n\n // emit event\n emit RewardClaimed(vault, _stakingCenter.rewardToken, out.reward);\n }\n }\n\n function _updateTotalStakeUnits() private {\n // update cached totalStakeUnits\n _stakingCenter.totalStakeUnits = getCurrentTotalStakeUnits();\n // update cached lastUpdate\n _stakingCenter.lastUpdate = block.timestamp;\n }\n}\n"},"Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI\u0027s implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n uint256 index = digits - 1;\n temp = value;\n while (temp != 0) {\n buffer[index--] = bytes1(uint8(48 + temp % 10));\n temp /= 10;\n }\n return string(buffer);\n }\n}\n"},"TransferHelper.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-or-later\n\npragma solidity \u003e=0.6.0;\n\n// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false\nlibrary TransferHelper {\n function safeApprove(\n address token,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027approve(address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::safeApprove: approve failed\u0027\n );\n }\n\n function safeTransfer(\n address token,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027transfer(address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::safeTransfer: transfer failed\u0027\n );\n }\n\n function safeTransferFrom(\n address token,\n address from,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027transferFrom(address,address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::transferFrom: transferFrom failed\u0027\n );\n }\n\n function safeTransferETH(address to, uint256 value) internal {\n (bool success, ) = to.call{value: value}(new bytes(0));\n require(success, \u0027TransferHelper::safeTransferETH: ETH transfer failed\u0027);\n }\n}\n"},"VaultB.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\npragma abicoder v2;\n\nimport {SafeMath} from \"./SafeMath.sol\";\nimport {IERC20} from \"./IERC20.sol\";\nimport {Initializable} from \"./Initializable.sol\";\nimport {EnumerableSet} from \"./EnumerableSet.sol\";\nimport {Address} from \"./Address.sol\";\nimport {TransferHelper} from \"./TransferHelper.sol\";\n\nimport {EIP712} from \"./EIP712.sol\";\nimport {ERC1271} from \"./ERC1271.sol\";\nimport {OwnableERC721} from \"./OwnableERC721.sol\";\nimport {ECDSA} from \"./ECDSA.sol\";\nimport {IRageQuit} from \"./StakingCenterHaVa.sol\";\n\ninterface IERC1271 {\n function isValidSignature(bytes32 _messageHash, bytes memory _signature)\n external\n view\n returns (bytes4 magicValue);\n}\n\ninterface IUniversalVaultB {\n /* user events */\n\n event Locked(address delegate, address token, uint256 amount);\n event Unlocked(address delegate, address token, uint256 amount);\n event RageQuit(address delegate, address token, bool notified, string reason);\n\n /* data types */\n\n struct LockData {\n address delegate;\n address token;\n uint256 balance;\n }\n\n /* initialize function */\n\n function initialize() external;\n\n /* user functions */\n\n function lock(\n address token,\n uint256 amount,\n bytes calldata permission\n ) external;\n\n function unlock(\n address token,\n uint256 amount,\n bool send,\n bytes calldata permission\n ) external;\n\n function rageQuit(address delegate, address token)\n external\n returns (bool notified, string memory error);\n\n function transferERC20(\n address token,\n address to,\n uint256 amount\n ) external;\n\n function transferETH(address to, uint256 amount) external payable;\n\n /* pure functions */\n\n function calculateLockID(address delegate, address token)\n external\n pure\n returns (bytes32 lockID);\n\n /* getter functions */\n\n function getPermissionHash(\n bytes32 eip712TypeHash,\n address delegate,\n address token,\n uint256 amount,\n uint256 nonce\n ) external view returns (bytes32 permissionHash);\n\n function getNonce() external view returns (uint256 nonce);\n\n function owner() external view returns (address ownerAddress);\n\n function getLockSetCount() external view returns (uint256 count);\n\n function getLockAt(uint256 index) external view returns (LockData memory lockData);\n\n function getBalanceDelegated(address token, address delegate)\n external\n view\n returns (uint256 balance);\n\n function getBalanceLocked(address token) external view returns (uint256 balance);\n\n function checkBalances() external view returns (bool validity);\n}\n\n/// @title Vault\n/// @notice Vault for isolated storage of staking tokens\n/// @dev Warning: not compatible with rebasing tokens\ncontract VaultB is\n IUniversalVaultB,\n EIP712(\"UniversalVault\", \"1.0.0\"),\n ERC1271,\n OwnableERC721,\n Initializable\n{\n using SafeMath for uint256;\n using Address for address;\n using Address for address payable;\n using EnumerableSet for EnumerableSet.Bytes32Set;\n\n /* constant */\n\n // Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks\n // the gas requirement cannot be determined at runtime by querying the delegate\n // as it could potentially be manipulated by a malicious delegate who could force\n // the calls to revert.\n // The gas limit could alternatively be set upon vault initialization or creation\n // of a lock, but the gas consumption trade-offs are not favorable.\n // Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide\n // an error code that allows for reliably catching out-of-gas errors on remote calls.\n uint256 public constant RAGEQUIT_GAS = 500000;\n bytes32 public constant LOCK_TYPEHASH =\n keccak256(\"Lock(address delegate,address token,uint256 amount,uint256 nonce)\");\n bytes32 public constant UNLOCK_TYPEHASH =\n keccak256(\"Unlock(address delegate,address token,uint256 amount,uint256 nonce)\");\n\n /* storage */\n\n uint256 private _nonce;\n mapping(bytes32 =\u003e LockData) private _locks;\n EnumerableSet.Bytes32Set private _lockSet;\n\n /* initialization function */\n\n function initializeLock() external initializer {}\n\n function initialize() external override initializer {\n OwnableERC721._setNFT(msg.sender);\n }\n\n /* ether receive */\n\n receive() external payable {}\n\n /* internal overrides */\n\n function _getOwner() internal view override(ERC1271) returns (address ownerAddress) {\n return OwnableERC721.owner();\n }\n\n /* pure functions */\n\n function calculateLockID(address delegate, address token)\n public\n pure\n override\n returns (bytes32 lockID)\n {\n return keccak256(abi.encodePacked(delegate, token));\n }\n\n /* getter functions */\n\n function getPermissionHash(\n bytes32 eip712TypeHash,\n address delegate,\n address token,\n uint256 amount,\n uint256 nonce\n ) public view override returns (bytes32 permissionHash) {\n return\n EIP712._hashTypedDataV4(\n keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce))\n );\n }\n\n function getNonce() external view override returns (uint256 nonce) {\n return _nonce;\n }\n\n function owner()\n public\n view\n override(IUniversalVaultB, OwnableERC721)\n returns (address ownerAddress)\n {\n return OwnableERC721.owner();\n }\n\n function getLockSetCount() external view override returns (uint256 count) {\n return _lockSet.length();\n }\n\n function getLockAt(uint256 index) external view override returns (LockData memory lockData) {\n return _locks[_lockSet.at(index)];\n }\n\n function getBalanceDelegated(address token, address delegate)\n external\n view\n override\n returns (uint256 balance)\n {\n return _locks[calculateLockID(delegate, token)].balance;\n }\n\n function getBalanceLocked(address token) public view override returns (uint256 balance) {\n uint256 count = _lockSet.length();\n for (uint256 index; index \u003c count; index++) {\n LockData storage _lockData = _locks[_lockSet.at(index)];\n if (_lockData.token == token \u0026\u0026 _lockData.balance \u003e balance)\n balance = _lockData.balance;\n }\n return balance;\n }\n\n function checkBalances() external view override returns (bool validity) {\n // iterate over all token locks and validate sufficient balance\n uint256 count = _lockSet.length();\n for (uint256 index; index \u003c count; index++) {\n // fetch storage lock reference\n LockData storage _lockData = _locks[_lockSet.at(index)];\n // if insufficient balance and no∏t shutdown, return false\n if (IERC20(_lockData.token).balanceOf(address(this)) \u003c _lockData.balance) return false;\n }\n // if sufficient balance or shutdown, return true\n return true;\n }\n\n /* user functions */\n\n /// @notice Lock ERC20 tokens in the vault\n /// access control: called by delegate with signed permission from owner\n /// state machine: anytime\n /// state scope:\n /// - insert or update _locks\n /// - increase _nonce\n /// token transfer: none\n /// @param token Address of token being locked\n /// @param amount Amount of tokens being locked\n /// @param permission Permission signature payload\n function lock(\n address token,\n uint256 amount,\n bytes calldata permission\n )\n external\n override\n onlyValidSignature(\n getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce),\n permission\n )\n {\n // get lock id\n bytes32 lockID = calculateLockID(msg.sender, token);\n\n // add lock to storage\n if (_lockSet.contains(lockID)) {\n // if lock already exists, increase amount\n _locks[lockID].balance = _locks[lockID].balance.add(amount);\n } else {\n // if does not exist, create new lock\n // add lock to set\n assert(_lockSet.add(lockID));\n // add lock data to storage\n _locks[lockID] = LockData(msg.sender, token, amount);\n }\n\n // validate sufficient balance\n require(\n IERC20(token).balanceOf(address(this)) \u003e= _locks[lockID].balance,\n \"UniversalVault: insufficient balance\"\n );\n\n // increase nonce\n _nonce += 1;\n\n // emit event\n emit Locked(msg.sender, token, amount);\n }\n\n /// @notice Unlock ERC20 tokens in the vault\n /// access control: called by delegate with signed permission from owner\n /// state machine: after valid lock from delegate\n /// state scope:\n /// - remove or update _locks\n /// - increase _nonce\n /// token transfer: none\n /// @param token Address of token being unlocked\n /// @param amount Amount of tokens being unlocked\n /// @param permission Permission signature payload\n function unlock(\n address token,\n uint256 amount,\n bool send,\n bytes calldata permission\n )\n external\n override\n onlyValidSignature(\n getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce),\n permission\n )\n {\n // get lock id\n bytes32 lockID = calculateLockID(msg.sender, token);\n\n // validate existing lock\n require(_lockSet.contains(lockID), \"UniversalVault: missing lock\");\n\n // update lock data\n if (_locks[lockID].balance \u003e amount) {\n // substract amount from lock balance\n _locks[lockID].balance = _locks[lockID].balance.sub(amount);\n } else {\n // delete lock data\n delete _locks[lockID];\n assert(_lockSet.remove(lockID));\n }\n\n // increase nonce\n _nonce += 1;\n\n // emit event\n emit Unlocked(msg.sender, token, amount);\n\n // send to owner if allowed\n if (send) {\n TransferHelper.safeTransfer(token, _getOwner(), amount);\n }\n }\n\n /// @notice Forcibly cancel delegate lock\n /// @dev This function will attempt to notify the delegate of the rage quit using\n /// a fixed amount of gas.\n /// access control: only owner\n /// state machine: after valid lock from delegate\n /// state scope:\n /// - remove item from _locks\n /// token transfer: none\n /// @param delegate Address of delegate\n /// @param token Address of token being unlocked\n function rageQuit(address delegate, address token)\n external\n override\n onlyOwner\n returns (bool notified, string memory error)\n {\n // get lock id\n bytes32 lockID = calculateLockID(delegate, token);\n\n // validate existing lock\n require(_lockSet.contains(lockID), \"UniversalVault: missing lock\");\n\n // attempt to notify delegate\n if (delegate.isContract()) {\n // check for sufficient gas\n require(gasleft() \u003e= RAGEQUIT_GAS, \"UniversalVault: insufficient gas\");\n\n // attempt rageQuit notification\n try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {\n notified = true;\n } catch Error(string memory res) {\n notified = false;\n error = res;\n } catch (bytes memory) {\n notified = false;\n }\n }\n\n // update lock storage\n assert(_lockSet.remove(lockID));\n delete _locks[lockID];\n\n // emit event\n emit RageQuit(delegate, token, notified, error);\n }\n\n /// @notice Transfer ERC20 tokens out of vault\n /// access control: only owner\n /// state machine: when balance \u003e= max(lock) + amount\n /// state scope: none\n /// token transfer: transfer any token\n /// @param token Address of token being transferred\n /// @param to Address of the recipient\n /// @param amount Amount of tokens to transfer\n function transferERC20(\n address token,\n address to,\n uint256 amount\n ) external override onlyOwner {\n // check for sufficient balance\n require(\n IERC20(token).balanceOf(address(this)) \u003e= getBalanceLocked(token).add(amount),\n \"UniversalVault: insufficient balance\"\n );\n // perform transfer\n TransferHelper.safeTransfer(token, to, amount);\n }\n\n /// @notice Transfer ERC20 tokens out of vault\n /// access control: only owner\n /// state machine: when balance \u003e= amount\n /// state scope: none\n /// token transfer: transfer any token\n /// @param to Address of the recipient\n /// @param amount Amount of ETH to transfer\n function transferETH(address to, uint256 amount) external payable override onlyOwner {\n // perform transfer\n TransferHelper.safeTransferETH(to, amount);\n }\n \n}"},"VaultFactoryB.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {ERC721} from \"./ERC721.sol\";\n\nimport {IVaultFactory} from \"./IVaultFactory.sol\";\nimport {IInstanceRegistry} from \"./InstanceRegistry.sol\";\nimport {ProxyFactory} from \"./ProxyFactory.sol\";\n\nimport {IUniversalVaultB} from \"./VaultB.sol\";\n\n/// @title VaultFactoryB\ncontract VaultFactoryB is IInstanceRegistry, ERC721, IVaultFactory {\n address private immutable _template;\n mapping(address =\u003e address) private _ownerVault;\n\n constructor(address template) ERC721(\"Vault v1\", \"VAULT-V1\") {\n require(template != address(0), \"VaultFactory: invalid template\");\n _template = template;\n }\n\n /* registry functions */\n\n function isInstance(address instance) external view override returns (bool validity) {\n return ERC721._exists(uint256(instance));\n }\n\n function instanceCount() external view override returns (uint256 count) {\n return ERC721.totalSupply();\n }\n\n function instanceAt(uint256 index) external view override returns (address instance) {\n return address(ERC721.tokenByIndex(index));\n }\n\n /* factory functions */\n\n // function create(bytes calldata) external override returns (address vault) {\n // return create();\n // }\n\n // function create2(bytes calldata, bytes32 salt) external override returns (address vault) {\n // return create2(salt);\n // }\n\n function create() public override returns (address vault) {\n // create clone and initialize\n vault = ProxyFactory._create(\n _template,\n abi.encodeWithSelector(IUniversalVaultB.initialize.selector)\n );\n\n // mint nft to caller\n ERC721._safeMint(msg.sender, uint256(vault));\n _ownerVault[msg.sender] = vault;\n\n // emit event\n emit InstanceAdded(vault);\n\n // explicit return\n return vault;\n }\n\n function createFor(address beneficiary) public override returns (address vault) {\n // create clone and initialize\n vault = ProxyFactory._create(\n _template,\n abi.encodeWithSelector(IUniversalVaultB.initialize.selector)\n );\n\n // mint nft to caller\n ERC721._safeMint(beneficiary, uint256(vault));\n _ownerVault[beneficiary] = vault;\n\n // emit event\n emit InstanceAdded(vault);\n\n // explicit return\n return vault;\n }\n\n function create2(bytes32 salt) public override returns (address vault) {\n // create clone and initialize\n vault = ProxyFactory._create2(\n _template,\n abi.encodeWithSelector(IUniversalVaultB.initialize.selector),\n salt\n );\n\n // mint nft to caller\n ERC721._safeMint(msg.sender, uint256(vault));\n _ownerVault[msg.sender] = vault;\n\n // emit event\n emit InstanceAdded(vault);\n\n // explicit return\n return vault;\n }\n\n /* getter functions */\n\n function getTemplate() external view returns (address template) {\n return _template;\n }\n\n function getOwnerVault(address owner) external view override returns (address) {\n return _ownerVault[owner];\n }\n}"}}
File 2 of 3: VaultB
{"Address.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\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 function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size \u003e 0;\n }\n\n /**\n * @dev Replacement for Solidity\u0027s `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 \u003e= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance \u003e= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length \u003e 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"},"AddressUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\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 function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size \u003e 0;\n }\n\n /**\n * @dev Replacement for Solidity\u0027s `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 \u003e= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance \u003e= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length \u003e 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"},"Context.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n"},"ContextUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\nimport \"./Initializable.sol\";\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal initializer {\n __Context_init_unchained();\n }\n\n function __Context_init_unchained() internal initializer {\n }\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n uint256[50] private __gap;\n}\n"},"ECDSA.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n // Check the signature length\n if (signature.length != 65) {\n revert(\"ECDSA: invalid signature length\");\n }\n\n // Divide the signature in r, s and v variables\n bytes32 r;\n bytes32 s;\n uint8 v;\n\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n // solhint-disable-next-line no-inline-assembly\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n\n return recover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (281): 0 \u003c s \u003c secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n require(uint256(s) \u003c= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, \"ECDSA: invalid signature \u0027s\u0027 value\");\n require(v == 27 || v == 28, \"ECDSA: invalid signature \u0027v\u0027 value\");\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n require(signer != address(0), \"ECDSA: invalid signature\");\n\n return signer;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * replicates the behavior of the\n * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]\n * JSON-RPC method.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n }\n}\n"},"EIP712.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/* solhint-disable max-line-length */\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n */\nabstract contract EIP712 {\n /* solhint-disable var-name-mixedcase */\n bytes32 private immutable _HASHED_NAME;\n bytes32 private immutable _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH =\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n );\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n\n constructor(string memory name, string memory version) {\n _HASHED_NAME = keccak256(bytes(name));\n _HASHED_VERSION = keccak256(bytes(version));\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 name,\n bytes32 version\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, name, version, _getChainId(), address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", _domainSeparatorV4(), structHash));\n }\n\n function _getChainId() private view returns (uint256 chainId) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal view virtual returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal view virtual returns (bytes32) {\n return _HASHED_VERSION;\n }\n}"},"EnumerableSet.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping (bytes32 =\u003e uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value\u0027s index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) { // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as \u0027swap and pop\u0027).\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n // so rarely, we still do the swap anyway to avoid the gas cost of adding an \u0027if\u0027 statement.\n\n bytes32 lastvalue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastvalue;\n // Update the index for the moved value\n set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n require(set._values.length \u003e index, \"EnumerableSet: index out of bounds\");\n return set._values[index];\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n}\n"},"ERC1271.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {ECDSA} from \"./ECDSA.sol\";\nimport {Address} from \"./Address.sol\";\n\ninterface IERC1271 {\n function isValidSignature(bytes32 _messageHash, bytes memory _signature)\n external\n view\n returns (bytes4 magicValue);\n}\n\nlibrary SignatureChecker {\n using ECDSA for bytes32;\n\n function isValidSignature(\n address signer,\n bytes32 hash,\n bytes memory signature\n ) internal view returns (bool) {\n if (Address.isContract(signer)) {\n bytes4 selector = IERC1271.isValidSignature.selector;\n (bool success, bytes memory returndata) = signer.staticcall(\n abi.encodeWithSelector(selector, hash, signature)\n );\n return success \u0026\u0026 abi.decode(returndata, (bytes4)) == selector;\n } else {\n return hash.toEthSignedMessageHash().recover(signature) == signer;\n }\n }\n}\n\n/// @title ERC1271\n/// @notice Module for ERC1271 compatibility\nabstract contract ERC1271 is IERC1271 {\n // Valid magic value bytes4(keccak256(\"isValidSignature(bytes32,bytes)\")\n bytes4 internal constant VALID_SIG = IERC1271.isValidSignature.selector;\n // Invalid magic value\n bytes4 internal constant INVALID_SIG = bytes4(0);\n\n modifier onlyValidSignature(\n bytes32 permissionHash,\n bytes memory signature\n ) {\n require(\n isValidSignature(permissionHash, signature) == VALID_SIG,\n \"ERC1271: Invalid signature\"\n );\n _;\n }\n\n function _getOwner() internal view virtual returns (address owner);\n\n function isValidSignature(bytes32 permissionHash, bytes memory signature)\n public\n view\n override\n returns (bytes4)\n {\n return\n SignatureChecker.isValidSignature(\n _getOwner(),\n permissionHash,\n signature\n )\n ? VALID_SIG\n : INVALID_SIG;\n }\n}\n"},"IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.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"},"IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\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\u0027s account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller\u0027s 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\u0027s allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller\u0027s\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"},"IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\n\nimport \"./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``\u0027s 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`, 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 be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev 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 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 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 /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n}\n"},"IFactory.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\ninterface IFactory {\n function create(bytes calldata args) external returns (address instance);\n\n function create2(bytes calldata args, bytes32 salt) external returns (address instance);\n}"},"Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n\n// solhint-disable-next-line compiler-version\npragma solidity \u003e=0.4.24 \u003c0.8.0;\n\nimport \"./AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since a proxied contract can\u0027t have a constructor, it\u0027s common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n */\nabstract contract Initializable {\n\n /**\n * @dev Indicates that the contract has been initialized.\n */\n bool private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Modifier to protect an initializer function from being invoked twice.\n */\n modifier initializer() {\n require(_initializing || _isConstructor() || !_initialized, \"Initializable: contract is already initialized\");\n\n bool isTopLevelCall = !_initializing;\n if (isTopLevelCall) {\n _initializing = true;\n _initialized = true;\n }\n\n _;\n\n if (isTopLevelCall) {\n _initializing = false;\n }\n }\n\n /// @dev Returns true if and only if the function is running in the constructor\n function _isConstructor() private view returns (bool) {\n return !AddressUpgradeable.isContract(address(this));\n }\n}\n"},"InstanceRegistry.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {EnumerableSet} from \"./EnumerableSet.sol\";\n\ninterface IInstanceRegistry {\n /* events */\n\n event InstanceAdded(address instance);\n event InstanceRemoved(address instance);\n\n /* view functions */\n\n function isInstance(address instance) external view returns (bool validity);\n\n function instanceCount() external view returns (uint256 count);\n\n function instanceAt(uint256 index) external view returns (address instance);\n}\n\n/// @title InstanceRegistry\ncontract InstanceRegistry is IInstanceRegistry {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /* storage */\n\n EnumerableSet.AddressSet private _instanceSet;\n\n /* view functions */\n\n function isInstance(address instance) public view override returns (bool validity) {\n return _instanceSet.contains(instance);\n }\n\n function instanceCount() public view override returns (uint256 count) {\n return _instanceSet.length();\n }\n\n function instanceAt(uint256 index) public view override returns (address instance) {\n return _instanceSet.at(index);\n }\n\n /* admin functions */\n\n function _register(address instance) internal {\n require(_instanceSet.add(instance), \"InstanceRegistry: already registered\");\n emit InstanceAdded(instance);\n }\n}"},"IVaultFactory.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\ninterface IVaultFactory {\n function create() external returns (address vault);\n\n function createFor(address beneficiary) external returns (address vault);\n\n function create2(bytes32 salt) external returns (address vault);\n\n function getOwnerVault(address owner) external view returns (address);\n}"},"Ownable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\nimport \"./Context.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor () internal {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n"},"OwnableERC721.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {IERC721} from \"./IERC721.sol\";\n\n/// @title OwnableERC721\n/// @notice Use ERC721 ownership for access control\ncontract OwnableERC721 {\n address private _nftAddress;\n\n modifier onlyOwner() {\n require(owner() == msg.sender, \"OwnableERC721: caller is not the owner\");\n _;\n }\n\n function _setNFT(address nftAddress) internal {\n _nftAddress = nftAddress;\n }\n\n function nft() public view virtual returns (address nftAddress) {\n return _nftAddress;\n }\n\n function owner() public view virtual returns (address ownerAddress) {\n return IERC721(_nftAddress).ownerOf(uint256(address(this)));\n }\n}"},"OwnableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\nimport \"./ContextUpgradeable.sol\";\nimport \"./Initializable.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal initializer {\n __Context_init_unchained();\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal initializer {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n uint256[49] private __gap;\n}\n"},"Powered.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {IPowerSwitch} from \"./PowerSwitch.sol\";\n\ninterface IPowered {\n function isOnline() external view returns (bool status);\n\n function isOffline() external view returns (bool status);\n\n function isShutdown() external view returns (bool status);\n\n function getPowerSwitch() external view returns (address powerSwitch);\n\n function getPowerController() external view returns (address controller);\n}\n\n/// @title Powered\n/// @notice Helper for calling external PowerSwitch\ncontract Powered is IPowered {\n /* storage */\n\n address private _powerSwitch;\n\n /* modifiers */\n\n modifier onlyOnline() {\n _onlyOnline();\n _;\n }\n\n modifier onlyOffline() {\n _onlyOffline();\n _;\n }\n\n modifier notShutdown() {\n _notShutdown();\n _;\n }\n\n modifier onlyShutdown() {\n _onlyShutdown();\n _;\n }\n\n /* initializer */\n\n function _setPowerSwitch(address powerSwitch) internal {\n _powerSwitch = powerSwitch;\n }\n\n /* getter functions */\n\n function isOnline() public view override returns (bool status) {\n return IPowerSwitch(_powerSwitch).isOnline();\n }\n\n function isOffline() public view override returns (bool status) {\n return IPowerSwitch(_powerSwitch).isOffline();\n }\n\n function isShutdown() public view override returns (bool status) {\n return IPowerSwitch(_powerSwitch).isShutdown();\n }\n\n function getPowerSwitch() public view override returns (address powerSwitch) {\n return _powerSwitch;\n }\n\n function getPowerController() public view override returns (address controller) {\n return IPowerSwitch(_powerSwitch).getPowerController();\n }\n\n /* convenience functions */\n\n function _onlyOnline() private view {\n require(isOnline(), \"Powered: is not online\");\n }\n\n function _onlyOffline() private view {\n require(isOffline(), \"Powered: is not offline\");\n }\n\n function _notShutdown() private view {\n require(!isShutdown(), \"Powered: is shutdown\");\n }\n\n function _onlyShutdown() private view {\n require(isShutdown(), \"Powered: is not shutdown\");\n }\n}"},"PowerSwitch.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {Ownable} from \"./Ownable.sol\";\n\ninterface IPowerSwitch {\n /* admin events */\n\n event PowerOn();\n event PowerOff();\n event EmergencyShutdown();\n\n /* data types */\n\n enum State {Online, Offline, Shutdown}\n\n /* admin functions */\n\n function powerOn() external;\n\n function powerOff() external;\n\n function emergencyShutdown() external;\n\n /* view functions */\n\n function isOnline() external view returns (bool status);\n\n function isOffline() external view returns (bool status);\n\n function isShutdown() external view returns (bool status);\n\n function getStatus() external view returns (State status);\n\n function getPowerController() external view returns (address controller);\n}\n\n/// @title PowerSwitch\n/// @notice Standalone pausing and emergency stop functionality\ncontract PowerSwitch is IPowerSwitch, Ownable {\n /* storage */\n\n IPowerSwitch.State private _status;\n\n /* initializer */\n\n constructor(address owner) {\n // sanity check owner\n require(owner != address(0), \"PowerSwitch: invalid owner\");\n // transfer ownership\n Ownable.transferOwnership(owner);\n }\n\n /* admin functions */\n\n /// @notice Turn Power On\n /// access control: only admin\n /// state machine: only when offline\n /// state scope: only modify _status\n /// token transfer: none\n function powerOn() external override onlyOwner {\n require(_status == IPowerSwitch.State.Offline, \"PowerSwitch: cannot power on\");\n _status = IPowerSwitch.State.Online;\n emit PowerOn();\n }\n\n /// @notice Turn Power Off\n /// access control: only admin\n /// state machine: only when online\n /// state scope: only modify _status\n /// token transfer: none\n function powerOff() external override onlyOwner {\n require(_status == IPowerSwitch.State.Online, \"PowerSwitch: cannot power off\");\n _status = IPowerSwitch.State.Offline;\n emit PowerOff();\n }\n\n /// @notice Shutdown Permanently\n /// access control: only admin\n /// state machine:\n /// - when online or offline\n /// - can only be called once\n /// state scope: only modify _status\n /// token transfer: none\n function emergencyShutdown() external override onlyOwner {\n require(_status != IPowerSwitch.State.Shutdown, \"PowerSwitch: cannot shutdown\");\n _status = IPowerSwitch.State.Shutdown;\n emit EmergencyShutdown();\n }\n\n /* getter functions */\n\n function isOnline() external view override returns (bool status) {\n return _status == State.Online;\n }\n\n function isOffline() external view override returns (bool status) {\n return _status == State.Offline;\n }\n\n function isShutdown() external view override returns (bool status) {\n return _status == State.Shutdown;\n }\n\n function getStatus() external view override returns (IPowerSwitch.State status) {\n return _status;\n }\n\n function getPowerController() external view override returns (address controller) {\n return Ownable.owner();\n }\n}"},"RewardPool.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {Ownable} from \"./Ownable.sol\";\nimport {TransferHelper} from \"./TransferHelper.sol\";\n\nimport {Powered} from \"./Powered.sol\";\n\ninterface IRewardPool {\n function sendERC20(\n address token,\n address to,\n uint256 value\n ) external;\n\n function rescueERC20(address[] calldata tokens, address recipient) external;\n}\n\n/// @title Reward Pool\n/// @notice Vault for isolated storage of reward tokens\ncontract RewardPool is IRewardPool, Powered, Ownable {\n constructor(address powerSwitch) {\n Powered._setPowerSwitch(powerSwitch);\n }\n\n /// @notice Send an ERC20 token\n /// access control: only owner\n /// state machine:\n /// - can be called multiple times\n /// - only online\n /// state scope: none\n /// token transfer: transfer tokens from self to recipient\n /// @param token address The token to send\n /// @param to address The recipient to send to\n /// @param value uint256 Amount of tokens to send\n function sendERC20(\n address token,\n address to,\n uint256 value\n ) external override onlyOwner onlyOnline {\n TransferHelper.safeTransfer(token, to, value);\n }\n\n /// @notice Rescue multiple ERC20 tokens\n /// access control: only power controller\n /// state machine:\n /// - can be called multiple times\n /// - only shutdown\n /// state scope: none\n /// token transfer: transfer tokens from self to recipient\n /// @param tokens address[] The tokens to rescue\n /// @param recipient address The recipient to rescue to\n function rescueERC20(address[] calldata tokens, address recipient) external override onlyShutdown {\n // only callable by controller\n require(msg.sender == Powered.getPowerController(), \"RewardPool: only controller can withdraw after shutdown\");\n\n // assert recipient is defined\n require(recipient != address(0), \"RewardPool: recipient not defined\");\n\n // transfer tokens\n for (uint256 index = 0; index \u003c tokens.length; index++) {\n // get token\n address token = tokens[index];\n // get balance\n uint256 balance = IERC20(token).balanceOf(address(this));\n // transfer token\n TransferHelper.safeTransfer(token, recipient, balance);\n }\n }\n}"},"SafeMath.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Wrappers over Solidity\u0027s arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it\u0027s recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n uint256 c = a + b;\n if (c \u003c a) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b \u003e a) return (false, 0);\n return (true, a - b);\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n // Gas optimization: this is cheaper than requiring \u0027a\u0027 not being zero, but the\n // benefit is lost if \u0027b\u0027 is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity\u0027s `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c \u003e= a, \"SafeMath: addition overflow\");\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity\u0027s `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b \u003c= a, \"SafeMath: subtraction overflow\");\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity\u0027s `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0) return 0;\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b \u003e 0, \"SafeMath: division by zero\");\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b \u003e 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity\u0027s `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b \u003c= a, errorMessage);\n return a - b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryDiv}.\n *\n * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b \u003e 0, errorMessage);\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b \u003e 0, errorMessage);\n return a % b;\n }\n}\n"},"StakingCenterHaVa.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\npragma abicoder v2;\n\nimport {SafeMath} from \"./SafeMath.sol\";\nimport {EnumerableSet} from \"./EnumerableSet.sol\";\nimport {IERC20} from \"./IERC20.sol\";\nimport {OwnableUpgradeable} from \"./OwnableUpgradeable.sol\";\nimport {TransferHelper} from \"./TransferHelper.sol\";\n\nimport {Powered} from \"./Powered.sol\";\nimport {IUniversalVaultB} from \"./VaultB.sol\";\nimport {IRewardPool} from \"./RewardPool.sol\";\nimport {IFactory} from \"./IFactory.sol\";\nimport {IVaultFactory} from \"./IVaultFactory.sol\";\nimport {IInstanceRegistry} from \"./InstanceRegistry.sol\";\n\ninterface IRageQuit {\n function rageQuit() external;\n}\n\ninterface IStakingCenterHaVa {\n event StakingCenterCreated(address rewardPool, address powerSwitch);\n event StakingCenterFunded(uint256 amount, uint256 duration);\n event BonusTokenRegistered(address token);\n event VaultFactoryRegistered(address factory);\n\n event Staked(address vault, uint256 amount);\n event Unstaked(address vault, uint256 amount);\n event RewardClaimed(address vault, address token, uint256 amount);\n\n struct StakingCenterData {\n address stakingToken;\n address rewardToken;\n address rewardPool;\n RewardScaling rewardScaling;\n uint256 rewardSharesOutstanding;\n uint256 totalStake;\n uint256 totalStakeUnits;\n uint256 lastUpdate;\n RewardSchedule[] rewardSchedules;\n }\n\n struct RewardSchedule {\n uint256 duration;\n uint256 start;\n uint256 shares;\n }\n\n struct VaultData {\n address owner;\n uint256 totalStake;\n StakeData[] stakes;\n }\n\n struct StakeData {\n uint256 amount;\n uint256 timestamp;\n }\n\n struct RewardScaling {\n uint256 floor;\n uint256 ceiling;\n uint256 time;\n }\n\n struct RewardOutput {\n uint256 lastStakeAmount;\n uint256 newStakesCount;\n uint256 reward;\n uint256 newTotalStakeUnits;\n }\n\n function stake(address vault, uint256 amount, bytes calldata permission) external;\n\n function unstakeAndClaim(address vault, uint256 amount, bytes calldata permission) external;\n\n function getStakingCenterData() external view returns (StakingCenterData memory stakingCenter);\n\n function getCurrentUnlockedRewards() external view returns (uint256 unlockedRewards);\n \n function getFutureUnlockedRewards(uint256 timestamp) external view returns (uint256 unlockedRewards);\n\n function getBonusTokenSetLength() external view returns (uint256 length);\n\n function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);\n\n function isValidAddress(address target) external view returns (bool validity);\n\n function getCurrentTotalStakeUnits() external view returns (uint256 totalStakeUnits);\n\n function getFutureTotalStakeUnits(uint256 timestamp) external view returns (uint256 totalStakeUnits);\n\n function getVaultData(address vault) external view returns (VaultData memory vaultData);\n\n function getCurrentVaultReward(address vault) external view returns (uint256 reward);\n\n function getFutureVaultReward(address vault, uint256 timestamp) external view returns (uint256 reward);\n\n function getCurrentStakeReward(address vault, uint256 stakeAmount) external view returns (uint256 reward);\n\n function getFutureStakeReward(address vault, uint256 stakeAmount, uint256 timestamp) external view returns (uint256 reward);\n\n function getCurrentVaultStakeUnits(address vault) external view returns (uint256 stakeUnits);\n\n function getFutureVaultStakeUnits(address vault, uint256 timestamp) external view returns (uint256 stakeUnits);\n\n function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp) external pure returns (uint256 totalStakeUnits);\n\n function calculateStakeUnits(uint256 amount, uint256 start, uint256 end) external pure returns (uint256 stakeUnits);\n\n function calculateRewardFromStakes(StakeData[] memory stakes, uint256 unstakeAmount, uint256 unlockedRewards,\n uint256 totalStakeUnits, uint256 timestamp, RewardScaling memory rewardScaling) external pure returns (RewardOutput memory out);\n\n function calculateReward(uint256 unlockedRewards, uint256 stakeAmount, uint256 stakeDuration,\n uint256 totalStakeUnits, RewardScaling memory rewardScaling) external pure returns (uint256 reward);\n\n function calculateUnlockedRewards(RewardSchedule[] memory rewardSchedules, uint256 rewardBalance,\n uint256 sharesOutstanding, uint256 timestamp) external pure returns (uint256 unlockedRewards);\n}\n\ncontract StakingCenterHaVa is IStakingCenterHaVa, Powered, OwnableUpgradeable {\n using SafeMath for uint256;\n using EnumerableSet for EnumerableSet.AddressSet;\n \n uint256 public constant MAX_STAKES_PER_VAULT = 30;\n uint256 public constant MAX_REWARD_TOKENS = 50;\n uint256 public constant BASE_SHARES_PER_WEI = 1000000;\n\n StakingCenterData private _stakingCenter;\n mapping(address =\u003e VaultData) private _vaults;\n mapping(address =\u003e uint256) private _rewardsEarned;\n EnumerableSet.AddressSet private _bonusTokenSet;\n address private _vaultFactory;\n\n function initializeLock() external initializer {}\n\n function initialize(\n address ownerAddress,\n address rewardPoolFactory,\n address powerSwitchFactory,\n address vaultFactory,\n address stakingToken,\n address rewardToken,\n RewardScaling calldata rewardScaling\n ) external initializer {\n // the scaling floor must be smaller than ceiling\n require(rewardScaling.floor \u003c= rewardScaling.ceiling, \"StakingCenter: floor above ceiling\");\n require(rewardScaling.floor \u003e 0, \"StakingCenter: scaling floor must be greater than 0\");\n require(rewardScaling.ceiling \u003e 0, \"StakingCenter: scaling ceiling must be greater than 0\");\n\n // setting rewardScalingTime to 0 would cause divide by zero error\n // to disable reward scaling, use rewardScalingFloor == rewardScalingCeiling\n require(rewardScaling.time != 0, \"StakingCenter: scaling time cannot be zero\");\n\n // deploy power switch\n address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(ownerAddress));\n\n // deploy reward pool\n address rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));\n\n // set internal configs\n OwnableUpgradeable.__Ownable_init();\n OwnableUpgradeable.transferOwnership(ownerAddress);\n Powered._setPowerSwitch(powerSwitch);\n\n // commit to storage\n _stakingCenter.stakingToken = stakingToken;\n _stakingCenter.rewardToken = rewardToken;\n _stakingCenter.rewardPool = rewardPool;\n _stakingCenter.rewardScaling = rewardScaling;\n\n _vaultFactory = vaultFactory;\n\n // emit event\n emit StakingCenterCreated(rewardPool, powerSwitch);\n }\n\n function getBonusTokenSetLength() external view override returns (uint256 length) {\n return _bonusTokenSet.length();\n }\n\n function getBonusTokenAtIndex(uint256 index) external view override returns (address bonusToken) {\n return _bonusTokenSet.at(index);\n }\n\n function isValidAddress(address target) public view override returns (bool validity) {\n // sanity check target for potential input errors\n return\n target != address(this) \u0026\u0026\n target != address(0) \u0026\u0026\n target != _stakingCenter.stakingToken \u0026\u0026\n target != _stakingCenter.rewardToken \u0026\u0026\n target != _stakingCenter.rewardPool \u0026\u0026\n !_bonusTokenSet.contains(target);\n }\n\n function getStakingCenterData() external view override returns (StakingCenterData memory stakingCenter) {\n return _stakingCenter;\n }\n\n function getCurrentUnlockedRewards() public view override returns (uint256 unlockedRewards) {\n // calculate reward available based on state\n return getFutureUnlockedRewards(block.timestamp);\n }\n\n function getFutureUnlockedRewards(uint256 timestamp) public view override returns (uint256 unlockedRewards) {\n // get reward amount remaining\n uint256 remainingRewards = IERC20(_stakingCenter.rewardToken).balanceOf(_stakingCenter.rewardPool);\n // calculate reward available based on state\n unlockedRewards = calculateUnlockedRewards(\n _stakingCenter.rewardSchedules,\n remainingRewards,\n _stakingCenter.rewardSharesOutstanding,\n timestamp\n );\n // explicit return\n return unlockedRewards;\n }\n\n function getCurrentTotalStakeUnits() public view override returns (uint256 totalStakeUnits) {\n // calculate new stake units\n return getFutureTotalStakeUnits(block.timestamp);\n }\n\n function getFutureTotalStakeUnits(uint256 timestamp) public view override returns (uint256 totalStakeUnits) {\n // return early if no change\n if (timestamp == _stakingCenter.lastUpdate) return _stakingCenter.totalStakeUnits;\n // calculate new stake units\n uint256 newStakeUnits = calculateStakeUnits(_stakingCenter.totalStake, _stakingCenter.lastUpdate, timestamp);\n // add to cached total\n totalStakeUnits = _stakingCenter.totalStakeUnits.add(newStakeUnits);\n // explicit return\n return totalStakeUnits;\n }\n\n function getVaultData(address vault) external view override returns (VaultData memory vaultData) {\n return _vaults[vault];\n }\n\n function getCurrentVaultReward(address vault) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n _vaults[vault]\n .totalStake,\n getCurrentUnlockedRewards(),\n getCurrentTotalStakeUnits(),\n block\n .timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getFutureVaultReward(address vault, uint256 timestamp) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n _vaults[vault]\n .totalStake,\n getFutureUnlockedRewards(timestamp),\n getFutureTotalStakeUnits(timestamp),\n timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getCurrentStakeReward(address vault, uint256 stakeAmount) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n stakeAmount,\n getCurrentUnlockedRewards(),\n getCurrentTotalStakeUnits(),\n block\n .timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getFutureStakeReward(\n address vault,\n uint256 stakeAmount,\n uint256 timestamp\n ) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n stakeAmount,\n getFutureUnlockedRewards(timestamp),\n getFutureTotalStakeUnits(timestamp),\n timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getCurrentVaultStakeUnits(address vault) public view override returns (uint256 stakeUnits) {\n // calculate stake units\n return getFutureVaultStakeUnits(vault, block.timestamp);\n }\n\n function getFutureVaultStakeUnits(address vault, uint256 timestamp)\n public\n view\n override\n returns (uint256 stakeUnits)\n {\n // calculate stake units\n return calculateTotalStakeUnits(_vaults[vault].stakes, timestamp);\n }\n\n function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)\n public\n pure\n override\n returns (uint256 totalStakeUnits)\n {\n for (uint256 index; index \u003c stakes.length; index++) {\n // reference stake\n StakeData memory stakeData = stakes[index];\n // calculate stake units\n uint256 stakeUnits = calculateStakeUnits(stakeData.amount, stakeData.timestamp, timestamp);\n // add to running total\n totalStakeUnits = totalStakeUnits.add(stakeUnits);\n }\n }\n\n function calculateStakeUnits(\n uint256 amount,\n uint256 start,\n uint256 end\n ) public pure override returns (uint256 stakeUnits) {\n // calculate duration\n uint256 duration = end.sub(start);\n // calculate stake units\n stakeUnits = duration.mul(amount);\n // explicit return\n return stakeUnits;\n }\n\n function fundStakingCenter(uint256 amount, uint256 duration) external onlyOwner onlyOnline {\n // validate duration\n require(duration != 0, \"StakingCenter: invalid duration\");\n\n // create new reward shares\n // if existing rewards on this StakingCenter\n // mint new shares proportional to % change in rewards remaining\n // newShares = remainingShares * newReward / remainingRewards\n // else\n // mint new shares with BASE_SHARES_PER_WEI initial conversion rate\n // store as fixed point number with same of decimals as reward token\n uint256 newRewardShares;\n if (_stakingCenter.rewardSharesOutstanding \u003e 0) {\n uint256 remainingRewards = IERC20(_stakingCenter.rewardToken).balanceOf(_stakingCenter.rewardPool);\n newRewardShares = _stakingCenter.rewardSharesOutstanding.mul(amount).div(remainingRewards);\n } else {\n newRewardShares = amount.mul(BASE_SHARES_PER_WEI);\n }\n\n // add reward shares to total\n _stakingCenter.rewardSharesOutstanding = _stakingCenter.rewardSharesOutstanding.add(newRewardShares);\n\n // store new reward schedule\n _stakingCenter.rewardSchedules.push(RewardSchedule(duration, block.timestamp, newRewardShares));\n\n // transfer reward tokens to reward pool\n TransferHelper.safeTransfer(_stakingCenter.rewardToken, _stakingCenter.rewardPool, amount);\n\n // emit event\n emit StakingCenterFunded(amount, duration);\n }\n\n function registerVaultFactory(address factory) external onlyOwner notShutdown {\n // add factory to set\n require(isValidAddress(factory), \"StakingCenter: vault factory already registered\");\n\n _vaultFactory = factory;\n\n // emit event\n emit VaultFactoryRegistered(factory);\n }\n\n function registerBonusToken(address bonusToken) external onlyOwner onlyOnline {\n // verify valid bonus token\n require(isValidAddress(bonusToken));\n\n // verify bonus token count\n require(_bonusTokenSet.length() \u003c MAX_REWARD_TOKENS, \"StakingCenter: max bonus tokens reached \");\n\n // add token to set\n assert(_bonusTokenSet.add(bonusToken));\n\n // emit event\n emit BonusTokenRegistered(bonusToken);\n }\n\n function calculateRewardFromStakes(\n StakeData[] memory stakes,\n uint256 unstakeAmount,\n uint256 unlockedRewards,\n uint256 totalStakeUnits,\n uint256 timestamp,\n RewardScaling memory rewardScaling\n ) public pure override returns (RewardOutput memory out) {\n uint256 stakesToDrop = 0;\n while (unstakeAmount \u003e 0) {\n // fetch vault stake storage reference\n StakeData memory lastStake = stakes[stakes.length.sub(stakesToDrop).sub(1)];\n\n // calculate stake duration\n uint256 stakeDuration = timestamp.sub(lastStake.timestamp);\n\n uint256 currentAmount;\n if (lastStake.amount \u003e unstakeAmount) {\n // set current amount to remaining unstake amount\n currentAmount = unstakeAmount;\n // amount of last stake is reduced\n out.lastStakeAmount = lastStake.amount.sub(unstakeAmount);\n } else {\n // set current amount to amount of last stake\n currentAmount = lastStake.amount;\n // add to stakes to drop\n stakesToDrop += 1;\n }\n\n // update remaining unstakeAmount\n unstakeAmount = unstakeAmount.sub(currentAmount);\n\n // calculate reward amount\n uint256 currentReward =\n calculateReward(unlockedRewards, currentAmount, stakeDuration, totalStakeUnits, rewardScaling);\n\n // update cumulative reward\n out.reward = out.reward.add(currentReward);\n\n // update cached unlockedRewards\n unlockedRewards = unlockedRewards.sub(currentReward);\n\n // calculate time weighted stake\n uint256 stakeUnits = currentAmount.mul(stakeDuration);\n\n // update cached totalStakeUnits\n totalStakeUnits = totalStakeUnits.sub(stakeUnits);\n }\n\n // explicit return\n return RewardOutput(out.lastStakeAmount, stakes.length.sub(stakesToDrop), out.reward, totalStakeUnits);\n }\n\n function calculateReward(\n uint256 unlockedRewards,\n uint256 stakeAmount,\n uint256 stakeDuration,\n uint256 totalStakeUnits,\n RewardScaling memory rewardScaling\n ) public pure override returns (uint256 reward) {\n // calculate time weighted stake\n uint256 stakeUnits = stakeAmount.mul(stakeDuration);\n\n // calculate base reward\n uint256 baseReward = 0;\n if (totalStakeUnits != 0) {\n // scale reward according to proportional weight\n baseReward = unlockedRewards.mul(stakeUnits).div(totalStakeUnits);\n }\n\n if (stakeDuration \u003e= rewardScaling.time || rewardScaling.floor == rewardScaling.ceiling) {\n // no reward scaling applied\n reward = baseReward;\n } else {\n // calculate minimum reward using scaling floor\n uint256 minReward = baseReward.mul(rewardScaling.floor).div(rewardScaling.ceiling);\n\n // calculate bonus reward with vested portion of scaling factor\n uint256 bonusReward =\n baseReward\n .mul(stakeDuration)\n .mul(rewardScaling.ceiling.sub(rewardScaling.floor))\n .div(rewardScaling.ceiling)\n .div(rewardScaling.time);\n\n // add minimum reward and bonus reward\n reward = minReward.add(bonusReward);\n }\n\n // explicit return\n return reward;\n }\n\n function calculateUnlockedRewards(\n RewardSchedule[] memory rewardSchedules,\n uint256 rewardBalance,\n uint256 sharesOutstanding,\n uint256 timestamp\n ) public pure override returns (uint256 unlockedRewards) {\n // return 0 if no registered schedules\n if (rewardSchedules.length == 0) {\n return 0;\n }\n\n // calculate reward shares locked across all reward schedules\n uint256 sharesLocked;\n for (uint256 index = 0; index \u003c rewardSchedules.length; index++) {\n // fetch reward schedule storage reference\n RewardSchedule memory schedule = rewardSchedules[index];\n\n // caculate amount of shares available on this schedule\n uint256 currentSharesLocked = 0;\n if (timestamp.sub(schedule.start) \u003c schedule.duration) {\n currentSharesLocked = schedule.shares.sub(\n schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration)\n );\n }\n\n // add to running total\n sharesLocked = sharesLocked.add(currentSharesLocked);\n }\n\n // convert shares to reward\n uint256 rewardLocked = sharesLocked.mul(rewardBalance).div(sharesOutstanding);\n\n // calculate amount available\n unlockedRewards = rewardBalance.sub(rewardLocked);\n\n // explicit return\n return unlockedRewards;\n }\n\n function stake(\n address vault,\n uint256 amount,\n bytes calldata permission\n ) external override onlyOnline {\n // verify non-zero amount\n require(amount != 0);\n\n // verify the vault is a valid vault and ONLY one of ours\n require(IInstanceRegistry(_vaultFactory).isInstance(vault), \"StakingCenter: Invalid vault\");\n\n // send tokens to vault\n IERC20(_stakingCenter.stakingToken).transferFrom(msg.sender, vault, amount);\n\n // fetch vault storage reference\n VaultData storage vaultData = _vaults[vault];\n\n // verify stakes boundary not reached\n require(vaultData.stakes.length \u003c MAX_STAKES_PER_VAULT, \"StakingCenter: MAX_STAKES_PER_VAULT reached\");\n\n // update cached sum of stake units across all vaults\n _updateTotalStakeUnits();\n\n // store amount and timestamp\n vaultData.stakes.push(StakeData(amount, block.timestamp));\n\n // update cached total vault and StakingCenter amounts\n vaultData.totalStake = vaultData.totalStake.add(amount);\n _stakingCenter.totalStake = _stakingCenter.totalStake.add(amount);\n\n // call lock on vault\n IUniversalVaultB(vault).lock(_stakingCenter.stakingToken, amount, permission);\n\n // emit event\n vaultData.owner = msg.sender;\n emit Staked(vault, amount);\n }\n\n function unstakeAndClaim(\n address vault,\n uint256 amount,\n bytes calldata permission\n ) external override onlyOnline {\n // verify the vault is a valid vault and ONLY one of ours\n require(IInstanceRegistry(_vaultFactory).isInstance(vault));\n \n // fetch vault storage reference\n VaultData storage vaultData = _vaults[vault];\n require(vaultData.owner == msg.sender, \"incorrect owner\");\n\n // check for sufficient vault stake amount\n require(vaultData.totalStake \u003e= amount);\n\n // check for sufficient StakingCenter stake amount\n // if this check fails, there is a bug in stake accounting\n assert(_stakingCenter.totalStake \u003e= amount);\n\n // update cached sum of stake units across all vaults\n _updateTotalStakeUnits();\n\n // get reward amount remaining\n uint256 remainingRewards = IERC20(_stakingCenter.rewardToken).balanceOf(_stakingCenter.rewardPool);\n\n // calculate vested portion of reward pool\n uint256 unlockedRewards =\n calculateUnlockedRewards(\n _stakingCenter.rewardSchedules,\n remainingRewards,\n _stakingCenter.rewardSharesOutstanding,\n block.timestamp\n );\n\n // calculate vault time weighted reward with scaling\n RewardOutput memory out =\n calculateRewardFromStakes(\n vaultData.stakes,\n (amount == 0 ? vaultData.totalStake : amount),\n unlockedRewards,\n _stakingCenter.totalStakeUnits,\n block.timestamp,\n _stakingCenter.rewardScaling\n );\n\n if (amount != 0) {\n // update stake data in storage\n if (out.newStakesCount == 0) {\n // all stakes have been unstaked\n delete vaultData.stakes;\n } else {\n // some stakes have been completely or partially unstaked\n // delete fully unstaked stakes\n while (vaultData.stakes.length \u003e out.newStakesCount) vaultData.stakes.pop();\n\n // only perform when lastStakeAmount is set\n if (out.lastStakeAmount \u003e 0) {\n // update partially unstaked stake\n vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount;\n }\n }\n\n // update cached stake totals\n vaultData.totalStake = vaultData.totalStake.sub(amount);\n _stakingCenter.totalStake = _stakingCenter.totalStake.sub(amount);\n _stakingCenter.totalStakeUnits = out.newTotalStakeUnits;\n\n // unlock staking tokens from vault\n IUniversalVaultB(vault).unlock(_stakingCenter.stakingToken, amount, true, permission);\n\n // emit event\n emit Unstaked(vault, amount);\n } else {\n for (uint256 index; index \u003c vaultData.stakes.length; index++) {\n // update timestamps\n vaultData.stakes[index].timestamp = block.timestamp;\n }\n }\n\n // only perform on non-zero reward\n if (out.reward \u003e 0) {\n // calculate shares to burn\n // sharesToBurn = sharesOutstanding * reward / remainingRewards\n uint256 sharesToBurn = _stakingCenter.rewardSharesOutstanding.mul(out.reward).div(remainingRewards);\n\n // burn claimed shares\n _stakingCenter.rewardSharesOutstanding = _stakingCenter.rewardSharesOutstanding.sub(sharesToBurn);\n\n // transfer bonus tokens from reward pool to recipient\n if (_bonusTokenSet.length() \u003e 0) {\n for (uint256 index = 0; index \u003c _bonusTokenSet.length(); index++) {\n // fetch bonus token address reference\n address bonusToken = _bonusTokenSet.at(index);\n\n // calculate bonus token amount\n // bonusAmount = bonusRemaining * reward / remainingRewards\n uint256 bonusAmount =\n IERC20(bonusToken).balanceOf(_stakingCenter.rewardPool).mul(out.reward).div(remainingRewards);\n\n // transfer if amount is non-zero\n if (bonusAmount \u003e 0) {\n // transfer bonus token\n IRewardPool(_stakingCenter.rewardPool).sendERC20(bonusToken, vaultData.owner, bonusAmount);\n\n // emit event\n emit RewardClaimed(vault, bonusToken, bonusAmount);\n }\n }\n }\n\n // transfer reward tokens from reward pool to recipient\n IRewardPool(_stakingCenter.rewardPool).sendERC20(_stakingCenter.rewardToken, vaultData.owner, out.reward);\n _rewardsEarned[vault] = _rewardsEarned[vault].add(out.reward);\n\n // emit event\n emit RewardClaimed(vault, _stakingCenter.rewardToken, out.reward);\n }\n }\n\n function _updateTotalStakeUnits() private {\n // update cached totalStakeUnits\n _stakingCenter.totalStakeUnits = getCurrentTotalStakeUnits();\n // update cached lastUpdate\n _stakingCenter.lastUpdate = block.timestamp;\n }\n}\n"},"TransferHelper.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-or-later\n\npragma solidity \u003e=0.6.0;\n\n// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false\nlibrary TransferHelper {\n function safeApprove(\n address token,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027approve(address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::safeApprove: approve failed\u0027\n );\n }\n\n function safeTransfer(\n address token,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027transfer(address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::safeTransfer: transfer failed\u0027\n );\n }\n\n function safeTransferFrom(\n address token,\n address from,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027transferFrom(address,address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::transferFrom: transferFrom failed\u0027\n );\n }\n\n function safeTransferETH(address to, uint256 value) internal {\n (bool success, ) = to.call{value: value}(new bytes(0));\n require(success, \u0027TransferHelper::safeTransferETH: ETH transfer failed\u0027);\n }\n}\n"},"VaultB.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\npragma abicoder v2;\n\nimport {SafeMath} from \"./SafeMath.sol\";\nimport {IERC20} from \"./IERC20.sol\";\nimport {Initializable} from \"./Initializable.sol\";\nimport {EnumerableSet} from \"./EnumerableSet.sol\";\nimport {Address} from \"./Address.sol\";\nimport {TransferHelper} from \"./TransferHelper.sol\";\n\nimport {EIP712} from \"./EIP712.sol\";\nimport {ERC1271} from \"./ERC1271.sol\";\nimport {OwnableERC721} from \"./OwnableERC721.sol\";\nimport {ECDSA} from \"./ECDSA.sol\";\nimport {IRageQuit} from \"./StakingCenterHaVa.sol\";\n\ninterface IERC1271 {\n function isValidSignature(bytes32 _messageHash, bytes memory _signature)\n external\n view\n returns (bytes4 magicValue);\n}\n\ninterface IUniversalVaultB {\n /* user events */\n\n event Locked(address delegate, address token, uint256 amount);\n event Unlocked(address delegate, address token, uint256 amount);\n event RageQuit(address delegate, address token, bool notified, string reason);\n\n /* data types */\n\n struct LockData {\n address delegate;\n address token;\n uint256 balance;\n }\n\n /* initialize function */\n\n function initialize() external;\n\n /* user functions */\n\n function lock(\n address token,\n uint256 amount,\n bytes calldata permission\n ) external;\n\n function unlock(\n address token,\n uint256 amount,\n bool send,\n bytes calldata permission\n ) external;\n\n function rageQuit(address delegate, address token)\n external\n returns (bool notified, string memory error);\n\n function transferERC20(\n address token,\n address to,\n uint256 amount\n ) external;\n\n function transferETH(address to, uint256 amount) external payable;\n\n /* pure functions */\n\n function calculateLockID(address delegate, address token)\n external\n pure\n returns (bytes32 lockID);\n\n /* getter functions */\n\n function getPermissionHash(\n bytes32 eip712TypeHash,\n address delegate,\n address token,\n uint256 amount,\n uint256 nonce\n ) external view returns (bytes32 permissionHash);\n\n function getNonce() external view returns (uint256 nonce);\n\n function owner() external view returns (address ownerAddress);\n\n function getLockSetCount() external view returns (uint256 count);\n\n function getLockAt(uint256 index) external view returns (LockData memory lockData);\n\n function getBalanceDelegated(address token, address delegate)\n external\n view\n returns (uint256 balance);\n\n function getBalanceLocked(address token) external view returns (uint256 balance);\n\n function checkBalances() external view returns (bool validity);\n}\n\n/// @title Vault\n/// @notice Vault for isolated storage of staking tokens\n/// @dev Warning: not compatible with rebasing tokens\ncontract VaultB is\n IUniversalVaultB,\n EIP712(\"UniversalVault\", \"1.0.0\"),\n ERC1271,\n OwnableERC721,\n Initializable\n{\n using SafeMath for uint256;\n using Address for address;\n using Address for address payable;\n using EnumerableSet for EnumerableSet.Bytes32Set;\n\n /* constant */\n\n // Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks\n // the gas requirement cannot be determined at runtime by querying the delegate\n // as it could potentially be manipulated by a malicious delegate who could force\n // the calls to revert.\n // The gas limit could alternatively be set upon vault initialization or creation\n // of a lock, but the gas consumption trade-offs are not favorable.\n // Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide\n // an error code that allows for reliably catching out-of-gas errors on remote calls.\n uint256 public constant RAGEQUIT_GAS = 500000;\n bytes32 public constant LOCK_TYPEHASH =\n keccak256(\"Lock(address delegate,address token,uint256 amount,uint256 nonce)\");\n bytes32 public constant UNLOCK_TYPEHASH =\n keccak256(\"Unlock(address delegate,address token,uint256 amount,uint256 nonce)\");\n\n /* storage */\n\n uint256 private _nonce;\n mapping(bytes32 =\u003e LockData) private _locks;\n EnumerableSet.Bytes32Set private _lockSet;\n\n /* initialization function */\n\n function initializeLock() external initializer {}\n\n function initialize() external override initializer {\n OwnableERC721._setNFT(msg.sender);\n }\n\n /* ether receive */\n\n receive() external payable {}\n\n /* internal overrides */\n\n function _getOwner() internal view override(ERC1271) returns (address ownerAddress) {\n return OwnableERC721.owner();\n }\n\n /* pure functions */\n\n function calculateLockID(address delegate, address token)\n public\n pure\n override\n returns (bytes32 lockID)\n {\n return keccak256(abi.encodePacked(delegate, token));\n }\n\n /* getter functions */\n\n function getPermissionHash(\n bytes32 eip712TypeHash,\n address delegate,\n address token,\n uint256 amount,\n uint256 nonce\n ) public view override returns (bytes32 permissionHash) {\n return\n EIP712._hashTypedDataV4(\n keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce))\n );\n }\n\n function getNonce() external view override returns (uint256 nonce) {\n return _nonce;\n }\n\n function owner()\n public\n view\n override(IUniversalVaultB, OwnableERC721)\n returns (address ownerAddress)\n {\n return OwnableERC721.owner();\n }\n\n function getLockSetCount() external view override returns (uint256 count) {\n return _lockSet.length();\n }\n\n function getLockAt(uint256 index) external view override returns (LockData memory lockData) {\n return _locks[_lockSet.at(index)];\n }\n\n function getBalanceDelegated(address token, address delegate)\n external\n view\n override\n returns (uint256 balance)\n {\n return _locks[calculateLockID(delegate, token)].balance;\n }\n\n function getBalanceLocked(address token) public view override returns (uint256 balance) {\n uint256 count = _lockSet.length();\n for (uint256 index; index \u003c count; index++) {\n LockData storage _lockData = _locks[_lockSet.at(index)];\n if (_lockData.token == token \u0026\u0026 _lockData.balance \u003e balance)\n balance = _lockData.balance;\n }\n return balance;\n }\n\n function checkBalances() external view override returns (bool validity) {\n // iterate over all token locks and validate sufficient balance\n uint256 count = _lockSet.length();\n for (uint256 index; index \u003c count; index++) {\n // fetch storage lock reference\n LockData storage _lockData = _locks[_lockSet.at(index)];\n // if insufficient balance and no∏t shutdown, return false\n if (IERC20(_lockData.token).balanceOf(address(this)) \u003c _lockData.balance) return false;\n }\n // if sufficient balance or shutdown, return true\n return true;\n }\n\n /* user functions */\n\n /// @notice Lock ERC20 tokens in the vault\n /// access control: called by delegate with signed permission from owner\n /// state machine: anytime\n /// state scope:\n /// - insert or update _locks\n /// - increase _nonce\n /// token transfer: none\n /// @param token Address of token being locked\n /// @param amount Amount of tokens being locked\n /// @param permission Permission signature payload\n function lock(\n address token,\n uint256 amount,\n bytes calldata permission\n )\n external\n override\n onlyValidSignature(\n getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce),\n permission\n )\n {\n // get lock id\n bytes32 lockID = calculateLockID(msg.sender, token);\n\n // add lock to storage\n if (_lockSet.contains(lockID)) {\n // if lock already exists, increase amount\n _locks[lockID].balance = _locks[lockID].balance.add(amount);\n } else {\n // if does not exist, create new lock\n // add lock to set\n assert(_lockSet.add(lockID));\n // add lock data to storage\n _locks[lockID] = LockData(msg.sender, token, amount);\n }\n\n // validate sufficient balance\n require(\n IERC20(token).balanceOf(address(this)) \u003e= _locks[lockID].balance,\n \"UniversalVault: insufficient balance\"\n );\n\n // increase nonce\n _nonce += 1;\n\n // emit event\n emit Locked(msg.sender, token, amount);\n }\n\n /// @notice Unlock ERC20 tokens in the vault\n /// access control: called by delegate with signed permission from owner\n /// state machine: after valid lock from delegate\n /// state scope:\n /// - remove or update _locks\n /// - increase _nonce\n /// token transfer: none\n /// @param token Address of token being unlocked\n /// @param amount Amount of tokens being unlocked\n /// @param permission Permission signature payload\n function unlock(\n address token,\n uint256 amount,\n bool send,\n bytes calldata permission\n )\n external\n override\n onlyValidSignature(\n getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce),\n permission\n )\n {\n // get lock id\n bytes32 lockID = calculateLockID(msg.sender, token);\n\n // validate existing lock\n require(_lockSet.contains(lockID), \"UniversalVault: missing lock\");\n\n // update lock data\n if (_locks[lockID].balance \u003e amount) {\n // substract amount from lock balance\n _locks[lockID].balance = _locks[lockID].balance.sub(amount);\n } else {\n // delete lock data\n delete _locks[lockID];\n assert(_lockSet.remove(lockID));\n }\n\n // increase nonce\n _nonce += 1;\n\n // emit event\n emit Unlocked(msg.sender, token, amount);\n\n // send to owner if allowed\n if (send) {\n TransferHelper.safeTransfer(token, _getOwner(), amount);\n }\n }\n\n /// @notice Forcibly cancel delegate lock\n /// @dev This function will attempt to notify the delegate of the rage quit using\n /// a fixed amount of gas.\n /// access control: only owner\n /// state machine: after valid lock from delegate\n /// state scope:\n /// - remove item from _locks\n /// token transfer: none\n /// @param delegate Address of delegate\n /// @param token Address of token being unlocked\n function rageQuit(address delegate, address token)\n external\n override\n onlyOwner\n returns (bool notified, string memory error)\n {\n // get lock id\n bytes32 lockID = calculateLockID(delegate, token);\n\n // validate existing lock\n require(_lockSet.contains(lockID), \"UniversalVault: missing lock\");\n\n // attempt to notify delegate\n if (delegate.isContract()) {\n // check for sufficient gas\n require(gasleft() \u003e= RAGEQUIT_GAS, \"UniversalVault: insufficient gas\");\n\n // attempt rageQuit notification\n try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {\n notified = true;\n } catch Error(string memory res) {\n notified = false;\n error = res;\n } catch (bytes memory) {\n notified = false;\n }\n }\n\n // update lock storage\n assert(_lockSet.remove(lockID));\n delete _locks[lockID];\n\n // emit event\n emit RageQuit(delegate, token, notified, error);\n }\n\n /// @notice Transfer ERC20 tokens out of vault\n /// access control: only owner\n /// state machine: when balance \u003e= max(lock) + amount\n /// state scope: none\n /// token transfer: transfer any token\n /// @param token Address of token being transferred\n /// @param to Address of the recipient\n /// @param amount Amount of tokens to transfer\n function transferERC20(\n address token,\n address to,\n uint256 amount\n ) external override onlyOwner {\n // check for sufficient balance\n require(\n IERC20(token).balanceOf(address(this)) \u003e= getBalanceLocked(token).add(amount),\n \"UniversalVault: insufficient balance\"\n );\n // perform transfer\n TransferHelper.safeTransfer(token, to, amount);\n }\n\n /// @notice Transfer ERC20 tokens out of vault\n /// access control: only owner\n /// state machine: when balance \u003e= amount\n /// state scope: none\n /// token transfer: transfer any token\n /// @param to Address of the recipient\n /// @param amount Amount of ETH to transfer\n function transferETH(address to, uint256 amount) external payable override onlyOwner {\n // perform transfer\n TransferHelper.safeTransferETH(to, amount);\n }\n \n}"}}
File 3 of 3: VaultB
{"Address.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\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 function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size \u003e 0;\n }\n\n /**\n * @dev Replacement for Solidity\u0027s `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 \u003e= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance \u003e= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length \u003e 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"},"AddressUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\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 function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size \u003e 0;\n }\n\n /**\n * @dev Replacement for Solidity\u0027s `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 \u003e= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance \u003e= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length \u003e 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"},"Context.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n"},"ContextUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\nimport \"./Initializable.sol\";\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal initializer {\n __Context_init_unchained();\n }\n\n function __Context_init_unchained() internal initializer {\n }\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n uint256[50] private __gap;\n}\n"},"ECDSA.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n // Check the signature length\n if (signature.length != 65) {\n revert(\"ECDSA: invalid signature length\");\n }\n\n // Divide the signature in r, s and v variables\n bytes32 r;\n bytes32 s;\n uint8 v;\n\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n // solhint-disable-next-line no-inline-assembly\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n\n return recover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (281): 0 \u003c s \u003c secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n require(uint256(s) \u003c= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, \"ECDSA: invalid signature \u0027s\u0027 value\");\n require(v == 27 || v == 28, \"ECDSA: invalid signature \u0027v\u0027 value\");\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n require(signer != address(0), \"ECDSA: invalid signature\");\n\n return signer;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * replicates the behavior of the\n * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]\n * JSON-RPC method.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n }\n}\n"},"EIP712.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/* solhint-disable max-line-length */\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n */\nabstract contract EIP712 {\n /* solhint-disable var-name-mixedcase */\n bytes32 private immutable _HASHED_NAME;\n bytes32 private immutable _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH =\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n );\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n\n constructor(string memory name, string memory version) {\n _HASHED_NAME = keccak256(bytes(name));\n _HASHED_VERSION = keccak256(bytes(version));\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 name,\n bytes32 version\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, name, version, _getChainId(), address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", _domainSeparatorV4(), structHash));\n }\n\n function _getChainId() private view returns (uint256 chainId) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal view virtual returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal view virtual returns (bytes32) {\n return _HASHED_VERSION;\n }\n}"},"EnumerableSet.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping (bytes32 =\u003e uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value\u0027s index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) { // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as \u0027swap and pop\u0027).\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n // so rarely, we still do the swap anyway to avoid the gas cost of adding an \u0027if\u0027 statement.\n\n bytes32 lastvalue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastvalue;\n // Update the index for the moved value\n set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n require(set._values.length \u003e index, \"EnumerableSet: index out of bounds\");\n return set._values[index];\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n}\n"},"ERC1271.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {ECDSA} from \"./ECDSA.sol\";\nimport {Address} from \"./Address.sol\";\n\ninterface IERC1271 {\n function isValidSignature(bytes32 _messageHash, bytes memory _signature)\n external\n view\n returns (bytes4 magicValue);\n}\n\nlibrary SignatureChecker {\n using ECDSA for bytes32;\n\n function isValidSignature(\n address signer,\n bytes32 hash,\n bytes memory signature\n ) internal view returns (bool) {\n if (Address.isContract(signer)) {\n bytes4 selector = IERC1271.isValidSignature.selector;\n (bool success, bytes memory returndata) = signer.staticcall(\n abi.encodeWithSelector(selector, hash, signature)\n );\n return success \u0026\u0026 abi.decode(returndata, (bytes4)) == selector;\n } else {\n return hash.toEthSignedMessageHash().recover(signature) == signer;\n }\n }\n}\n\n/// @title ERC1271\n/// @notice Module for ERC1271 compatibility\nabstract contract ERC1271 is IERC1271 {\n // Valid magic value bytes4(keccak256(\"isValidSignature(bytes32,bytes)\")\n bytes4 internal constant VALID_SIG = IERC1271.isValidSignature.selector;\n // Invalid magic value\n bytes4 internal constant INVALID_SIG = bytes4(0);\n\n modifier onlyValidSignature(\n bytes32 permissionHash,\n bytes memory signature\n ) {\n require(\n isValidSignature(permissionHash, signature) == VALID_SIG,\n \"ERC1271: Invalid signature\"\n );\n _;\n }\n\n function _getOwner() internal view virtual returns (address owner);\n\n function isValidSignature(bytes32 permissionHash, bytes memory signature)\n public\n view\n override\n returns (bytes4)\n {\n return\n SignatureChecker.isValidSignature(\n _getOwner(),\n permissionHash,\n signature\n )\n ? VALID_SIG\n : INVALID_SIG;\n }\n}\n"},"IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.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"},"IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\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\u0027s account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller\u0027s 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\u0027s allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller\u0027s\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"},"IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.2 \u003c0.8.0;\n\nimport \"./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``\u0027s 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`, 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 be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev 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 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 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 /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n}\n"},"IFactory.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\ninterface IFactory {\n function create(bytes calldata args) external returns (address instance);\n\n function create2(bytes calldata args, bytes32 salt) external returns (address instance);\n}"},"Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n\n// solhint-disable-next-line compiler-version\npragma solidity \u003e=0.4.24 \u003c0.8.0;\n\nimport \"./AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since a proxied contract can\u0027t have a constructor, it\u0027s common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n */\nabstract contract Initializable {\n\n /**\n * @dev Indicates that the contract has been initialized.\n */\n bool private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Modifier to protect an initializer function from being invoked twice.\n */\n modifier initializer() {\n require(_initializing || _isConstructor() || !_initialized, \"Initializable: contract is already initialized\");\n\n bool isTopLevelCall = !_initializing;\n if (isTopLevelCall) {\n _initializing = true;\n _initialized = true;\n }\n\n _;\n\n if (isTopLevelCall) {\n _initializing = false;\n }\n }\n\n /// @dev Returns true if and only if the function is running in the constructor\n function _isConstructor() private view returns (bool) {\n return !AddressUpgradeable.isContract(address(this));\n }\n}\n"},"InstanceRegistry.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {EnumerableSet} from \"./EnumerableSet.sol\";\n\ninterface IInstanceRegistry {\n /* events */\n\n event InstanceAdded(address instance);\n event InstanceRemoved(address instance);\n\n /* view functions */\n\n function isInstance(address instance) external view returns (bool validity);\n\n function instanceCount() external view returns (uint256 count);\n\n function instanceAt(uint256 index) external view returns (address instance);\n}\n\n/// @title InstanceRegistry\ncontract InstanceRegistry is IInstanceRegistry {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /* storage */\n\n EnumerableSet.AddressSet private _instanceSet;\n\n /* view functions */\n\n function isInstance(address instance) public view override returns (bool validity) {\n return _instanceSet.contains(instance);\n }\n\n function instanceCount() public view override returns (uint256 count) {\n return _instanceSet.length();\n }\n\n function instanceAt(uint256 index) public view override returns (address instance) {\n return _instanceSet.at(index);\n }\n\n /* admin functions */\n\n function _register(address instance) internal {\n require(_instanceSet.add(instance), \"InstanceRegistry: already registered\");\n emit InstanceAdded(instance);\n }\n}"},"IVaultFactory.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\ninterface IVaultFactory {\n function create() external returns (address vault);\n\n function createFor(address beneficiary) external returns (address vault);\n\n function create2(bytes32 salt) external returns (address vault);\n\n function getOwnerVault(address owner) external view returns (address);\n}"},"Ownable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\nimport \"./Context.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor () internal {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n"},"OwnableERC721.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {IERC721} from \"./IERC721.sol\";\n\n/// @title OwnableERC721\n/// @notice Use ERC721 ownership for access control\ncontract OwnableERC721 {\n address private _nftAddress;\n\n modifier onlyOwner() {\n require(owner() == msg.sender, \"OwnableERC721: caller is not the owner\");\n _;\n }\n\n function _setNFT(address nftAddress) internal {\n _nftAddress = nftAddress;\n }\n\n function nft() public view virtual returns (address nftAddress) {\n return _nftAddress;\n }\n\n function owner() public view virtual returns (address ownerAddress) {\n return IERC721(_nftAddress).ownerOf(uint256(address(this)));\n }\n}"},"OwnableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\nimport \"./ContextUpgradeable.sol\";\nimport \"./Initializable.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal initializer {\n __Context_init_unchained();\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal initializer {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n uint256[49] private __gap;\n}\n"},"Powered.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {IPowerSwitch} from \"./PowerSwitch.sol\";\n\ninterface IPowered {\n function isOnline() external view returns (bool status);\n\n function isOffline() external view returns (bool status);\n\n function isShutdown() external view returns (bool status);\n\n function getPowerSwitch() external view returns (address powerSwitch);\n\n function getPowerController() external view returns (address controller);\n}\n\n/// @title Powered\n/// @notice Helper for calling external PowerSwitch\ncontract Powered is IPowered {\n /* storage */\n\n address private _powerSwitch;\n\n /* modifiers */\n\n modifier onlyOnline() {\n _onlyOnline();\n _;\n }\n\n modifier onlyOffline() {\n _onlyOffline();\n _;\n }\n\n modifier notShutdown() {\n _notShutdown();\n _;\n }\n\n modifier onlyShutdown() {\n _onlyShutdown();\n _;\n }\n\n /* initializer */\n\n function _setPowerSwitch(address powerSwitch) internal {\n _powerSwitch = powerSwitch;\n }\n\n /* getter functions */\n\n function isOnline() public view override returns (bool status) {\n return IPowerSwitch(_powerSwitch).isOnline();\n }\n\n function isOffline() public view override returns (bool status) {\n return IPowerSwitch(_powerSwitch).isOffline();\n }\n\n function isShutdown() public view override returns (bool status) {\n return IPowerSwitch(_powerSwitch).isShutdown();\n }\n\n function getPowerSwitch() public view override returns (address powerSwitch) {\n return _powerSwitch;\n }\n\n function getPowerController() public view override returns (address controller) {\n return IPowerSwitch(_powerSwitch).getPowerController();\n }\n\n /* convenience functions */\n\n function _onlyOnline() private view {\n require(isOnline(), \"Powered: is not online\");\n }\n\n function _onlyOffline() private view {\n require(isOffline(), \"Powered: is not offline\");\n }\n\n function _notShutdown() private view {\n require(!isShutdown(), \"Powered: is shutdown\");\n }\n\n function _onlyShutdown() private view {\n require(isShutdown(), \"Powered: is not shutdown\");\n }\n}"},"PowerSwitch.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {Ownable} from \"./Ownable.sol\";\n\ninterface IPowerSwitch {\n /* admin events */\n\n event PowerOn();\n event PowerOff();\n event EmergencyShutdown();\n\n /* data types */\n\n enum State {Online, Offline, Shutdown}\n\n /* admin functions */\n\n function powerOn() external;\n\n function powerOff() external;\n\n function emergencyShutdown() external;\n\n /* view functions */\n\n function isOnline() external view returns (bool status);\n\n function isOffline() external view returns (bool status);\n\n function isShutdown() external view returns (bool status);\n\n function getStatus() external view returns (State status);\n\n function getPowerController() external view returns (address controller);\n}\n\n/// @title PowerSwitch\n/// @notice Standalone pausing and emergency stop functionality\ncontract PowerSwitch is IPowerSwitch, Ownable {\n /* storage */\n\n IPowerSwitch.State private _status;\n\n /* initializer */\n\n constructor(address owner) {\n // sanity check owner\n require(owner != address(0), \"PowerSwitch: invalid owner\");\n // transfer ownership\n Ownable.transferOwnership(owner);\n }\n\n /* admin functions */\n\n /// @notice Turn Power On\n /// access control: only admin\n /// state machine: only when offline\n /// state scope: only modify _status\n /// token transfer: none\n function powerOn() external override onlyOwner {\n require(_status == IPowerSwitch.State.Offline, \"PowerSwitch: cannot power on\");\n _status = IPowerSwitch.State.Online;\n emit PowerOn();\n }\n\n /// @notice Turn Power Off\n /// access control: only admin\n /// state machine: only when online\n /// state scope: only modify _status\n /// token transfer: none\n function powerOff() external override onlyOwner {\n require(_status == IPowerSwitch.State.Online, \"PowerSwitch: cannot power off\");\n _status = IPowerSwitch.State.Offline;\n emit PowerOff();\n }\n\n /// @notice Shutdown Permanently\n /// access control: only admin\n /// state machine:\n /// - when online or offline\n /// - can only be called once\n /// state scope: only modify _status\n /// token transfer: none\n function emergencyShutdown() external override onlyOwner {\n require(_status != IPowerSwitch.State.Shutdown, \"PowerSwitch: cannot shutdown\");\n _status = IPowerSwitch.State.Shutdown;\n emit EmergencyShutdown();\n }\n\n /* getter functions */\n\n function isOnline() external view override returns (bool status) {\n return _status == State.Online;\n }\n\n function isOffline() external view override returns (bool status) {\n return _status == State.Offline;\n }\n\n function isShutdown() external view override returns (bool status) {\n return _status == State.Shutdown;\n }\n\n function getStatus() external view override returns (IPowerSwitch.State status) {\n return _status;\n }\n\n function getPowerController() external view override returns (address controller) {\n return Ownable.owner();\n }\n}"},"RewardPool.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {Ownable} from \"./Ownable.sol\";\nimport {TransferHelper} from \"./TransferHelper.sol\";\n\nimport {Powered} from \"./Powered.sol\";\n\ninterface IRewardPool {\n function sendERC20(\n address token,\n address to,\n uint256 value\n ) external;\n\n function rescueERC20(address[] calldata tokens, address recipient) external;\n}\n\n/// @title Reward Pool\n/// @notice Vault for isolated storage of reward tokens\ncontract RewardPool is IRewardPool, Powered, Ownable {\n constructor(address powerSwitch) {\n Powered._setPowerSwitch(powerSwitch);\n }\n\n /// @notice Send an ERC20 token\n /// access control: only owner\n /// state machine:\n /// - can be called multiple times\n /// - only online\n /// state scope: none\n /// token transfer: transfer tokens from self to recipient\n /// @param token address The token to send\n /// @param to address The recipient to send to\n /// @param value uint256 Amount of tokens to send\n function sendERC20(\n address token,\n address to,\n uint256 value\n ) external override onlyOwner onlyOnline {\n TransferHelper.safeTransfer(token, to, value);\n }\n\n /// @notice Rescue multiple ERC20 tokens\n /// access control: only power controller\n /// state machine:\n /// - can be called multiple times\n /// - only shutdown\n /// state scope: none\n /// token transfer: transfer tokens from self to recipient\n /// @param tokens address[] The tokens to rescue\n /// @param recipient address The recipient to rescue to\n function rescueERC20(address[] calldata tokens, address recipient) external override onlyShutdown {\n // only callable by controller\n require(msg.sender == Powered.getPowerController(), \"RewardPool: only controller can withdraw after shutdown\");\n\n // assert recipient is defined\n require(recipient != address(0), \"RewardPool: recipient not defined\");\n\n // transfer tokens\n for (uint256 index = 0; index \u003c tokens.length; index++) {\n // get token\n address token = tokens[index];\n // get balance\n uint256 balance = IERC20(token).balanceOf(address(this));\n // transfer token\n TransferHelper.safeTransfer(token, recipient, balance);\n }\n }\n}"},"SafeMath.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/**\n * @dev Wrappers over Solidity\u0027s arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it\u0027s recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n uint256 c = a + b;\n if (c \u003c a) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b \u003e a) return (false, 0);\n return (true, a - b);\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n // Gas optimization: this is cheaper than requiring \u0027a\u0027 not being zero, but the\n // benefit is lost if \u0027b\u0027 is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity\u0027s `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c \u003e= a, \"SafeMath: addition overflow\");\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity\u0027s `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b \u003c= a, \"SafeMath: subtraction overflow\");\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity\u0027s `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0) return 0;\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b \u003e 0, \"SafeMath: division by zero\");\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b \u003e 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity\u0027s `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b \u003c= a, errorMessage);\n return a - b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryDiv}.\n *\n * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b \u003e 0, errorMessage);\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b \u003e 0, errorMessage);\n return a % b;\n }\n}\n"},"StakingCenterHaVa.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\npragma abicoder v2;\n\nimport {SafeMath} from \"./SafeMath.sol\";\nimport {EnumerableSet} from \"./EnumerableSet.sol\";\nimport {IERC20} from \"./IERC20.sol\";\nimport {OwnableUpgradeable} from \"./OwnableUpgradeable.sol\";\nimport {TransferHelper} from \"./TransferHelper.sol\";\n\nimport {Powered} from \"./Powered.sol\";\nimport {IUniversalVaultB} from \"./VaultB.sol\";\nimport {IRewardPool} from \"./RewardPool.sol\";\nimport {IFactory} from \"./IFactory.sol\";\nimport {IVaultFactory} from \"./IVaultFactory.sol\";\nimport {IInstanceRegistry} from \"./InstanceRegistry.sol\";\n\ninterface IRageQuit {\n function rageQuit() external;\n}\n\ninterface IStakingCenterHaVa {\n event StakingCenterCreated(address rewardPool, address powerSwitch);\n event StakingCenterFunded(uint256 amount, uint256 duration);\n event BonusTokenRegistered(address token);\n event VaultFactoryRegistered(address factory);\n\n event Staked(address vault, uint256 amount);\n event Unstaked(address vault, uint256 amount);\n event RewardClaimed(address vault, address token, uint256 amount);\n\n struct StakingCenterData {\n address stakingToken;\n address rewardToken;\n address rewardPool;\n RewardScaling rewardScaling;\n uint256 rewardSharesOutstanding;\n uint256 totalStake;\n uint256 totalStakeUnits;\n uint256 lastUpdate;\n RewardSchedule[] rewardSchedules;\n }\n\n struct RewardSchedule {\n uint256 duration;\n uint256 start;\n uint256 shares;\n }\n\n struct VaultData {\n address owner;\n uint256 totalStake;\n StakeData[] stakes;\n }\n\n struct StakeData {\n uint256 amount;\n uint256 timestamp;\n }\n\n struct RewardScaling {\n uint256 floor;\n uint256 ceiling;\n uint256 time;\n }\n\n struct RewardOutput {\n uint256 lastStakeAmount;\n uint256 newStakesCount;\n uint256 reward;\n uint256 newTotalStakeUnits;\n }\n\n function stake(address vault, uint256 amount, bytes calldata permission) external;\n\n function unstakeAndClaim(address vault, uint256 amount, bytes calldata permission) external;\n\n function getStakingCenterData() external view returns (StakingCenterData memory stakingCenter);\n\n function getCurrentUnlockedRewards() external view returns (uint256 unlockedRewards);\n \n function getFutureUnlockedRewards(uint256 timestamp) external view returns (uint256 unlockedRewards);\n\n function getBonusTokenSetLength() external view returns (uint256 length);\n\n function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);\n\n function isValidAddress(address target) external view returns (bool validity);\n\n function getCurrentTotalStakeUnits() external view returns (uint256 totalStakeUnits);\n\n function getFutureTotalStakeUnits(uint256 timestamp) external view returns (uint256 totalStakeUnits);\n\n function getVaultData(address vault) external view returns (VaultData memory vaultData);\n\n function getCurrentVaultReward(address vault) external view returns (uint256 reward);\n\n function getFutureVaultReward(address vault, uint256 timestamp) external view returns (uint256 reward);\n\n function getCurrentStakeReward(address vault, uint256 stakeAmount) external view returns (uint256 reward);\n\n function getFutureStakeReward(address vault, uint256 stakeAmount, uint256 timestamp) external view returns (uint256 reward);\n\n function getCurrentVaultStakeUnits(address vault) external view returns (uint256 stakeUnits);\n\n function getFutureVaultStakeUnits(address vault, uint256 timestamp) external view returns (uint256 stakeUnits);\n\n function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp) external pure returns (uint256 totalStakeUnits);\n\n function calculateStakeUnits(uint256 amount, uint256 start, uint256 end) external pure returns (uint256 stakeUnits);\n\n function calculateRewardFromStakes(StakeData[] memory stakes, uint256 unstakeAmount, uint256 unlockedRewards,\n uint256 totalStakeUnits, uint256 timestamp, RewardScaling memory rewardScaling) external pure returns (RewardOutput memory out);\n\n function calculateReward(uint256 unlockedRewards, uint256 stakeAmount, uint256 stakeDuration,\n uint256 totalStakeUnits, RewardScaling memory rewardScaling) external pure returns (uint256 reward);\n\n function calculateUnlockedRewards(RewardSchedule[] memory rewardSchedules, uint256 rewardBalance,\n uint256 sharesOutstanding, uint256 timestamp) external pure returns (uint256 unlockedRewards);\n}\n\ncontract StakingCenterHaVa is IStakingCenterHaVa, Powered, OwnableUpgradeable {\n using SafeMath for uint256;\n using EnumerableSet for EnumerableSet.AddressSet;\n \n uint256 public constant MAX_STAKES_PER_VAULT = 30;\n uint256 public constant MAX_REWARD_TOKENS = 50;\n uint256 public constant BASE_SHARES_PER_WEI = 1000000;\n\n StakingCenterData private _stakingCenter;\n mapping(address =\u003e VaultData) private _vaults;\n mapping(address =\u003e uint256) private _rewardsEarned;\n EnumerableSet.AddressSet private _bonusTokenSet;\n address private _vaultFactory;\n\n function initializeLock() external initializer {}\n\n function initialize(\n address ownerAddress,\n address rewardPoolFactory,\n address powerSwitchFactory,\n address vaultFactory,\n address stakingToken,\n address rewardToken,\n RewardScaling calldata rewardScaling\n ) external initializer {\n // the scaling floor must be smaller than ceiling\n require(rewardScaling.floor \u003c= rewardScaling.ceiling, \"StakingCenter: floor above ceiling\");\n require(rewardScaling.floor \u003e 0, \"StakingCenter: scaling floor must be greater than 0\");\n require(rewardScaling.ceiling \u003e 0, \"StakingCenter: scaling ceiling must be greater than 0\");\n\n // setting rewardScalingTime to 0 would cause divide by zero error\n // to disable reward scaling, use rewardScalingFloor == rewardScalingCeiling\n require(rewardScaling.time != 0, \"StakingCenter: scaling time cannot be zero\");\n\n // deploy power switch\n address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(ownerAddress));\n\n // deploy reward pool\n address rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));\n\n // set internal configs\n OwnableUpgradeable.__Ownable_init();\n OwnableUpgradeable.transferOwnership(ownerAddress);\n Powered._setPowerSwitch(powerSwitch);\n\n // commit to storage\n _stakingCenter.stakingToken = stakingToken;\n _stakingCenter.rewardToken = rewardToken;\n _stakingCenter.rewardPool = rewardPool;\n _stakingCenter.rewardScaling = rewardScaling;\n\n _vaultFactory = vaultFactory;\n\n // emit event\n emit StakingCenterCreated(rewardPool, powerSwitch);\n }\n\n function getBonusTokenSetLength() external view override returns (uint256 length) {\n return _bonusTokenSet.length();\n }\n\n function getBonusTokenAtIndex(uint256 index) external view override returns (address bonusToken) {\n return _bonusTokenSet.at(index);\n }\n\n function isValidAddress(address target) public view override returns (bool validity) {\n // sanity check target for potential input errors\n return\n target != address(this) \u0026\u0026\n target != address(0) \u0026\u0026\n target != _stakingCenter.stakingToken \u0026\u0026\n target != _stakingCenter.rewardToken \u0026\u0026\n target != _stakingCenter.rewardPool \u0026\u0026\n !_bonusTokenSet.contains(target);\n }\n\n function getStakingCenterData() external view override returns (StakingCenterData memory stakingCenter) {\n return _stakingCenter;\n }\n\n function getCurrentUnlockedRewards() public view override returns (uint256 unlockedRewards) {\n // calculate reward available based on state\n return getFutureUnlockedRewards(block.timestamp);\n }\n\n function getFutureUnlockedRewards(uint256 timestamp) public view override returns (uint256 unlockedRewards) {\n // get reward amount remaining\n uint256 remainingRewards = IERC20(_stakingCenter.rewardToken).balanceOf(_stakingCenter.rewardPool);\n // calculate reward available based on state\n unlockedRewards = calculateUnlockedRewards(\n _stakingCenter.rewardSchedules,\n remainingRewards,\n _stakingCenter.rewardSharesOutstanding,\n timestamp\n );\n // explicit return\n return unlockedRewards;\n }\n\n function getCurrentTotalStakeUnits() public view override returns (uint256 totalStakeUnits) {\n // calculate new stake units\n return getFutureTotalStakeUnits(block.timestamp);\n }\n\n function getFutureTotalStakeUnits(uint256 timestamp) public view override returns (uint256 totalStakeUnits) {\n // return early if no change\n if (timestamp == _stakingCenter.lastUpdate) return _stakingCenter.totalStakeUnits;\n // calculate new stake units\n uint256 newStakeUnits = calculateStakeUnits(_stakingCenter.totalStake, _stakingCenter.lastUpdate, timestamp);\n // add to cached total\n totalStakeUnits = _stakingCenter.totalStakeUnits.add(newStakeUnits);\n // explicit return\n return totalStakeUnits;\n }\n\n function getVaultData(address vault) external view override returns (VaultData memory vaultData) {\n return _vaults[vault];\n }\n\n function getCurrentVaultReward(address vault) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n _vaults[vault]\n .totalStake,\n getCurrentUnlockedRewards(),\n getCurrentTotalStakeUnits(),\n block\n .timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getFutureVaultReward(address vault, uint256 timestamp) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n _vaults[vault]\n .totalStake,\n getFutureUnlockedRewards(timestamp),\n getFutureTotalStakeUnits(timestamp),\n timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getCurrentStakeReward(address vault, uint256 stakeAmount) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n stakeAmount,\n getCurrentUnlockedRewards(),\n getCurrentTotalStakeUnits(),\n block\n .timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getFutureStakeReward(\n address vault,\n uint256 stakeAmount,\n uint256 timestamp\n ) external view override returns (uint256 reward) {\n // calculate rewards\n return\n calculateRewardFromStakes(\n _vaults[vault]\n .stakes,\n stakeAmount,\n getFutureUnlockedRewards(timestamp),\n getFutureTotalStakeUnits(timestamp),\n timestamp,\n _stakingCenter\n .rewardScaling\n )\n .reward;\n }\n\n function getCurrentVaultStakeUnits(address vault) public view override returns (uint256 stakeUnits) {\n // calculate stake units\n return getFutureVaultStakeUnits(vault, block.timestamp);\n }\n\n function getFutureVaultStakeUnits(address vault, uint256 timestamp)\n public\n view\n override\n returns (uint256 stakeUnits)\n {\n // calculate stake units\n return calculateTotalStakeUnits(_vaults[vault].stakes, timestamp);\n }\n\n function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)\n public\n pure\n override\n returns (uint256 totalStakeUnits)\n {\n for (uint256 index; index \u003c stakes.length; index++) {\n // reference stake\n StakeData memory stakeData = stakes[index];\n // calculate stake units\n uint256 stakeUnits = calculateStakeUnits(stakeData.amount, stakeData.timestamp, timestamp);\n // add to running total\n totalStakeUnits = totalStakeUnits.add(stakeUnits);\n }\n }\n\n function calculateStakeUnits(\n uint256 amount,\n uint256 start,\n uint256 end\n ) public pure override returns (uint256 stakeUnits) {\n // calculate duration\n uint256 duration = end.sub(start);\n // calculate stake units\n stakeUnits = duration.mul(amount);\n // explicit return\n return stakeUnits;\n }\n\n function fundStakingCenter(uint256 amount, uint256 duration) external onlyOwner onlyOnline {\n // validate duration\n require(duration != 0, \"StakingCenter: invalid duration\");\n\n // create new reward shares\n // if existing rewards on this StakingCenter\n // mint new shares proportional to % change in rewards remaining\n // newShares = remainingShares * newReward / remainingRewards\n // else\n // mint new shares with BASE_SHARES_PER_WEI initial conversion rate\n // store as fixed point number with same of decimals as reward token\n uint256 newRewardShares;\n if (_stakingCenter.rewardSharesOutstanding \u003e 0) {\n uint256 remainingRewards = IERC20(_stakingCenter.rewardToken).balanceOf(_stakingCenter.rewardPool);\n newRewardShares = _stakingCenter.rewardSharesOutstanding.mul(amount).div(remainingRewards);\n } else {\n newRewardShares = amount.mul(BASE_SHARES_PER_WEI);\n }\n\n // add reward shares to total\n _stakingCenter.rewardSharesOutstanding = _stakingCenter.rewardSharesOutstanding.add(newRewardShares);\n\n // store new reward schedule\n _stakingCenter.rewardSchedules.push(RewardSchedule(duration, block.timestamp, newRewardShares));\n\n // transfer reward tokens to reward pool\n TransferHelper.safeTransfer(_stakingCenter.rewardToken, _stakingCenter.rewardPool, amount);\n\n // emit event\n emit StakingCenterFunded(amount, duration);\n }\n\n function registerVaultFactory(address factory) external onlyOwner notShutdown {\n // add factory to set\n require(isValidAddress(factory), \"StakingCenter: vault factory already registered\");\n\n _vaultFactory = factory;\n\n // emit event\n emit VaultFactoryRegistered(factory);\n }\n\n function registerBonusToken(address bonusToken) external onlyOwner onlyOnline {\n // verify valid bonus token\n require(isValidAddress(bonusToken));\n\n // verify bonus token count\n require(_bonusTokenSet.length() \u003c MAX_REWARD_TOKENS, \"StakingCenter: max bonus tokens reached \");\n\n // add token to set\n assert(_bonusTokenSet.add(bonusToken));\n\n // emit event\n emit BonusTokenRegistered(bonusToken);\n }\n\n function calculateRewardFromStakes(\n StakeData[] memory stakes,\n uint256 unstakeAmount,\n uint256 unlockedRewards,\n uint256 totalStakeUnits,\n uint256 timestamp,\n RewardScaling memory rewardScaling\n ) public pure override returns (RewardOutput memory out) {\n uint256 stakesToDrop = 0;\n while (unstakeAmount \u003e 0) {\n // fetch vault stake storage reference\n StakeData memory lastStake = stakes[stakes.length.sub(stakesToDrop).sub(1)];\n\n // calculate stake duration\n uint256 stakeDuration = timestamp.sub(lastStake.timestamp);\n\n uint256 currentAmount;\n if (lastStake.amount \u003e unstakeAmount) {\n // set current amount to remaining unstake amount\n currentAmount = unstakeAmount;\n // amount of last stake is reduced\n out.lastStakeAmount = lastStake.amount.sub(unstakeAmount);\n } else {\n // set current amount to amount of last stake\n currentAmount = lastStake.amount;\n // add to stakes to drop\n stakesToDrop += 1;\n }\n\n // update remaining unstakeAmount\n unstakeAmount = unstakeAmount.sub(currentAmount);\n\n // calculate reward amount\n uint256 currentReward =\n calculateReward(unlockedRewards, currentAmount, stakeDuration, totalStakeUnits, rewardScaling);\n\n // update cumulative reward\n out.reward = out.reward.add(currentReward);\n\n // update cached unlockedRewards\n unlockedRewards = unlockedRewards.sub(currentReward);\n\n // calculate time weighted stake\n uint256 stakeUnits = currentAmount.mul(stakeDuration);\n\n // update cached totalStakeUnits\n totalStakeUnits = totalStakeUnits.sub(stakeUnits);\n }\n\n // explicit return\n return RewardOutput(out.lastStakeAmount, stakes.length.sub(stakesToDrop), out.reward, totalStakeUnits);\n }\n\n function calculateReward(\n uint256 unlockedRewards,\n uint256 stakeAmount,\n uint256 stakeDuration,\n uint256 totalStakeUnits,\n RewardScaling memory rewardScaling\n ) public pure override returns (uint256 reward) {\n // calculate time weighted stake\n uint256 stakeUnits = stakeAmount.mul(stakeDuration);\n\n // calculate base reward\n uint256 baseReward = 0;\n if (totalStakeUnits != 0) {\n // scale reward according to proportional weight\n baseReward = unlockedRewards.mul(stakeUnits).div(totalStakeUnits);\n }\n\n if (stakeDuration \u003e= rewardScaling.time || rewardScaling.floor == rewardScaling.ceiling) {\n // no reward scaling applied\n reward = baseReward;\n } else {\n // calculate minimum reward using scaling floor\n uint256 minReward = baseReward.mul(rewardScaling.floor).div(rewardScaling.ceiling);\n\n // calculate bonus reward with vested portion of scaling factor\n uint256 bonusReward =\n baseReward\n .mul(stakeDuration)\n .mul(rewardScaling.ceiling.sub(rewardScaling.floor))\n .div(rewardScaling.ceiling)\n .div(rewardScaling.time);\n\n // add minimum reward and bonus reward\n reward = minReward.add(bonusReward);\n }\n\n // explicit return\n return reward;\n }\n\n function calculateUnlockedRewards(\n RewardSchedule[] memory rewardSchedules,\n uint256 rewardBalance,\n uint256 sharesOutstanding,\n uint256 timestamp\n ) public pure override returns (uint256 unlockedRewards) {\n // return 0 if no registered schedules\n if (rewardSchedules.length == 0) {\n return 0;\n }\n\n // calculate reward shares locked across all reward schedules\n uint256 sharesLocked;\n for (uint256 index = 0; index \u003c rewardSchedules.length; index++) {\n // fetch reward schedule storage reference\n RewardSchedule memory schedule = rewardSchedules[index];\n\n // caculate amount of shares available on this schedule\n uint256 currentSharesLocked = 0;\n if (timestamp.sub(schedule.start) \u003c schedule.duration) {\n currentSharesLocked = schedule.shares.sub(\n schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration)\n );\n }\n\n // add to running total\n sharesLocked = sharesLocked.add(currentSharesLocked);\n }\n\n // convert shares to reward\n uint256 rewardLocked = sharesLocked.mul(rewardBalance).div(sharesOutstanding);\n\n // calculate amount available\n unlockedRewards = rewardBalance.sub(rewardLocked);\n\n // explicit return\n return unlockedRewards;\n }\n\n function stake(\n address vault,\n uint256 amount,\n bytes calldata permission\n ) external override onlyOnline {\n // verify non-zero amount\n require(amount != 0);\n\n // verify the vault is a valid vault and ONLY one of ours\n require(IInstanceRegistry(_vaultFactory).isInstance(vault), \"StakingCenter: Invalid vault\");\n\n // send tokens to vault\n IERC20(_stakingCenter.stakingToken).transferFrom(msg.sender, vault, amount);\n\n // fetch vault storage reference\n VaultData storage vaultData = _vaults[vault];\n\n // verify stakes boundary not reached\n require(vaultData.stakes.length \u003c MAX_STAKES_PER_VAULT, \"StakingCenter: MAX_STAKES_PER_VAULT reached\");\n\n // update cached sum of stake units across all vaults\n _updateTotalStakeUnits();\n\n // store amount and timestamp\n vaultData.stakes.push(StakeData(amount, block.timestamp));\n\n // update cached total vault and StakingCenter amounts\n vaultData.totalStake = vaultData.totalStake.add(amount);\n _stakingCenter.totalStake = _stakingCenter.totalStake.add(amount);\n\n // call lock on vault\n IUniversalVaultB(vault).lock(_stakingCenter.stakingToken, amount, permission);\n\n // emit event\n vaultData.owner = msg.sender;\n emit Staked(vault, amount);\n }\n\n function unstakeAndClaim(\n address vault,\n uint256 amount,\n bytes calldata permission\n ) external override onlyOnline {\n // verify the vault is a valid vault and ONLY one of ours\n require(IInstanceRegistry(_vaultFactory).isInstance(vault));\n \n // fetch vault storage reference\n VaultData storage vaultData = _vaults[vault];\n require(vaultData.owner == msg.sender, \"incorrect owner\");\n\n // check for sufficient vault stake amount\n require(vaultData.totalStake \u003e= amount);\n\n // check for sufficient StakingCenter stake amount\n // if this check fails, there is a bug in stake accounting\n assert(_stakingCenter.totalStake \u003e= amount);\n\n // update cached sum of stake units across all vaults\n _updateTotalStakeUnits();\n\n // get reward amount remaining\n uint256 remainingRewards = IERC20(_stakingCenter.rewardToken).balanceOf(_stakingCenter.rewardPool);\n\n // calculate vested portion of reward pool\n uint256 unlockedRewards =\n calculateUnlockedRewards(\n _stakingCenter.rewardSchedules,\n remainingRewards,\n _stakingCenter.rewardSharesOutstanding,\n block.timestamp\n );\n\n // calculate vault time weighted reward with scaling\n RewardOutput memory out =\n calculateRewardFromStakes(\n vaultData.stakes,\n (amount == 0 ? vaultData.totalStake : amount),\n unlockedRewards,\n _stakingCenter.totalStakeUnits,\n block.timestamp,\n _stakingCenter.rewardScaling\n );\n\n if (amount != 0) {\n // update stake data in storage\n if (out.newStakesCount == 0) {\n // all stakes have been unstaked\n delete vaultData.stakes;\n } else {\n // some stakes have been completely or partially unstaked\n // delete fully unstaked stakes\n while (vaultData.stakes.length \u003e out.newStakesCount) vaultData.stakes.pop();\n\n // only perform when lastStakeAmount is set\n if (out.lastStakeAmount \u003e 0) {\n // update partially unstaked stake\n vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount;\n }\n }\n\n // update cached stake totals\n vaultData.totalStake = vaultData.totalStake.sub(amount);\n _stakingCenter.totalStake = _stakingCenter.totalStake.sub(amount);\n _stakingCenter.totalStakeUnits = out.newTotalStakeUnits;\n\n // unlock staking tokens from vault\n IUniversalVaultB(vault).unlock(_stakingCenter.stakingToken, amount, true, permission);\n\n // emit event\n emit Unstaked(vault, amount);\n } else {\n for (uint256 index; index \u003c vaultData.stakes.length; index++) {\n // update timestamps\n vaultData.stakes[index].timestamp = block.timestamp;\n }\n }\n\n // only perform on non-zero reward\n if (out.reward \u003e 0) {\n // calculate shares to burn\n // sharesToBurn = sharesOutstanding * reward / remainingRewards\n uint256 sharesToBurn = _stakingCenter.rewardSharesOutstanding.mul(out.reward).div(remainingRewards);\n\n // burn claimed shares\n _stakingCenter.rewardSharesOutstanding = _stakingCenter.rewardSharesOutstanding.sub(sharesToBurn);\n\n // transfer bonus tokens from reward pool to recipient\n if (_bonusTokenSet.length() \u003e 0) {\n for (uint256 index = 0; index \u003c _bonusTokenSet.length(); index++) {\n // fetch bonus token address reference\n address bonusToken = _bonusTokenSet.at(index);\n\n // calculate bonus token amount\n // bonusAmount = bonusRemaining * reward / remainingRewards\n uint256 bonusAmount =\n IERC20(bonusToken).balanceOf(_stakingCenter.rewardPool).mul(out.reward).div(remainingRewards);\n\n // transfer if amount is non-zero\n if (bonusAmount \u003e 0) {\n // transfer bonus token\n IRewardPool(_stakingCenter.rewardPool).sendERC20(bonusToken, vaultData.owner, bonusAmount);\n\n // emit event\n emit RewardClaimed(vault, bonusToken, bonusAmount);\n }\n }\n }\n\n // transfer reward tokens from reward pool to recipient\n IRewardPool(_stakingCenter.rewardPool).sendERC20(_stakingCenter.rewardToken, vaultData.owner, out.reward);\n _rewardsEarned[vault] = _rewardsEarned[vault].add(out.reward);\n\n // emit event\n emit RewardClaimed(vault, _stakingCenter.rewardToken, out.reward);\n }\n }\n\n function _updateTotalStakeUnits() private {\n // update cached totalStakeUnits\n _stakingCenter.totalStakeUnits = getCurrentTotalStakeUnits();\n // update cached lastUpdate\n _stakingCenter.lastUpdate = block.timestamp;\n }\n}\n"},"TransferHelper.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-or-later\n\npragma solidity \u003e=0.6.0;\n\n// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false\nlibrary TransferHelper {\n function safeApprove(\n address token,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027approve(address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::safeApprove: approve failed\u0027\n );\n }\n\n function safeTransfer(\n address token,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027transfer(address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::safeTransfer: transfer failed\u0027\n );\n }\n\n function safeTransferFrom(\n address token,\n address from,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027transferFrom(address,address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::transferFrom: transferFrom failed\u0027\n );\n }\n\n function safeTransferETH(address to, uint256 value) internal {\n (bool success, ) = to.call{value: value}(new bytes(0));\n require(success, \u0027TransferHelper::safeTransferETH: ETH transfer failed\u0027);\n }\n}\n"},"VaultB.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.7.6;\npragma abicoder v2;\n\nimport {SafeMath} from \"./SafeMath.sol\";\nimport {IERC20} from \"./IERC20.sol\";\nimport {Initializable} from \"./Initializable.sol\";\nimport {EnumerableSet} from \"./EnumerableSet.sol\";\nimport {Address} from \"./Address.sol\";\nimport {TransferHelper} from \"./TransferHelper.sol\";\n\nimport {EIP712} from \"./EIP712.sol\";\nimport {ERC1271} from \"./ERC1271.sol\";\nimport {OwnableERC721} from \"./OwnableERC721.sol\";\nimport {ECDSA} from \"./ECDSA.sol\";\nimport {IRageQuit} from \"./StakingCenterHaVa.sol\";\n\ninterface IERC1271 {\n function isValidSignature(bytes32 _messageHash, bytes memory _signature)\n external\n view\n returns (bytes4 magicValue);\n}\n\ninterface IUniversalVaultB {\n /* user events */\n\n event Locked(address delegate, address token, uint256 amount);\n event Unlocked(address delegate, address token, uint256 amount);\n event RageQuit(address delegate, address token, bool notified, string reason);\n\n /* data types */\n\n struct LockData {\n address delegate;\n address token;\n uint256 balance;\n }\n\n /* initialize function */\n\n function initialize() external;\n\n /* user functions */\n\n function lock(\n address token,\n uint256 amount,\n bytes calldata permission\n ) external;\n\n function unlock(\n address token,\n uint256 amount,\n bool send,\n bytes calldata permission\n ) external;\n\n function rageQuit(address delegate, address token)\n external\n returns (bool notified, string memory error);\n\n function transferERC20(\n address token,\n address to,\n uint256 amount\n ) external;\n\n function transferETH(address to, uint256 amount) external payable;\n\n /* pure functions */\n\n function calculateLockID(address delegate, address token)\n external\n pure\n returns (bytes32 lockID);\n\n /* getter functions */\n\n function getPermissionHash(\n bytes32 eip712TypeHash,\n address delegate,\n address token,\n uint256 amount,\n uint256 nonce\n ) external view returns (bytes32 permissionHash);\n\n function getNonce() external view returns (uint256 nonce);\n\n function owner() external view returns (address ownerAddress);\n\n function getLockSetCount() external view returns (uint256 count);\n\n function getLockAt(uint256 index) external view returns (LockData memory lockData);\n\n function getBalanceDelegated(address token, address delegate)\n external\n view\n returns (uint256 balance);\n\n function getBalanceLocked(address token) external view returns (uint256 balance);\n\n function checkBalances() external view returns (bool validity);\n}\n\n/// @title Vault\n/// @notice Vault for isolated storage of staking tokens\n/// @dev Warning: not compatible with rebasing tokens\ncontract VaultB is\n IUniversalVaultB,\n EIP712(\"UniversalVault\", \"1.0.0\"),\n ERC1271,\n OwnableERC721,\n Initializable\n{\n using SafeMath for uint256;\n using Address for address;\n using Address for address payable;\n using EnumerableSet for EnumerableSet.Bytes32Set;\n\n /* constant */\n\n // Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks\n // the gas requirement cannot be determined at runtime by querying the delegate\n // as it could potentially be manipulated by a malicious delegate who could force\n // the calls to revert.\n // The gas limit could alternatively be set upon vault initialization or creation\n // of a lock, but the gas consumption trade-offs are not favorable.\n // Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide\n // an error code that allows for reliably catching out-of-gas errors on remote calls.\n uint256 public constant RAGEQUIT_GAS = 500000;\n bytes32 public constant LOCK_TYPEHASH =\n keccak256(\"Lock(address delegate,address token,uint256 amount,uint256 nonce)\");\n bytes32 public constant UNLOCK_TYPEHASH =\n keccak256(\"Unlock(address delegate,address token,uint256 amount,uint256 nonce)\");\n\n /* storage */\n\n uint256 private _nonce;\n mapping(bytes32 =\u003e LockData) private _locks;\n EnumerableSet.Bytes32Set private _lockSet;\n\n /* initialization function */\n\n function initializeLock() external initializer {}\n\n function initialize() external override initializer {\n OwnableERC721._setNFT(msg.sender);\n }\n\n /* ether receive */\n\n receive() external payable {}\n\n /* internal overrides */\n\n function _getOwner() internal view override(ERC1271) returns (address ownerAddress) {\n return OwnableERC721.owner();\n }\n\n /* pure functions */\n\n function calculateLockID(address delegate, address token)\n public\n pure\n override\n returns (bytes32 lockID)\n {\n return keccak256(abi.encodePacked(delegate, token));\n }\n\n /* getter functions */\n\n function getPermissionHash(\n bytes32 eip712TypeHash,\n address delegate,\n address token,\n uint256 amount,\n uint256 nonce\n ) public view override returns (bytes32 permissionHash) {\n return\n EIP712._hashTypedDataV4(\n keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce))\n );\n }\n\n function getNonce() external view override returns (uint256 nonce) {\n return _nonce;\n }\n\n function owner()\n public\n view\n override(IUniversalVaultB, OwnableERC721)\n returns (address ownerAddress)\n {\n return OwnableERC721.owner();\n }\n\n function getLockSetCount() external view override returns (uint256 count) {\n return _lockSet.length();\n }\n\n function getLockAt(uint256 index) external view override returns (LockData memory lockData) {\n return _locks[_lockSet.at(index)];\n }\n\n function getBalanceDelegated(address token, address delegate)\n external\n view\n override\n returns (uint256 balance)\n {\n return _locks[calculateLockID(delegate, token)].balance;\n }\n\n function getBalanceLocked(address token) public view override returns (uint256 balance) {\n uint256 count = _lockSet.length();\n for (uint256 index; index \u003c count; index++) {\n LockData storage _lockData = _locks[_lockSet.at(index)];\n if (_lockData.token == token \u0026\u0026 _lockData.balance \u003e balance)\n balance = _lockData.balance;\n }\n return balance;\n }\n\n function checkBalances() external view override returns (bool validity) {\n // iterate over all token locks and validate sufficient balance\n uint256 count = _lockSet.length();\n for (uint256 index; index \u003c count; index++) {\n // fetch storage lock reference\n LockData storage _lockData = _locks[_lockSet.at(index)];\n // if insufficient balance and no∏t shutdown, return false\n if (IERC20(_lockData.token).balanceOf(address(this)) \u003c _lockData.balance) return false;\n }\n // if sufficient balance or shutdown, return true\n return true;\n }\n\n /* user functions */\n\n /// @notice Lock ERC20 tokens in the vault\n /// access control: called by delegate with signed permission from owner\n /// state machine: anytime\n /// state scope:\n /// - insert or update _locks\n /// - increase _nonce\n /// token transfer: none\n /// @param token Address of token being locked\n /// @param amount Amount of tokens being locked\n /// @param permission Permission signature payload\n function lock(\n address token,\n uint256 amount,\n bytes calldata permission\n )\n external\n override\n onlyValidSignature(\n getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce),\n permission\n )\n {\n // get lock id\n bytes32 lockID = calculateLockID(msg.sender, token);\n\n // add lock to storage\n if (_lockSet.contains(lockID)) {\n // if lock already exists, increase amount\n _locks[lockID].balance = _locks[lockID].balance.add(amount);\n } else {\n // if does not exist, create new lock\n // add lock to set\n assert(_lockSet.add(lockID));\n // add lock data to storage\n _locks[lockID] = LockData(msg.sender, token, amount);\n }\n\n // validate sufficient balance\n require(\n IERC20(token).balanceOf(address(this)) \u003e= _locks[lockID].balance,\n \"UniversalVault: insufficient balance\"\n );\n\n // increase nonce\n _nonce += 1;\n\n // emit event\n emit Locked(msg.sender, token, amount);\n }\n\n /// @notice Unlock ERC20 tokens in the vault\n /// access control: called by delegate with signed permission from owner\n /// state machine: after valid lock from delegate\n /// state scope:\n /// - remove or update _locks\n /// - increase _nonce\n /// token transfer: none\n /// @param token Address of token being unlocked\n /// @param amount Amount of tokens being unlocked\n /// @param permission Permission signature payload\n function unlock(\n address token,\n uint256 amount,\n bool send,\n bytes calldata permission\n )\n external\n override\n onlyValidSignature(\n getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce),\n permission\n )\n {\n // get lock id\n bytes32 lockID = calculateLockID(msg.sender, token);\n\n // validate existing lock\n require(_lockSet.contains(lockID), \"UniversalVault: missing lock\");\n\n // update lock data\n if (_locks[lockID].balance \u003e amount) {\n // substract amount from lock balance\n _locks[lockID].balance = _locks[lockID].balance.sub(amount);\n } else {\n // delete lock data\n delete _locks[lockID];\n assert(_lockSet.remove(lockID));\n }\n\n // increase nonce\n _nonce += 1;\n\n // emit event\n emit Unlocked(msg.sender, token, amount);\n\n // send to owner if allowed\n if (send) {\n TransferHelper.safeTransfer(token, _getOwner(), amount);\n }\n }\n\n /// @notice Forcibly cancel delegate lock\n /// @dev This function will attempt to notify the delegate of the rage quit using\n /// a fixed amount of gas.\n /// access control: only owner\n /// state machine: after valid lock from delegate\n /// state scope:\n /// - remove item from _locks\n /// token transfer: none\n /// @param delegate Address of delegate\n /// @param token Address of token being unlocked\n function rageQuit(address delegate, address token)\n external\n override\n onlyOwner\n returns (bool notified, string memory error)\n {\n // get lock id\n bytes32 lockID = calculateLockID(delegate, token);\n\n // validate existing lock\n require(_lockSet.contains(lockID), \"UniversalVault: missing lock\");\n\n // attempt to notify delegate\n if (delegate.isContract()) {\n // check for sufficient gas\n require(gasleft() \u003e= RAGEQUIT_GAS, \"UniversalVault: insufficient gas\");\n\n // attempt rageQuit notification\n try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {\n notified = true;\n } catch Error(string memory res) {\n notified = false;\n error = res;\n } catch (bytes memory) {\n notified = false;\n }\n }\n\n // update lock storage\n assert(_lockSet.remove(lockID));\n delete _locks[lockID];\n\n // emit event\n emit RageQuit(delegate, token, notified, error);\n }\n\n /// @notice Transfer ERC20 tokens out of vault\n /// access control: only owner\n /// state machine: when balance \u003e= max(lock) + amount\n /// state scope: none\n /// token transfer: transfer any token\n /// @param token Address of token being transferred\n /// @param to Address of the recipient\n /// @param amount Amount of tokens to transfer\n function transferERC20(\n address token,\n address to,\n uint256 amount\n ) external override onlyOwner {\n // check for sufficient balance\n require(\n IERC20(token).balanceOf(address(this)) \u003e= getBalanceLocked(token).add(amount),\n \"UniversalVault: insufficient balance\"\n );\n // perform transfer\n TransferHelper.safeTransfer(token, to, amount);\n }\n\n /// @notice Transfer ERC20 tokens out of vault\n /// access control: only owner\n /// state machine: when balance \u003e= amount\n /// state scope: none\n /// token transfer: transfer any token\n /// @param to Address of the recipient\n /// @param amount Amount of ETH to transfer\n function transferETH(address to, uint256 amount) external payable override onlyOwner {\n // perform transfer\n TransferHelper.safeTransferETH(to, amount);\n }\n \n}"}}