creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "contracts/unstable/vaults/base/StakedEthVault.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"contracts/unstable/interfaces/InUSD.sol\";\nimport \"contracts/unstable/interfaces/IConfigurator.sol\";\nimport \"contracts/unstable/interfaces/IZkOracle.sol\";\nimport \"@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol\";\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\n\ncontract StakedEthVault is ReentrancyGuard {\n    using SafeERC20 for IERC20;\n\n    InUSD public immutable nUSD;\n    IERC20 public immutable collateralAsset;\n    IConfigurator public immutable configurator;\n\n    uint256 public poolTotalCirculation;\n\n    // Maybe using struct packing would save some gas on critical functions\n    mapping(address => uint256) public depositedAsset;\n    mapping(address => uint256) public borrowed;\n    mapping(address => uint256) public feeStored;\n    mapping(address => uint256) public feeUpdatedAt;\n\n    event DepositEther(address indexed onBehalfOf, address asset, uint256 etherAmount, uint256 assetAmount, uint256 timestamp);\n\n    event DepositAsset(address indexed onBehalfOf, address asset, uint256 amount, uint256 timestamp);\n    event WithdrawAsset(address indexed sponsor, address asset, address indexed onBehalfOf, uint256 amount, uint256 timestamp);\n    event Mint(address indexed sponsor, address indexed onBehalfOf, uint256 amount, uint256 originationFee, uint256 timestamp);\n    event Burn(address indexed sponsor, address indexed onBehalfOf, uint256 amount, uint256 timestamp);\n    event LiquidationRecord(address indexed provider, address indexed keeper, address indexed debtor, uint256 nusdAmount, uint256 LiquidateAssetAmount, uint256 keeperReward, bool superLiquidation);\n    event Redemption(address indexed caller, address indexed debtor, uint256 nusdToProtocol, uint256 nusdToRepay, uint256 collateralReceived);\n\n    // MultiRewards farming functionality\n    struct Reward {\n        uint256 rewardsDuration;\n        uint256 periodFinish;\n        uint256 rewardRate;\n        uint256 lastUpdateTime;\n        uint256 rewardPerTokenStored;\n    }\n\n    mapping(address => Reward) public rewardData;\n    address[] public rewardTokens;\n\n    mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;\n    mapping(address => mapping(address => uint256)) public rewards;\n\n    event RewardAdded(uint256 reward);\n    event RewardPaid(address indexed user, address indexed rewardsToken, uint256 reward);\n    event RewardsDurationUpdated(address token, uint256 newDuration);\n    event Recovered(address token, uint256 amount);\n\n    //constructor\n    constructor(address _collateral, address _configurator) {\n        collateralAsset = IERC20(_collateral);\n        configurator = IConfigurator(_configurator);\n        nUSD = InUSD(configurator.nUSD());\n    }\n\n    function totalDepositedAsset() public view virtual returns (uint256) {\n        return collateralAsset.balanceOf(address(this));\n    }\n\n    /**\n     * @notice Deposit staked ETH, update the interest distribution, can mint nUSD directly\n     * Emits a `DepositAsset` event.\n     *\n     * Requirements:\n     * - `assetAmount` Must be higher than 0.\n     * - `mintAmount` Send 0 if deposit only, no mint of nUSD\n     */\n    function depositAssetToMint(uint256 assetAmount, uint256 mintAmount) external updateReward(msg.sender) nonReentrant virtual {\n        require(assetAmount > 0, \"Deposit should be > 0\");\n        collateralAsset.safeTransferFrom(msg.sender, address(this), assetAmount);\n\n        depositedAsset[msg.sender] += assetAmount;\n        if (mintAmount > 0) {\n            _mintnUSD(msg.sender, msg.sender, mintAmount);\n        }\n        emit DepositAsset(msg.sender, address(collateralAsset), assetAmount, block.timestamp);\n    }\n\n    /**\n     * @notice Withdraw collateral assets to an address\n     * Emits a `WithdrawAsset` event.\n     *\n     * Requirements:\n     * - `onBehalfOf` cannot be the zero address.\n     * - `amount` Must be higher than 0.\n     *\n     * @dev Withdraw collateral. Check user’s collateral ratio after withdrawal, should be higher than `safeCollateralRatio`\n     */\n    function withdraw(address onBehalfOf, uint256 amount) external updateReward(msg.sender) nonReentrant virtual {\n        require(onBehalfOf != address(0), \"to zero address\");\n        require(amount != 0, \"zero amount\");\n        _withdraw(msg.sender, onBehalfOf, amount);\n    }\n\n    /**\n     * @notice The mint amount number of nUSD is minted to the address\n     * Emits a `Mint` event.\n     *\n     * Requirements:\n     * - `onBehalfOf` cannot be the zero address.\n     */\n    function mint(address onBehalfOf, uint256 amount) external nonReentrant virtual {\n        require(onBehalfOf != address(0), \"to zero address\");\n        require(amount != 0, \"zero amount\");\n        _mintnUSD(msg.sender, onBehalfOf, amount);\n    }\n\n    /**\n     * @notice Burn the amount of nUSD and payback the amount of minted nUSD\n     * Emits a `Burn` event.\n     * Requirements:\n     * - `onBehalfOf` cannot be the zero address.\n     * - `amount` Must be higher than 0.\n     * @dev Calling the internal`_repay`function.\n     */\n    function burn(address onBehalfOf, uint256 amount) external nonReentrant virtual {\n        require(onBehalfOf != address(0), \"to zero address\");\n        require(amount != 0, \"zero amount\");\n        _repay(msg.sender, onBehalfOf, amount);\n    }\n\n    /**\n     * @notice Keeper liquidates borrowers whose collateral ratio is below badCollateralRatio, using nUSD provided by Liquidation Provider.\n     *\n     * Requirements:\n     * - onBehalfOf Collateral Ratio should be below badCollateralRatio\n     * - assetAmount should be less than 50% of collateral - If liquidating 50% of the collateral doesn't bring the position to health, you should allow a full liquidation.\n     * - provider should authorize Unstable to utilize nUSD\n     * @dev After liquidation, borrower's debt is reduced by assetAmount * assetPrice, providers and keepers can receive up to an additional 10% liquidation reward.\n     */\n    //TODO: logic for full liquidation in case 50% doesn't bring to health\n    function liquidation(address provider, address debtor, uint256 assetAmount) external updateReward(debtor) nonReentrant virtual {\n        uint256 assetPrice = getAssetPrice();\n        uint256 debtorCollateralRatio = getCollateralRatio(debtor);\n        require(debtorCollateralRatio < configurator.getBadCollateralRatio(address(this)), \"Borrowers collateral ratio should below badCollateralRatio\");\n        require(assetAmount * 2 <= depositedAsset[debtor], \"a max of 50% collateral can be liquidated\");\n        require(nUSD.allowance(provider, address(this)) != 0 || msg.sender == provider, \"provider should authorize to provide liquidation nUSD\");\n        uint256 nusdAmount = assetAmount * assetPrice / 1e18;\n\n        _repay(provider, debtor, nusdAmount);\n        uint256 reducedAsset = assetAmount;\n        //If collateralRatio is 100-110%, liquidator bonus is less than 10%\n        if(debtorCollateralRatio > 100_00 && debtorCollateralRatio < 110_00) {\n            reducedAsset = assetAmount * debtorCollateralRatio / 100_00;\n        }\n        //If collateralRatio is more than 110%, 10% liquidation bonus\n        if(debtorCollateralRatio >= 110_00) {\n            reducedAsset = assetAmount * 11 / 10; //10% bonus\n        }\n        depositedAsset[debtor] -= reducedAsset;\n        uint256 rewardToKeeper;\n        //Send keeper reward <- Which is taken from the liquidator payment.\n        uint256 keeperReward = configurator.getKeeperReward(address(this));\n        if (msg.sender != provider && debtorCollateralRatio >= 100_00 + keeperReward) {\n            rewardToKeeper = assetAmount * keeperReward / 100_00;\n            collateralAsset.safeTransfer(msg.sender, rewardToKeeper);\n        }\n        collateralAsset.safeTransfer(provider, reducedAsset - rewardToKeeper);\n        emit LiquidationRecord(provider, msg.sender, debtor, nusdAmount, reducedAsset, rewardToKeeper, false);\n    }\n\n    /**\n     * @notice Choose a Redemption Provider, redeem `nusdAmount` of nUSD and get 1:1 value of collateral minus fees\n     * Emits a `Redemption` event.\n     *\n     * *Requirements:\n     * - `debtor`debt must equal to or above`nusdAmount`\n     * - `debtor` must be eligible, use `calculateRedemption` to check\n     */\n    function redemption(address debtor, uint256 nusdAmount, uint256 minReceiveAmount) external updateReward(debtor) nonReentrant virtual {\n        require(debtor != msg.sender, \"no self redeem\"); //TODO: is this necessary?\n        (, , uint256 nusdToProtocol, uint256 nusdToRepay, , uint256 collateralReceived) = calculateRedemption(debtor, nusdAmount);\n        require(collateralReceived >= minReceiveAmount, \"Collateral amount is less than minReceiveAmount\");\n        if(nusdToProtocol > 0) {\n            nUSD.transferFrom(msg.sender, address(configurator), nusdToProtocol);\n        }\n        _repay(msg.sender, debtor, nusdToRepay);\n        depositedAsset[debtor] -= collateralReceived;\n        collateralAsset.safeTransfer(msg.sender, collateralReceived);\n        emit Redemption(msg.sender, debtor, nusdToProtocol, nusdToRepay, collateralReceived);\n    }\n\n    /**\n     * @notice Calculate redemption for a provider and nusdAmount\n     */\n    function calculateRedemption(address debtor, uint256 nusdAmount) public view returns\n    (uint256 providerFee, uint256 protocolFee, uint256 nusdToProtocol, uint256 nusdToRepay, uint256 nusdToConvert, uint256 collateralReceived) {\n        // providerFee, protocolFee and nusdToConvert are never used.\n        require(nusdAmount > 0, \"redemption should be > 0\");\n        require(getBorrowedOf(debtor) >= nusdAmount, \"nusdAmount cannot surpass providers debt\");\n        uint256 assetPrice = getAssetPrice();\n        uint256 providerCollateralRatio = (depositedAsset[debtor] * assetPrice * 10_000) / getBorrowedOf(debtor) / 1e18;\n        (providerFee, protocolFee) = configurator.getRedemptionFee(address(this), providerCollateralRatio);\n        nusdToProtocol = nusdAmount * protocolFee / 10_000;\n        nusdToRepay = nusdAmount - nusdToProtocol;\n        nusdToConvert = nusdToRepay * (10_000 - providerFee) / 10_000;\n        collateralReceived = nusdToConvert * 1e18 / assetPrice;\n    }\n\n    /**\n     * @notice Get the maximum amount of nUSD that can be redeemed from a specified provider\n     */\n    function getRedeemableAmount(address provider) public view returns(uint256) {\n        IConfigurator.RedemptionConfig memory config = configurator.getRedemptionConfig(address(this));\n        if(!config.enabled) return 0;\n        if(getBorrowedOf(provider) == 0) return 0;\n        if(getCollateralRatio(provider) > config.maxCollateralRatio || getCollateralRatio(provider) < 10_000) return 0;\n        return getBorrowedOf(provider);\n    }\n\n    /**\n     * @dev Refresh accrued interest fee before adding totalSupply. Check providers collateralRatio cannot below `safeCollateralRatio`after minting. Collect origination fee.\n     */\n    function _mintnUSD(address _provider, address _onBehalfOf, uint256 _mintAmount) internal virtual {\n        require(!isDepegged(), \"Collateral is depegged, minting paused\");\n        require(poolTotalCirculation + _mintAmount <= configurator.mintVaultMaxSupply(address(this)), \"exceeds cap\");\n        _updateFee(_provider);\n\n        borrowed[_provider] += _mintAmount;\n        uint256 originationFee = getOriginationFee(_mintAmount);\n        nUSD.mint(address(configurator), originationFee);\n        nUSD.mint(_onBehalfOf, _mintAmount - originationFee);\n        poolTotalCirculation += _mintAmount;\n        require(_checkHealth(_provider), \"user is unhealthy after mint\");\n        emit Mint(_provider, _onBehalfOf, _mintAmount, originationFee, block.timestamp);\n    }\n\n    /**\n     * @dev Calculate origination fee based on pool utilization.\n     */\n    function getOriginationFee(uint256 _mintAmount) public view returns(uint256) {\n        (uint256 minOriginationFee, uint256 maxOriginationFee) = configurator.getOriginationFee(address(this));\n        uint256 poolUtilization = (poolTotalCirculation + _mintAmount) * 1e18 / configurator.mintVaultMaxSupply(address(this));\n        return (maxOriginationFee - minOriginationFee) * poolUtilization * _mintAmount / 1e18 / 10000;\n    }\n\n    /**\n     * @notice Burn _provideramount nUSD to payback minted nUSD for _onBehalfOf.\n     * @dev Refresh accrued interest fee before reducing nUSDCirculation.\n     */\n    function _repay(address _provider, address _onBehalfOf, uint256 _amount) internal virtual {\n        // _amount can be more than the amount owed, and the excess will be ignored.\n        _updateFee(_onBehalfOf);\n        uint256 _feeStored = feeStored[_onBehalfOf];\n        uint256 _toRepay = _min(borrowed[_onBehalfOf] + _feeStored, _amount);\n\n        if(_toRepay > _feeStored) {\n            if(_feeStored > 0) {\n                nUSD.transferFrom(_provider, address(configurator), _feeStored);\n                feeStored[_onBehalfOf] = 0;\n            }\n            // First we repay the fees, then principal with the rest\n            nUSD.burn(_provider, _toRepay - _feeStored);\n            borrowed[_onBehalfOf] -= _toRepay - _feeStored;\n            poolTotalCirculation -= _toRepay - _feeStored;\n        } else {\n            // The user provided an amount to repay below the fees owed, so we only repay fees and no principal.\n            nUSD.transferFrom(_provider, address(configurator), _toRepay);\n            feeStored[_onBehalfOf] = _feeStored - _toRepay;\n        }\n        emit Burn(_provider, _onBehalfOf, _toRepay, block.timestamp);\n    }\n\n    function _withdraw(address _provider, address _onBehalfOf, uint256 _amount) internal virtual {\n        require(depositedAsset[_provider] >= _amount, \"Withdraw amount exceeds deposited amount.\");\n        depositedAsset[_provider] -= _amount;\n        collateralAsset.safeTransfer(_onBehalfOf, _amount);\n        if (getBorrowedOf(_provider) > 0) {\n            require(_checkHealth(_provider), \"User is unhealthy after withdraw\");\n        }\n        emit WithdrawAsset(_provider, address(collateralAsset), _onBehalfOf, _amount, block.timestamp);\n    }\n\n    /**\n     * @param user The address of the user.\n     * @dev Get USD value of current collateral asset and minted nUSD through price oracle / Collateral asset USD value must higher than safe Collateral Ratio.\n     * @return true if the user is healthy, false otherwise.\n     */\n    function _checkHealth(address user) internal view returns(bool) {\n        uint256 price = getAssetPrice();\n        if ((depositedAsset[user] * price * 10_000) < (getBorrowedOf(user) * configurator.getSafeCollateralRatio(address(this)) * 1e18 / 10_000)) {\n            return false;\n        } else {\n            return true;\n        }\n    }\n\n    function _updateFee(address user) internal {\n        if (block.timestamp > feeUpdatedAt[user]) {\n            feeStored[user] += _newFee(user);\n            feeUpdatedAt[user] = block.timestamp;\n        }\n    }\n\n    function _newFee(address user) internal view returns (uint256) {\n        uint256 secondsInYear = 86_400 * 365;\n        uint256 secondsSinceLastFee = block.timestamp - feeUpdatedAt[user];\n        return borrowed[user] * configurator.borrowApr(address(this)) * secondsSinceLastFee / secondsInYear / 10_000;\n    }\n\n    /**\n    * @dev Return configured oracle address\n    */\n    function getZkOracle() public view returns (address) {\n        return configurator.zkOracleAddress(address(collateralAsset));\n    }\n\n    /**\n     * @dev Return rate of collateral asset in ETH terms through zkOracle.\n     */\n    function getMarketRate() public view returns (uint256) {\n        IZkOracle zkOracle = IZkOracle(getZkOracle());\n        return zkOracle.getMarketRate();\n    }\n\n    /**\n     * @dev Return redemption rate of collateral asset in ETH terms through zkOracle.\n     */\n    function getRedemptionRate() public view returns (uint256) {\n        IZkOracle zkOracle = IZkOracle(getZkOracle());\n        return zkOracle.getRedemptionRate();\n    }\n\n    /**\n     * @dev Return value of collateral asset in underlying terms through zkOracle.\n     * @notice This will have a market rate and also redemption rate\n     */\n    function getAssetToUnderlyingRate() public view returns (uint256) {\n        uint256 redemptionRate = getRedemptionRate();\n\n        if(configurator.useMarketRate(address(this))) {\n            uint256 marketRate = getMarketRate();\n            if(marketRate == 0) {\n                return redemptionRate; //In case market price oracle is broken, default to redemptionRate\n            } else { // If chainlink prices flash crash below minAnswer, you will get stale prices. I'm not sure you can do much about that.\n                return _min(marketRate, redemptionRate); //even if marketRate is toggled, don't allow over-peg valuation\n            }\n        } else {\n            return redemptionRate;\n        }\n    }\n\n    /**\n     * @dev Check if the collateral asset is depegged according to threshold set in configurator\n     */\n    function isDepegged() public view returns (bool) {\n        uint256 marketRate = getMarketRate();\n        if(marketRate == 0) {\n            return false; //if market rate oracle is zero, presume market rate is not configured and take no action\n        }\n        uint256 redemptionRate = getRedemptionRate();\n        uint256 minMarketRate = redemptionRate * (10_000 - configurator.getDepegThreshold(address(this))) / 10_000;\n        return marketRate < minMarketRate;\n    }\n\n    /**\n     * @dev Return value of underlying asset in USD terms.\n     * @notice This *should* only be market rate, returns chainlink ETH price as default\n     */\n    function getUnderlyingToUsdPrice() public view returns (uint256) {\n        (,int price, , , ) = AggregatorV3Interface(configurator.etherOracle()).latestRoundData();\n        return uint256(price) * 1e10;\n    }\n\n    /**\n     * @dev Get USD value of collateral asset\n     */\n    function getAssetPrice() public view returns (uint256) {\n        return getAssetToUnderlyingRate() * getUnderlyingToUsdPrice() / 1e18;\n    }\n\n    /**\n     * @dev Returns the current borrowing amount for the user, including borrowed shares and accumulated fees.\n     * @param user The address of the user.\n     * @return The total borrowing amount for the user.\n     */\n    function getBorrowedOf(address user) public view returns (uint256) {\n        return borrowed[user] + feeStored[user] + _newFee(user);\n    }\n\n    function getPoolTotalCirculation() public view returns (uint256) {\n        return poolTotalCirculation;\n    }\n\n    function getAsset() external view returns (address) {\n        return address(collateralAsset);\n    }\n\n    //View functions - frontend friendly\n    function getCollateralRatio(address user) public view returns (uint256) {\n        if (getBorrowedOf(user) == 0) return 10_000 * 1e18; //really big number\n        return (depositedAsset[user] * getAssetPrice() * 10_000) / getBorrowedOf(user) / 1e18;\n    }\n\n    function isHealthy(address user) external view returns(bool) {\n        return _checkHealth(user);\n    }\n\n    function getOverallCollateralRatio() public view returns (uint256) {\n        return (totalDepositedAsset() * getAssetPrice() * 10_000) / poolTotalCirculation / 1e18;\n    }\n\n    function getLiquidateableAmount(address user) public view returns (uint256 collateralAmount, uint256 nUsdAmount) {\n        if (getCollateralRatio(user) > configurator.getSafeCollateralRatio(address(this))) return (0, 0);\n        collateralAmount = depositedAsset[user] / 2;\n        nUsdAmount = collateralAmount * getAssetPrice() / 1e18;\n    }\n\n    function getLiquidateFund(address user) public view returns (uint256 nusdAmount) {\n        InUSD token = InUSD(configurator.nUSD());\n        uint256 approval = token.allowance(user, address(this));\n        if (approval == 0) return 0;\n        uint256 bal = token.balanceOf(user);\n        nusdAmount = approval > bal ? bal : approval; // You have a _min function\n    }\n\n    function getWithdrawableAmount(address user) public view returns (uint256) {\n        if (getBorrowedOf(user) == 0)\n            return depositedAsset[user];\n        uint256 safeCollateralRatio = configurator.getSafeCollateralRatio(address(this));\n        if (getCollateralRatio(user) <= safeCollateralRatio) return 0;\n        return depositedAsset[user] * (getCollateralRatio(user) - safeCollateralRatio) / getCollateralRatio(user);\n    }\n\n    function roomToCap() public view returns (uint256) {\n        if(poolTotalCirculation >= configurator.mintVaultMaxSupply(address(this))) return 0; //deal with case where it's above cap\n        return configurator.mintVaultMaxSupply(address(this)) - poolTotalCirculation;\n    }\n\n    function getMaxMintableAmountWithDeposit(address user, uint256 deposit) public view returns (uint256 nusdAmount) {\n        uint256 newDepositedAmount = depositedAsset[user] + deposit;\n        uint256 safeCollateralRatio = configurator.getSafeCollateralRatio(address(this));\n        uint256 userBorrow = getBorrowedOf(user);\n        uint256 cap = configurator.mintVaultMaxSupply(address(this));\n        uint256 maxBorrowAtSafeRatio = newDepositedAmount * getAssetPrice() * 10_000 / safeCollateralRatio / 1e18;\n        uint256 effectiveMax = _min(maxBorrowAtSafeRatio, cap);\n\n        if(userBorrow >= effectiveMax) {\n            return 0; //if user has already borrowed more than the max, then no mintable amount\n        } else {\n            uint256 mintMax = effectiveMax - userBorrow;\n            return mintMax - getOriginationFee(mintMax);\n        }\n    }\n\n    function getTVL() public view returns (uint256) {\n        return totalDepositedAsset() * getAssetPrice() / 1e18;\n    }\n\n    function _min(uint256 _a, uint256 _b) private pure returns (uint256) {\n        return _a < _b ? _a : _b;\n    }\n\n    //MultiRewards farming functionality\n    //Modified from https://github.com/curvefi/multi-rewards\n    //staked asset is replaced with deposited collateral (depositedOf[user])\n    //access control is managed via rewardManager as specified in configurator\n\n    //views for multirewards\n    function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) {\n        return _min(block.timestamp, rewardData[_rewardsToken].periodFinish);\n    }\n\n    //total balance of collateral asset\n    function _totalSupply() internal view returns(uint256) {\n        return totalDepositedAsset();\n    }\n\n    function rewardPerToken(address _rewardsToken) public view returns (uint256) {\n        if (_totalSupply() == 0) {\n            return rewardData[_rewardsToken].rewardPerTokenStored;\n        }\n        return rewardData[_rewardsToken].rewardPerTokenStored +\n            (lastTimeRewardApplicable(_rewardsToken) - rewardData[_rewardsToken].lastUpdateTime) *\n            rewardData[_rewardsToken].rewardRate * 1e18 / _totalSupply();\n    }\n\n    function earned(address account, address _rewardsToken) public view returns (uint256) {\n        return (depositedAsset[account] * (rewardPerToken(_rewardsToken) - userRewardPerTokenPaid[account][_rewardsToken])) /\n        1e18 + rewards[account][_rewardsToken];\n    }\n\n    function getRewardTokens() external view returns (address[] memory) {\n        return rewardTokens;\n    }\n\n    function getRewardForDuration(address _rewardsToken) external view returns (uint256) {\n        return rewardData[_rewardsToken].rewardRate * rewardData[_rewardsToken].rewardsDuration;\n    }\n\n    //multiRewards restricted functions\n    function addReward(address _rewardsToken, uint256 _rewardsDuration) public onlyRewardManager {\n        require(_rewardsToken != address(collateralAsset) && _rewardsToken != address(nUSD), \"Reward cannot be collateral asset or nUSD\");\n        require(_rewardsDuration > 0, \"Reward duration must be non-zero\");\n        require(rewardData[_rewardsToken].rewardsDuration == 0, \"Reward already exists\");\n        rewardTokens.push(_rewardsToken);\n        rewardData[_rewardsToken].rewardsDuration = _rewardsDuration;\n    }\n\n    function notifyRewardAmount(address _rewardsToken, uint256 reward) external onlyRewardManager updateReward(address(0)) {\n        require(rewardData[_rewardsToken].rewardsDuration != 0, \"Reward does not exist, addReward first\");\n        IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), reward);\n        if (block.timestamp >= rewardData[_rewardsToken].periodFinish) {\n            rewardData[_rewardsToken].rewardRate = reward / rewardData[_rewardsToken].rewardsDuration;\n        } else {\n            uint256 remaining = rewardData[_rewardsToken].periodFinish - block.timestamp;\n            uint256 leftover = remaining * rewardData[_rewardsToken].rewardRate;\n            rewardData[_rewardsToken].rewardRate = (reward + leftover) / rewardData[_rewardsToken].rewardsDuration;\n        }\n        rewardData[_rewardsToken].lastUpdateTime = block.timestamp;\n        rewardData[_rewardsToken].periodFinish = block.timestamp + rewardData[_rewardsToken].rewardsDuration;\n        emit RewardAdded(reward);\n    }\n\n    function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyRewardManager {\n        require(tokenAddress != address(collateralAsset) && tokenAddress != address(nUSD), \"Cannot withdraw collateral asset or nUSD\");\n        require(rewardData[tokenAddress].lastUpdateTime == 0, \"Cannot withdraw reward token\");\n        IERC20(tokenAddress).safeTransfer(msg.sender, tokenAmount);\n        emit Recovered(tokenAddress, tokenAmount);\n    }\n\n    function setRewardsDuration(address _rewardsToken, uint256 _rewardsDuration) external onlyRewardManager {\n        require(block.timestamp > rewardData[_rewardsToken].periodFinish, \"Reward period still active\");\n        require(_rewardsDuration > 0, \"Reward duration must be non-zero\");\n        rewardData[_rewardsToken].rewardsDuration = _rewardsDuration;\n        emit RewardsDurationUpdated(_rewardsToken, rewardData[_rewardsToken].rewardsDuration);\n    }\n\n    //modifier\n    modifier updateReward(address account) {\n        for (uint256 i = 0; i < rewardTokens.length; ) {\n            address token = rewardTokens[i];\n            rewardData[token].rewardPerTokenStored = rewardPerToken(token);\n            rewardData[token].lastUpdateTime = lastTimeRewardApplicable(token);\n            if (account != address(0)) {\n                rewards[account][token] = earned(account, token);\n                userRewardPerTokenPaid[account][token] = rewardData[token].rewardPerTokenStored;\n            }\n            unchecked {i = i+1;}\n        }\n        _;\n    }\n\n    modifier onlyRewardManager() {\n        require(configurator.isRewardManager(msg.sender), \"Not reward manager\");\n        _;\n    }\n\n    //multirewards mutative functions\n    function getReward() public nonReentrant updateReward(msg.sender) {\n        for (uint256 i = 0; i < rewardTokens.length; ) {\n            address _rewardsToken = rewardTokens[i];\n            uint256 reward = rewards[msg.sender][_rewardsToken];\n            if (reward > 0) {\n                rewards[msg.sender][_rewardsToken] = 0;\n                IERC20(_rewardsToken).safeTransfer(msg.sender, reward);\n                emit RewardPaid(msg.sender, _rewardsToken, reward);\n            }\n            unchecked { i = i+1; }\n        }\n    }\n}"
      },
      "node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n     * Revert on invalid signature.\n     */\n    function safePermit(\n        IERC20Permit token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return\n            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n    }\n}\n"
      },
      "contracts/unstable/interfaces/InUSD.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\ninterface InUSD {\n    function totalSupply() external view returns (uint256);\n    function balanceOf(address account) external view returns (uint256);\n    function transfer(address to, uint256 amount) external returns (bool);\n    function allowance(address owner, address spender) external view returns (uint256);\n    function approve(address spender, uint256 amount) external returns (bool);\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n    function mint(\n        address to,\n        uint256 amount\n    ) external returns (bool);\n    function burn(\n        address account,\n        uint256 amount\n    ) external returns (bool);\n}"
      },
      "contracts/unstable/interfaces/IConfigurator.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\ninterface IConfigurator {\n    struct OriginationFeeConfig {\n        uint16 minOriginationFee; // fee at 0% utilization\n        uint16 maxOriginationFee; // fee at 100% utilization\n    }\n\n    struct RedemptionConfig {\n        bool enabled; //whether a vault can redeem\n        uint16 baseFee; // base fee for redemption\n        uint16 maxMultiplier; // fee for redemption\n        uint16 maxCollateralRatio; // collateral ratio for max fee multiplier\n        uint16 providerShare; // share of redemption fee that goes to provider\n    }\n\n    function zkOracleAddress(address vault) external view returns(address);\n    function vaultEnabled(address vault) external view returns(bool);\n    function vaultMintPaused(address vault) external view returns(bool);\n    function vaultBurnPaused(address vault) external view returns(bool);\n    function mintVaultMaxSupply(address vault) external view returns(uint256);\n    function getBadCollateralRatio(address vault) external view returns(uint256);\n    function getSafeCollateralRatio(address vault) external view returns(uint256);\n    function borrowApr(address vault) external view returns(uint256);\n    function getKeeperReward(address vault) external view returns(uint256);\n    function getOriginationFee(address vault) external view returns(uint256, uint256);\n    function getRedemptionFee(address vault, uint256 collateralRatio) external view returns(uint256, uint256);\n    function getRedemptionConfig(address vault) external view returns(RedemptionConfig memory);\n    function getDepegThreshold(address vault) external view returns(uint256);\n    function useMarketRate(address vault) external view returns(bool);\n\n    function treasury() external view returns(address);\n    function flashloanFee() external view returns(uint256);\n    function owner() external view returns (address);\n    function admin() external view returns(address);\n    function nUSD() external view returns(address);\n    function etherOracle() external view returns(address);\n    function getAllVaults() external view returns(address[] memory);\n    function getAllCollaterals() external view returns(address[] memory);\n    function isRewardManager(address user) external view returns(bool);\n}"
      },
      "contracts/unstable/interfaces/IZkOracle.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\ninterface IZkOracle {\n    //@notice returns the address of the asset\n    function assetAddress() external view returns (address);\n    //@notice returns the market rate of the collateral in terms of underlying\n    function getMarketRate() external view returns (uint256);\n    //@notice returns the backing or redemption rate of the collateral in terms of underlying\n    function getRedemptionRate() external view returns (uint256);\n}"
      },
      "node_modules/@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface AggregatorV3Interface {\n  function decimals() external view returns (uint8);\n\n  function description() external view returns (string memory);\n\n  function version() external view returns (uint256);\n\n  function getRoundData(uint80 _roundId)\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n\n  function latestRoundData()\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n}\n"
      },
      "node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == _ENTERED;\n    }\n}\n"
      },
      "node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
      },
      "node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "node_modules/@openzeppelin/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     *\n     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "@chainlink/=node_modules/@chainlink/",
        "@eth-optimism/=node_modules/@eth-optimism/",
        "@layerzerolabs/=node_modules/@layerzerolabs/",
        "@openzeppelin-3/=node_modules/@layerzerolabs/solidity-examples/node_modules/@openzeppelin-3/",
        "@openzeppelin/=node_modules/@openzeppelin/",
        "@redstone-finance/=node_modules/@redstone-finance/",
        "@uniswap/=node_modules/@uniswap/",
        "erc721a/=node_modules/erc721a/",
        "eth-gas-reporter/=node_modules/eth-gas-reporter/",
        "forge-std/=lib/forge-std/src/",
        "hardhat-deploy/=node_modules/hardhat-deploy/",
        "hardhat/=node_modules/hardhat/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 9999
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "viaIR": false,
      "libraries": {}
    }
  }}