creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "contracts/liquidator/FlashLiquidator.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.24;\n\nimport {NotionalProxy} from \"@interfaces/notional/NotionalProxy.sol\";\nimport {IStrategyVault} from \"@interfaces/notional/IStrategyVault.sol\";\nimport {IERC7399} from \"@interfaces/IERC7399.sol\";\nimport {WETH9} from \"@interfaces/WETH9.sol\";\nimport {TokenUtils, IERC20} from \"@contracts/utils/TokenUtils.sol\";\nimport {Constants} from \"@contracts/global/Constants.sol\";\nimport {\n    Token,\n    VaultAccount,\n    BatchLend,\n    BalanceActionWithTrades,\n    TradeActionType,\n    DepositActionType,\n    PortfolioAsset\n} from \"@contracts/global/Types.sol\";\nimport {BoringOwnable} from \"./BoringOwnable.sol\";\nimport {Deployments} from \"@deployments/Deployments.sol\";\n\ncontract FlashLiquidator is BoringOwnable {\n    using TokenUtils for IERC20;\n    uint16 internal constant ONLY_VAULT_DELEVERAGE = 1 << 5;\n\n    uint256 internal constant MAX_CURRENCIES = 3;\n\n    NotionalProxy public immutable NOTIONAL;\n\n    enum LiquidationType {\n        UNKNOWN,\n        DELEVERAGE_VAULT_ACCOUNT,\n        LIQUIDATE_CASH_BALANCE\n    }\n\n    struct LiquidationParams {\n        LiquidationType liquidationType;\n        address vault;\n        address[] accounts;\n        bytes redeemData;\n        // NOTE: these two are only used for cash liquidation\n        uint16 currencyId;\n        uint16 currencyIndex;\n    }\n\n    error ErrInvalidCurrencyIndex(uint16 index);\n\n    constructor() {\n        // Make sure we are using the correct Deployments lib\n        uint256 chainId;\n        assembly { chainId := chainid() }\n        require(Deployments.CHAIN_ID == chainId);\n\n        NOTIONAL = Deployments.NOTIONAL;\n        owner = msg.sender;\n        uint16 maxCurrencyId = Deployments.NOTIONAL.getMaxCurrencyId();\n        uint16[] memory currencies = new uint16[](maxCurrencyId);\n        for (uint16 i = 1; i <= maxCurrencyId; i++) currencies[i - 1] = i;\n        enableCurrencies(currencies);\n\n        emit OwnershipTransferred(address(0), owner);\n    }\n\n    function callback(\n        address /* initiator */,\n        address paymentReceiver,\n        address /* asset */,\n        uint256 /* amount */,\n        uint256 fee,\n        bytes calldata data\n    ) external returns (bytes memory) {\n        handleLiquidation(fee, paymentReceiver, data);\n        return \"\";\n    }\n\n    /// @notice Used for profit estimation off chain\n    function estimateProfit(\n        address flashLenderWrapper,\n        address asset,\n        uint256 amount,\n        LiquidationParams calldata params\n    ) external onlyOwner returns (uint256) {\n        uint256 balance = IERC20(asset).balanceOf(address(this));\n        _flashLiquidate(flashLenderWrapper, asset, amount, false, params);\n        return IERC20(asset).balanceOf(address(this)) - balance;\n    }\n\n    function flashLiquidateBatch(\n        address[] calldata flashLenderWrapper,\n        address[] calldata asset,\n        uint256[] calldata amount,\n        LiquidationParams[] calldata params\n    ) external {\n        for (uint256 i; i < asset.length; i++) {\n            _flashLiquidate(flashLenderWrapper[i], asset[i], amount[i], true, params[i]);\n        }\n    }\n\n    /// @notice Primary entry point for the liquidation call\n    function flashLiquidate(\n        address flashLenderWrapper,\n        address asset,\n        uint256 amount,\n        LiquidationParams calldata params\n    ) external {\n        _flashLiquidate(flashLenderWrapper, asset, amount, true, params);\n    }\n\n    function _flashLiquidate(address flashLender, address asset, uint256 amount, bool withdraw, LiquidationParams calldata params)\n        internal\n    {\n        IERC7399(flashLender).flash(\n            address(this), asset, amount, abi.encode(asset, amount, withdraw, params), this.callback\n        );\n    }\n\n    /// @notice This is the primary entry point after the flash lender transfers the funds\n    function handleLiquidation(uint256 fee, address paymentReceiver, bytes memory data) internal {\n        (\n            address asset,\n            uint256 amount,\n            bool withdraw,\n            LiquidationParams memory params\n        ) = abi.decode(data, (address, uint256, bool, LiquidationParams));\n        bool isWETH = asset == address(Deployments.WETH);\n        bool useVaultDeleverage = (\n            NOTIONAL.getVaultConfig(params.vault).flags & ONLY_VAULT_DELEVERAGE == ONLY_VAULT_DELEVERAGE\n        );\n\n        // Notional uses ETH internally but flash lenders may send WETH\n        if (isWETH) _unwrapETH(amount);\n\n        // Liquidator will liquidate the all the accounts in batch\n        uint256 vaultSharesFromLiquidation;\n        for (uint256 i; i < params.accounts.length; i++) {\n            address account = params.accounts[i];\n            (\n                VaultAccount memory vaultAccount,\n                int256 accruedFeeInUnderlying\n            ) = _settleAccountIfNeeded(account, params.vault);\n\n            if (params.liquidationType == LiquidationType.DELEVERAGE_VAULT_ACCOUNT) {\n                // Accrue the total vault shares received by deleveraging\n                vaultSharesFromLiquidation += _deleverageVaultAccount(\n                    account, params.vault, useVaultDeleverage, accruedFeeInUnderlying, isWETH\n                );\n            } else if (params.liquidationType == LiquidationType.LIQUIDATE_CASH_BALANCE) {\n                // NOTE: cannot do batch cash liquidations at this point\n                require(params.accounts.length == 1);\n                _liquidateCashBalance(vaultAccount, params, asset, useVaultDeleverage);\n            }\n        }\n\n        // Exit all the vault shares that we've accumulated during liquidation\n        if (0 < vaultSharesFromLiquidation) {\n            NOTIONAL.exitVault(\n                address(this),\n                params.vault,\n                address(this),\n                vaultSharesFromLiquidation,\n                0, 0, params.redeemData\n            );\n        }\n\n        // Rewrap ETH for repayment\n        if (isWETH) _wrapETH();\n\n        uint256 currentBalance = IERC20(asset).balanceOf(address(this));\n        // force revert if there is no profit\n        require(currentBalance > amount);\n\n        // Send profits back to the owner\n        if (withdraw) {\n            _withdrawToOwner(asset, currentBalance - amount - fee);\n        }\n\n        // Repay the flash lender\n        IERC20(asset).checkTransfer(paymentReceiver, amount + fee);\n    }\n\n    /// @notice Used to maintain approvals for various currencies, called initially in the constructor\n    function enableCurrencies(uint16[] memory currencies) public onlyOwner {\n        for (uint256 i; i < currencies.length; i++) {\n            (/* Token memory assetToken */, Token memory underlyingToken) = NOTIONAL.getCurrency(currencies[i]);\n            IERC20(underlyingToken.tokenAddress).checkApprove(address(NOTIONAL), type(uint256).max);\n        }\n    }\n\n    /// @notice Used via static call on the liquidation bot to get parameters for liquidation\n    function getOptimalDeleveragingParams(\n        address account, address vault\n    ) external returns (uint16 currencyIndex, int256 maxUnderlying) {\n        (/* */, int256 accruedFeeInUnderlying) = _settleAccountIfNeeded(account, vault);\n        return _getOptimalDeleveragingParams(account, vault, accruedFeeInUnderlying);\n    }\n\n    /*** INTERNAL METHODS ***/\n\n    function _settleAccountIfNeeded(\n        address account, address vault\n    ) private returns (VaultAccount memory vaultAccount, int256 accruedFeeInUnderlying) {\n        (\n            vaultAccount,\n            accruedFeeInUnderlying\n        ) = NOTIONAL.getVaultAccountWithFeeAccrual(account, vault);\n\n        if (vaultAccount.maturity != 0 && vaultAccount.maturity < block.timestamp) {\n            NOTIONAL.settleVaultAccount(account, vault);\n        }\n    }\n\n    function _getOptimalDeleveragingParams(\n        address account,\n        address vault,\n        int256 accruedFeeInUnderlying\n    ) private view returns (uint16 currencyIndex, int256 maxUnderlying) {\n        (\n            /* VaultAccountHealthFactors memory h */,\n            int256[3] memory maxLiquidatorDepositUnderlying,\n            uint256[3] memory vaultSharesToLiquidator\n        ) = NOTIONAL.getVaultAccountHealthFactors(account, vault);\n\n        currencyIndex = vaultSharesToLiquidator[0] < vaultSharesToLiquidator[1] ? \n            (vaultSharesToLiquidator[1] < vaultSharesToLiquidator[2] ? 2 : 1) :\n            (vaultSharesToLiquidator[0] < vaultSharesToLiquidator[2] ? 2 : 0); \n        maxUnderlying = maxLiquidatorDepositUnderlying[currencyIndex];\n\n        // If there is an accrued fee, add it to the max underlying to ensure that dust\n        // amounts do not cause liquidations to fail.\n        if (maxUnderlying > 0) maxUnderlying = maxUnderlying + accruedFeeInUnderlying;\n    }\n\n    function _deleverageVaultAccount(\n        address account,\n        address vault,\n        bool useVaultDeleverage,\n        int256 accruedFeeInUnderlying,\n        bool isETH\n    ) private returns (uint256 vaultSharesFromLiquidation) {\n        (uint16 currencyIndex, int256 maxUnderlying) = _getOptimalDeleveragingParams(\n            account, vault, accruedFeeInUnderlying\n        );\n        // Short circuit accounts where no liquidation is necessary\n        if (maxUnderlying == 0) return 0;\n\n        uint256 msgValue = isETH ? uint256(maxUnderlying * 1e10) : 0;\n        if (useVaultDeleverage) {\n            (\n                vaultSharesFromLiquidation, /* */\n            ) = IStrategyVault(vault).deleverageAccount{value: msgValue}(\n                account, vault, address(this), currencyIndex, maxUnderlying\n            );\n        } else {\n            (\n                vaultSharesFromLiquidation, /* */\n            ) = NOTIONAL.deleverageAccount{value: msgValue}(\n                account, vault, address(this), currencyIndex, maxUnderlying\n            );\n        }\n    }\n\n    function _liquidateCashBalance(\n        VaultAccount memory vaultAccount,\n        LiquidationParams memory params,\n        address asset,\n        bool useVaultDeleverage\n    ) private {\n        require(vaultAccount.maturity != Constants.PRIME_CASH_VAULT_MATURITY);\n\n        int256 cashBalance;\n        if (params.currencyIndex == 0) {\n            cashBalance = vaultAccount.tempCashBalance;\n        } else if (params.currencyIndex < MAX_CURRENCIES) {\n            (/* */, /* */, int256[2] memory accountSecondaryCashHeld) = \n                NOTIONAL.getVaultAccountSecondaryDebt(vaultAccount.account, params.vault);\n            cashBalance = accountSecondaryCashHeld[params.currencyIndex - 1];\n        } else {\n            revert ErrInvalidCurrencyIndex(params.currencyIndex);\n        }\n\n        (int256 fCashDeposit, /* */)  = NOTIONAL.getfCashRequiredToLiquidateCash(\n            params.currencyId, vaultAccount.maturity, cashBalance\n        );\n\n        _lend(params.currencyId, vaultAccount.maturity, uint256(fCashDeposit), 0, asset);\n\n        if (useVaultDeleverage) {\n            IStrategyVault(params.vault).liquidateVaultCashBalance(\n                vaultAccount.account, params.vault, address(this), params.currencyIndex, fCashDeposit\n            );\n        } else {\n            NOTIONAL.liquidateVaultCashBalance(\n                vaultAccount.account, params.vault, address(this), params.currencyIndex, fCashDeposit\n            );\n        }\n\n        // Withdraw all cash held\n        NOTIONAL.withdraw(params.currencyId, type(uint88).max, true);\n    }\n\n    function _lend(\n        uint16 currencyId,\n        uint256 maturity,\n        uint256 fCashAmount,\n        uint32 minLendRate,\n        address asset\n    ) private {\n        // ETH prevents usage of BatchLend here. This also prevents batch cash liquidations\n        BalanceActionWithTrades[] memory action = new BalanceActionWithTrades[](1);\n        action[0].actionType = DepositActionType.DepositUnderlying;\n        action[0].depositActionAmount = currencyId == Constants.ETH_CURRENCY_ID ? \n            address(this).balance : \n            IERC20(asset).balanceOf(address(this));\n        action[0].currencyId = currencyId;\n        action[0].withdrawEntireCashBalance = true;\n        action[0].redeemToUnderlying = true;\n        uint256 marketIndex = NOTIONAL.getMarketIndex(maturity, block.timestamp);\n\n        action[0].trades = new bytes32[](1);\n        action[0].trades[0] = bytes32(\n            (uint256(uint8(TradeActionType.Lend)) << 248) |\n            (uint256(marketIndex) << 240) |\n            (uint256(fCashAmount) << 152) |\n            (uint256(minLendRate) << 120)\n        );\n        \n        uint256 msgValue;\n        if (currencyId == Constants.ETH_CURRENCY_ID) {\n            msgValue = action[0].depositActionAmount;\n        }\n\n        NOTIONAL.batchBalanceAndTradeAction{value: msgValue}(address(this), action);\n    }\n\n    function _withdrawToOwner(address token, uint256 amount) private {\n        if (amount == type(uint256).max) {\n            amount = IERC20(token).balanceOf(address(this));\n        }\n        if (amount > 0) {\n            IERC20(token).checkTransfer(owner, amount);\n        }\n    }\n\n    function _wrapETH() private {\n        Deployments.WETH.deposit{value: address(this).balance}();\n    }\n\n    function _unwrapETH(uint256 amount) private {\n        Deployments.WETH.withdraw(amount);\n    }\n\n    function withdrawToOwner(address token, uint256 amount) external onlyOwner {\n        _withdrawToOwner(token, amount);\n    }\n\n    function wrapETH() external onlyOwner {\n        _wrapETH();\n    }\n\n    receive() external payable {} \n}"
      },
      "interfaces/notional/NotionalProxy.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\npragma abicoder v2;\n\nimport \"../../contracts/global/Types.sol\";\nimport \"./nTokenERC20.sol\";\nimport \"./nERC1155Interface.sol\";\nimport \"./NotionalGovernance.sol\";\nimport \"./NotionalCalculations.sol\";\nimport \"./NotionalViews.sol\";\nimport \"./NotionalTreasury.sol\";\nimport {IVaultController} from \"./IVaultController.sol\";\n\ninterface NotionalProxy is\n    nTokenERC20,\n    nERC1155Interface,\n    NotionalGovernance,\n    NotionalTreasury,\n    NotionalCalculations,\n    NotionalViews,\n    IVaultController\n{\n    /** User trading events */\n    event CashBalanceChange(\n        address indexed account,\n        uint16 indexed currencyId,\n        int256 netCashChange\n    );\n    event nTokenSupplyChange(\n        address indexed account,\n        uint16 indexed currencyId,\n        int256 tokenSupplyChange\n    );\n    event MarketsInitialized(uint16 currencyId);\n    event SweepCashIntoMarkets(uint16 currencyId, int256 cashIntoMarkets);\n    event SettledCashDebt(\n        address indexed settledAccount,\n        uint16 indexed currencyId,\n        address indexed settler,\n        int256 amountToSettleAsset,\n        int256 fCashAmount\n    );\n    event nTokenResidualPurchase(\n        uint16 indexed currencyId,\n        uint40 indexed maturity,\n        address indexed purchaser,\n        int256 fCashAmountToPurchase,\n        int256 netAssetCashNToken\n    );\n    event LendBorrowTrade(\n        address indexed account,\n        uint16 indexed currencyId,\n        uint40 maturity,\n        int256 netAssetCash,\n        int256 netfCash\n    );\n    event AddRemoveLiquidity(\n        address indexed account,\n        uint16 indexed currencyId,\n        uint40 maturity,\n        int256 netAssetCash,\n        int256 netfCash,\n        int256 netLiquidityTokens\n    );\n\n    /// @notice Emitted once when incentives are migrated\n    event IncentivesMigrated(\n        uint16 currencyId,\n        uint256 migrationEmissionRate,\n        uint256 finalIntegralTotalSupply,\n        uint256 migrationTime\n    );\n\n    /// @notice Emitted when reserve fees are accrued\n    event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee);\n    /// @notice Emitted whenever an account context has updated\n    event AccountContextUpdate(address indexed account);\n    /// @notice Emitted when an account has assets that are settled\n    event AccountSettled(address indexed account);\n    /// @notice Emitted when an asset rate is settled\n    event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);\n\n    /* Liquidation Events */\n    event LiquidateLocalCurrency(\n        address indexed liquidated,\n        address indexed liquidator,\n        uint16 localCurrencyId,\n        int256 netLocalFromLiquidator\n    );\n\n    event LiquidateCollateralCurrency(\n        address indexed liquidated,\n        address indexed liquidator,\n        uint16 localCurrencyId,\n        uint16 collateralCurrencyId,\n        int256 netLocalFromLiquidator,\n        int256 netCollateralTransfer,\n        int256 netNTokenTransfer\n    );\n\n    event LiquidatefCashEvent(\n        address indexed liquidated,\n        address indexed liquidator,\n        uint16 localCurrencyId,\n        uint16 fCashCurrency,\n        int256 netLocalFromLiquidator,\n        uint256[] fCashMaturities,\n        int256[] fCashNotionalTransfer\n    );\n\n    /** UUPS Upgradeable contract calls */\n    function upgradeTo(address newImplementation) external;\n\n    function upgradeToAndCall(address newImplementation, bytes memory data) external payable;\n\n    function getImplementation() external view returns (address);\n\n    function owner() external view returns (address);\n\n    function pauseRouter() external view returns (address);\n\n    function pauseGuardian() external view returns (address);\n\n    /** Initialize Markets Action */\n    function initializeMarkets(uint16 currencyId, bool isFirstInit) external;\n\n    function sweepCashIntoMarkets(uint16 currencyId) external;\n\n    /** Redeem nToken Action */\n    function nTokenRedeem(\n        address redeemer,\n        uint16 currencyId,\n        uint96 tokensToRedeem_,\n        bool sellTokenAssets,\n        bool acceptResidualAssets\n    ) external returns (int256);\n\n    /** Account Action */\n    function enableBitmapCurrency(uint16 currencyId) external;\n\n    function settleAccount(address account) external;\n\n    function depositUnderlyingToken(\n        address account,\n        uint16 currencyId,\n        uint256 amountExternalPrecision\n    ) external payable returns (uint256);\n\n    function depositAssetToken(\n        address account,\n        uint16 currencyId,\n        uint256 amountExternalPrecision\n    ) external returns (uint256);\n\n    function withdraw(\n        uint16 currencyId,\n        uint88 amountInternalPrecision,\n        bool redeemToUnderlying\n    ) external returns (uint256);\n\n    /** Batch Action */\n    function batchBalanceAction(address account, BalanceAction[] calldata actions) external payable;\n\n    function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions)\n        external\n        payable;\n\n    function batchBalanceAndTradeActionWithCallback(\n        address account,\n        BalanceActionWithTrades[] calldata actions,\n        bytes calldata callbackData\n    ) external payable;\n\n    function batchLend(address account, BatchLend[] calldata actions) external;\n\n    /** Liquidation Action */\n    function calculateLocalCurrencyLiquidation(\n        address liquidateAccount,\n        uint16 localCurrency,\n        uint96 maxNTokenLiquidation\n    ) external returns (int256, int256);\n\n    function liquidateLocalCurrency(\n        address liquidateAccount,\n        uint16 localCurrency,\n        uint96 maxNTokenLiquidation\n    ) external returns (int256, int256);\n\n    function calculateCollateralCurrencyLiquidation(\n        address liquidateAccount,\n        uint16 localCurrency,\n        uint16 collateralCurrency,\n        uint128 maxCollateralLiquidation,\n        uint96 maxNTokenLiquidation\n    )\n        external\n        returns (\n            int256,\n            int256,\n            int256\n        );\n\n    function liquidateCollateralCurrency(\n        address liquidateAccount,\n        uint16 localCurrency,\n        uint16 collateralCurrency,\n        uint128 maxCollateralLiquidation,\n        uint96 maxNTokenLiquidation,\n        bool withdrawCollateral,\n        bool redeemToUnderlying\n    )\n        external\n        returns (\n            int256,\n            int256,\n            int256\n        );\n\n    function calculatefCashLocalLiquidation(\n        address liquidateAccount,\n        uint16 localCurrency,\n        uint256[] calldata fCashMaturities,\n        uint256[] calldata maxfCashLiquidateAmounts\n    ) external returns (int256[] memory, int256);\n\n    function liquidatefCashLocal(\n        address liquidateAccount,\n        uint16 localCurrency,\n        uint256[] calldata fCashMaturities,\n        uint256[] calldata maxfCashLiquidateAmounts\n    ) external returns (int256[] memory, int256);\n\n    function calculatefCashCrossCurrencyLiquidation(\n        address liquidateAccount,\n        uint16 localCurrency,\n        uint16 fCashCurrency,\n        uint256[] calldata fCashMaturities,\n        uint256[] calldata maxfCashLiquidateAmounts\n    ) external returns (int256[] memory, int256);\n\n    function liquidatefCashCrossCurrency(\n        address liquidateAccount,\n        uint16 localCurrency,\n        uint16 fCashCurrency,\n        uint256[] calldata fCashMaturities,\n        uint256[] calldata maxfCashLiquidateAmounts\n    ) external returns (int256[] memory, int256);\n}\n"
      },
      "interfaces/notional/IStrategyVault.sol": {
        "content": "// SPDX-License-Identifier: GPL-v3\npragma solidity >=0.7.6;\n\ninterface IStrategyVault {\n\n    struct StrategyVaultRoles {\n        bytes32 emergencyExit;\n        bytes32 rewardReinvestment;\n        bytes32 staticSlippageTrading;\n    }\n\n    function decimals() external view returns (uint8);\n    function name() external view returns (string memory);\n    function strategy() external view returns (bytes4 strategyId);\n\n    // Tells a vault to deposit some amount of tokens from Notional and mint strategy tokens with it.\n    function depositFromNotional(\n        address account,\n        uint256 depositAmount,\n        uint256 maturity,\n        bytes calldata data\n    ) external payable returns (uint256 strategyTokensMinted);\n\n    // Tells a vault to redeem some amount of strategy tokens from Notional and transfer the resulting asset cash\n    function redeemFromNotional(\n        address account,\n        address receiver,\n        uint256 strategyTokens,\n        uint256 maturity,\n        uint256 underlyingToRepayDebt,\n        bytes calldata data\n    ) external returns (uint256 transferToReceiver);\n\n    function convertStrategyToUnderlying(\n        address account,\n        uint256 strategyTokens,\n        uint256 maturity\n    ) external view returns (int256 underlyingValue);\n\n    function getExchangeRate(uint256 maturity) external view returns (int256);\n\n    function deleverageAccount(\n        address account,\n        address vault,\n        address liquidator,\n        uint16 currencyIndex,\n        int256 depositUnderlyingInternal\n    ) external payable returns (uint256 vaultSharesFromLiquidation, int256 depositAmountPrimeCash);\n\n    function liquidateVaultCashBalance(\n        address account,\n        address vault,\n        address liquidator,\n        uint256 currencyIndex,\n        int256 fCashDeposit\n    ) external returns (int256 cashToLiquidator);\n\n    function convertVaultSharesToPrimeMaturity(\n        address account,\n        uint256 vaultShares,\n        uint256 maturity\n    ) external returns (uint256 primeVaultShares);\n}"
      },
      "interfaces/IERC7399.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @dev Specification for flash lenders compatible with ERC-7399\ninterface IERC7399 {\n    /// @dev The amount of currency available to be lent.\n    /// @param asset The loan currency.\n    /// @return The amount of `asset` that can be borrowed.\n    function maxFlashLoan(address asset) external view returns (uint256);\n\n    /// @dev The fee to be charged for a given loan.\n    /// @param asset The loan currency.\n    /// @param amount The amount of assets lent.\n    /// @return The amount of `asset` to be charged for the loan, on top of the returned principal.\n    function flashFee(address asset, uint256 amount) external view returns (uint256);\n\n    /// @dev Initiate a flash loan.\n    /// @param loanReceiver The address receiving the flash loan\n    /// @param asset The asset to be loaned\n    /// @param amount The amount to loaned\n    /// @param data The ABI encoded user data\n    /// @param callback The address and signature of the callback function\n    /// @return result ABI encoded result of the callback\n    function flash(\n        address loanReceiver,\n        address asset,\n        uint256 amount,\n        bytes calldata data,\n        /// @dev callback. This is a combination of the callback receiver address, and the signature of callback\n        /// function. It is encoded packed as 20 bytes + 4 bytes.\n        /// @dev the return of the callback function is not encoded in the parameter, but must be `returns (bytes\n        /// memory)` for compliance with the standard.\n        /// @param initiator The address that called this function\n        /// @param paymentReceiver The address that needs to receive the amount plus fee at the end of the callback\n        /// @param asset The asset to be loaned\n        /// @param amount The amount to loaned\n        /// @param fee The fee to be paid\n        /// @param data The ABI encoded data to be passed to the callback\n        /// @return result ABI encoded result of the callback\n        function(address, address, address, uint256, uint256, bytes memory) external returns (bytes memory) callback\n    )\n        external\n        returns (bytes memory);\n    /// @dev Alternative entry point for the ERC7399 flash loan, without function pointers. Packs data to convert the\n    /// legacy flash loan into an ERC7399 flash loan. Then it calls the legacy flash loan. Once the flash loan is done,\n    /// checks if there is any return data and returns it.\n    function flash(\n        address loanReceiver,\n        address asset,\n        uint256 amount,\n        bytes calldata initiatorData,\n        address callbackTarget,\n        bytes4 callbackSelector\n    )\n        external\n        returns (bytes memory result);\n}"
      },
      "interfaces/WETH9.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\ninterface WETH9 {\n    function deposit() external payable;\n\n    function withdraw(uint256 wad) external;\n}\n"
      },
      "contracts/utils/TokenUtils.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.24;\n\nimport {IERC20} from \"@interfaces/IERC20.sol\";\nimport {IEIP20NonStandard} from \"@interfaces/IEIP20NonStandard.sol\";\nimport {Deployments} from \"@deployments/Deployments.sol\";\n\nlibrary TokenUtils {\n    error ERC20Error();\n\n    function getDecimals(address token) internal view returns (uint8 decimals) {\n        decimals = (token == Deployments.ETH_ADDRESS || token == Deployments.ALT_ETH_ADDRESS) ?\n            18 : IERC20(token).decimals();\n        require(decimals <= 18);\n    }\n\n    function tokenBalance(address token) internal view returns (uint256) {\n        return\n            token == Deployments.ETH_ADDRESS\n                ? address(this).balance\n                : IERC20(token).balanceOf(address(this));\n    }\n\n    function checkApprove(IERC20 token, address spender, uint256 amount) internal {\n        if (address(token) == address(0)) return;\n\n        IEIP20NonStandard(address(token)).approve(spender, 0);\n        _checkReturnCode();\n        if (amount > 0) {\n            IEIP20NonStandard(address(token)).approve(spender, amount);\n            _checkReturnCode();\n        }\n    }\n\n    function checkRevoke(IERC20 token, address spender) internal {\n        if (address(token) == address(0)) return;\n\n        IEIP20NonStandard(address(token)).approve(spender, 0);\n        _checkReturnCode();\n    }\n\n    function checkTransfer(IERC20 token, address receiver, uint256 amount) internal {\n        IEIP20NonStandard(address(token)).transfer(receiver, amount);\n        _checkReturnCode();\n    }\n\n    // Supports checking return codes on non-standard ERC20 contracts\n    function _checkReturnCode() private pure {\n        bool success;\n        uint256[1] memory result;\n        assembly {\n            switch returndatasize()\n                case 0 {\n                    // This is a non-standard ERC-20\n                    success := 1 // set success to true\n                }\n                case 32 {\n                    // This is a compliant ERC-20\n                    returndatacopy(result, 0, 32)\n                    success := mload(result) // Set `success = returndata` of external call\n                }\n                default {\n                    // This is an excessively non-compliant ERC-20, revert.\n                    revert(0, 0)\n                }\n        }\n\n        if (!success) revert ERC20Error();\n    }\n}"
      },
      "contracts/global/Constants.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\n\n/// @title All shared constants for the Notional system should be declared here.\nlibrary Constants {\n    uint8 internal constant CETH_DECIMAL_PLACES = 8;\n\n    // Token precision used for all internal balances, TokenHandler library ensures that we\n    // limit the dust amount caused by precision mismatches\n    int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;\n    uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18;\n\n    // ETH will be initialized as the first currency\n    address internal constant ETH_ADDRESS = address(0);\n    uint256 internal constant ETH_CURRENCY_ID = 1;\n    uint8 internal constant ETH_DECIMAL_PLACES = 18;\n    int256 internal constant ETH_DECIMALS = 1e18;\n    // Used to prevent overflow when converting decimal places to decimal precision values via\n    // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this\n    // constraint when storing decimal places in governance.\n    uint256 internal constant MAX_DECIMAL_PLACES = 36;\n\n    // Address of the reserve account\n    address internal constant RESERVE = address(0);\n\n    // Most significant bit\n    bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000;\n\n    // Each bit set in this mask marks where an active market should be in the bitmap\n    // if the first bit refers to the reference time. Used to detect idiosyncratic\n    // fcash in the nToken accounts\n    bytes32 internal constant ACTIVE_MARKETS_MASK = (\n        MSB >> ( 90 - 1) | // 3 month\n        MSB >> (105 - 1) | // 6 month\n        MSB >> (135 - 1) | // 1 year\n        MSB >> (147 - 1) | // 2 year\n        MSB >> (183 - 1) | // 5 year\n        MSB >> (211 - 1) | // 10 year\n        MSB >> (251 - 1)   // 20 year\n    );\n\n    // Basis for percentages\n    int256 internal constant PERCENTAGE_DECIMALS = 100;\n    // Max number of traded markets, also used as the maximum number of assets in a portfolio array\n    uint256 internal constant MAX_TRADED_MARKET_INDEX = 7;\n    // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral\n    // for a bitmap portfolio\n    uint256 internal constant MAX_BITMAP_ASSETS = 20;\n    uint256 internal constant FIVE_MINUTES = 300;\n\n    // Internal date representations, note we use a 6/30/360 week/month/year convention here\n    uint256 internal constant DAY = 86400;\n    // We use six day weeks to ensure that all time references divide evenly\n    uint256 internal constant WEEK = DAY * 6;\n    uint256 internal constant MONTH = WEEK * 5;\n    uint256 internal constant QUARTER = MONTH * 3;\n    uint256 internal constant YEAR = QUARTER * 4;\n\n    // These constants are used in DateTime.sol\n    uint256 internal constant DAYS_IN_WEEK = 6;\n    uint256 internal constant DAYS_IN_MONTH = 30;\n    uint256 internal constant DAYS_IN_QUARTER = 90;\n\n    // Offsets for each time chunk denominated in days\n    uint256 internal constant MAX_DAY_OFFSET = 90;\n    uint256 internal constant MAX_WEEK_OFFSET = 360;\n    uint256 internal constant MAX_MONTH_OFFSET = 2160;\n    uint256 internal constant MAX_QUARTER_OFFSET = 7650;\n\n    // Offsets for each time chunk denominated in bits\n    uint256 internal constant WEEK_BIT_OFFSET = 90;\n    uint256 internal constant MONTH_BIT_OFFSET = 135;\n    uint256 internal constant QUARTER_BIT_OFFSET = 195;\n\n    // This is a constant that represents the time period that all rates are normalized by, 360 days\n    uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY;\n    // Number of decimal places that rates are stored in, equals 100%\n    int256 internal constant RATE_PRECISION = 1e9;\n    // One basis point in RATE_PRECISION terms\n    uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000);\n    // Used to when calculating the amount to deleverage of a market when minting nTokens\n    uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT;\n    // Used for scaling cash group factors\n    uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT;\n    // Used for residual purchase incentive and cash withholding buffer\n    uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT;\n\n    // This is the ABDK64x64 representation of RATE_PRECISION\n    // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION)\n    int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000;\n    int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176;\n    // Limit the market proportion so that borrowing cannot hit extremely high interest rates\n    int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100;\n\n    uint8 internal constant FCASH_ASSET_TYPE = 1;\n    // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed)\n    uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2;\n    uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8;\n\n    // Used for converting bool to bytes1, solidity does not have a native conversion\n    // method for this\n    bytes1 internal constant BOOL_FALSE = 0x00;\n    bytes1 internal constant BOOL_TRUE = 0x01;\n\n    // Account context flags\n    bytes1 internal constant HAS_ASSET_DEBT = 0x01;\n    bytes1 internal constant HAS_CASH_DEBT = 0x02;\n    bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000;\n    bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000;\n    bytes2 internal constant UNMASK_FLAGS = 0x3FFF;\n    uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS);\n\n    // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets.\n    int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8;\n    uint256 internal constant SLIPPAGE_LIMIT_PRECISION = 1e8;\n\n    /// @notice Precision for all percentages used by the vault\n    /// 1e4 = 100% (i.e. maxPoolShare)\n    uint16 internal constant VAULT_PERCENT_BASIS = 1e4;\n\n    // Placeholder constant to mark the variable rate prime cash maturity\n    uint40 internal constant PRIME_CASH_VAULT_MATURITY = type(uint40).max;\n\n    uint256 internal constant CHAIN_ID_MAINNET = 1;\n    uint256 internal constant CHAIN_ID_ARBITRUM = 42161;\n}\n"
      },
      "contracts/global/Types.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\npragma abicoder v2;\n\nimport \"@interfaces/chainlink/AggregatorV2V3Interface.sol\";\nimport \"@interfaces/notional/IPrimeCashHoldingsOracle.sol\";\nimport \"@interfaces/notional/AssetRateAdapter.sol\";\n\n/// @notice Different types of internal tokens\n///  - UnderlyingToken: underlying asset for a cToken (except for Ether)\n///  - cToken: Compound interest bearing token\n///  - cETH: Special handling for cETH tokens\n///  - Ether: the one and only\n///  - NonMintable: tokens that do not have an underlying (therefore not cTokens)\n///  - aToken: Aave interest bearing tokens\nenum TokenType {\n    UnderlyingToken,\n    cToken,\n    cETH,\n    Ether,\n    NonMintable,\n    aToken\n}\n\n/// @notice Specifies the different trade action types in the system. Each trade action type is\n/// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the\n/// 32 byte trade action object. The schemas for each trade action type are defined below.\nenum TradeActionType {\n    // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused)\n    Lend,\n    // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused)\n    Borrow,\n    // (uint8 TradeActionType, uint8 MarketIndex, uint88 primeCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)\n    AddLiquidity,\n    // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)\n    RemoveLiquidity,\n    // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused)\n    PurchaseNTokenResidual,\n    // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle)\n    SettleCashDebt\n}\n\n/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades\nenum DepositActionType {\n    // No deposit action\n    None,\n    // Deposit asset cash, depositActionAmount is specified in asset cash external precision\n    DepositAsset,\n    // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token\n    // external precision\n    DepositUnderlying,\n    // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of\n    // nTokens into the account\n    DepositAssetAndMintNToken,\n    // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens\n    DepositUnderlyingAndMintNToken,\n    // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action\n    // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.\n    RedeemNToken,\n    // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in\n    // Notional internal 8 decimal precision.\n    ConvertCashToNToken\n}\n\n/// @notice Used internally for PortfolioHandler state\nenum AssetStorageState {\n    NoChange,\n    Update,\n    Delete,\n    RevertIfStored\n}\n\n/****** Calldata objects ******/\n\n/// @notice Defines a batch lending action\nstruct BatchLend {\n    uint16 currencyId;\n    // True if the contract should try to transfer underlying tokens instead of asset tokens\n    bool depositUnderlying;\n    // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation\n    bytes32[] trades;\n}\n\n/// @notice Defines a balance action for batchAction\nstruct BalanceAction {\n    // Deposit action to take (if any)\n    DepositActionType actionType;\n    uint16 currencyId;\n    // Deposit action amount must correspond to the depositActionType, see documentation above.\n    uint256 depositActionAmount;\n    // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision\n    uint256 withdrawAmountInternalPrecision;\n    // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash\n    // residual left from trading.\n    bool withdrawEntireCashBalance;\n    // If set to true, will redeem asset cash to the underlying token on withdraw.\n    bool redeemToUnderlying;\n}\n\n/// @notice Defines a balance action with a set of trades to do as well\nstruct BalanceActionWithTrades {\n    DepositActionType actionType;\n    uint16 currencyId;\n    uint256 depositActionAmount;\n    uint256 withdrawAmountInternalPrecision;\n    bool withdrawEntireCashBalance;\n    bool redeemToUnderlying;\n    // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation\n    bytes32[] trades;\n}\n\n/****** In memory objects ******/\n/// @notice Internal object that represents settled cash balances\nstruct SettleAmount {\n    uint16 currencyId;\n    int256 positiveSettledCash;\n    int256 negativeSettledCash;\n    PrimeRate presentPrimeRate;\n}\n\n/// @notice Internal object that represents a token\nstruct Token {\n    address tokenAddress;\n    bool hasTransferFee;\n    int256 decimals;\n    TokenType tokenType;\n    uint256 deprecated_maxCollateralBalance;\n}\n\n/// @notice Internal object that represents an nToken portfolio\nstruct nTokenPortfolio {\n    CashGroupParameters cashGroup;\n    PortfolioState portfolioState;\n    int256 totalSupply;\n    int256 cashBalance;\n    uint256 lastInitializedTime;\n    bytes6 parameters;\n    address tokenAddress;\n}\n\n/// @notice Internal object used during liquidation\nstruct LiquidationFactors {\n    address account;\n    // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision\n    int256 netETHValue;\n    // Amount of net local currency asset cash before haircuts and buffers available\n    int256 localPrimeAvailable;\n    // Amount of net collateral currency asset cash before haircuts and buffers available\n    int256 collateralAssetAvailable;\n    // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based\n    // on liquidation type\n    int256 nTokenHaircutPrimeValue;\n    // nToken parameters for calculating liquidation amount\n    bytes6 nTokenParameters;\n    // ETH exchange rate from local currency to ETH\n    ETHRate localETHRate;\n    // ETH exchange rate from collateral currency to ETH\n    ETHRate collateralETHRate;\n    // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required\n    PrimeRate localPrimeRate;\n    // Used during currency liquidations if the account has liquidity tokens\n    CashGroupParameters collateralCashGroup;\n    // Used during currency liquidations if it is only a calculation, defaults to false\n    bool isCalculation;\n}\n\n/// @notice Internal asset array portfolio state\nstruct PortfolioState {\n    // Array of currently stored assets\n    PortfolioAsset[] storedAssets;\n    // Array of new assets to add\n    PortfolioAsset[] newAssets;\n    uint256 lastNewAssetIndex;\n    // Holds the length of stored assets after accounting for deleted assets\n    uint256 storedAssetLength;\n}\n\n/// @notice In memory ETH exchange rate used during free collateral calculation.\nstruct ETHRate {\n    // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle\n    int256 rateDecimals;\n    // The exchange rate from base to ETH (if rate invert is required it is already done)\n    int256 rate;\n    // Amount of buffer as a multiple with a basis of 100 applied to negative balances.\n    int256 buffer;\n    // Amount of haircut as a multiple with a basis of 100 applied to positive balances\n    int256 haircut;\n    // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate\n    // as an incentive given to liquidators.\n    int256 liquidationDiscount;\n}\n\n/// @notice Internal object used to handle balance state during a transaction\nstruct BalanceState {\n    uint16 currencyId;\n    // Cash balance stored in balance state at the beginning of the transaction\n    int256 storedCashBalance;\n    // nToken balance stored at the beginning of the transaction\n    int256 storedNTokenBalance;\n    // The net cash change as a result of asset settlement or trading\n    int256 netCashChange;\n    // Amount of prime cash to redeem and withdraw from the system\n    int256 primeCashWithdraw;\n    // Net token transfers into or out of the account\n    int256 netNTokenTransfer;\n    // Net token supply change from minting or redeeming\n    int256 netNTokenSupplyChange;\n    // The last time incentives were claimed for this currency\n    uint256 lastClaimTime;\n    // Accumulator for incentives that the account no longer has a claim over\n    uint256 accountIncentiveDebt;\n    // Prime rate for converting prime cash balances\n    PrimeRate primeRate;\n}\n\n/// @dev Asset rate used to convert between underlying cash and asset cash\nstruct Deprecated_AssetRateParameters {\n    // Address of the asset rate oracle\n    AssetRateAdapter rateOracle;\n    // The exchange rate from base to quote (if invert is required it is already done)\n    int256 rate;\n    // The decimals of the underlying, the rate converts to the underlying decimals\n    int256 underlyingDecimals;\n}\n\n/// @dev Cash group when loaded into memory\nstruct CashGroupParameters {\n    uint16 currencyId;\n    uint256 maxMarketIndex;\n    PrimeRate primeRate;\n    bytes32 data;\n}\n\n/// @dev A portfolio asset when loaded in memory\nstruct PortfolioAsset {\n    // Asset currency id\n    uint16 currencyId;\n    uint256 maturity;\n    // Asset type, fCash or liquidity token.\n    uint256 assetType;\n    // fCash amount or liquidity token amount\n    int256 notional;\n    // Used for managing portfolio asset state\n    uint256 storageSlot;\n    // The state of the asset for when it is written to storage\n    AssetStorageState storageState;\n}\n\n/// @dev Market object as represented in memory\nstruct MarketParameters {\n    bytes32 storageSlot;\n    uint256 maturity;\n    // Total amount of fCash available for purchase in the market.\n    int256 totalfCash;\n    // Total amount of cash available for purchase in the market.\n    int256 totalPrimeCash;\n    // Total amount of liquidity tokens (representing a claim on liquidity) in the market.\n    int256 totalLiquidity;\n    // This is the previous annualized interest rate in RATE_PRECISION that the market traded\n    // at. This is used to calculate the rate anchor to smooth interest rates over time.\n    uint256 lastImpliedRate;\n    // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while\n    // remaining resistent to flash loan attacks.\n    uint256 oracleRate;\n    // This is the timestamp of the previous trade\n    uint256 previousTradeTime;\n}\n\n/****** Storage objects ******/\n\n/// @dev Token object in storage:\n///  20 bytes for token address\n///  1 byte for hasTransferFee\n///  1 byte for tokenType\n///  1 byte for tokenDecimals\n///  9 bytes for maxCollateralBalance (may not always be set)\nstruct TokenStorage {\n    // Address of the token\n    address tokenAddress;\n    // Transfer fees will change token deposit behavior\n    bool hasTransferFee;\n    TokenType tokenType;\n    uint8 decimalPlaces;\n    uint72 deprecated_maxCollateralBalance;\n}\n\n/// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes.\nstruct ETHRateStorage {\n    // Address of the rate oracle\n    AggregatorV2V3Interface rateOracle;\n    // The decimal places of precision that the rate oracle uses\n    uint8 rateDecimalPlaces;\n    // True of the exchange rate must be inverted\n    bool mustInvert;\n    // NOTE: both of these governance values are set with BUFFER_DECIMALS precision\n    // Amount of buffer to apply to the exchange rate for negative balances.\n    uint8 buffer;\n    // Amount of haircut to apply to the exchange rate for positive balances\n    uint8 haircut;\n    // Liquidation discount in percentage point terms, 106 means a 6% discount\n    uint8 liquidationDiscount;\n}\n\n/// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes.\nstruct AssetRateStorage {\n    // Address of the rate oracle\n    AssetRateAdapter rateOracle;\n    // The decimal places of the underlying asset\n    uint8 underlyingDecimalPlaces;\n}\n\n/// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts\n/// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there\n/// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the\n/// length.\nstruct CashGroupSettings {\n    // Index of the AMMs on chain that will be made available. Idiosyncratic fCash\n    // that is dated less than the longest AMM will be tradable.\n    uint8 maxMarketIndex;\n    // Time window in 5 minute increments that the rate oracle will be averaged over\n    uint8 rateOracleTimeWindow5Min;\n    // Total fees per trade, specified in BPS\n    uint8 totalFeeBPS;\n    // Share of the fees given to the protocol, denominated in percentage\n    uint8 reserveFeeShare;\n    // Debt buffer specified in 5 BPS increments\n    uint8 debtBuffer5BPS;\n    // fCash haircut specified in 5 BPS increments\n    uint8 fCashHaircut5BPS;\n    // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This\n    // is the basis points for the penalty rate that will be added the current 3 month oracle rate.\n    uint8 settlementPenaltyRate5BPS;\n    // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for\n    uint8 liquidationfCashHaircut5BPS;\n    // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for\n    uint8 liquidationDebtBuffer5BPS;\n    // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100\n    uint8[] liquidityTokenHaircuts;\n    // Rate scalar used to determine the slippage of the market\n    uint8[] rateScalars;\n}\n\n/// @dev Holds account level context information used to determine settlement and\n/// free collateral actions. Total storage is 28 bytes\nstruct AccountContext {\n    // Used to check when settlement must be triggered on an account\n    uint40 nextSettleTime;\n    // For lenders that never incur debt, we use this flag to skip the free collateral check.\n    bytes1 hasDebt;\n    // Length of the account's asset array\n    uint8 assetArrayLength;\n    // If this account has bitmaps set, this is the corresponding currency id\n    uint16 bitmapCurrencyId;\n    // 9 total active currencies possible (2 bytes each)\n    bytes18 activeCurrencies;\n    // If this is set to true, the account can borrow variable prime cash and incur\n    // negative cash balances inside BatchAction. This does not impact the settlement\n    // of negative fCash to prime cash which will happen regardless of this setting. This\n    // exists here mainly as a safety setting to ensure that accounts do not accidentally\n    // incur negative cash balances.\n    bool allowPrimeBorrow;\n}\n\n/// @dev Holds nToken context information mapped via the nToken address, total storage is\n/// 16 bytes\nstruct nTokenContext {\n    // Currency id that the nToken represents\n    uint16 currencyId;\n    // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by\n    // INTERNAL_TOKEN_PRECISION to get the actual rate)\n    uint32 incentiveAnnualEmissionRate;\n    // The last block time at utc0 that the nToken was initialized at, zero if it\n    // has never been initialized\n    uint32 lastInitializedTime;\n    // Length of the asset array, refers to the number of liquidity tokens an nToken\n    // currently holds\n    uint8 assetArrayLength;\n    // Each byte is a specific nToken parameter\n    bytes5 nTokenParameters;\n    // Reserved bytes for future usage\n    bytes15 _unused;\n    // Set to true if a secondary rewarder is set\n    bool hasSecondaryRewarder;\n}\n\n/// @dev Holds account balance information, total storage 32 bytes\nstruct BalanceStorage {\n    // Number of nTokens held by the account\n    uint80 nTokenBalance;\n    // Last time the account claimed their nTokens\n    uint32 lastClaimTime;\n    // Incentives that the account no longer has a claim over\n    uint56 accountIncentiveDebt;\n    // Cash balance of the account\n    int88 cashBalance;\n}\n\n/// @dev Holds information about a settlement rate, total storage 25 bytes\nstruct SettlementRateStorage {\n    uint40 blockTime;\n    uint128 settlementRate;\n    uint8 underlyingDecimalPlaces;\n}\n\n/// @dev Holds information about a market, total storage is 42 bytes so this spans\n/// two storage words\nstruct MarketStorage {\n    // Total fCash in the market\n    uint80 totalfCash;\n    // Total asset cash in the market\n    uint80 totalPrimeCash;\n    // Last annualized interest rate the market traded at\n    uint32 lastImpliedRate;\n    // Last recorded oracle rate for the market\n    uint32 oracleRate;\n    // Last time a trade was made\n    uint32 previousTradeTime;\n    // This is stored in slot + 1\n    uint80 totalLiquidity;\n}\n\nstruct InterestRateParameters {\n    // First kink for the utilization rate in RATE_PRECISION\n    uint256 kinkUtilization1;\n    // Second kink for the utilization rate in RATE_PRECISION\n    uint256 kinkUtilization2;\n    // First kink interest rate in RATE_PRECISION\n    uint256 kinkRate1;\n    // Second kink interest rate in RATE_PRECISION\n    uint256 kinkRate2;\n    // Max interest rate in RATE_PRECISION\n    uint256 maxRate;\n    // Minimum fee charged in RATE_PRECISION\n    uint256 minFeeRate;\n    // Maximum fee charged in RATE_PRECISION\n    uint256 maxFeeRate;\n    // Percentage of the interest rate that will be applied as a fee\n    uint256 feeRatePercent;\n}\n\n// Specific interest rate curve settings for each market\nstruct InterestRateCurveSettings {\n    // First kink for the utilization rate, specified as a percentage\n    // between 1-100\n    uint8 kinkUtilization1;\n    // Second kink for the utilization rate, specified as a percentage\n    // between 1-100\n    uint8 kinkUtilization2;\n    // Interest rate at the first kink, set as 1/256 units from the kink\n    // rate max\n    uint8 kinkRate1;\n    // Interest rate at the second kink, set as 1/256 units from the kink\n    // rate max\n    uint8 kinkRate2;\n    // Max interest rate, set in 25 bps increments\n    uint8 maxRate25BPS;\n    // Minimum fee charged in basis points\n    uint8 minFeeRateBPS;\n    // Maximum fee charged in basis points\n    uint8 maxFeeRateBPS;\n    // Percentage of the interest rate that will be applied as a fee\n    uint8 feeRatePercent;\n}\n\nstruct ifCashStorage {\n    // Notional amount of fCash at the slot, limited to int128 to allow for\n    // future expansion\n    int128 notional;\n}\n\n/// @dev A single portfolio asset in storage, total storage of 19 bytes\nstruct PortfolioAssetStorage {\n    // Currency Id for the asset\n    uint16 currencyId;\n    // Maturity of the asset\n    uint40 maturity;\n    // Asset type (fCash or Liquidity Token marker)\n    uint8 assetType;\n    // Notional\n    int88 notional;\n}\n\n/// @dev nToken total supply factors for the nToken, includes factors related\n/// to claiming incentives, total storage 32 bytes. This is the deprecated version\nstruct nTokenTotalSupplyStorage_deprecated {\n    // Total supply of the nToken\n    uint96 totalSupply;\n    // Integral of the total supply used for calculating the average total supply\n    uint128 integralTotalSupply;\n    // Last timestamp the supply value changed, used for calculating the integralTotalSupply\n    uint32 lastSupplyChangeTime;\n}\n\n/// @dev nToken total supply factors for the nToken, includes factors related\n/// to claiming incentives, total storage 32 bytes.\nstruct nTokenTotalSupplyStorage {\n    // Total supply of the nToken\n    uint96 totalSupply;\n    // How many NOTE incentives should be issued per nToken in 1e18 precision\n    uint128 accumulatedNOTEPerNToken;\n    // Last timestamp when the accumulation happened\n    uint32 lastAccumulatedTime;\n}\n\n/// @dev Used in view methods to return account balances in a developer friendly manner\nstruct AccountBalance {\n    uint16 currencyId;\n    int256 cashBalance;\n    int256 nTokenBalance;\n    uint256 lastClaimTime;\n    uint256 accountIncentiveDebt;\n}\n\nstruct VaultConfigParams {\n    // Vault Flags (documented in VaultConfiguration.sol)\n    uint16 flags;\n    // Primary currency the vault borrows in\n    uint16 borrowCurrencyId;\n    // Specified in whole tokens in 1e8 precision, allows a 4.2 billion min borrow size\n    uint256 minAccountBorrowSize;\n    // Minimum collateral ratio for a vault specified in basis points, valid values are greater than 10_000\n    // where the largest minimum collateral ratio is 65_536 which is much higher than anything reasonable.\n    uint16 minCollateralRatioBPS;\n    // Allows up to a 12.75% annualized fee\n    uint8 feeRate5BPS;\n    // A percentage that represents the share of the cash raised that will go to the liquidator\n    uint8 liquidationRate;\n    // A percentage of the fee given to the protocol\n    uint8 reserveFeeShare;\n    // Maximum market index where a vault can borrow from\n    uint8 maxBorrowMarketIndex;\n    // Maximum collateral ratio that a liquidator can push a an account to during deleveraging\n    uint16 maxDeleverageCollateralRatioBPS;\n    // An optional list of secondary borrow currencies\n    uint16[2] secondaryBorrowCurrencies;\n    // Required collateral ratio for accounts to stay inside a vault, prevents accounts\n    // from \"free riding\" on vaults. Enforced on entry and exit, not on deleverage.\n    uint16 maxRequiredAccountCollateralRatioBPS;\n    // Specified in whole tokens in 1e8 precision, allows a 4.2 billion min borrow size\n    uint256[2] minAccountSecondaryBorrow;\n    // Specified as a percent discount off the exchange rate of the excess cash that will be paid to\n    // the liquidator during liquidateExcessVaultCash\n    uint8 excessCashLiquidationBonus;\n}\n\nstruct VaultBorrowCapacityStorage {\n    // Total fCash across all maturities that caps the borrow capacity\n    uint80 maxBorrowCapacity;\n    // Total fCash debt across all maturities\n    uint80 totalfCashDebt;\n}\n\nstruct VaultAccountSecondaryDebtShareStorage {\n    // Maturity for the account's secondary borrows. This is stored separately from\n    // the vault account maturity to ensure that we have access to the proper state\n    // during a roll borrow position. It should never be allowed to deviate from the\n    // vaultAccount.maturity value (unless it is cleared to zero).\n    uint40 maturity;\n    // Account debt for the first secondary currency in either fCash or pCash denomination\n    uint80 accountDebtOne;\n    // Account debt for the second secondary currency in either fCash or pCash denomination\n    uint80 accountDebtTwo;\n}\n\nstruct VaultConfig {\n    address vault;\n    uint16 flags;\n    uint16 borrowCurrencyId;\n    int256 minAccountBorrowSize;\n    int256 feeRate;\n    int256 minCollateralRatio;\n    int256 liquidationRate;\n    int256 reserveFeeShare;\n    uint256 maxBorrowMarketIndex;\n    int256 maxDeleverageCollateralRatio;\n    uint16[2] secondaryBorrowCurrencies;\n    PrimeRate primeRate;\n    int256 maxRequiredAccountCollateralRatio;\n    int256[2] minAccountSecondaryBorrow;\n}\n\n/// @notice Represents a Vault's current borrow and collateral state\nstruct VaultStateStorage {\n    // This represents the total amount of borrowing in the vault for the current\n    // vault term. If the vault state is the prime cash maturity, this is stored in\n    // prime cash debt denomination, if fCash then it is stored in internal underlying.\n    uint80 totalDebt;\n    // The total amount of prime cash in the pool held as a result of emergency settlement\n    uint80 deprecated_totalPrimeCash;\n    // Total vault shares in this maturity\n    uint80 totalVaultShares;\n    // Set to true if a vault's debt position has been migrated to the prime cash vault\n    bool isSettled;\n    // NOTE: 8 bits left\n    // ----- This breaks into a new storage slot -------    \n    // The total amount of strategy tokens held in the pool\n    uint80 deprecated_totalStrategyTokens;\n    // Valuation of a strategy token at settlement\n    int80 deprecated_settlementStrategyTokenValue;\n    // NOTE: 96 bits left\n}\n\n/// @notice Represents the remaining assets in a vault post settlement\nstruct Deprecated_VaultSettledAssetsStorage {\n    // Remaining strategy tokens that have not been withdrawn\n    uint80 remainingStrategyTokens;\n    // Remaining asset cash that has not been withdrawn\n    int80 remainingPrimeCash;\n}\n\nstruct VaultState {\n    uint256 maturity;\n    // Total debt is always denominated in underlying on the stack\n    int256 totalDebtUnderlying;\n    uint256 totalVaultShares;\n    bool isSettled;\n}\n\n/// @notice Represents an account's position within an individual vault\nstruct VaultAccountStorage {\n    // Total amount of debt for the account in the primary borrowed currency.\n    // If the account is borrowing prime cash, this is stored in prime cash debt\n    // denomination, if fCash then it is stored in internal underlying.\n    uint80 accountDebt;\n    // Vault shares that the account holds\n    uint80 vaultShares;\n    // Maturity when the vault shares and fCash will mature\n    uint40 maturity;\n    // Last time when a vault was entered or exited, used to ensure that vault accounts do not\n    // flash enter/exit. While there is no specified attack vector here, we can use it to prevent\n    // an entire class of attacks from happening without reducing UX.\n    // NOTE: in the original version this value was set to the block.number, however, in this\n    // version it is being changed to time based. On ETH mainnet block heights are much smaller\n    // than block times, accounts that migrate from lastEntryBlockHeight => lastUpdateBlockTime\n    // will not see any issues with entering / exiting the protocol.\n    uint32 lastUpdateBlockTime;\n    // ----------------  Second Storage Slot ----------------------\n    // Cash balances held by the vault account as a result of lending at zero interest or due\n    // to deleveraging (liquidation). In the previous version of leveraged vaults, accounts would\n    // simply lend at zero interest which was not a problem. However, with vaults being able to\n    // discount fCash to present value, lending at zero percent interest may have an adverse effect\n    // on the account's collateral position (i.e. lending at zero puts them further into danger).\n    // Holding cash against debt will eliminate that risk, making vault liquidation more similar to\n    // regular Notional liquidation.\n    uint80 primaryCash;\n    uint80 secondaryCashOne;\n    uint80 secondaryCashTwo;\n}\n\nstruct VaultAccount {\n    // On the stack, account debts are always in underlying\n    int256 accountDebtUnderlying;\n    uint256 maturity;\n    uint256 vaultShares;\n    address account;\n    // This cash balance is used just within a transaction to track deposits\n    // and withdraws for an account. Must be zeroed by the time we store the account\n    int256 tempCashBalance;\n    uint256 lastUpdateBlockTime;\n}\n\n// Used to hold vault account liquidation factors in memory\nstruct VaultAccountHealthFactors {\n    // Account's calculated collateral ratio\n    int256 collateralRatio;\n    // Total outstanding debt across all borrowed currencies in primary\n    int256 totalDebtOutstandingInPrimary;\n    // Total value of vault shares in underlying denomination\n    int256 vaultShareValueUnderlying;\n    // Debt outstanding in local currency denomination after present value and\n    // account cash held netting applied\n    int256[3] debtOutstanding;\n}\n\n// PrimeCashInterestRateParameters take up 16 bytes, this takes up 32 bytes so we\n// can expand another 16 bytes to increase the storage slots a bit....\nstruct PrimeCashFactorsStorage {\n    // Storage slot 1 [Prime Supply Factors, 248 bytes]\n    uint40 lastAccrueTime;\n    uint88 totalPrimeSupply;\n    uint88 lastTotalUnderlyingValue;\n    // Overflows at 429% interest using RATE_PRECISION\n    uint32 oracleSupplyRate;\n    bool allowDebt;\n\n    // Storage slot 2 [Prime Debt Factors, 256 bytes]\n    uint88 totalPrimeDebt;\n    // Each one of these values below is stored as a FloatingPoint32 value which\n    // gives us approx 7 digits of precision for each value. Because these are used\n    // to maintain supply and borrow caps, they are not required to be exact.\n    uint32 maxUnderlyingSupply;\n    uint128 _reserved;\n    // Reserving the next 128 bytes for future use in case we decide to implement debt\n    // caps on a currency. In that case, we will need to track the total fcash overall\n    // and subtract the total debt held in vaults.\n    // uint32 maxUnderlyingDebt;\n    // uint32 totalfCashDebtOverall;\n    // uint32 totalfCashDebtInVaults;\n    // uint32 totalPrimeDebtInVaults;\n    // 8 bytes left\n    \n    // Storage slot 3 [Prime Scalars, 240 bytes]\n    // Scalars are stored in 18 decimal precision (i.e. double rate precision) and uint80\n    // maxes out at approx 1,210,000e18\n    // ln(1,210,000) = rate * years = 14\n    // Approx 46 years at 30% interest\n    // Approx 233 years at 6% interest\n    uint80 underlyingScalar;\n    uint80 supplyScalar;\n    uint80 debtScalar;\n    // The time window in 5 min increments that the rate oracle will be averaged over\n    uint8 rateOracleTimeWindow5Min;\n    // 8 bytes left\n}\n\nstruct PrimeCashFactors {\n    uint256 lastAccrueTime;\n    uint256 totalPrimeSupply;\n    uint256 totalPrimeDebt;\n    uint256 oracleSupplyRate;\n    uint256 lastTotalUnderlyingValue;\n    uint256 underlyingScalar;\n    uint256 supplyScalar;\n    uint256 debtScalar;\n    uint256 rateOracleTimeWindow;\n}\n\nstruct PrimeRate {\n    int256 supplyFactor;\n    int256 debtFactor;\n    uint256 oracleSupplyRate;\n}\n\nstruct PrimeSettlementRateStorage {\n    uint80 supplyScalar;\n    uint80 debtScalar;\n    uint80 underlyingScalar;\n    bool isSet;\n}\n\nstruct PrimeCashHoldingsOracle {\n   IPrimeCashHoldingsOracle oracle; \n}\n\n// Per currency rebalancing context\nstruct RebalancingContextStorage {\n    // Holds the previous underlying scalar to calculate the oracle money market rate\n    uint80 previousUnderlyingScalarAtRebalance;\n    // Rebalancing has a cool down period that sets the time averaging of the oracle money market rate\n    uint40 rebalancingCooldownInSeconds;\n    uint40 lastRebalanceTimestampInSeconds;\n    // The annualized underlying money market interest rate calculated based on the underlying scalar\n    uint32 oracleMoneyMarketRate;\n    // 64 bytes left\n}\n\nstruct TotalfCashDebtStorage {\n    uint80 totalfCashDebt;\n    // These two variables are used to track fCash lend at zero\n    // edge conditions for leveraged vaults.\n    uint80 fCashDebtHeldInSettlementReserve;\n    uint80 primeCashHeldInSettlementReserve;\n}\n"
      },
      "contracts/liquidator/BoringOwnable.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.24;\n\n// Audit on 5-Jan-2021 by Keno and BoringCrypto\n// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol\n// Edited by BoringCrypto\n\ncontract BoringOwnableData {\n    address public owner;\n    address public pendingOwner;\n}\n\ncontract BoringOwnable is BoringOwnableData {\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.\n    /// Can only be invoked by the current `owner`.\n    /// @param newOwner Address of the new owner.\n    /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.\n    /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.\n    function transferOwnership(\n        address newOwner,\n        bool direct,\n        bool renounce\n    ) external onlyOwner {\n        if (direct) {\n            // Checks\n            require(newOwner != address(0) || renounce, \"Ownable: zero address\");\n\n            // Effects\n            emit OwnershipTransferred(owner, newOwner);\n            owner = newOwner;\n            pendingOwner = address(0);\n        } else {\n            // Effects\n            pendingOwner = newOwner;\n        }\n    }\n\n    /// @notice Needs to be called by `pendingOwner` to claim ownership.\n    function claimOwnership() external {\n        address _pendingOwner = pendingOwner;\n\n        // Checks\n        require(msg.sender == _pendingOwner, \"Ownable: caller != pending owner\");\n\n        // Effects\n        emit OwnershipTransferred(owner, _pendingOwner);\n        owner = _pendingOwner;\n        pendingOwner = address(0);\n    }\n\n    /// @notice Only allows the `owner` to execute the function.\n    modifier onlyOwner() {\n        require(msg.sender == owner, \"Ownable: caller is not the owner\");\n        _;\n    }\n}"
      },
      "contracts/global/mainnet/Deployments.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\n\nimport {Constants} from \"../Constants.sol\";\nimport {NotionalProxy} from \"@interfaces/notional/NotionalProxy.sol\";\nimport {IWstETH} from \"@interfaces/IWstETH.sol\";\nimport {IBalancerVault, IAsset} from \"@interfaces/balancer/IBalancerVault.sol\";\nimport {WETH9} from \"@interfaces/WETH9.sol\";\nimport {ISwapRouter as UniV3ISwapRouter} from \"@interfaces/uniswap/v3/ISwapRouter.sol\";\nimport {IUniV2Router2} from \"@interfaces/uniswap/v2/IUniV2Router2.sol\";\nimport {ICurveRouter} from \"@interfaces/curve/ICurveRouter.sol\";\nimport {ICurveRegistry} from \"@interfaces/curve/ICurveRegistry.sol\";\nimport {ICurveMetaRegistry} from \"@interfaces/curve/ICurveMetaRegistry.sol\";\nimport {ICurveRouterV2} from \"@interfaces/curve/ICurveRouterV2.sol\";\nimport {ITradingModule} from \"@interfaces/trading/ITradingModule.sol\";\nimport {IWrappedfCashFactory} from \"@interfaces/notional/IWrappedfCashFactory.sol\";\nimport {AggregatorV2V3Interface} from \"@interfaces/chainlink/AggregatorV2V3Interface.sol\";\n\n/// @title Hardcoded Deployment Addresses for Mainnet\nlibrary Deployments {\n    uint256 internal constant CHAIN_ID = Constants.CHAIN_ID_MAINNET;\n    NotionalProxy internal constant NOTIONAL = NotionalProxy(0x6e7058c91F85E0F6db4fc9da2CA41241f5e4263f);\n    address internal constant ETH_ADDRESS = address(0);\n    WETH9 internal constant WETH = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);\n    IBalancerVault internal constant BALANCER_VAULT =\n        IBalancerVault(0xBA12222222228d8Ba445958a75a0704d566BF2C8);\n\n    UniV3ISwapRouter internal constant UNIV3_ROUTER = UniV3ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564);\n    address internal constant ZERO_EX = 0xDef1C0ded9bec7F1a1670819833240f027b25EfF;\n    IUniV2Router2 internal constant UNIV2_ROUTER = IUniV2Router2(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);\n\n    address internal constant ALT_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n\n    ICurveRouterV2 public constant CURVE_ROUTER_V2 = ICurveRouterV2(0x99a58482BD75cbab83b27EC03CA68fF489b5788f);\n    ICurveMetaRegistry public constant CURVE_META_REGISTRY = ICurveMetaRegistry(0xF98B45FA17DE75FB1aD0e7aFD971b0ca00e379fC);\n    address internal constant CURVE_V1_HANDLER = 0x46a8a9CF4Fc8e99EC3A14558ACABC1D93A27de68;\n    address internal constant CURVE_V2_HANDLER = 0xC4F389020002396143B863F6325aA6ae481D19CE;\n    address internal constant CURVE_MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;\n\n    ITradingModule internal constant TRADING_MODULE = ITradingModule(0x594734c7e06C3D483466ADBCe401C6Bd269746C8);\n    address internal constant TREASURY_MANAGER = 0x53144559C0d4a3304e2DD9dAfBD685247429216d;\n    // Notional Inc\n    address internal constant EMERGENCY_EXIT_MANAGER = 0x02479BFC7Dce53A02e26fE7baea45a0852CB0909;\n    address internal constant BALANCER_SPOT_PRICE = 0xA153B3E85833F8a323E60Dcdc08F6286eae28728;\n    IWrappedfCashFactory internal constant WRAPPED_FCASH_FACTORY = IWrappedfCashFactory(address(0));\n\n    // Chainlink L2 Sequencer Uptime: https://docs.chain.link/data-feeds/l2-sequencer-feeds/\n    AggregatorV2V3Interface internal constant SEQUENCER_UPTIME_ORACLE = AggregatorV2V3Interface(address(0));\n    address internal constant FLASH_LENDER_AAVE = 0x0c86c636ed5593705b5675d370c831972C787841;\n}"
      },
      "interfaces/notional/nTokenERC20.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\npragma abicoder v2;\n\ninterface nTokenERC20 {\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n    function nTokenTotalSupply(address nTokenAddress) external view returns (uint256);\n\n    function nTokenBalanceOf(uint16 currencyId, address account) external view returns (uint256);\n\n    function nTokenTransferAllowance(\n        uint16 currencyId,\n        address owner,\n        address spender\n    ) external view returns (uint256);\n\n    function pCashTransferAllowance(\n        uint16 currencyId,\n        address owner,\n        address spender\n    ) external view returns (uint256);\n\n    function nTokenTransferApprove(\n        uint16 currencyId,\n        address owner,\n        address spender,\n        uint256 amount\n    ) external returns (bool);\n\n    function pCashTransferApprove(\n        uint16 currencyId,\n        address owner,\n        address spender,\n        uint256 amount\n    ) external returns (bool);\n\n    function nTokenTransfer(\n        uint16 currencyId,\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n\n    function pCashTransfer(\n        uint16 currencyId,\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n\n    function nTokenTransferFrom(\n        uint16 currencyId,\n        address spender,\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n\n    function pCashTransferFrom(\n        uint16 currencyId,\n        address spender,\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n\n    function nTokenTransferApproveAll(address spender, uint256 amount) external returns (bool);\n\n    function nTokenClaimIncentives() external returns (uint256);\n\n}\n"
      },
      "interfaces/notional/nERC1155Interface.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\npragma abicoder v2;\n\nimport \"../../contracts/global/Types.sol\";\n\ninterface nERC1155Interface {\n    event TransferSingle(\n        address indexed operator,\n        address indexed from,\n        address indexed to,\n        uint256 id,\n        uint256 value\n    );\n    event TransferBatch(\n        address indexed operator,\n        address indexed from,\n        address indexed to,\n        uint256[] ids,\n        uint256[] values\n    );\n    event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n    event URI(string value, uint256 indexed id);\n\n    function supportsInterface(bytes4 interfaceId) external pure returns (bool);\n\n    function balanceOf(address account, uint256 id) external view returns (uint256);\n\n    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n        external\n        view\n        returns (uint256[] memory);\n\n    function signedBalanceOf(address account, uint256 id) external view returns (int256);\n\n    function signedBalanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n        external\n        view\n        returns (int256[] memory);\n\n    function setApprovalForAll(address operator, bool approved) external;\n\n    function isApprovedForAll(address account, address operator) external view returns (bool);\n\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 id,\n        uint256 amount,\n        bytes calldata data\n    ) external payable;\n\n    function safeBatchTransferFrom(\n        address from,\n        address to,\n        uint256[] calldata ids,\n        uint256[] calldata amounts,\n        bytes calldata data\n    ) external payable;\n\n    function decodeToAssets(uint256[] calldata ids, uint256[] calldata amounts)\n        external\n        view\n        returns (PortfolioAsset[] memory);\n\n    function encodeToId(\n        uint16 currencyId,\n        uint40 maturity,\n        uint8 assetType\n    ) external pure returns (uint256 id);\n}\n"
      },
      "interfaces/notional/NotionalGovernance.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\npragma abicoder v2;\n\nimport \"../../contracts/global/Types.sol\";\nimport \"../../interfaces/chainlink/AggregatorV2V3Interface.sol\";\nimport \"../../interfaces/notional/NotionalGovernance.sol\";\nimport \"../../interfaces/notional/IRewarder.sol\";\nimport \"../../interfaces/aave/ILendingPool.sol\";\n\ninterface NotionalGovernance {\n    event ListCurrency(uint16 newCurrencyId);\n    event UpdateETHRate(uint16 currencyId);\n    event UpdateAssetRate(uint16 currencyId);\n    event UpdateCashGroup(uint16 currencyId);\n    event DeployNToken(uint16 currencyId, address nTokenAddress);\n    event UpdateDepositParameters(uint16 currencyId);\n    event UpdateInitializationParameters(uint16 currencyId);\n    event UpdateIncentiveEmissionRate(uint16 currencyId, uint32 newEmissionRate);\n    event UpdateTokenCollateralParameters(uint16 currencyId);\n    event UpdateGlobalTransferOperator(address operator, bool approved);\n    event UpdateAuthorizedCallbackContract(address operator, bool approved);\n    event UpdateMaxCollateralBalance(uint16 currencyId, uint72 maxCollateralBalance);\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n    event PauseRouterAndGuardianUpdated(address indexed pauseRouter, address indexed pauseGuardian);\n    event UpdateSecondaryIncentiveRewarder(uint16 indexed currencyId, address rewarder);\n    event UpdateLendingPool(address pool);\n\n    function transferOwnership(address newOwner, bool direct) external;\n\n    function claimOwnership() external;\n\n    function upgradeNTokenBeacon(address newImplementation) external;\n\n    function setPauseRouterAndGuardian(address pauseRouter_, address pauseGuardian_) external;\n\n    function listCurrency(\n        TokenStorage calldata assetToken,\n        TokenStorage calldata underlyingToken,\n        AggregatorV2V3Interface rateOracle,\n        bool mustInvert,\n        uint8 buffer,\n        uint8 haircut,\n        uint8 liquidationDiscount\n    ) external returns (uint16 currencyId);\n\n    function updateMaxCollateralBalance(\n        uint16 currencyId,\n        uint72 maxCollateralBalanceInternalPrecision\n    ) external;\n\n    function enableCashGroup(\n        uint16 currencyId,\n        AssetRateAdapter assetRateOracle,\n        CashGroupSettings calldata cashGroup,\n        string calldata underlyingName,\n        string calldata underlyingSymbol\n    ) external;\n\n    function updateDepositParameters(\n        uint16 currencyId,\n        uint32[] calldata depositShares,\n        uint32[] calldata leverageThresholds\n    ) external;\n\n    function updateInitializationParameters(\n        uint16 currencyId,\n        uint32[] calldata annualizedAnchorRates,\n        uint32[] calldata proportions\n    ) external;\n\n    function updateIncentiveEmissionRate(uint16 currencyId, uint32 newEmissionRate) external;\n\n    function updateTokenCollateralParameters(\n        uint16 currencyId,\n        uint8 residualPurchaseIncentive10BPS,\n        uint8 pvHaircutPercentage,\n        uint8 residualPurchaseTimeBufferHours,\n        uint8 cashWithholdingBuffer10BPS,\n        uint8 liquidationHaircutPercentage\n    ) external;\n\n    function updateCashGroup(uint16 currencyId, CashGroupSettings calldata cashGroup) external;\n\n    function updateAssetRate(uint16 currencyId, AssetRateAdapter rateOracle) external;\n\n    function updateETHRate(\n        uint16 currencyId,\n        AggregatorV2V3Interface rateOracle,\n        bool mustInvert,\n        uint8 buffer,\n        uint8 haircut,\n        uint8 liquidationDiscount\n    ) external;\n\n    function updateGlobalTransferOperator(address operator, bool approved) external;\n\n    function updateAuthorizedCallbackContract(address operator, bool approved) external;\n\n    function setLendingPool(ILendingPool pool) external;\n\n    function setSecondaryIncentiveRewarder(uint16 currencyId, IRewarder rewarder) external;\n}\n"
      },
      "interfaces/notional/NotionalCalculations.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\npragma abicoder v2;\n\nimport \"../../contracts/global/Types.sol\";\n\ninterface NotionalCalculations {\n    function calculateNTokensToMint(uint16 currencyId, uint88 amountToDepositExternalPrecision)\n        external\n        view\n        returns (uint256);\n\n    function nTokenPresentValueAssetDenominated(uint16 currencyId) external view returns (int256);\n\n    function nTokenPresentValueUnderlyingDenominated(uint16 currencyId)\n        external\n        view\n        returns (int256);\n\n    function convertNTokenToUnderlying(uint16 currencyId, int256 nTokenBalance) external view returns (int256);\n\n    function getfCashAmountGivenCashAmount(\n        uint16 currencyId,\n        int88 netCashToAccount,\n        uint256 marketIndex,\n        uint256 blockTime\n    ) external view returns (int256);\n\n    function getCashAmountGivenfCashAmount(\n        uint16 currencyId,\n        int88 fCashAmount,\n        uint256 marketIndex,\n        uint256 blockTime\n    ) external view returns (int256, int256);\n\n    function nTokenGetClaimableIncentives(address account, uint256 blockTime)\n        external\n        view\n        returns (uint256);\n\n    function getPresentfCashValue(\n        uint16 currencyId,\n        uint256 maturity,\n        int256 notional,\n        uint256 blockTime,\n        bool riskAdjusted\n    ) external view returns (int256 presentValue);\n\n    function getMarketIndex(\n        uint256 maturity,\n        uint256 blockTime\n    ) external pure returns (uint8 marketIndex);\n\n    function getfCashLendFromDeposit(\n        uint16 currencyId,\n        uint256 depositAmountExternal,\n        uint256 maturity,\n        uint32 minLendRate,\n        uint256 blockTime,\n        bool useUnderlying\n    ) external view returns (\n        uint88 fCashAmount,\n        uint8 marketIndex,\n        bytes32 encodedTrade\n    );\n\n    function getfCashBorrowFromPrincipal(\n        uint16 currencyId,\n        uint256 borrowedAmountExternal,\n        uint256 maturity,\n        uint32 maxBorrowRate,\n        uint256 blockTime,\n        bool useUnderlying\n    ) external view returns (\n        uint88 fCashDebt,\n        uint8 marketIndex,\n        bytes32 encodedTrade\n    );\n\n    function getDepositFromfCashLend(\n        uint16 currencyId,\n        uint256 fCashAmount,\n        uint256 maturity,\n        uint32 minLendRate,\n        uint256 blockTime\n    ) external view returns (\n        uint256 depositAmountUnderlying,\n        uint256 depositAmountAsset,\n        uint8 marketIndex,\n        bytes32 encodedTrade\n    );\n\n    function getPrincipalFromfCashBorrow(\n        uint16 currencyId,\n        uint256 fCashBorrow,\n        uint256 maturity,\n        uint32 maxBorrowRate,\n        uint256 blockTime\n    ) external view returns (\n        uint256 borrowAmountUnderlying,\n        uint256 borrowAmountAsset,\n        uint8 marketIndex,\n        bytes32 encodedTrade\n    );\n\n    function convertCashBalanceToExternal(\n        uint16 currencyId,\n        int256 cashBalanceInternal,\n        bool useUnderlying\n    ) external view returns (int256);\n\n    function convertUnderlyingToPrimeCash(\n        uint16 currencyId,\n        int256 underlyingExternal\n    ) external view returns (int256);\n\n    function convertSettledfCash(\n        uint16 currencyId,\n        uint256 maturity,\n        int256 fCashBalance,\n        uint256 blockTime\n    ) external view returns (int256 signedPrimeSupplyValue);\n\n    function accruePrimeInterest(\n        uint16 currencyId\n    ) external returns (PrimeRate memory pr, PrimeCashFactors memory);\n}\n"
      },
      "interfaces/notional/NotionalViews.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\npragma abicoder v2;\n\nimport \"../../contracts/global/Types.sol\";\n\ninterface NotionalViews {\n    function getMaxCurrencyId() external view returns (uint16);\n\n    function getCurrencyId(address tokenAddress) external view returns (uint16 currencyId);\n\n    function getCurrency(uint16 currencyId)\n        external\n        view\n        returns (Token memory assetToken, Token memory underlyingToken);\n\n    function getRateStorage(uint16 currencyId)\n        external\n        view\n        returns (ETHRateStorage memory ethRate, AssetRateStorage memory assetRate);\n\n    function getCurrencyAndRates(uint16 currencyId)\n        external\n        view\n        returns (\n            Token memory assetToken,\n            Token memory underlyingToken,\n            ETHRate memory ethRate,\n            Deprecated_AssetRateParameters memory assetRate\n        );\n\n    function getCashGroup(uint16 currencyId) external view returns (CashGroupSettings memory);\n\n    function getCashGroupAndAssetRate(uint16 currencyId)\n        external\n        view\n        returns (CashGroupSettings memory cashGroup, Deprecated_AssetRateParameters memory assetRate);\n\n    function getInterestRateCurve(uint16 currencyId) external view returns (\n        InterestRateParameters[] memory nextInterestRateCurve,\n        InterestRateParameters[] memory activeInterestRateCurve\n    );\n\n    function getInitializationParameters(uint16 currencyId)\n        external\n        view\n        returns (int256[] memory annualizedAnchorRates, int256[] memory proportions);\n\n    function getDepositParameters(uint16 currencyId)\n        external\n        view\n        returns (int256[] memory depositShares, int256[] memory leverageThresholds);\n\n    function nTokenAddress(uint16 currencyId) external view returns (address);\n\n    function pCashAddress(uint16 currencyId) external view returns (address);\n\n    function pDebtAddress(uint16 currencyId) external view returns (address);\n\n    function getNoteToken() external view returns (address);\n\n    function getOwnershipStatus() external view returns (address owner, address pendingOwner);\n\n    function getGlobalTransferOperatorStatus(address operator)\n        external\n        view\n        returns (bool isAuthorized);\n\n    function getAuthorizedCallbackContractStatus(address callback)\n        external\n        view\n        returns (bool isAuthorized);\n\n    function getSecondaryIncentiveRewarder(uint16 currencyId)\n        external\n        view\n        returns (address incentiveRewarder);\n\n    function getPrimeFactors(uint16 currencyId, uint256 blockTime) external view returns (\n        PrimeRate memory primeRate,\n        PrimeCashFactors memory factors,\n        uint256 maxUnderlyingSupply,\n        uint256 totalUnderlyingSupply\n    );\n\n    function getPrimeFactorsStored(uint16 currencyId) external view returns (PrimeCashFactors memory);\n\n    function getPrimeCashHoldingsOracle(uint16 currencyId) external view returns (address);\n\n    function getTotalfCashDebtOutstanding(uint16 currencyId, uint256 maturity) external view returns (int256);\n\n    function getSettlementRate(uint16 currencyId, uint40 maturity)\n        external\n        view\n        returns (PrimeRate memory);\n\n    function getMarket(\n        uint16 currencyId,\n        uint256 maturity,\n        uint256 settlementDate\n    ) external view returns (MarketParameters memory);\n\n    function getActiveMarkets(uint16 currencyId) external view returns (MarketParameters[] memory);\n\n    function getActiveMarketsAtBlockTime(uint16 currencyId, uint32 blockTime)\n        external\n        view\n        returns (MarketParameters[] memory);\n\n    function getReserveBalance(uint16 currencyId) external view returns (int256 reserveBalance);\n\n    function getNTokenPortfolio(address tokenAddress)\n        external\n        view\n        returns (PortfolioAsset[] memory liquidityTokens, PortfolioAsset[] memory netfCashAssets);\n\n    function getNTokenAccount(address tokenAddress)\n        external\n        view\n        returns (\n            uint16 currencyId,\n            uint256 totalSupply,\n            uint256 incentiveAnnualEmissionRate,\n            uint256 lastInitializedTime,\n            bytes5 nTokenParameters,\n            int256 cashBalance,\n            uint256 accumulatedNOTEPerNToken,\n            uint256 lastAccumulatedTime\n        );\n\n    function getAccount(address account)\n        external\n        view\n        returns (\n            AccountContext memory accountContext,\n            AccountBalance[] memory accountBalances,\n            PortfolioAsset[] memory portfolio\n        );\n\n    function getAccountContext(address account) external view returns (AccountContext memory);\n\n    function getAccountPrimeDebtBalance(uint16 currencyId, address account) external view returns (\n        int256 debtBalance\n    );\n\n    function getAccountBalance(uint16 currencyId, address account)\n        external\n        view\n        returns (\n            int256 cashBalance,\n            int256 nTokenBalance,\n            uint256 lastClaimTime\n        );\n\n    function getAccountPortfolio(address account) external view returns (PortfolioAsset[] memory);\n\n    function getfCashNotional(\n        address account,\n        uint16 currencyId,\n        uint256 maturity\n    ) external view returns (int256);\n\n    function getAssetsBitmap(address account, uint16 currencyId) external view returns (bytes32);\n\n    function getFreeCollateral(address account) external view returns (int256, int256[] memory);\n\n    function getTreasuryManager() external view returns (address);\n\n    function getReserveBuffer(uint16 currencyId) external view returns (uint256);\n\n    function getRebalancingTarget(uint16 currencyId, address holding) external view returns (uint8);\n\n    function getRebalancingCooldown(uint16 currencyId) external view returns (uint40);\n\n    function getStoredTokenBalances(address[] calldata tokens) external view returns (uint256[] memory balances);\n}\n"
      },
      "interfaces/notional/NotionalTreasury.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\npragma abicoder v2;\n\ninterface NotionalTreasury {\n\n    /// @notice Emitted when reserve balance is updated\n    event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance);\n    /// @notice Emitted when reserve balance is harvested\n    event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount);\n    /// @dev Emitted when treasury manager is updated\n    event TreasuryManagerChanged(address indexed previousManager, address indexed newManager);\n    /// @dev Emitted when reserve buffer value is updated\n    event ReserveBufferUpdated(uint16 currencyId, uint256 bufferAmount);\n\n    function claimCOMPAndTransfer(address[] calldata ctokens) external returns (uint256);\n\n    function transferReserveToTreasury(uint16[] calldata currencies)\n        external\n        returns (uint256[] memory);\n\n    function setTreasuryManager(address manager) external;\n\n    function setReserveBuffer(uint16 currencyId, uint256 amount) external;\n\n    function setReserveCashBalance(uint16 currencyId, int256 reserveBalance) external;\n}\n"
      },
      "interfaces/notional/IVaultController.sol": {
        "content": "// SPDX-License-Identifier: GPL-v3\npragma solidity >=0.7.6;\npragma abicoder v2;\n\nimport {\n    VaultConfigParams,\n    VaultConfig,\n    VaultState,\n    VaultAccount,\n    VaultAccountHealthFactors,\n    PrimeRate\n} from \"../../contracts/global/Types.sol\";\n\ninterface IVaultAction {\n    /// @notice Emitted when a new vault is listed or updated\n    event VaultUpdated(address indexed vault, bool enabled, uint80 maxPrimaryBorrowCapacity);\n    /// @notice Emitted when a vault's status is updated\n    event VaultPauseStatus(address indexed vault, bool enabled);\n    /// @notice Emitted when a vault's deleverage status is updated\n    event VaultDeleverageStatus(address indexed vaultAddress, bool disableDeleverage);\n    /// @notice Emitted when a secondary currency borrow capacity is updated\n    event VaultUpdateSecondaryBorrowCapacity(address indexed vault, uint16 indexed currencyId, uint80 maxSecondaryBorrowCapacity);\n    /// @notice Emitted when the borrow capacity on a vault changes\n    event VaultBorrowCapacityChange(address indexed vault, uint16 indexed currencyId, uint256 totalUsedBorrowCapacity);\n\n    /// @notice Emitted when a vault executes a secondary borrow\n    event VaultSecondaryTransaction(\n        address indexed vault,\n        address indexed account,\n        uint16 indexed currencyId,\n        uint256 maturity,\n        int256 netUnderlyingDebt,\n        int256 netPrimeSupply\n    );\n\n    /** Vault Action Methods */\n\n    /// @notice Governance only method to whitelist a particular vault\n    function updateVault(\n        address vaultAddress,\n        VaultConfigParams memory vaultConfig,\n        uint80 maxPrimaryBorrowCapacity\n    ) external;\n\n    /// @notice Governance only method to pause a particular vault\n    function setVaultPauseStatus(\n        address vaultAddress,\n        bool enable\n    ) external;\n\n    function setVaultDeleverageStatus(\n        address vaultAddress,\n        bool disableDeleverage\n    ) external;\n\n    /// @notice Governance only method to set the borrow capacity\n    function setMaxBorrowCapacity(\n        address vaultAddress,\n        uint80 maxVaultBorrowCapacity\n    ) external;\n\n    /// @notice Governance only method to update a vault's secondary borrow capacity\n    function updateSecondaryBorrowCapacity(\n        address vaultAddress,\n        uint16 secondaryCurrencyId,\n        uint80 maxBorrowCapacity\n    ) external;\n\n    function borrowSecondaryCurrencyToVault(\n        address account,\n        uint256 maturity,\n        uint256[2] calldata underlyingToBorrow,\n        uint32[2] calldata maxBorrowRate,\n        uint32[2] calldata minRollLendRate\n    ) external returns (int256[2] memory underlyingTokensTransferred);\n\n    function repaySecondaryCurrencyFromVault(\n        address account,\n        uint256 maturity,\n        uint256[2] calldata underlyingToRepay,\n        uint32[2] calldata minLendRate\n    ) external payable returns (int256[2] memory underlyingDepositExternal);\n\n    function settleSecondaryBorrowForAccount(address vault, address account) external;\n}\n\ninterface IVaultAccountAction {\n    /**\n     * @notice Borrows a specified amount of fCash in the vault's borrow currency and deposits it\n     * all plus the depositAmountExternal into the vault to mint strategy tokens.\n     *\n     * @param account the address that will enter the vault\n     * @param vault the vault to enter\n     * @param depositAmountExternal some amount of additional collateral in the borrowed currency\n     * to be transferred to vault\n     * @param maturity the maturity to borrow at\n     * @param fCash amount to borrow\n     * @param maxBorrowRate maximum interest rate to borrow at\n     * @param vaultData additional data to pass to the vault contract\n     */\n    function enterVault(\n        address account,\n        address vault,\n        uint256 depositAmountExternal,\n        uint256 maturity,\n        uint256 fCash,\n        uint32 maxBorrowRate,\n        bytes calldata vaultData\n    ) external payable returns (uint256 strategyTokensAdded);\n\n    /**\n     * @notice Re-enters the vault at a longer dated maturity. The account's existing borrow\n     * position will be closed and a new borrow position at the specified maturity will be\n     * opened. All strategy token holdings will be rolled forward.\n     *\n     * @param account the address that will reenter the vault\n     * @param vault the vault to reenter\n     * @param fCashToBorrow amount of fCash to borrow in the next maturity\n     * @param maturity new maturity to borrow at\n     */\n    function rollVaultPosition(\n        address account,\n        address vault,\n        uint256 fCashToBorrow,\n        uint256 maturity,\n        uint256 depositAmountExternal,\n        uint32 minLendRate,\n        uint32 maxBorrowRate,\n        bytes calldata enterVaultData\n    ) external payable returns (uint256 strategyTokensAdded);\n\n    /**\n     * @notice Prior to maturity, allows an account to withdraw their position from the vault. Will\n     * redeem some number of vault shares to the borrow currency and close the borrow position by\n     * lending `fCashToLend`. Any shortfall in cash from lending will be transferred from the account,\n     * any excess profits will be transferred to the account.\n     *\n     * Post maturity, will net off the account's debt against vault cash balances and redeem all remaining\n     * strategy tokens back to the borrowed currency and transfer the profits to the account.\n     *\n     * @param account the address that will exit the vault\n     * @param vault the vault to enter\n     * @param vaultSharesToRedeem amount of vault tokens to exit, only relevant when exiting pre-maturity\n     * @param fCashToLend amount of fCash to lend\n     * @param minLendRate the minimum rate to lend at\n     * @param exitVaultData passed to the vault during exit\n     * @return underlyingToReceiver amount of underlying tokens returned to the receiver on exit\n     */\n    function exitVault(\n        address account,\n        address vault,\n        address receiver,\n        uint256 vaultSharesToRedeem,\n        uint256 fCashToLend,\n        uint32 minLendRate,\n        bytes calldata exitVaultData\n    ) external payable returns (uint256 underlyingToReceiver);\n\n    function settleVaultAccount(address account, address vault) external;\n}\n\ninterface IVaultLiquidationAction {\n    event VaultDeleverageAccount(\n        address indexed vault,\n        address indexed account,\n        uint16 currencyId,\n        uint256 vaultSharesToLiquidator,\n        int256 depositAmountPrimeCash\n    );\n\n    event VaultLiquidatorProfit(\n        address indexed vault,\n        address indexed account,\n        address indexed liquidator,\n        uint256 vaultSharesToLiquidator,\n        bool transferSharesToLiquidator\n    );\n    \n    event VaultAccountCashLiquidation(\n        address indexed vault,\n        address indexed account,\n        address indexed liquidator,\n        uint16 currencyId,\n        int256 fCashDeposit,\n        int256 cashToLiquidator\n    );\n\n    /**\n     * @notice If an account is below the minimum collateral ratio, this method wil deleverage (liquidate)\n     * that account. `depositAmountExternal` in the borrow currency will be transferred from the liquidator\n     * and used to offset the account's debt position. The liquidator will receive either vaultShares or\n     * cash depending on the vault's configuration.\n     * @param account the address that will exit the vault\n     * @param vault the vault to enter\n     * @param liquidator the address that will receive profits from liquidation\n     * @param depositAmountPrimeCash amount of cash to deposit\n     * @return vaultSharesFromLiquidation amount of vaultShares received from liquidation\n     */\n    function deleverageAccount(\n        address account,\n        address vault,\n        address liquidator,\n        uint16 currencyIndex,\n        int256 depositUnderlyingInternal\n    ) external payable returns (uint256 vaultSharesFromLiquidation, int256 depositAmountPrimeCash);\n\n    function liquidateVaultCashBalance(\n        address account,\n        address vault,\n        address liquidator,\n        uint256 currencyIndex,\n        int256 fCashDeposit\n    ) external returns (int256 cashToLiquidator);\n\n    function liquidateExcessVaultCash(\n        address account,\n        address vault,\n        address liquidator,\n        uint256 excessCashIndex,\n        uint256 debtIndex,\n        uint256 _depositUnderlyingInternal\n    ) external payable returns (int256 cashToLiquidator);\n}\n\ninterface IVaultAccountHealth {\n    function getVaultAccountHealthFactors(address account, address vault) external view returns (\n        VaultAccountHealthFactors memory h,\n        int256[3] memory maxLiquidatorDepositUnderlying,\n        uint256[3] memory vaultSharesToLiquidator\n    );\n\n    function calculateDepositAmountInDeleverage(\n        uint256 currencyIndex,\n        VaultAccount memory vaultAccount,\n        VaultConfig memory vaultConfig,\n        VaultState memory vaultState,\n        int256 depositUnderlyingInternal\n    ) external returns (int256 depositInternal, uint256 vaultSharesToLiquidator, PrimeRate memory);\n\n    function getfCashRequiredToLiquidateCash(\n        uint16 currencyId,\n        uint256 maturity,\n        int256 vaultAccountCashBalance\n    ) external view returns (int256 fCashRequired, int256 discountFactor);\n\n    function checkVaultAccountCollateralRatio(address vault, address account) external;\n\n    function getVaultAccount(address account, address vault) external view returns (VaultAccount memory);\n    function getVaultAccountWithFeeAccrual(\n        address account, address vault\n    ) external view returns (VaultAccount memory, int256 accruedPrimeVaultFeeInUnderlying);\n\n    function getVaultConfig(address vault) external view returns (VaultConfig memory vaultConfig);\n\n    function getBorrowCapacity(address vault, uint16 currencyId) external view returns (\n        uint256 currentPrimeDebtUnderlying,\n        uint256 totalfCashDebt,\n        uint256 maxBorrowCapacity\n    );\n\n    function getSecondaryBorrow(address vault, uint16 currencyId, uint256 maturity) \n        external view returns (int256 totalDebt);\n\n    /// @notice View method to get vault state\n    function getVaultState(address vault, uint256 maturity) external view returns (VaultState memory vaultState);\n\n    function getVaultAccountSecondaryDebt(address account, address vault) external view returns (\n        uint256 maturity,\n        int256[2] memory accountSecondaryDebt,\n        int256[2] memory accountSecondaryCashHeld\n    );\n\n    function signedBalanceOfVaultTokenId(address account, uint256 id) external view returns (int256);\n}\n\ninterface IVaultController is IVaultAccountAction, IVaultAction, IVaultLiquidationAction, IVaultAccountHealth {}"
      },
      "interfaces/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    function decimals() external view returns (uint8);\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 `recipient`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller'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 `sender` to `recipient` 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 sender, address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
      },
      "interfaces/IEIP20NonStandard.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\n\n/**\n * @title EIP20NonStandardInterface\n * @dev Version of ERC20 with no return values for `transfer` and `transferFrom`\n *  See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n */\ninterface IEIP20NonStandard {\n\n    /**\n     * @notice Get the total number of tokens in circulation\n     * @return The supply of tokens\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @notice Gets the balance of the specified address\n     * @param owner The address from which the balance will be retrieved\n     * @return balance\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    ///\n    /// !!!!!!!!!!!!!!\n    /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification\n    /// !!!!!!!!!!!!!!\n    ///\n\n    /**\n      * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n      * @param dst The address of the destination account\n      * @param amount The number of tokens to transfer\n      */\n    function transfer(address dst, uint256 amount) external;\n\n    ///\n    /// !!!!!!!!!!!!!!\n    /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification\n    /// !!!!!!!!!!!!!!\n    ///\n\n    /**\n      * @notice Transfer `amount` tokens from `src` to `dst`\n      * @param src The address of the source account\n      * @param dst The address of the destination account\n      * @param amount The number of tokens to transfer\n      */\n    function transferFrom(address src, address dst, uint256 amount) external;\n\n    ///\n    /// !!!!!!!!!!!!!!\n    /// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification\n    /// !!!!!!!!!!!!!!\n    ///\n\n    /**\n      * @notice Approve `spender` to transfer up to `amount` from `src`\n      * @dev This will overwrite the approval amount for `spender`\n      *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n      * @param spender The address of the account which may transfer tokens\n      * @param amount The number of tokens that are approved\n      */\n    function approve(address spender, uint256 amount) external;\n\n    /**\n      * @notice Get the current allowance from `owner` for `spender`\n      * @param owner The address of the account which owns the tokens to be spent\n      * @param spender The address of the account which may transfer tokens\n      * @return remaining The number of tokens allowed to be spent\n      */\n    function allowance(address owner, address spender) external view returns (uint256 remaining);\n\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n}"
      },
      "interfaces/chainlink/AggregatorV2V3Interface.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.0;\n\nimport \"./AggregatorInterface.sol\";\nimport \"./AggregatorV3Interface.sol\";\n\ninterface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface\n{\n}"
      },
      "interfaces/notional/IPrimeCashHoldingsOracle.sol": {
        "content": "// SPDX-License-Identifier: GPL-v3\npragma solidity >=0.7.0;\npragma abicoder v2;\n\nstruct DepositData {\n    address[] targets;\n    bytes[] callData;\n    uint256[] msgValue;\n    uint256 underlyingDepositAmount;\n    address assetToken;\n}\n\nstruct RedeemData {\n    address[] targets;\n    bytes[] callData;\n    uint256 expectedUnderlying;\n    address assetToken;\n}\n\ninterface IPrimeCashHoldingsOracle {\n    /// @notice Returns a list of the various holdings for the prime cash\n    /// currency\n    function holdings() external view returns (address[] memory);\n\n    /// @notice Returns the underlying token that all holdings can be redeemed\n    /// for.\n    function underlying() external view returns (address);\n    \n    /// @notice Returns the native decimal precision of the underlying token\n    function decimals() external view returns (uint8);\n\n    /// @notice Returns the total underlying held by the caller in all the\n    /// listed holdings\n    function getTotalUnderlyingValueStateful() external returns (\n        uint256 nativePrecision,\n        uint256 internalPrecision\n    );\n\n    function getTotalUnderlyingValueView() external view returns (\n        uint256 nativePrecision,\n        uint256 internalPrecision\n    );\n\n    /// @notice Returns calldata for how to withdraw an amount\n    function getRedemptionCalldata(uint256 withdrawAmount) external view returns (\n        RedeemData[] memory redeemData\n    );\n\n    function holdingValuesInUnderlying() external view returns (uint256[] memory);\n\n    function getRedemptionCalldataForRebalancing(\n        address[] calldata _holdings, \n        uint256[] calldata withdrawAmounts\n    ) external view returns (\n        RedeemData[] memory redeemData\n    );\n\n    function getDepositCalldataForRebalancing(\n        address[] calldata _holdings, \n        uint256[] calldata depositAmounts\n    ) external view returns (\n        DepositData[] memory depositData\n    );\n}\n"
      },
      "interfaces/notional/AssetRateAdapter.sol": {
        "content": "// SPDX-License-Identifier: GPL-v3\npragma solidity >=0.7.0;\n\n/// @notice Used as a wrapper for tokens that are interest bearing for an\n/// underlying token. Follows the cToken interface, however, can be adapted\n/// for other interest bearing tokens.\ninterface AssetRateAdapter {\n    function token() external view returns (address);\n\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 underlying() external view returns (address);\n\n    function getExchangeRateStateful() external returns (int256);\n\n    function getExchangeRateView() external view returns (int256);\n\n    function getAnnualizedSupplyRate() external view returns (uint256);\n}\n"
      },
      "interfaces/IWstETH.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\nimport {IERC20} from \"./IERC20.sol\";\n\ninterface IWstETH is IERC20 {\n    function unwrap(uint256 _wstETHAmount) external returns (uint256);\n    function wrap(uint256 _stETHAmount) external returns (uint256);\n    function getStETHByWstETH(uint256 _wstETHAmount) external view returns (uint256);\n    function stEthPerToken() external view returns (uint256);\n    function stETH() external view returns (address);\n}"
      },
      "interfaces/balancer/IBalancerVault.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\ninterface IAsset {\n    // solhint-disable-previous-line no-empty-blocks\n}\n\ninterface IBalancerVault {\n    enum PoolSpecialization {\n        GENERAL,\n        MINIMAL_SWAP_INFO,\n        TWO_TOKEN\n    }\n    enum JoinKind {\n        INIT,\n        EXACT_TOKENS_IN_FOR_BPT_OUT,\n        TOKEN_IN_FOR_EXACT_BPT_OUT,\n        ALL_TOKENS_IN_FOR_EXACT_BPT_OUT\n    }\n    enum MetaStableExitKind {\n        EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,\n        EXACT_BPT_IN_FOR_TOKENS_OUT,\n        BPT_IN_FOR_EXACT_TOKENS_OUT,\n        MANAGEMENT_FEE_TOKENS_OUT // for ManagedPool\n    }\n    enum ComposableExitKind {\n        EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,\n        BPT_IN_FOR_EXACT_TOKENS_OUT,\n        EXACT_BPT_IN_FOR_ALL_TOKENS_OUT\n    }\n    enum WeightedPoolExitKind {\n        EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,\n        EXACT_BPT_IN_FOR_TOKENS_OUT,\n        BPT_IN_FOR_EXACT_TOKENS_OUT,\n        MANAGEMENT_FEE_TOKENS_OUT // for InvestmentPool\n    }\n\n\n    enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }\n\n    /**\n     * @dev Returns a Pool's contract address and specialization setting.\n     */\n    function getPool(bytes32 poolId)\n        external\n        view\n        returns (address, PoolSpecialization);\n\n    function joinPool(\n        bytes32 poolId,\n        address sender,\n        address recipient,\n        JoinPoolRequest memory request\n    ) external payable;\n\n    struct JoinPoolRequest {\n        IAsset[] assets;\n        uint256[] maxAmountsIn;\n        bytes userData;\n        bool fromInternalBalance;\n    }\n\n    function exitPool(\n        bytes32 poolId,\n        address sender,\n        address payable recipient,\n        ExitPoolRequest memory request\n    ) external;\n\n    struct ExitPoolRequest {\n        IAsset[] assets;\n        uint256[] minAmountsOut;\n        bytes userData;\n        bool toInternalBalance;\n    }\n\n    enum SwapKind {\n        GIVEN_IN,\n        GIVEN_OUT\n    }\n\n    struct SingleSwap {\n        bytes32 poolId;\n        SwapKind kind;\n        IAsset assetIn;\n        IAsset assetOut;\n        uint256 amount;\n        bytes userData;\n    }\n\n    struct FundManagement {\n        address sender;\n        bool fromInternalBalance;\n        address payable recipient;\n        bool toInternalBalance;\n    }\n\n    function swap(\n        SingleSwap memory singleSwap,\n        FundManagement memory funds,\n        uint256 limit,\n        uint256 deadline\n    ) external payable returns (uint256);\n\n    struct BatchSwapStep {\n        bytes32 poolId;\n        uint256 assetInIndex;\n        uint256 assetOutIndex;\n        uint256 amount;\n        bytes userData;\n    }\n\n    function batchSwap(\n        SwapKind kind,\n        BatchSwapStep[] memory swaps,\n        IAsset[] memory assets,\n        FundManagement memory funds,\n        int256[] memory limits,\n        uint256 deadline\n    ) external payable returns (int256[] memory);\n\n    function getPoolTokens(bytes32 poolId)\n        external\n        view\n        returns (\n            address[] memory tokens,\n            uint256[] memory balances,\n            uint256 lastChangeBlock\n        );\n\n    function flashLoan(\n        address recipient, \n        address[] calldata tokens, \n        uint256[] calldata amounts, \n        bytes calldata userData\n    ) external;\n\n    struct UserBalanceOp {\n        UserBalanceOpKind kind;\n        IAsset asset;\n        uint256 amount;\n        address sender;\n        address payable recipient;\n    }\n\n    function manageUserBalance(UserBalanceOp[] memory ops) external payable;\n}\n"
      },
      "interfaces/uniswap/v3/ISwapRouter.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\npragma abicoder v2;\n\nimport './IUniswapV3SwapCallback.sol';\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via Uniswap V3\ninterface ISwapRouter is IUniswapV3SwapCallback {\n    struct ExactInputSingleParams {\n        address tokenIn;\n        address tokenOut;\n        uint24 fee;\n        address recipient;\n        uint256 deadline;\n        uint256 amountIn;\n        uint256 amountOutMinimum;\n        uint160 sqrtPriceLimitX96;\n    }\n\n    /// @notice Swaps `amountIn` of one token for as much as possible of another token\n    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n    /// @return amountOut The amount of the received token\n    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\n\n    struct ExactInputParams {\n        bytes path;\n        address recipient;\n        uint256 deadline;\n        uint256 amountIn;\n        uint256 amountOutMinimum;\n    }\n\n    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n    /// @return amountOut The amount of the received token\n    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\n\n    struct ExactOutputSingleParams {\n        address tokenIn;\n        address tokenOut;\n        uint24 fee;\n        address recipient;\n        uint256 deadline;\n        uint256 amountOut;\n        uint256 amountInMaximum;\n        uint160 sqrtPriceLimitX96;\n    }\n\n    /// @notice Swaps as little as possible of one token for `amountOut` of another token\n    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n    /// @return amountIn The amount of the input token\n    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\n\n    struct ExactOutputParams {\n        bytes path;\n        address recipient;\n        uint256 deadline;\n        uint256 amountOut;\n        uint256 amountInMaximum;\n    }\n\n    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\n    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n    /// @return amountIn The amount of the input token\n    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\n}\n"
      },
      "interfaces/uniswap/v2/IUniV2Router2.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\npragma abicoder v2;\n\ninterface IUniV2Router2 {\n    function swapETHForExactTokens(\n        uint256 amountOut,\n        address[] calldata path,\n        address to,\n        uint256 deadline\n    ) external payable returns (uint256[] memory amounts);\n\n    function swapExactETHForTokens(\n        uint256 amountOutMin,\n        address[] calldata path,\n        address to,\n        uint256 deadline\n    ) external payable returns (uint256[] memory amounts);\n\n    function swapTokensForExactETH(\n        uint256 amountOut,\n        uint256 amountInMax,\n        address[] calldata path,\n        address to,\n        uint256 deadline\n    ) external returns (uint256[] memory amounts);\n\n    function swapExactTokensForETH(\n        uint256 amountIn,\n        uint256 amountOutMin,\n        address[] calldata path,\n        address to,\n        uint256 deadline\n    ) external returns (uint256[] memory amounts);\n\n    function swapExactTokensForTokens(\n        uint256 amountIn,\n        uint256 amountOutMin,\n        address[] calldata path,\n        address to,\n        uint256 deadline\n    ) external returns (uint256[] memory amounts);\n\n    function swapTokensForExactTokens(\n        uint256 amountOut,\n        uint256 amountInMax,\n        address[] calldata path,\n        address to,\n        uint256 deadline\n    ) external returns (uint256[] memory amounts);\n}\n"
      },
      "interfaces/curve/ICurveRouter.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\ninterface ICurveRouter {\n    function exchange(\n        uint256 _amount,\n        address[6] calldata _route,\n        uint256[8] calldata _indices,\n        uint256 _min_received\n    ) external payable;\n\n    function get_exchange_routing(\n        address _initial,\n        address _target,\n        uint256 _amount\n    ) external view returns (\n        address[6] memory route,\n        uint256[8] memory indexes,\n        uint256 expectedOutputAmount\n    );\n\n    function can_route(address _initial, address _target) external view returns (bool);\n}\n"
      },
      "interfaces/curve/ICurveRegistry.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\ninterface ICurveRegistry {\n    function find_pool_for_coins(address _from, address _to, uint256 i)\n        external\n        view\n        returns (address);\n}\n"
      },
      "interfaces/curve/ICurveMetaRegistry.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\ninterface ICurveMetaRegistry {\n    function get_registry_handlers_from_pool(address _pool)\n        external\n        view\n        returns (address[10] memory);\n}\n"
      },
      "interfaces/curve/ICurveRouterV2.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\ninterface ICurveRouterV2 {\n    function exchange(\n        address _pool,\n        address _from,\n        address _to,\n        uint256 _amount,\n        uint256 _expected,\n        address _receiver\n    ) external returns (uint256);\n\n    function exchange_multiple(\n        address[9] calldata _route,\n        uint256[3][4] calldata _swap_params,\n        uint256 _amount,\n        uint256 _expected,\n        address[4] calldata _pools,\n        address _receiver\n    ) external returns (uint256);\n}\n"
      },
      "interfaces/trading/ITradingModule.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\nimport \"../chainlink/AggregatorV2V3Interface.sol\";\n\nenum DexId {\n    _UNUSED,        // flag = 1\n    UNISWAP_V2,     // flag = 2\n    UNISWAP_V3,     // flag = 4\n    ZERO_EX,        // flag = 8\n    BALANCER_V2,    // flag = 16\n    // NOTE: this id is unused in the TradingModule\n    CURVE,          // flag = 32 \n    NOTIONAL_VAULT, // flag = 64\n    CURVE_V2        // flag = 128\n}\n\nenum TradeType {\n    EXACT_IN_SINGLE,  // flag = 1\n    EXACT_OUT_SINGLE, // flag = 2\n    EXACT_IN_BATCH,   // flag = 4\n    EXACT_OUT_BATCH   // flag = 8\n}\n\nstruct Trade {\n    TradeType tradeType;\n    address sellToken;\n    address buyToken;\n    uint256 amount;\n    /// minBuyAmount or maxSellAmount\n    uint256 limit;\n    uint256 deadline;\n    bytes exchangeData;\n}\n\nerror InvalidTrade();\nerror DynamicTradeFailed();\nerror TradeFailed();\n\ninterface ITradingModule {\n    struct TokenPermissions {\n        bool allowSell;\n        /// @notice allowed DEXes\n        uint32 dexFlags;\n        /// @notice allowed trade types\n        uint32 tradeTypeFlags; \n    }\n\n    event TradeExecuted(\n        address indexed sellToken,\n        address indexed buyToken,\n        uint256 sellAmount,\n        uint256 buyAmount\n    );\n\n    event PriceOracleUpdated(address token, address oracle);\n    event MaxOracleFreshnessUpdated(uint32 currentValue, uint32 newValue);\n    event TokenPermissionsUpdated(address sender, address token, TokenPermissions permissions);\n\n    function priceOracles(address token) external view returns (AggregatorV2V3Interface oracle, uint8 rateDecimals);\n\n    function getExecutionData(uint16 dexId, address from, Trade calldata trade)\n        external view returns (\n            address spender,\n            address target,\n            uint256 value,\n            bytes memory params\n        );\n\n    function setPriceOracle(address token, AggregatorV2V3Interface oracle) external;\n\n    function setTokenPermissions(\n        address sender, \n        address token, \n        TokenPermissions calldata permissions\n    ) external;\n\n    function getOraclePrice(address inToken, address outToken)\n        external view returns (int256 answer, int256 decimals);\n\n    function executeTrade(\n        uint16 dexId,\n        Trade calldata trade\n    ) external payable returns (uint256 amountSold, uint256 amountBought);\n\n    function executeTradeWithDynamicSlippage(\n        uint16 dexId,\n        Trade memory trade,\n        uint32 dynamicSlippageLimit\n    ) external payable returns (uint256 amountSold, uint256 amountBought);\n\n    function getLimitAmount(\n        address from,\n        TradeType tradeType,\n        address sellToken,\n        address buyToken,\n        uint256 amount,\n        uint32 slippageLimit\n    ) external view returns (uint256 limitAmount);\n\n    function canExecuteTrade(address from, uint16 dexId, Trade calldata trade) external view returns (bool);\n}\n"
      },
      "interfaces/notional/IWrappedfCashFactory.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\ninterface IWrappedfCashFactory {\n    function deployWrapper(uint16 currencyId, uint40 maturity) external returns (address);\n    function computeAddress(uint16 currencyId, uint40 maturity) external view returns (address);\n}\n"
      },
      "interfaces/notional/IRewarder.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\n\ninterface IRewarder {\n    function claimRewards(\n        address account,\n        uint16 currencyId,\n        uint256 nTokenBalanceBefore,\n        uint256 nTokenBalanceAfter,\n        int256  netNTokenSupplyChange,\n        uint256 NOTETokensClaimed\n    ) external;\n}"
      },
      "interfaces/aave/ILendingPool.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.7.6;\npragma abicoder v2;\n\nstruct LendingPoolStorage {\n  ILendingPool lendingPool;\n}\n\ninterface ILendingPool {\n\n  /**\n   * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n   * - E.g. User deposits 100 USDC and gets in return 100 aUSDC\n   * @param asset The address of the underlying asset to deposit\n   * @param amount The amount to be deposited\n   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n   *   is a different wallet\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   **/\n  function deposit(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n   * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n   * @param asset The address of the underlying asset to withdraw\n   * @param amount The underlying amount to be withdrawn\n   *   - Send the value type(uint256).max in order to withdraw the whole aToken balance\n   * @param to Address that will receive the underlying, same as msg.sender if the user\n   *   wants to receive it on his own wallet, or a different address if the beneficiary is a\n   *   different wallet\n   * @return The final amount withdrawn\n   **/\n  function withdraw(\n    address asset,\n    uint256 amount,\n    address to\n  ) external returns (uint256);\n\n  /**\n   * @dev Returns the normalized income normalized income of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The reserve's normalized income\n   */\n  function getReserveNormalizedIncome(address asset) external view returns (uint256);\n\n    /**\n   * @dev Returns the state and configuration of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The state of the reserve\n   **/\n  function getReserveData(address asset) external view returns (ReserveData memory);\n\n  // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.\n  struct ReserveData {\n    //stores the reserve configuration\n    ReserveConfigurationMap configuration;\n    //the liquidity index. Expressed in ray\n    uint128 liquidityIndex;\n    //variable borrow index. Expressed in ray\n    uint128 variableBorrowIndex;\n    //the current supply rate. Expressed in ray\n    uint128 currentLiquidityRate;\n    //the current variable borrow rate. Expressed in ray\n    uint128 currentVariableBorrowRate;\n    //the current stable borrow rate. Expressed in ray\n    uint128 currentStableBorrowRate;\n    uint40 lastUpdateTimestamp;\n    //tokens addresses\n    address aTokenAddress;\n    address stableDebtTokenAddress;\n    address variableDebtTokenAddress;\n    //address of the interest rate strategy\n    address interestRateStrategyAddress;\n    //the id of the reserve. Represents the position in the list of the active reserves\n    uint8 id;\n  }\n\n  struct ReserveConfigurationMap {\n    //bit 0-15: LTV\n    //bit 16-31: Liq. threshold\n    //bit 32-47: Liq. bonus\n    //bit 48-55: Decimals\n    //bit 56: Reserve is active\n    //bit 57: reserve is frozen\n    //bit 58: borrowing is enabled\n    //bit 59: stable rate borrowing enabled\n    //bit 60-63: reserved\n    //bit 64-79: reserve factor\n    uint256 data;\n  }\n\n  struct UserConfigurationMap {\n    uint256 data;\n  }\n\n  enum InterestRateMode {NONE, STABLE, VARIABLE}\n}\n"
      },
      "interfaces/chainlink/AggregatorInterface.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.0;\n\ninterface AggregatorInterface {\n  function latestAnswer() external view returns (int256);\n  function latestTimestamp() external view returns (uint256);\n  function latestRound() external view returns (uint256);\n  function getAnswer(uint256 roundId) external view returns (int256);\n  function getTimestamp(uint256 roundId) external view returns (uint256);\n\n  event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);\n  event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);\n}"
      },
      "interfaces/chainlink/AggregatorV3Interface.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.0;\n\ninterface AggregatorV3Interface {\n\n  function decimals() external view returns (uint8);\n  function description() external view returns (string memory);\n  function version() external view returns (uint256);\n\n  // getRoundData and latestRoundData should both raise \"No data present\"\n  // if they do not have data to report, instead of returning unset values\n  // which could be misinterpreted as actual reported values.\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}"
      },
      "interfaces/uniswap/v3/IUniswapV3SwapCallback.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n    /// @dev In the implementation you must pay the pool tokens owed for the swap.\n    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n    function uniswapV3SwapCallback(\n        int256 amount0Delta,\n        int256 amount1Delta,\n        bytes calldata data\n    ) external;\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "forge-std/=lib/forge-std/src/",
        "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
        "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
        "@interfaces/=interfaces/",
        "@contracts/=contracts/",
        "@deployments/=contracts/global/mainnet/",
        "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "shanghai",
      "viaIR": false,
      "libraries": {
        "contracts/vaults/common/StrategyUtils.sol": {
          "StrategyUtils": "0xE78D09c8B6cCF9C1732d14353a708b75f6C67c67"
        }
      }
    }
  }}