{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/NestedFactory.sol",
    "Parent Contracts": [
        "node_modules/@openzeppelin/contracts/utils/Multicall.sol",
        "contracts/MixinOperatorResolver.sol",
        "node_modules/@openzeppelin/contracts/access/Ownable.sol",
        "node_modules/@openzeppelin/contracts/utils/Context.sol",
        "node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol",
        "contracts/interfaces/INestedFactory.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract NestedFactory is INestedFactory, ReentrancyGuard, Ownable, MixinOperatorResolver, Multicall {\n    using SafeERC20 for IERC20;\n    address private constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n\n    /// @dev Supported operators by the factory contract\n    bytes32[] private operators;\n\n    /// @dev Current feeSplitter contract/address\n    FeeSplitter public feeSplitter;\n\n    /// @dev Current reserve contract/address\n    NestedReserve public reserve;\n\n    NestedAsset public immutable nestedAsset;\n    IWETH public immutable weth;\n    NestedRecords public immutable nestedRecords;\n\n    constructor(\n        NestedAsset _nestedAsset,\n        NestedRecords _nestedRecords,\n        FeeSplitter _feeSplitter,\n        IWETH _weth,\n        address _operatorResolver\n    ) MixinOperatorResolver(_operatorResolver) {\n        nestedAsset = _nestedAsset;\n        nestedRecords = _nestedRecords;\n        feeSplitter = _feeSplitter;\n        weth = _weth;\n    }\n\n    /// @dev Reverts the transaction if the caller is not the token owner\n    /// @param _nftId The NFT Id\n    modifier onlyTokenOwner(uint256 _nftId) {\n        require(nestedAsset.ownerOf(_nftId) == _msgSender(), \"NestedFactory: Not the token owner\");\n        _;\n    }\n\n    /// @dev Reverts the transaction if the nft is locked (hold by design).\n    /// The block.timestamp must be greater than NFT record lock timestamp\n    /// @param _nftId The NFT Id\n    modifier isUnlocked(uint256 _nftId) {\n        require(block.timestamp > nestedRecords.getLockTimestamp(_nftId), \"NestedFactory: The NFT is currently locked\");\n        _;\n    }\n\n    /// @dev Receive function\n    receive() external payable {}\n\n    /// @notice Get the required operator addresses\n    function resolverAddressesRequired() public view override returns (bytes32[] memory addresses) {\n        return operators;\n    }\n\n    /// @inheritdoc INestedFactory\n    function addOperator(bytes32 operator) external override onlyOwner {\n        operators.push(operator);\n    }\n\n    /// @inheritdoc INestedFactory\n    function removeOperator(bytes32 operator) external override onlyOwner {\n        uint256 i = 0;\n        while (operators[i] != operator) {\n            i++;\n        }\n        require(i > 0, \"NestedFactory::removeOperator: Cant remove non-existent operator\");\n        delete operators[i];\n    }\n\n    /// @inheritdoc INestedFactory\n    function setReserve(NestedReserve _reserve) external override onlyOwner {\n        require(address(reserve) == address(0), \"NestedFactory::setReserve: Reserve is immutable\");\n        reserve = _reserve;\n        emit ReserveUpdated(address(_reserve));\n    }\n\n    /// @inheritdoc INestedFactory\n    function setFeeSplitter(FeeSplitter _feeSplitter) external override onlyOwner {\n        require(address(_feeSplitter) != address(0), \"NestedFactory::setFeeSplitter: Invalid feeSplitter address\");\n        feeSplitter = _feeSplitter;\n        emit FeeSplitterUpdated(address(_feeSplitter));\n    }\n\n    /// @inheritdoc INestedFactory\n    function create(\n        uint256 _originalTokenId,\n        IERC20 _sellToken,\n        uint256 _sellTokenAmount,\n        Order[] calldata _orders\n    ) external payable override nonReentrant {\n        require(_orders.length > 0, \"NestedFactory::create: Missing orders\");\n\n        uint256 nftId = nestedAsset.mint(_msgSender(), _originalTokenId);\n        (uint256 fees, IERC20 tokenSold) = _submitInOrders(nftId, _sellToken, _sellTokenAmount, _orders, true, false);\n\n        _transferFeeWithRoyalty(fees, tokenSold, nftId);\n        emit NftCreated(nftId, _originalTokenId);\n    }\n\n    /// @inheritdoc INestedFactory\n    function addTokens(\n        uint256 _nftId,\n        IERC20 _sellToken,\n        uint256 _sellTokenAmount,\n        Order[] calldata _orders\n    ) external payable override nonReentrant onlyTokenOwner(_nftId) {\n        require(_orders.length > 0, \"NestedFactory::addTokens: Missing orders\");\n\n        (uint256 fees, IERC20 tokenSold) = _submitInOrders(_nftId, _sellToken, _sellTokenAmount, _orders, true, false);\n        _transferFeeWithRoyalty(fees, tokenSold, _nftId);\n        emit NftUpdated(_nftId);\n    }\n\n    /// @inheritdoc INestedFactory\n    function swapTokenForTokens(\n        uint256 _nftId,\n        IERC20 _sellToken,\n        uint256 _sellTokenAmount,\n        Order[] calldata _orders\n    ) external override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) {\n        require(_orders.length > 0, \"NestedFactory::swapTokenForTokens: Missing orders\");\n        require(\n            nestedRecords.getAssetReserve(_nftId) == address(reserve),\n            \"NestedFactory::swapTokenForTokens: Assets in different reserve\"\n        );\n\n        (uint256 fees, IERC20 tokenSold) = _submitInOrders(_nftId, _sellToken, _sellTokenAmount, _orders, true, true);\n        _transferFeeWithRoyalty(fees, tokenSold, _nftId);\n\n        emit NftUpdated(_nftId);\n    }\n\n    /// @inheritdoc INestedFactory\n    function sellTokensToNft(\n        uint256 _nftId,\n        IERC20 _buyToken,\n        uint256[] memory _sellTokensAmount,\n        Order[] calldata _orders\n    ) external override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) {\n        require(_orders.length > 0, \"NestedFactory::sellTokensToNft: Missing orders\");\n        require(_sellTokensAmount.length == _orders.length, \"NestedFactory::sellTokensToNft: Input lengths must match\");\n        require(\n            nestedRecords.getAssetReserve(_nftId) == address(reserve),\n            \"NestedFactory::sellTokensToNft: Assets in different reserve\"\n        );\n\n        (uint256 feesAmount, ) = _submitOutOrders(_nftId, _buyToken, _sellTokensAmount, _orders, true, true);\n        _transferFeeWithRoyalty(feesAmount, _buyToken, _nftId);\n\n        emit NftUpdated(_nftId);\n    }\n\n    /// @inheritdoc INestedFactory\n    function sellTokensToWallet(\n        uint256 _nftId,\n        IERC20 _buyToken,\n        uint256[] memory _sellTokensAmount,\n        Order[] calldata _orders\n    ) external override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) {\n        require(_orders.length > 0, \"NestedFactory::sellTokensToWallet: Missing orders\");\n        require(\n            _sellTokensAmount.length == _orders.length,\n            \"NestedFactory::sellTokensToWallet: Input lengths must match\"\n        );\n        require(\n            nestedRecords.getAssetReserve(_nftId) == address(reserve),\n            \"NestedFactory::sellTokensToWallet: Assets in different reserve\"\n        );\n\n        (uint256 feesAmount, uint256 amountBought) = _submitOutOrders(\n            _nftId,\n            _buyToken,\n            _sellTokensAmount,\n            _orders,\n            false,\n            true\n        );\n        _transferFeeWithRoyalty(feesAmount, _buyToken, _nftId);\n        _safeTransferAndUnwrap(_buyToken, amountBought - feesAmount, _msgSender());\n\n        emit NftUpdated(_nftId);\n    }\n\n    /// @inheritdoc INestedFactory\n    function destroy(\n        uint256 _nftId,\n        IERC20 _buyToken,\n        Order[] calldata _orders\n    ) external override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) {\n        address[] memory tokens = nestedRecords.getAssetTokens(_nftId);\n        require(_orders.length > 0, \"NestedFactory::destroy: Missing orders\");\n        require(tokens.length == _orders.length, \"NestedFactory::destroy: Missing sell args\");\n        require(\n            nestedRecords.getAssetReserve(_nftId) == address(reserve),\n            \"NestedFactory::destroy: Assets in different reserve\"\n        );\n\n        uint256 buyTokenInitialBalance = _buyToken.balanceOf(address(this));\n\n        for (uint256 i = 0; i < tokens.length; i++) {\n            NestedRecords.Holding memory holding = nestedRecords.getAssetHolding(_nftId, tokens[i]);\n            reserve.withdraw(IERC20(holding.token), holding.amount);\n\n            _safeSubmitOrder(tokens[i], address(_buyToken), holding.amount, _nftId, _orders[i]);\n            nestedRecords.freeHolding(_nftId, tokens[i]);\n        }\n\n        // Amount calculation to send fees and tokens\n        uint256 amountBought = _buyToken.balanceOf(address(this)) - buyTokenInitialBalance;\n        uint256 amountFees = _calculateFees(_msgSender(), amountBought);\n        amountBought = amountBought - amountFees;\n\n        _transferFeeWithRoyalty(amountFees, _buyToken, _nftId);\n        _safeTransferAndUnwrap(_buyToken, amountBought, _msgSender());\n\n        // Burn NFT\n        nestedRecords.removeNFT(_nftId);\n        nestedAsset.burn(_msgSender(), _nftId);\n        emit NftBurned(_nftId);\n    }\n\n    /// @inheritdoc INestedFactory\n    function withdraw(uint256 _nftId, uint256 _tokenIndex)\n        external\n        override\n        nonReentrant\n        onlyTokenOwner(_nftId)\n        isUnlocked(_nftId)\n    {\n        uint256 assetTokensLength = nestedRecords.getAssetTokensLength(_nftId);\n        require(assetTokensLength > _tokenIndex, \"NestedFactory::withdraw: Invalid token index\");\n        // Use destroy instead if NFT has a single holding\n        require(assetTokensLength > 1, \"NestedFactory::withdraw: Can't withdraw the last asset\");\n\n        NestedRecords.Holding memory holding = nestedRecords.getAssetHolding(\n            _nftId,\n            nestedRecords.getAssetTokens(_nftId)[_tokenIndex]\n        );\n        reserve.withdraw(IERC20(holding.token), holding.amount);\n        _safeTransferWithFees(IERC20(holding.token), holding.amount, _msgSender(), _nftId);\n\n        nestedRecords.deleteAsset(_nftId, _tokenIndex);\n\n        emit NftUpdated(_nftId);\n    }\n\n    /// @inheritdoc INestedFactory\n    function increaseLockTimestamp(uint256 _nftId, uint256 _timestamp) external override onlyTokenOwner(_nftId) {\n        nestedRecords.updateLockTimestamp(_nftId, _timestamp);\n    }\n\n    /// @inheritdoc INestedFactory\n    function unlockTokens(IERC20 _token) external override onlyOwner {\n        _token.transfer(owner(), _token.balanceOf(address(this)));\n    }\n\n    /// @dev For every orders, call the operator with the calldata\n    /// to submit buy orders (where the input is one asset).\n    /// @param _nftId The id of the NFT impacted by the orders\n    /// @param _inputToken Token used to make the orders\n    /// @param _inputTokenAmount Amount of input tokens to use\n    /// @param _orders Orders calldata\n    /// @param _reserved True if the output is store in the reserve/records, false if not.\n    /// @param _fromReserve True if the input tokens are from the reserve\n    /// @return feesAmount The total amount of fees\n    /// @return tokenSold The ERC20 token sold (in case of ETH to WETH)\n    function _submitInOrders(\n        uint256 _nftId,\n        IERC20 _inputToken,\n        uint256 _inputTokenAmount,\n        Order[] calldata _orders,\n        bool _reserved,\n        bool _fromReserve\n    ) private returns (uint256 feesAmount, IERC20 tokenSold) {\n        _inputToken = _transferInputTokens(_nftId, _inputToken, _inputTokenAmount, _fromReserve);\n        uint256 amountSpent;\n        for (uint256 i = 0; i < _orders.length; i++) {\n            amountSpent += _submitOrder(address(_inputToken), _orders[i].token, _nftId, _orders[i], _reserved);\n        }\n        feesAmount = _calculateFees(_msgSender(), amountSpent);\n        assert(amountSpent <= _inputTokenAmount - feesAmount); // overspent\n\n        // If input is from the reserve, update the records\n        if (_fromReserve) {\n            _decreaseHoldingAmount(_nftId, address(_inputToken), _inputTokenAmount);\n        }\n\n        _handleUnderSpending(_inputTokenAmount - feesAmount, amountSpent, _inputToken);\n\n        tokenSold = _inputToken;\n    }\n\n    /// @dev For every orders, call the operator with the calldata\n    /// to submit sell orders (where the output is one asset).\n    /// @param _nftId The id of the NFT impacted by the orders\n    /// @param _outputToken Token received for every orders\n    /// @param _inputTokenAmounts Amounts of tokens to use (respectively with Orders)\n    /// @param _orders Orders calldata\n    /// @param _reserved True if the output is store in the reserve/records, false if not.\n    /// @param _fromReserve True if the input tokens are from the reserve\n    /// @return feesAmount The total amount of fees\n    /// @return amountBought The total amount bought\n    function _submitOutOrders(\n        uint256 _nftId,\n        IERC20 _outputToken,\n        uint256[] memory _inputTokenAmounts,\n        Order[] calldata _orders,\n        bool _reserved,\n        bool _fromReserve\n    ) private returns (uint256 feesAmount, uint256 amountBought) {\n        uint256 _outputTokenInitialBalance = _outputToken.balanceOf(address(this));\n\n        for (uint256 i = 0; i < _orders.length; i++) {\n            IERC20 _inputToken = _transferInputTokens(\n                _nftId,\n                IERC20(_orders[i].token),\n                _inputTokenAmounts[i],\n                _fromReserve\n            );\n\n            // Submit order and update holding of spent token\n            uint256 amountSpent = _submitOrder(address(_inputToken), address(_outputToken), _nftId, _orders[i], false);\n            assert(amountSpent <= _inputTokenAmounts[i]);\n\n            if (_fromReserve) {\n                _decreaseHoldingAmount(_nftId, address(_inputToken), _inputTokenAmounts[i]);\n            }\n\n            // Under spent input amount send to fee splitter\n            if (_inputTokenAmounts[i] - amountSpent > 0) {\n                _transferFeeWithRoyalty(_inputTokenAmounts[i] - amountSpent, _inputToken, _nftId);\n            }\n        }\n\n        amountBought = _outputToken.balanceOf(address(this)) - _outputTokenInitialBalance;\n        feesAmount = _calculateFees(_msgSender(), amountBought);\n\n        if (_reserved) {\n            _transferToReserveAndStore(address(_outputToken), amountBought - feesAmount, _nftId);\n        }\n    }\n\n    /// @dev Call the operator to submit the order (commit/revert) and add the output\n    /// assets to the reserve (if needed).\n    /// @param _inputToken Token used to make the orders\n    /// @param _outputToken Expected output token\n    /// @param _nftId The nftId\n    /// @param _order The order calldata\n    /// @param _reserved True if the output is store in the reserve/records, false if not.\n    function _submitOrder(\n        address _inputToken,\n        address _outputToken,\n        uint256 _nftId,\n        Order calldata _order,\n        bool _reserved\n    ) private returns (uint256 amountSpent) {\n        address operator = requireAndGetAddress(_order.operator);\n        (bool success, bytes memory data) = OperatorHelpers.callOperator(operator, _order.commit, _order.callData);\n        require(success, \"NestedFactory::_submitOrder: Operator call failed\");\n\n        (uint256[] memory amounts, address[] memory tokens) = OperatorHelpers.decodeDataAndRequire(\n            data,\n            _inputToken,\n            _outputToken\n        );\n\n        if (_reserved) {\n            _transferToReserveAndStore(_outputToken, amounts[0], _nftId);\n        }\n        amountSpent = amounts[1];\n    }\n\n    /// @dev Call the operator to submit the order (commit/revert) but dont stop if\n    /// the call to the operator fail. It will send the input token back to the msg.sender.\n    /// Note : The _reserved Boolean has been removed (compare to _submitOrder) since it was\n    ///        useless for the only use case (destroy).\n    /// @param _inputToken Token used to make the orders\n    /// @param _outputToken Expected output token\n    /// @param _amountToSpend The input amount available (to spend)\n    /// @param _nftId The nftId\n    /// @param _order The order calldata\n    function _safeSubmitOrder(\n        address _inputToken,\n        address _outputToken,\n        uint256 _amountToSpend,\n        uint256 _nftId,\n        Order calldata _order\n    ) private {\n        address operator = requireAndGetAddress(_order.operator);\n        (bool success, bytes memory data) = OperatorHelpers.callOperator(operator, _order.commit, _order.callData);\n        if (success) {\n            (uint256[] memory amounts, address[] memory tokens) = OperatorHelpers.decodeDataAndRequire(\n                data,\n                _inputToken,\n                _outputToken\n            );\n            _handleUnderSpending(_amountToSpend, amounts[1], IERC20(_inputToken));\n        } else {\n            _safeTransferWithFees(IERC20(_inputToken), _amountToSpend, _msgSender(), _nftId);\n        }\n    }\n\n    /// @dev Transfer tokens to the reserve, and compute the amount received to store\n    /// in the records. We need to know the amount received in case of deflationary tokens.\n    /// @param _token The token address\n    /// @param _amount The amount to send to the reserve\n    /// @param _nftId The Token ID to store the assets\n    function _transferToReserveAndStore(\n        address _token,\n        uint256 _amount,\n        uint256 _nftId\n    ) private {\n        uint256 balanceReserveBefore = IERC20(_token).balanceOf(address(reserve));\n\n        // Send output to reserve\n        IERC20(_token).safeTransfer(address(reserve), _amount);\n\n        uint256 balanceReserveAfter = IERC20(_token).balanceOf(address(reserve));\n\n        nestedRecords.store(_nftId, _token, balanceReserveAfter - balanceReserveBefore, address(reserve));\n    }\n\n    /// @dev Choose between ERC20 (safeTransfer) and ETH (deposit), to transfer from the Reserve\n    ///      or the user wallet, to the factory.\n    /// @param _nftId The NFT id\n    /// @param _inputToken The token to receive\n    /// @param _inputTokenAmount Amount to transfer\n    /// @param _fromReserve True to transfer from the reserve\n    /// @return tokenUsed Token transfered (in case of ETH)\n    function _transferInputTokens(\n        uint256 _nftId,\n        IERC20 _inputToken,\n        uint256 _inputTokenAmount,\n        bool _fromReserve\n    ) private returns (IERC20 tokenUsed) {\n        if (_fromReserve) {\n            NestedRecords.Holding memory holding = nestedRecords.getAssetHolding(_nftId, address(_inputToken));\n            require(holding.amount >= _inputTokenAmount, \"NestedFactory:_transferInputTokens: Insufficient amount\");\n\n            // Get input from reserve\n            reserve.withdraw(IERC20(holding.token), _inputTokenAmount);\n        } else if (address(_inputToken) == ETH) {\n            require(msg.value == _inputTokenAmount, \"NestedFactory::_transferInputTokens: Insufficient amount in\");\n            weth.deposit{ value: msg.value }();\n            _inputToken = IERC20(address(weth));\n        } else {\n            _inputToken.safeTransferFrom(_msgSender(), address(this), _inputTokenAmount);\n        }\n        tokenUsed = _inputToken;\n    }\n\n    /// @dev Send the under spent amount to the FeeSplitter without the royalties.\n    ///      The \"under spent\" amount is the positive difference between the amount supposed\n    ///      to be spent and the amount really spent.\n    /// @param _amountToSpent The amount supposed to be spent\n    /// @param _amountSpent The amount really spent\n    /// @param _token The amount-related token\n    function _handleUnderSpending(\n        uint256 _amountToSpent,\n        uint256 _amountSpent,\n        IERC20 _token\n    ) private {\n        if (_amountToSpent - _amountSpent > 0) {\n            ExchangeHelpers.setMaxAllowance(_token, address(feeSplitter));\n            feeSplitter.sendFees(_token, _amountToSpent - _amountSpent);\n        }\n    }\n\n    /// @dev Send a fee to the FeeSplitter, royalties will be paid to the owner of the original asset\n    /// @param _amount Amount to send\n    /// @param _token Token to send\n    /// @param _nftId User portfolio ID used to find a potential royalties recipient\n    function _transferFeeWithRoyalty(\n        uint256 _amount,\n        IERC20 _token,\n        uint256 _nftId\n    ) private {\n        address originalOwner = nestedAsset.originalOwner(_nftId);\n        ExchangeHelpers.setMaxAllowance(_token, address(feeSplitter));\n        if (originalOwner != address(0)) {\n            feeSplitter.sendFeesWithRoyalties(originalOwner, _token, _amount);\n        } else {\n            feeSplitter.sendFees(_token, _amount);\n        }\n    }\n\n    /// @dev Decrease the amount of a NFT holding\n    /// @param _nftId The NFT id\n    /// @param _inputToken The token holding\n    /// @param _amount The amount to subtract from the actual holding amount\n    function _decreaseHoldingAmount(\n        uint256 _nftId,\n        address _inputToken,\n        uint256 _amount\n    ) private {\n        NestedRecords.Holding memory holding = nestedRecords.getAssetHolding(_nftId, _inputToken);\n        nestedRecords.updateHoldingAmount(_nftId, _inputToken, holding.amount - _amount);\n    }\n\n    /// @dev Transfer a token amount from the factory to the recipient.\n    ///      The token is unwrapped if WETH.\n    /// @param _token The token to transfer\n    /// @param _amount The amount to transfer\n    /// @param _dest The address receiving the funds\n    function _safeTransferAndUnwrap(\n        IERC20 _token,\n        uint256 _amount,\n        address _dest\n    ) private {\n        // if buy token is WETH, unwrap it instead of transferring it to the sender\n        if (address(_token) == address(weth)) {\n            IWETH(weth).withdraw(_amount);\n            (bool success, ) = _dest.call{ value: _amount }(\"\");\n            require(success, \"ETH_TRANSFER_ERROR\");\n        } else {\n            _token.safeTransfer(_dest, _amount);\n        }\n    }\n\n    /// @dev Transfer from factory and collect fees\n    /// @param _token The token to transfer\n    /// @param _amount The amount (with fees) to transfer\n    /// @param _dest The address receiving the funds\n    function _safeTransferWithFees(\n        IERC20 _token,\n        uint256 _amount,\n        address _dest,\n        uint256 _nftId\n    ) private {\n        uint256 feeAmount = _calculateFees(_dest, _amount);\n        _transferFeeWithRoyalty(feeAmount, _token, _nftId);\n        _token.safeTransfer(_dest, _amount - feeAmount);\n    }\n\n    /// @dev Calculate the fees for a specific user and amount (1%)\n    /// @param _user The user address\n    /// @param _amount The amount\n    /// @return The fees amount\n    function _calculateFees(address _user, uint256 _amount) private view returns (uint256) {\n        return _amount / 100;\n    }\n}"
}