{ "language": "Solidity", "sources": { "contracts/fund/FundAccount.sol": { "content": "// SPDX-License-Identifier: MIT\n// Decontracts Protocol. @2022\npragma solidity >=0.8.14;\n\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport {SafeERC20, IERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\n\nimport {IFundAccount, Nav, LpDetail, LpAction, FundCreateParams} from \"../interfaces/fund/IFundAccount.sol\";\nimport {IFundManager} from \"../interfaces/fund/IFundManager.sol\";\nimport {IFundFilter} from \"../interfaces/fund/IFundFilter.sol\";\nimport {Errors} from \"../libraries/Errors.sol\";\nimport {IWETH9} from \"../interfaces/external/IWETH9.sol\";\n\ncontract FundAccount is IFundAccount, Initializable {\n using SafeERC20 for IERC20;\n using Address for address;\n\n // Contract version\n uint256 public constant version = 1;\n\n // FundManager\n address public manager;\n address public weth9;\n IFundFilter public fundFilter;\n\n // Block time when the account was opened\n uint256 public override since;\n\n // Block time when the account was closed\n uint256 public override closed;\n\n // Fund create params\n string public override name;\n address public override gp;\n uint256 public override managementFee;\n uint256 public override carriedInterest;\n address public override underlyingToken;\n address public initiator;\n uint256 public initiatorAmount;\n address public recipient;\n uint256 public recipientMinAmount;\n address[] private _allowedProtocols;\n address[] private _allowedTokens;\n mapping(address => bool) public override isProtocolAllowed;\n mapping(address => bool) public override isTokenAllowed;\n\n // Fund runtime data\n uint256 public override totalUnit;\n uint256 public override totalCarryInterestAmount;\n uint256 public override lastUpdateManagementFeeAmount;\n uint256 private lastUpdateManagementFeeTime;\n address[] private _lps;\n mapping(address => LpDetail) private _lpDetails;\n\n receive() external payable {}\n\n //////////////////////////////////////////////////////////////////////////////////////////////\n /////////////////////////////////////// VIEW FUNCTIONS ///////////////////////////////////////\n //////////////////////////////////////////////////////////////////////////////////////////////\n\n function ethBalance() external view override returns (uint256) {\n return address(this).balance;\n }\n\n function totalManagementFeeAmount() external view override returns (uint256) {\n return lastUpdateManagementFeeAmount + _calcManagementFeeFromLastUpdate(_calcTotalValue());\n }\n\n function allowedProtocols() external view override returns (address[] memory) {\n return _allowedProtocols;\n }\n\n function allowedTokens() external view override returns (address[] memory) {\n return _allowedTokens;\n }\n\n function lpList() external view override returns (address[] memory) {\n return _lps;\n }\n\n function lpDetailInfo(address addr) external view override returns (LpDetail memory) {\n return _lpDetails[addr];\n }\n\n //////////////////////////////////////////////////////////////////////////////////////////////\n ///////////////////////////////////// FUND MANAGER ONLY //////////////////////////////////////\n //////////////////////////////////////////////////////////////////////////////////////////////\n\n // Caller restricted for manager only\n modifier onlyManager() {\n require(msg.sender == manager, Errors.NotManager);\n _;\n }\n\n function initialize(FundCreateParams memory params) external override initializer {\n manager = msg.sender;\n weth9 = IFundManager(manager).weth9();\n fundFilter = IFundManager(manager).fundFilter();\n since = block.timestamp;\n\n name = params.name;\n gp = params.gp;\n managementFee = params.managementFee;\n carriedInterest = params.carriedInterest;\n underlyingToken = params.underlyingToken;\n initiator = params.initiator;\n initiatorAmount = params.initiatorAmount;\n recipient = params.recipient;\n recipientMinAmount = params.recipientMinAmount;\n _allowedProtocols = params.allowedProtocols;\n _allowedTokens = params.allowedTokens;\n\n for (uint256 i = 0; i < _allowedProtocols.length; i++) {\n isProtocolAllowed[_allowedProtocols[i]] = true;\n }\n for (uint256 i = 0; i < _allowedTokens.length; i++) {\n isTokenAllowed[_allowedTokens[i]] = true;\n }\n }\n\n /// @dev Approve token for 3rd party contract\n /// @param token ERC20 token for allowance\n /// @param spender 3rd party contract address\n /// @param amount Allowance amount\n function approveToken(\n address token,\n address spender,\n uint256 amount\n ) external override onlyManager {\n IERC20(token).safeApprove(spender, 0);\n IERC20(token).safeApprove(spender, amount);\n }\n\n /// @dev Transfers tokens from account to provided address\n /// @param token ERC20 token address which should be transferred from this account\n /// @param to Address of recipient\n /// @param amount Amount to be transferred\n function safeTransfer(\n address token,\n address to,\n uint256 amount\n ) external override onlyManager {\n IERC20(token).safeTransfer(to, amount);\n }\n\n /// @dev setApprovalForAll of token in the account\n /// @param token ERC721 token address\n /// @param spender Approval to address\n /// @param approved approve all or not\n function setTokenApprovalForAll(\n address token,\n address spender,\n bool approved\n ) external override onlyManager {\n IERC721(token).setApprovalForAll(spender, approved);\n }\n\n /// @dev Executes financial order on 3rd party service\n /// @param target Contract address which should be called\n /// @param data Call data which should be sent\n function execute(\n address target,\n bytes memory data,\n uint256 value\n ) external override onlyManager returns (bytes memory) {\n return target.functionCallWithValue(data, value);\n }\n\n function updateName(string memory newName) external onlyManager {\n name = newName;\n }\n\n function buy(address lp, uint256 amount) external onlyManager {\n Nav memory nav = _updateManagementFeeAndCalcNav();\n _buy(lp, amount, nav);\n }\n\n function sell(address lp, uint256 ratio) external onlyManager {\n Nav memory nav = _updateManagementFeeAndCalcNav();\n (uint256 dao, uint256 carry) = _sell(lp, ratio, nav);\n _transfer(fundFilter.daoAddress(), dao);\n _transfer(gp, carry);\n }\n\n function close() external onlyManager {\n closed = block.timestamp;\n Nav memory nav = _updateManagementFeeAndCalcNav();\n uint256 daoSum;\n for (uint256 i = 0; i < _lps.length; i++) {\n (uint256 dao, ) = _sell(_lps[i], 10000, nav);\n daoSum += dao;\n }\n _transfer(fundFilter.daoAddress(), daoSum);\n _collect(true);\n }\n\n function collect() external onlyManager {\n _updateManagementFeeAmount(_calcTotalValue());\n _collect(false);\n }\n\n function wrapWETH9() external onlyManager {\n uint256 balance = address(this).balance;\n if (balance > 0) {\n IWETH9(weth9).deposit{value: balance}();\n }\n }\n\n function unwrapWETH9() external onlyManager {\n uint256 balance = IWETH9(weth9).balanceOf(address(this));\n if (balance > 0) {\n IWETH9(weth9).withdraw(balance);\n }\n }\n\n //////////////////////////////////////////////////////////////////////////////////////////////\n ///////////////////////////////////// PRIVATE FUNCTIONS //////////////////////////////////////\n //////////////////////////////////////////////////////////////////////////////////////////////\n\n function _calcTotalValue() private view returns (uint256) {\n if (closed > 0) {\n return _underlyingBalance();\n } else {\n return IFundManager(manager).calcTotalValue(address(this));\n }\n }\n\n function _calcManagementFeeFromLastUpdate(uint256 _totalValue) private view returns (uint256) {\n return (_totalValue * managementFee * (block.timestamp - lastUpdateManagementFeeTime)) / (1e4 * 365 * 86400);\n }\n\n function _updateManagementFeeAmount(uint256 _totalValue) private returns (uint256 recent) {\n recent = _calcManagementFeeFromLastUpdate(_totalValue);\n lastUpdateManagementFeeAmount += recent;\n lastUpdateManagementFeeTime = block.timestamp;\n }\n\n function _updateManagementFeeAndCalcNav() private returns (Nav memory nav) {\n uint256 totalValue = _calcTotalValue();\n uint256 recentFee = _updateManagementFeeAmount(totalValue);\n nav = Nav(totalValue - recentFee, totalUnit);\n }\n\n function _buy(\n address lp,\n uint256 amount,\n Nav memory nav\n ) private {\n // Calc unit from amount & nav\n uint256 unit;\n if (totalUnit == 0) {\n // account first buy (nav = 1)\n unit = amount;\n } else {\n unit = (amount * nav.totalUnit) / nav.totalValue;\n }\n\n // Update lpDetail\n LpDetail storage lpDetail = _lpDetails[lp];\n if (lpDetail.totalUnit == 0) {\n // lp first buy\n if (lp != initiator) {\n require(amount >= recipientMinAmount, Errors.NotEnoughBuyAmount);\n }\n _lps.push(lp);\n }\n lpDetail.lpActions.push(LpAction(1, amount, unit, block.timestamp, 0, 0, 0, 0));\n lpDetail.totalUnit += unit;\n lpDetail.totalAmount += amount;\n\n // Update account\n totalUnit += unit;\n }\n\n function _sell(\n address lp,\n uint256 ratio,\n Nav memory nav\n ) private returns (uint256 dao, uint256 carry) {\n // Calc unit from ratio & lp's holding units\n LpDetail storage lpDetail = _lpDetails[lp];\n uint256 unit = (lpDetail.totalUnit * ratio) / 1e4;\n\n // Calc amount from unit & nav\n uint256 amount = (nav.totalValue * unit) / nav.totalUnit;\n\n // Calc principal from unit & lp's holding nav\n uint256 base = (lpDetail.totalAmount * unit) / lpDetail.totalUnit;\n\n // Calc gain/loss detail from amount & base\n uint256 gain;\n uint256 loss;\n if (amount >= base) {\n gain = amount - base;\n dao = (gain * fundFilter.daoProfit()) / 1e4;\n carry = ((gain - dao) * carriedInterest) / 1e4;\n } else {\n loss = base - amount;\n }\n\n // Update lpDetail\n lpDetail.lpActions.push(LpAction(2, amount, unit, block.timestamp, gain, loss, carry, dao));\n lpDetail.totalUnit -= unit;\n lpDetail.totalAmount -= base;\n\n // Update account\n totalUnit -= unit;\n totalCarryInterestAmount += carry;\n\n // Transfer\n if (lp != gp) {\n _transfer(lp, amount - dao - carry);\n } else {\n // merge transfers for gp\n carry = amount - dao;\n }\n }\n\n function _collect(bool allBalance) private {\n uint256 collectAmount;\n if (allBalance) {\n collectAmount = _underlyingBalance();\n } else {\n collectAmount = lastUpdateManagementFeeAmount;\n }\n lastUpdateManagementFeeAmount = 0;\n _transfer(gp, collectAmount);\n }\n\n function _underlyingBalance() private view returns (uint256) {\n if (underlyingToken == weth9) {\n return address(this).balance;\n } else {\n return IERC20(underlyingToken).balanceOf(address(this));\n }\n }\n\n function _transfer(address to, uint256 value) private {\n if (value > 0) {\n if (underlyingToken == weth9) {\n if (to.code.length > 0) {\n // Smart contract may refuse to receive ETH\n // This will block execution of closing account\n // So send WETH to smart contract instead\n IWETH9(weth9).deposit{value: value}();\n IERC20(weth9).safeTransfer(to, value);\n } else {\n payable(to).transfer(value);\n }\n } else {\n IERC20(underlyingToken).safeTransfer(to, value);\n }\n }\n }\n}\n" }, "@openzeppelin/contracts/proxy/utils/Initializable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/Address.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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 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 Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized < type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" }, "@openzeppelin/contracts/token/ERC721/IERC721.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n" }, "@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "contracts/interfaces/fund/IFundAccount.sol": { "content": "// SPDX-License-Identifier: MIT\n// Decontracts Protocol. @2022\npragma solidity >=0.8.14;\n\nstruct Nav {\n // Net Asset Value, can't store as float\n uint256 totalValue;\n uint256 totalUnit;\n}\n\nstruct LpAction {\n uint256 actionType; // 1. buy, 2. sell\n uint256 amount;\n uint256 unit;\n uint256 time;\n uint256 gain;\n uint256 loss;\n uint256 carry;\n uint256 dao;\n}\n\nstruct LpDetail {\n uint256 totalAmount;\n uint256 totalUnit;\n LpAction[] lpActions;\n}\n\nstruct FundCreateParams {\n string name;\n address gp;\n uint256 managementFee;\n uint256 carriedInterest;\n address underlyingToken;\n address initiator;\n uint256 initiatorAmount;\n address recipient;\n uint256 recipientMinAmount;\n address[] allowedProtocols;\n address[] allowedTokens;\n}\n\ninterface IFundAccount {\n\n function since() external view returns (uint256);\n\n function closed() external view returns (uint256);\n\n function name() external view returns (string memory);\n\n function gp() external view returns (address);\n\n function managementFee() external view returns (uint256);\n\n function carriedInterest() external view returns (uint256);\n\n function underlyingToken() external view returns (address);\n\n function ethBalance() external view returns (uint256);\n\n function initiator() external view returns (address);\n\n function initiatorAmount() external view returns (uint256);\n\n function recipient() external view returns (address);\n\n function recipientMinAmount() external view returns (uint256);\n\n function lpList() external view returns (address[] memory);\n\n function lpDetailInfo(address addr) external view returns (LpDetail memory);\n\n function allowedProtocols() external view returns (address[] memory);\n\n function allowedTokens() external view returns (address[] memory);\n\n function isProtocolAllowed(address protocol) external view returns (bool);\n\n function isTokenAllowed(address token) external view returns (bool);\n\n function totalUnit() external view returns (uint256);\n\n function totalManagementFeeAmount() external view returns (uint256);\n\n function lastUpdateManagementFeeAmount() external view returns (uint256);\n\n function totalCarryInterestAmount() external view returns (uint256);\n\n function initialize(FundCreateParams memory params) external;\n\n function approveToken(\n address token,\n address spender,\n uint256 amount\n ) external;\n\n function safeTransfer(\n address token,\n address to,\n uint256 amount\n ) external;\n\n function setTokenApprovalForAll(\n address token,\n address spender,\n bool approved\n ) external;\n\n function execute(address target, bytes memory data, uint256 value) external returns (bytes memory);\n\n function buy(address lp, uint256 amount) external;\n\n function sell(address lp, uint256 ratio) external;\n\n function collect() external;\n\n function close() external;\n\n function updateName(string memory newName) external;\n\n function wrapWETH9() external;\n\n function unwrapWETH9() external;\n\n}\n" }, "contracts/interfaces/fund/IFundManager.sol": { "content": "// SPDX-License-Identifier: MIT\n// Decontracts Protocol. @2022\npragma solidity >=0.8.14;\n\nimport {IFundFilter} from \"./IFundFilter.sol\";\nimport {IPaymentGateway} from \"./IPaymentGateway.sol\";\n\ninterface IFundManager is IPaymentGateway {\n struct AccountCloseParams {\n address account;\n bytes[] paths;\n }\n\n function owner() external view returns (address);\n function fundFilter() external view returns (IFundFilter);\n\n function getAccountsCount(address) external view returns (uint256);\n function getAccounts(address) external view returns (address[] memory);\n\n function buyFund(address, uint256) external payable;\n function sellFund(address, uint256) external;\n function unwrapWETH9(address) external;\n\n function calcTotalValue(address account) external view returns (uint256 total);\n\n function lpTokensOfAccount(address account) external view returns (uint256[] memory);\n\n function provideAccountAllowance(\n address account,\n address token,\n address protocol,\n uint256 amount\n ) external;\n\n function executeOrder(\n address account,\n address protocol,\n bytes calldata data,\n uint256 value\n ) external returns (bytes memory);\n\n function onMint(\n address account,\n uint256 tokenId\n ) external;\n\n function onCollect(\n address account,\n uint256 tokenId\n ) external;\n\n function onIncrease(\n address account,\n uint256 tokenId\n ) external;\n\n // @dev Emit an event when new account is created\n // @param account The fund account address\n // @param initiator The initiator address\n // @param recipient The recipient address\n event AccountCreated(address indexed account, address indexed initiator, address indexed recipient);\n}\n" }, "contracts/interfaces/fund/IFundFilter.sol": { "content": "// SPDX-License-Identifier: MIT\n// Decontracts Protocol. @2022\npragma solidity >=0.8.14;\n\nstruct FundFilterInitializeParams {\n address priceOracle;\n address swapRouter;\n address positionManager;\n address positionViewer;\n address protocolAdapter;\n address[] allowedUnderlyingTokens;\n address[] allowedTokens;\n address[] allowedProtocols;\n uint256 minManagementFee;\n uint256 maxManagementFee;\n uint256 minCarriedInterest;\n uint256 maxCarriedInterest;\n address daoAddress;\n uint256 daoProfit;\n}\n\ninterface IFundFilter {\n\n event AllowedUnderlyingTokenUpdated(address indexed token, bool allowed);\n\n event AllowedTokenUpdated(address indexed token, bool allowed);\n\n event AllowedProtocolUpdated(address indexed protocol, bool allowed);\n\n function priceOracle() external view returns (address);\n\n function swapRouter() external view returns (address);\n\n function positionManager() external view returns (address);\n\n function positionViewer() external view returns (address);\n\n function protocolAdapter() external view returns (address);\n\n function allowedUnderlyingTokens() external view returns (address[] memory);\n\n function isUnderlyingTokenAllowed(address token) external view returns (bool);\n\n function allowedTokens() external view returns (address[] memory);\n\n function isTokenAllowed(address token) external view returns (bool);\n\n function allowedProtocols() external view returns (address[] memory);\n\n function isProtocolAllowed(address protocol) external view returns (bool);\n\n function minManagementFee() external view returns (uint256);\n\n function maxManagementFee() external view returns (uint256);\n\n function minCarriedInterest() external view returns (uint256);\n\n function maxCarriedInterest() external view returns (uint256);\n\n function daoAddress() external view returns (address);\n\n function daoProfit() external view returns (uint256);\n\n}\n" }, "contracts/libraries/Errors.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.14;\n\nlibrary Errors {\n // Create/Close Account\n string public constant InvalidInitiator = \"CA0\";\n string public constant InvalidRecipient = \"CA1\";\n string public constant InvalidGP = \"CA2\";\n string public constant InvalidNameLength = \"CA3\";\n string public constant InvalidManagementFee = \"CA4\";\n string public constant InvalidCarriedInterest = \"CA5\";\n string public constant InvalidUnderlyingToken = \"CA6\";\n string public constant InvalidAllowedProtocols = \"CA7\";\n string public constant InvalidAllowedTokens = \"CA8\";\n string public constant InvalidRecipientMinAmount = \"CA9\";\n\n // Others\n string public constant NotManager = \"FM0\";\n string public constant NotGP = \"FM1\";\n string public constant NotLP = \"FM2\";\n string public constant NotGPOrLP = \"FM3\";\n string public constant NotEnoughBuyAmount = \"FM4\";\n string public constant InvalidSellUnit = \"FM5\";\n string public constant NotEnoughBalance = \"FM6\";\n string public constant MissingAmount = \"FM7\";\n string public constant InvalidFundCreateParams = \"FM8\";\n string public constant InvalidName = \"FM9\";\n string public constant NotAccountOwner = \"FM10\";\n string public constant ContractCannotBeZeroAddress = \"FM11\";\n string public constant ExceedMaximumPositions = \"FM12\";\n string public constant NotAllowedToken = \"FM13\";\n string public constant NotAllowedProtocol = \"FM14\";\n string public constant FunctionCallIsNotAllowed = \"FM15\";\n string public constant PathNotAllowed = \"FM16\";\n string public constant ProtocolCannotBeZeroAddress = \"FM17\";\n string public constant CallerIsNotManagerOwner = \"FM18\";\n string public constant InvalidInitializeParams = \"FM19\";\n string public constant InvalidUpdateParams = \"FM20\";\n string public constant InvalidZeroAddress = \"FM21\";\n string public constant NotAllowedAdapter = \"FM22\";\n}\n" }, "contracts/interfaces/external/IWETH9.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.14;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IWETH9 is IERC20 {\n function deposit() external payable;\n\n function withdraw(uint256) external;\n}\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" }, "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n" }, "@openzeppelin/contracts/utils/introspection/IERC165.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" }, "contracts/interfaces/fund/IPaymentGateway.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.14;\n\ninterface IPaymentGateway {\n function weth9() external view returns (address);\n}\n" } }, "settings": { "viaIR": true, "optimizer": { "enabled": true, "runs": 100 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} } }