creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@morpho-org/morpho-blue/src/interfaces/IIrm.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport {MarketParams, Market} from \"./IMorpho.sol\";\n\n/// @title IIrm\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @notice Interface that Interest Rate Models (IRMs) used by Morpho must implement.\ninterface IIrm {\n    /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams`.\n    /// @dev Assumes that `market` corresponds to `marketParams`.\n    function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256);\n\n    /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams` without modifying any\n    /// storage.\n    /// @dev Assumes that `market` corresponds to `marketParams`.\n    function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);\n}\n"
      },
      "@morpho-org/morpho-blue/src/interfaces/IMorpho.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\ntype Id is bytes32;\n\nstruct MarketParams {\n    address loanToken;\n    address collateralToken;\n    address oracle;\n    address irm;\n    uint256 lltv;\n}\n\n/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest\n/// accrual.\nstruct Position {\n    uint256 supplyShares;\n    uint128 borrowShares;\n    uint128 collateral;\n}\n\n/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.\n/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.\n/// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last\n/// interest accrual.\nstruct Market {\n    uint128 totalSupplyAssets;\n    uint128 totalSupplyShares;\n    uint128 totalBorrowAssets;\n    uint128 totalBorrowShares;\n    uint128 lastUpdate;\n    uint128 fee;\n}\n\nstruct Authorization {\n    address authorizer;\n    address authorized;\n    bool isAuthorized;\n    uint256 nonce;\n    uint256 deadline;\n}\n\nstruct Signature {\n    uint8 v;\n    bytes32 r;\n    bytes32 s;\n}\n\n/// @dev This interface is used for factorizing IMorphoStaticTyping and IMorpho.\n/// @dev Consider using the IMorpho interface instead of this one.\ninterface IMorphoBase {\n    /// @notice The EIP-712 domain separator.\n    /// @dev Warning: Every EIP-712 signed message based on this domain separator can be reused on another chain sharing\n    /// the same chain id because the domain separator would be the same.\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n\n    /// @notice The owner of the contract.\n    /// @dev It has the power to change the owner.\n    /// @dev It has the power to set fees on markets and set the fee recipient.\n    /// @dev It has the power to enable but not disable IRMs and LLTVs.\n    function owner() external view returns (address);\n\n    /// @notice The fee recipient of all markets.\n    /// @dev The recipient receives the fees of a given market through a supply position on that market.\n    function feeRecipient() external view returns (address);\n\n    /// @notice Whether the `irm` is enabled.\n    function isIrmEnabled(address irm) external view returns (bool);\n\n    /// @notice Whether the `lltv` is enabled.\n    function isLltvEnabled(uint256 lltv) external view returns (bool);\n\n    /// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.\n    /// @dev Anyone is authorized to modify their own positions, regardless of this variable.\n    function isAuthorized(address authorizer, address authorized) external view returns (bool);\n\n    /// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.\n    function nonce(address authorizer) external view returns (uint256);\n\n    /// @notice Sets `newOwner` as `owner` of the contract.\n    /// @dev Warning: No two-step transfer ownership.\n    /// @dev Warning: The owner can be set to the zero address.\n    function setOwner(address newOwner) external;\n\n    /// @notice Enables `irm` as a possible IRM for market creation.\n    /// @dev Warning: It is not possible to disable an IRM.\n    function enableIrm(address irm) external;\n\n    /// @notice Enables `lltv` as a possible LLTV for market creation.\n    /// @dev Warning: It is not possible to disable a LLTV.\n    function enableLltv(uint256 lltv) external;\n\n    /// @notice Sets the `newFee` for the given market `marketParams`.\n    /// @param newFee The new fee, scaled by WAD.\n    /// @dev Warning: The recipient can be the zero address.\n    function setFee(MarketParams memory marketParams, uint256 newFee) external;\n\n    /// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.\n    /// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.\n    /// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To\n    /// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.\n    function setFeeRecipient(address newFeeRecipient) external;\n\n    /// @notice Creates the market `marketParams`.\n    /// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees\n    /// Morpho behaves as expected:\n    /// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.\n    /// - The token balance of Morpho should only decrease on `transfer` and `transferFrom`. In particular, tokens with\n    /// burn functions are not supported.\n    /// - The token should not re-enter Morpho on `transfer` nor `transferFrom`.\n    /// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount\n    /// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.\n    /// - The IRM should not re-enter Morpho.\n    /// - The oracle should return a price with the correct scaling.\n    /// @dev Here is a list of properties on the market's dependencies that could break Morpho's liveness properties\n    /// (funds could get stuck):\n    /// - The token can revert on `transfer` and `transferFrom` for a reason other than an approval or balance issue.\n    /// - A very high amount of assets (~1e35) supplied or borrowed can make the computation of `toSharesUp` and\n    /// `toSharesDown` overflow.\n    /// - The IRM can revert on `borrowRate`.\n    /// - A very high borrow rate returned by the IRM can make the computation of `interest` in `_accrueInterest`\n    /// overflow.\n    /// - The oracle can revert on `price`. Note that this can be used to prevent `borrow`, `withdrawCollateral` and\n    /// `liquidate` from being used under certain market conditions.\n    /// - A very high price returned by the oracle can make the computation of `maxBorrow` in `_isHealthy` overflow, or\n    /// the computation of `assetsRepaid` in `liquidate` overflow.\n    /// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to\n    /// the point where `totalBorrowShares` is very large and borrowing overflows.\n    function createMarket(MarketParams memory marketParams) external;\n\n    /// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's\n    /// `onMorphoSupply` function with the given `data`.\n    /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the\n    /// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific\n    /// amount of shares is given for full compatibility and precision.\n    /// @dev Supplying a large amount can revert for overflow.\n    /// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.\n    /// Consider using the `assets` parameter to avoid this.\n    /// @param marketParams The market to supply assets to.\n    /// @param assets The amount of assets to supply.\n    /// @param shares The amount of shares to mint.\n    /// @param onBehalf The address that will own the increased supply position.\n    /// @param data Arbitrary data to pass to the `onMorphoSupply` callback. Pass empty data if not needed.\n    /// @return assetsSupplied The amount of assets supplied.\n    /// @return sharesSupplied The amount of shares minted.\n    function supply(\n        MarketParams memory marketParams,\n        uint256 assets,\n        uint256 shares,\n        address onBehalf,\n        bytes memory data\n    ) external returns (uint256 assetsSupplied, uint256 sharesSupplied);\n\n    /// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.\n    /// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.\n    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.\n    /// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.\n    /// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to\n    /// conversion roundings between shares and assets.\n    /// @param marketParams The market to withdraw assets from.\n    /// @param assets The amount of assets to withdraw.\n    /// @param shares The amount of shares to burn.\n    /// @param onBehalf The address of the owner of the supply position.\n    /// @param receiver The address that will receive the withdrawn assets.\n    /// @return assetsWithdrawn The amount of assets withdrawn.\n    /// @return sharesWithdrawn The amount of shares burned.\n    function withdraw(\n        MarketParams memory marketParams,\n        uint256 assets,\n        uint256 shares,\n        address onBehalf,\n        address receiver\n    ) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);\n\n    /// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.\n    /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the\n    /// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is\n    /// given for full compatibility and precision.\n    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.\n    /// @dev Borrowing a large amount can revert for overflow.\n    /// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.\n    /// Consider using the `assets` parameter to avoid this.\n    /// @param marketParams The market to borrow assets from.\n    /// @param assets The amount of assets to borrow.\n    /// @param shares The amount of shares to mint.\n    /// @param onBehalf The address that will own the increased borrow position.\n    /// @param receiver The address that will receive the borrowed assets.\n    /// @return assetsBorrowed The amount of assets borrowed.\n    /// @return sharesBorrowed The amount of shares minted.\n    function borrow(\n        MarketParams memory marketParams,\n        uint256 assets,\n        uint256 shares,\n        address onBehalf,\n        address receiver\n    ) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);\n\n    /// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's\n    /// `onMorphoReplay` function with the given `data`.\n    /// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.\n    /// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.\n    /// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion\n    /// roundings between shares and assets.\n    /// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.\n    /// @param marketParams The market to repay assets to.\n    /// @param assets The amount of assets to repay.\n    /// @param shares The amount of shares to burn.\n    /// @param onBehalf The address of the owner of the debt position.\n    /// @param data Arbitrary data to pass to the `onMorphoRepay` callback. Pass empty data if not needed.\n    /// @return assetsRepaid The amount of assets repaid.\n    /// @return sharesRepaid The amount of shares burned.\n    function repay(\n        MarketParams memory marketParams,\n        uint256 assets,\n        uint256 shares,\n        address onBehalf,\n        bytes memory data\n    ) external returns (uint256 assetsRepaid, uint256 sharesRepaid);\n\n    /// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's\n    /// `onMorphoSupplyCollateral` function with the given `data`.\n    /// @dev Interest are not accrued since it's not required and it saves gas.\n    /// @dev Supplying a large amount can revert for overflow.\n    /// @param marketParams The market to supply collateral to.\n    /// @param assets The amount of collateral to supply.\n    /// @param onBehalf The address that will own the increased collateral position.\n    /// @param data Arbitrary data to pass to the `onMorphoSupplyCollateral` callback. Pass empty data if not needed.\n    function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)\n        external;\n\n    /// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.\n    /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.\n    /// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.\n    /// @param marketParams The market to withdraw collateral from.\n    /// @param assets The amount of collateral to withdraw.\n    /// @param onBehalf The address of the owner of the collateral position.\n    /// @param receiver The address that will receive the collateral assets.\n    function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)\n        external;\n\n    /// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the\n    /// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's\n    /// `onMorphoLiquidate` function with the given `data`.\n    /// @dev Either `seizedAssets` or `repaidShares` should be zero.\n    /// @dev Seizing more than the collateral balance will underflow and revert without any error message.\n    /// @dev Repaying more than the borrow balance will underflow and revert without any error message.\n    /// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.\n    /// @param marketParams The market of the position.\n    /// @param borrower The owner of the position.\n    /// @param seizedAssets The amount of collateral to seize.\n    /// @param repaidShares The amount of shares to repay.\n    /// @param data Arbitrary data to pass to the `onMorphoLiquidate` callback. Pass empty data if not needed.\n    /// @return The amount of assets seized.\n    /// @return The amount of assets repaid.\n    function liquidate(\n        MarketParams memory marketParams,\n        address borrower,\n        uint256 seizedAssets,\n        uint256 repaidShares,\n        bytes memory data\n    ) external returns (uint256, uint256);\n\n    /// @notice Executes a flash loan.\n    /// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all\n    /// markets combined, plus donations).\n    /// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:\n    /// - `flashFee` is zero.\n    /// - `maxFlashLoan` is the token's balance of this contract.\n    /// - The receiver of `assets` is the caller.\n    /// @param token The token to flash loan.\n    /// @param assets The amount of assets to flash loan.\n    /// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.\n    function flashLoan(address token, uint256 assets, bytes calldata data) external;\n\n    /// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.\n    /// @param authorized The authorized address.\n    /// @param newIsAuthorized The new authorization status.\n    function setAuthorization(address authorized, bool newIsAuthorized) external;\n\n    /// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.\n    /// @dev Warning: Reverts if the signature has already been submitted.\n    /// @dev The signature is malleable, but it has no impact on the security here.\n    /// @dev The nonce is passed as argument to be able to revert with a different error message.\n    /// @param authorization The `Authorization` struct.\n    /// @param signature The signature.\n    function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;\n\n    /// @notice Accrues interest for the given market `marketParams`.\n    function accrueInterest(MarketParams memory marketParams) external;\n\n    /// @notice Returns the data stored on the different `slots`.\n    function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory);\n}\n\n/// @dev This interface is inherited by Morpho so that function signatures are checked by the compiler.\n/// @dev Consider using the IMorpho interface instead of this one.\ninterface IMorphoStaticTyping is IMorphoBase {\n    /// @notice The state of the position of `user` on the market corresponding to `id`.\n    /// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest\n    /// accrual.\n    function position(Id id, address user)\n        external\n        view\n        returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);\n\n    /// @notice The state of the market corresponding to `id`.\n    /// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.\n    /// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.\n    /// @dev Warning: `totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last interest\n    /// accrual.\n    function market(Id id)\n        external\n        view\n        returns (\n            uint128 totalSupplyAssets,\n            uint128 totalSupplyShares,\n            uint128 totalBorrowAssets,\n            uint128 totalBorrowShares,\n            uint128 lastUpdate,\n            uint128 fee\n        );\n\n    /// @notice The market params corresponding to `id`.\n    /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer\n    /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.\n    function idToMarketParams(Id id)\n        external\n        view\n        returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);\n}\n\n/// @title IMorpho\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @dev Use this interface for Morpho to have access to all the functions with the appropriate function signatures.\ninterface IMorpho is IMorphoBase {\n    /// @notice The state of the position of `user` on the market corresponding to `id`.\n    /// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest\n    /// accrual.\n    function position(Id id, address user) external view returns (Position memory p);\n\n    /// @notice The state of the market corresponding to `id`.\n    /// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.\n    /// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.\n    /// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last\n    /// interest accrual.\n    function market(Id id) external view returns (Market memory m);\n\n    /// @notice The market params corresponding to `id`.\n    /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer\n    /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.\n    function idToMarketParams(Id id) external view returns (MarketParams memory);\n}\n"
      },
      "@morpho-org/morpho-blue/src/interfaces/IMorphoCallbacks.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title IMorphoLiquidateCallback\n/// @notice Interface that liquidators willing to use `liquidate`'s callback must implement.\ninterface IMorphoLiquidateCallback {\n    /// @notice Callback called when a liquidation occurs.\n    /// @dev The callback is called only if data is not empty.\n    /// @param repaidAssets The amount of repaid assets.\n    /// @param data Arbitrary data passed to the `liquidate` function.\n    function onMorphoLiquidate(uint256 repaidAssets, bytes calldata data) external;\n}\n\n/// @title IMorphoRepayCallback\n/// @notice Interface that users willing to use `repay`'s callback must implement.\ninterface IMorphoRepayCallback {\n    /// @notice Callback called when a repayment occurs.\n    /// @dev The callback is called only if data is not empty.\n    /// @param assets The amount of repaid assets.\n    /// @param data Arbitrary data passed to the `repay` function.\n    function onMorphoRepay(uint256 assets, bytes calldata data) external;\n}\n\n/// @title IMorphoSupplyCallback\n/// @notice Interface that users willing to use `supply`'s callback must implement.\ninterface IMorphoSupplyCallback {\n    /// @notice Callback called when a supply occurs.\n    /// @dev The callback is called only if data is not empty.\n    /// @param assets The amount of supplied assets.\n    /// @param data Arbitrary data passed to the `supply` function.\n    function onMorphoSupply(uint256 assets, bytes calldata data) external;\n}\n\n/// @title IMorphoSupplyCollateralCallback\n/// @notice Interface that users willing to use `supplyCollateral`'s callback must implement.\ninterface IMorphoSupplyCollateralCallback {\n    /// @notice Callback called when a supply of collateral occurs.\n    /// @dev The callback is called only if data is not empty.\n    /// @param assets The amount of supplied collateral.\n    /// @param data Arbitrary data passed to the `supplyCollateral` function.\n    function onMorphoSupplyCollateral(uint256 assets, bytes calldata data) external;\n}\n\n/// @title IMorphoFlashLoanCallback\n/// @notice Interface that users willing to use `flashLoan`'s callback must implement.\ninterface IMorphoFlashLoanCallback {\n    /// @notice Callback called when a flash loan occurs.\n    /// @dev The callback is called only if data is not empty.\n    /// @param assets The amount of assets that was flash loaned.\n    /// @param data Arbitrary data passed to the `flashLoan` function.\n    function onMorphoFlashLoan(uint256 assets, bytes calldata data) external;\n}\n"
      },
      "@morpho-org/morpho-blue/src/interfaces/IOracle.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title IOracle\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @notice Interface that oracles used by Morpho must implement.\n/// @dev It is the user's responsibility to select markets with safe oracles.\ninterface IOracle {\n    /// @notice Returns the price of 1 asset of collateral token quoted in 1 asset of loan token, scaled by 1e36.\n    /// @dev It corresponds to the price of 10**(collateral token decimals) assets of collateral token quoted in\n    /// 10**(loan token decimals) assets of loan token with `36 + loan token decimals - collateral token decimals`\n    /// decimals of precision.\n    function price() external view returns (uint256);\n}\n"
      },
      "@morpho-org/morpho-blue/src/libraries/ConstantsLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @dev The maximum fee a market can have (25%).\nuint256 constant MAX_FEE = 0.25e18;\n\n/// @dev Oracle price scale.\nuint256 constant ORACLE_PRICE_SCALE = 1e36;\n\n/// @dev Liquidation cursor.\nuint256 constant LIQUIDATION_CURSOR = 0.3e18;\n\n/// @dev Max liquidation incentive factor.\nuint256 constant MAX_LIQUIDATION_INCENTIVE_FACTOR = 1.15e18;\n\n/// @dev The EIP-712 typeHash for EIP712Domain.\nbytes32 constant DOMAIN_TYPEHASH = keccak256(\"EIP712Domain(uint256 chainId,address verifyingContract)\");\n\n/// @dev The EIP-712 typeHash for Authorization.\nbytes32 constant AUTHORIZATION_TYPEHASH =\n    keccak256(\"Authorization(address authorizer,address authorized,bool isAuthorized,uint256 nonce,uint256 deadline)\");\n"
      },
      "@morpho-org/morpho-blue/src/libraries/ErrorsLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title ErrorsLib\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @notice Library exposing error messages.\nlibrary ErrorsLib {\n    /// @notice Thrown when the caller is not the owner.\n    string internal constant NOT_OWNER = \"not owner\";\n\n    /// @notice Thrown when the LLTV to enable exceeds the maximum LLTV.\n    string internal constant MAX_LLTV_EXCEEDED = \"max LLTV exceeded\";\n\n    /// @notice Thrown when the fee to set exceeds the maximum fee.\n    string internal constant MAX_FEE_EXCEEDED = \"max fee exceeded\";\n\n    /// @notice Thrown when the value is already set.\n    string internal constant ALREADY_SET = \"already set\";\n\n    /// @notice Thrown when the IRM is not enabled at market creation.\n    string internal constant IRM_NOT_ENABLED = \"IRM not enabled\";\n\n    /// @notice Thrown when the LLTV is not enabled at market creation.\n    string internal constant LLTV_NOT_ENABLED = \"LLTV not enabled\";\n\n    /// @notice Thrown when the market is already created.\n    string internal constant MARKET_ALREADY_CREATED = \"market already created\";\n\n    /// @notice Thrown when a token to transfer doesn't have code.\n    string internal constant NO_CODE = \"no code\";\n\n    /// @notice Thrown when the market is not created.\n    string internal constant MARKET_NOT_CREATED = \"market not created\";\n\n    /// @notice Thrown when not exactly one of the input amount is zero.\n    string internal constant INCONSISTENT_INPUT = \"inconsistent input\";\n\n    /// @notice Thrown when zero assets is passed as input.\n    string internal constant ZERO_ASSETS = \"zero assets\";\n\n    /// @notice Thrown when a zero address is passed as input.\n    string internal constant ZERO_ADDRESS = \"zero address\";\n\n    /// @notice Thrown when the caller is not authorized to conduct an action.\n    string internal constant UNAUTHORIZED = \"unauthorized\";\n\n    /// @notice Thrown when the collateral is insufficient to `borrow` or `withdrawCollateral`.\n    string internal constant INSUFFICIENT_COLLATERAL = \"insufficient collateral\";\n\n    /// @notice Thrown when the liquidity is insufficient to `withdraw` or `borrow`.\n    string internal constant INSUFFICIENT_LIQUIDITY = \"insufficient liquidity\";\n\n    /// @notice Thrown when the position to liquidate is healthy.\n    string internal constant HEALTHY_POSITION = \"position is healthy\";\n\n    /// @notice Thrown when the authorization signature is invalid.\n    string internal constant INVALID_SIGNATURE = \"invalid signature\";\n\n    /// @notice Thrown when the authorization signature is expired.\n    string internal constant SIGNATURE_EXPIRED = \"signature expired\";\n\n    /// @notice Thrown when the nonce is invalid.\n    string internal constant INVALID_NONCE = \"invalid nonce\";\n\n    /// @notice Thrown when a token transfer reverted.\n    string internal constant TRANSFER_REVERTED = \"transfer reverted\";\n\n    /// @notice Thrown when a token transfer returned false.\n    string internal constant TRANSFER_RETURNED_FALSE = \"transfer returned false\";\n\n    /// @notice Thrown when a token transferFrom reverted.\n    string internal constant TRANSFER_FROM_REVERTED = \"transferFrom reverted\";\n\n    /// @notice Thrown when a token transferFrom returned false\n    string internal constant TRANSFER_FROM_RETURNED_FALSE = \"transferFrom returned false\";\n\n    /// @notice Thrown when the maximum uint128 is exceeded.\n    string internal constant MAX_UINT128_EXCEEDED = \"max uint128 exceeded\";\n}\n"
      },
      "@morpho-org/morpho-blue/src/libraries/MarketParamsLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport {Id, MarketParams} from \"../interfaces/IMorpho.sol\";\n\n/// @title MarketParamsLib\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @notice Library to convert a market to its id.\nlibrary MarketParamsLib {\n    /// @notice The length of the data used to compute the id of a market.\n    /// @dev The length is 5 * 32 because `MarketParams` has 5 variables of 32 bytes each.\n    uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;\n\n    /// @notice Returns the id of the market `marketParams`.\n    function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {\n        assembly (\"memory-safe\") {\n            marketParamsId := keccak256(marketParams, MARKET_PARAMS_BYTES_LENGTH)\n        }\n    }\n}\n"
      },
      "@morpho-org/morpho-blue/src/libraries/MathLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nuint256 constant WAD = 1e18;\n\n/// @title MathLib\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @notice Library to manage fixed-point arithmetic.\nlibrary MathLib {\n    /// @dev Returns (`x` * `y`) / `WAD` rounded down.\n    function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, y, WAD);\n    }\n\n    /// @dev Returns (`x` * `WAD`) / `y` rounded down.\n    function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, WAD, y);\n    }\n\n    /// @dev Returns (`x` * `WAD`) / `y` rounded up.\n    function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, WAD, y);\n    }\n\n    /// @dev Returns (`x` * `y`) / `d` rounded down.\n    function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {\n        return (x * y) / d;\n    }\n\n    /// @dev Returns (`x` * `y`) / `d` rounded up.\n    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {\n        return (x * y + (d - 1)) / d;\n    }\n\n    /// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1, to approximate a\n    /// continuous compound interest rate.\n    function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {\n        uint256 firstTerm = x * n;\n        uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD);\n        uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD);\n\n        return firstTerm + secondTerm + thirdTerm;\n    }\n}\n"
      },
      "@morpho-org/morpho-blue/src/libraries/periphery/MorphoBalancesLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport {Id, MarketParams, Market, IMorpho} from \"../../interfaces/IMorpho.sol\";\nimport {IIrm} from \"../../interfaces/IIrm.sol\";\n\nimport {MathLib} from \"../MathLib.sol\";\nimport {UtilsLib} from \"../UtilsLib.sol\";\nimport {MorphoLib} from \"./MorphoLib.sol\";\nimport {SharesMathLib} from \"../SharesMathLib.sol\";\nimport {MarketParamsLib} from \"../MarketParamsLib.sol\";\n\n/// @title MorphoBalancesLib\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @notice Helper library exposing getters with the expected value after interest accrual.\n/// @dev This library is not used in Morpho itself and is intended to be used by integrators.\n/// @dev The getter to retrieve the expected total borrow shares is not exposed because interest accrual does not apply\n/// to it. The value can be queried directly on Morpho using `totalBorrowShares`.\nlibrary MorphoBalancesLib {\n    using MathLib for uint256;\n    using MathLib for uint128;\n    using UtilsLib for uint256;\n    using MorphoLib for IMorpho;\n    using SharesMathLib for uint256;\n    using MarketParamsLib for MarketParams;\n\n    /// @notice Returns the expected market balances of a market after having accrued interest.\n    /// @return The expected total supply assets.\n    /// @return The expected total supply shares.\n    /// @return The expected total borrow assets.\n    /// @return The expected total borrow shares.\n    function expectedMarketBalances(IMorpho morpho, MarketParams memory marketParams)\n        internal\n        view\n        returns (uint256, uint256, uint256, uint256)\n    {\n        Id id = marketParams.id();\n        Market memory market = morpho.market(id);\n\n        uint256 elapsed = block.timestamp - market.lastUpdate;\n\n        // Skipped if elapsed == 0 or totalBorrowAssets == 0 because interest would be null, or if irm == address(0).\n        if (elapsed != 0 && market.totalBorrowAssets != 0 && marketParams.irm != address(0)) {\n            uint256 borrowRate = IIrm(marketParams.irm).borrowRateView(marketParams, market);\n            uint256 interest = market.totalBorrowAssets.wMulDown(borrowRate.wTaylorCompounded(elapsed));\n            market.totalBorrowAssets += interest.toUint128();\n            market.totalSupplyAssets += interest.toUint128();\n\n            if (market.fee != 0) {\n                uint256 feeAmount = interest.wMulDown(market.fee);\n                // The fee amount is subtracted from the total supply in this calculation to compensate for the fact\n                // that total supply is already updated.\n                uint256 feeShares =\n                    feeAmount.toSharesDown(market.totalSupplyAssets - feeAmount, market.totalSupplyShares);\n                market.totalSupplyShares += feeShares.toUint128();\n            }\n        }\n\n        return (market.totalSupplyAssets, market.totalSupplyShares, market.totalBorrowAssets, market.totalBorrowShares);\n    }\n\n    /// @notice Returns the expected total supply assets of a market after having accrued interest.\n    function expectedTotalSupplyAssets(IMorpho morpho, MarketParams memory marketParams)\n        internal\n        view\n        returns (uint256 totalSupplyAssets)\n    {\n        (totalSupplyAssets,,,) = expectedMarketBalances(morpho, marketParams);\n    }\n\n    /// @notice Returns the expected total borrow assets of a market after having accrued interest.\n    function expectedTotalBorrowAssets(IMorpho morpho, MarketParams memory marketParams)\n        internal\n        view\n        returns (uint256 totalBorrowAssets)\n    {\n        (,, totalBorrowAssets,) = expectedMarketBalances(morpho, marketParams);\n    }\n\n    /// @notice Returns the expected total supply shares of a market after having accrued interest.\n    function expectedTotalSupplyShares(IMorpho morpho, MarketParams memory marketParams)\n        internal\n        view\n        returns (uint256 totalSupplyShares)\n    {\n        (, totalSupplyShares,,) = expectedMarketBalances(morpho, marketParams);\n    }\n\n    /// @notice Returns the expected supply assets balance of `user` on a market after having accrued interest.\n    /// @dev Warning: Wrong for `feeRecipient` because their supply shares increase is not taken into account.\n    /// @dev Warning: Withdrawing using the expected supply assets can lead to a revert due to conversion roundings from\n    /// assets to shares.\n    function expectedSupplyAssets(IMorpho morpho, MarketParams memory marketParams, address user)\n        internal\n        view\n        returns (uint256)\n    {\n        Id id = marketParams.id();\n        uint256 supplyShares = morpho.supplyShares(id, user);\n        (uint256 totalSupplyAssets, uint256 totalSupplyShares,,) = expectedMarketBalances(morpho, marketParams);\n\n        return supplyShares.toAssetsDown(totalSupplyAssets, totalSupplyShares);\n    }\n\n    /// @notice Returns the expected borrow assets balance of `user` on a market after having accrued interest.\n    /// @dev Warning: The expected balance is rounded up, so it may be greater than the market's expected total borrow\n    /// assets.\n    function expectedBorrowAssets(IMorpho morpho, MarketParams memory marketParams, address user)\n        internal\n        view\n        returns (uint256)\n    {\n        Id id = marketParams.id();\n        uint256 borrowShares = morpho.borrowShares(id, user);\n        (,, uint256 totalBorrowAssets, uint256 totalBorrowShares) = expectedMarketBalances(morpho, marketParams);\n\n        return borrowShares.toAssetsUp(totalBorrowAssets, totalBorrowShares);\n    }\n}\n"
      },
      "@morpho-org/morpho-blue/src/libraries/periphery/MorphoLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport {IMorpho, Id} from \"../../interfaces/IMorpho.sol\";\nimport {MorphoStorageLib} from \"./MorphoStorageLib.sol\";\n\n/// @title MorphoLib\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @notice Helper library to access Morpho storage variables.\n/// @dev Warning: Supply and borrow getters may return outdated values that do not include accrued interest.\nlibrary MorphoLib {\n    function supplyShares(IMorpho morpho, Id id, address user) internal view returns (uint256) {\n        bytes32[] memory slot = _array(MorphoStorageLib.positionSupplySharesSlot(id, user));\n        return uint256(morpho.extSloads(slot)[0]);\n    }\n\n    function borrowShares(IMorpho morpho, Id id, address user) internal view returns (uint256) {\n        bytes32[] memory slot = _array(MorphoStorageLib.positionBorrowSharesAndCollateralSlot(id, user));\n        return uint128(uint256(morpho.extSloads(slot)[0]));\n    }\n\n    function collateral(IMorpho morpho, Id id, address user) internal view returns (uint256) {\n        bytes32[] memory slot = _array(MorphoStorageLib.positionBorrowSharesAndCollateralSlot(id, user));\n        return uint256(morpho.extSloads(slot)[0] >> 128);\n    }\n\n    function totalSupplyAssets(IMorpho morpho, Id id) internal view returns (uint256) {\n        bytes32[] memory slot = _array(MorphoStorageLib.marketTotalSupplyAssetsAndSharesSlot(id));\n        return uint128(uint256(morpho.extSloads(slot)[0]));\n    }\n\n    function totalSupplyShares(IMorpho morpho, Id id) internal view returns (uint256) {\n        bytes32[] memory slot = _array(MorphoStorageLib.marketTotalSupplyAssetsAndSharesSlot(id));\n        return uint256(morpho.extSloads(slot)[0] >> 128);\n    }\n\n    function totalBorrowAssets(IMorpho morpho, Id id) internal view returns (uint256) {\n        bytes32[] memory slot = _array(MorphoStorageLib.marketTotalBorrowAssetsAndSharesSlot(id));\n        return uint128(uint256(morpho.extSloads(slot)[0]));\n    }\n\n    function totalBorrowShares(IMorpho morpho, Id id) internal view returns (uint256) {\n        bytes32[] memory slot = _array(MorphoStorageLib.marketTotalBorrowAssetsAndSharesSlot(id));\n        return uint256(morpho.extSloads(slot)[0] >> 128);\n    }\n\n    function lastUpdate(IMorpho morpho, Id id) internal view returns (uint256) {\n        bytes32[] memory slot = _array(MorphoStorageLib.marketLastUpdateAndFeeSlot(id));\n        return uint128(uint256(morpho.extSloads(slot)[0]));\n    }\n\n    function fee(IMorpho morpho, Id id) internal view returns (uint256) {\n        bytes32[] memory slot = _array(MorphoStorageLib.marketLastUpdateAndFeeSlot(id));\n        return uint256(morpho.extSloads(slot)[0] >> 128);\n    }\n\n    function _array(bytes32 x) private pure returns (bytes32[] memory) {\n        bytes32[] memory res = new bytes32[](1);\n        res[0] = x;\n        return res;\n    }\n}\n"
      },
      "@morpho-org/morpho-blue/src/libraries/periphery/MorphoStorageLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport {Id} from \"../../interfaces/IMorpho.sol\";\n\n/// @title MorphoStorageLib\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @notice Helper library exposing getters to access Morpho storage variables' slot.\n/// @dev This library is not used in Morpho itself and is intended to be used by integrators.\nlibrary MorphoStorageLib {\n    /* SLOTS */\n\n    uint256 internal constant OWNER_SLOT = 0;\n    uint256 internal constant FEE_RECIPIENT_SLOT = 1;\n    uint256 internal constant POSITION_SLOT = 2;\n    uint256 internal constant MARKET_SLOT = 3;\n    uint256 internal constant IS_IRM_ENABLED_SLOT = 4;\n    uint256 internal constant IS_LLTV_ENABLED_SLOT = 5;\n    uint256 internal constant IS_AUTHORIZED_SLOT = 6;\n    uint256 internal constant NONCE_SLOT = 7;\n    uint256 internal constant ID_TO_MARKET_PARAMS_SLOT = 8;\n\n    /* SLOT OFFSETS */\n\n    uint256 internal constant LOAN_TOKEN_OFFSET = 0;\n    uint256 internal constant COLLATERAL_TOKEN_OFFSET = 1;\n    uint256 internal constant ORACLE_OFFSET = 2;\n    uint256 internal constant IRM_OFFSET = 3;\n    uint256 internal constant LLTV_OFFSET = 4;\n\n    uint256 internal constant SUPPLY_SHARES_OFFSET = 0;\n    uint256 internal constant BORROW_SHARES_AND_COLLATERAL_OFFSET = 1;\n\n    uint256 internal constant TOTAL_SUPPLY_ASSETS_AND_SHARES_OFFSET = 0;\n    uint256 internal constant TOTAL_BORROW_ASSETS_AND_SHARES_OFFSET = 1;\n    uint256 internal constant LAST_UPDATE_AND_FEE_OFFSET = 2;\n\n    /* GETTERS */\n\n    function ownerSlot() internal pure returns (bytes32) {\n        return bytes32(OWNER_SLOT);\n    }\n\n    function feeRecipientSlot() internal pure returns (bytes32) {\n        return bytes32(FEE_RECIPIENT_SLOT);\n    }\n\n    function positionSupplySharesSlot(Id id, address user) internal pure returns (bytes32) {\n        return bytes32(\n            uint256(keccak256(abi.encode(user, keccak256(abi.encode(id, POSITION_SLOT))))) + SUPPLY_SHARES_OFFSET\n        );\n    }\n\n    function positionBorrowSharesAndCollateralSlot(Id id, address user) internal pure returns (bytes32) {\n        return bytes32(\n            uint256(keccak256(abi.encode(user, keccak256(abi.encode(id, POSITION_SLOT)))))\n                + BORROW_SHARES_AND_COLLATERAL_OFFSET\n        );\n    }\n\n    function marketTotalSupplyAssetsAndSharesSlot(Id id) internal pure returns (bytes32) {\n        return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + TOTAL_SUPPLY_ASSETS_AND_SHARES_OFFSET);\n    }\n\n    function marketTotalBorrowAssetsAndSharesSlot(Id id) internal pure returns (bytes32) {\n        return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + TOTAL_BORROW_ASSETS_AND_SHARES_OFFSET);\n    }\n\n    function marketLastUpdateAndFeeSlot(Id id) internal pure returns (bytes32) {\n        return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + LAST_UPDATE_AND_FEE_OFFSET);\n    }\n\n    function isIrmEnabledSlot(address irm) internal pure returns (bytes32) {\n        return keccak256(abi.encode(irm, IS_IRM_ENABLED_SLOT));\n    }\n\n    function isLltvEnabledSlot(uint256 lltv) internal pure returns (bytes32) {\n        return keccak256(abi.encode(lltv, IS_LLTV_ENABLED_SLOT));\n    }\n\n    function isAuthorizedSlot(address authorizer, address authorizee) internal pure returns (bytes32) {\n        return keccak256(abi.encode(authorizee, keccak256(abi.encode(authorizer, IS_AUTHORIZED_SLOT))));\n    }\n\n    function nonceSlot(address authorizer) internal pure returns (bytes32) {\n        return keccak256(abi.encode(authorizer, NONCE_SLOT));\n    }\n\n    function idToLoanTokenSlot(Id id) internal pure returns (bytes32) {\n        return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + LOAN_TOKEN_OFFSET);\n    }\n\n    function idToCollateralTokenSlot(Id id) internal pure returns (bytes32) {\n        return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + COLLATERAL_TOKEN_OFFSET);\n    }\n\n    function idToOracleSlot(Id id) internal pure returns (bytes32) {\n        return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + ORACLE_OFFSET);\n    }\n\n    function idToIrmSlot(Id id) internal pure returns (bytes32) {\n        return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + IRM_OFFSET);\n    }\n\n    function idToLltvSlot(Id id) internal pure returns (bytes32) {\n        return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + LLTV_OFFSET);\n    }\n}\n"
      },
      "@morpho-org/morpho-blue/src/libraries/SharesMathLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport {MathLib} from \"./MathLib.sol\";\n\n/// @title SharesMathLib\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @notice Shares management library.\n/// @dev This implementation mitigates share price manipulations, using OpenZeppelin's method of virtual shares:\n/// https://docs.openzeppelin.com/contracts/4.x/erc4626#inflation-attack.\nlibrary SharesMathLib {\n    using MathLib for uint256;\n\n    /// @dev The number of virtual shares has been chosen low enough to prevent overflows, and high enough to ensure\n    /// high precision computations.\n    /// @dev Virtual shares can never be redeemed for the assets they are entitled to, but it is assumed the share price\n    /// stays low enough not to inflate these assets to a significant value.\n    /// @dev Warning: The assets to which virtual borrow shares are entitled behave like unrealizable bad debt.\n    uint256 internal constant VIRTUAL_SHARES = 1e6;\n\n    /// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is\n    /// empty.\n    uint256 internal constant VIRTUAL_ASSETS = 1;\n\n    /// @dev Calculates the value of `assets` quoted in shares, rounding down.\n    function toSharesDown(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {\n        return assets.mulDivDown(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);\n    }\n\n    /// @dev Calculates the value of `shares` quoted in assets, rounding down.\n    function toAssetsDown(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {\n        return shares.mulDivDown(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);\n    }\n\n    /// @dev Calculates the value of `assets` quoted in shares, rounding up.\n    function toSharesUp(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {\n        return assets.mulDivUp(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);\n    }\n\n    /// @dev Calculates the value of `shares` quoted in assets, rounding up.\n    function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {\n        return shares.mulDivUp(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);\n    }\n}\n"
      },
      "@morpho-org/morpho-blue/src/libraries/UtilsLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport {ErrorsLib} from \"../libraries/ErrorsLib.sol\";\n\n/// @title UtilsLib\n/// @author Morpho Labs\n/// @custom:contact security@morpho.org\n/// @notice Library exposing helpers.\n/// @dev Inspired by https://github.com/morpho-org/morpho-utils.\nlibrary UtilsLib {\n    /// @dev Returns true if there is exactly one zero among `x` and `y`.\n    function exactlyOneZero(uint256 x, uint256 y) internal pure returns (bool z) {\n        assembly {\n            z := xor(iszero(x), iszero(y))\n        }\n    }\n\n    /// @dev Returns the min of `x` and `y`.\n    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        assembly {\n            z := xor(x, mul(xor(x, y), lt(y, x)))\n        }\n    }\n\n    /// @dev Returns `x` safely cast to uint128.\n    function toUint128(uint256 x) internal pure returns (uint128) {\n        require(x <= type(uint128).max, ErrorsLib.MAX_UINT128_EXCEEDED);\n        return uint128(x);\n    }\n\n    /// @dev Returns max(0, x - y).\n    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        assembly {\n            z := mul(gt(x, y), sub(x, y))\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n     * Revert on invalid signature.\n     */\n    function safePermit(\n        IERC20Permit token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return\n            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     *\n     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "@prb/math/src/Common.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.19;\n\n// Common.sol\n//\n// Common mathematical functions needed by both SD59x18 and UD60x18. Note that these global functions do not\n// always operate with SD59x18 and UD60x18 numbers.\n\n/*//////////////////////////////////////////////////////////////////////////\n                                CUSTOM ERRORS\n//////////////////////////////////////////////////////////////////////////*/\n\n/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.\nerror PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);\n\n/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.\nerror PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);\n\n/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.\nerror PRBMath_MulDivSigned_InputTooSmall();\n\n/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.\nerror PRBMath_MulDivSigned_Overflow(int256 x, int256 y);\n\n/*//////////////////////////////////////////////////////////////////////////\n                                    CONSTANTS\n//////////////////////////////////////////////////////////////////////////*/\n\n/// @dev The maximum value a uint128 number can have.\nuint128 constant MAX_UINT128 = type(uint128).max;\n\n/// @dev The maximum value a uint40 number can have.\nuint40 constant MAX_UINT40 = type(uint40).max;\n\n/// @dev The unit number, which the decimal precision of the fixed-point types.\nuint256 constant UNIT = 1e18;\n\n/// @dev The unit number inverted mod 2^256.\nuint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;\n\n/// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant\n/// bit in the binary representation of `UNIT`.\nuint256 constant UNIT_LPOTD = 262144;\n\n/*//////////////////////////////////////////////////////////////////////////\n                                    FUNCTIONS\n//////////////////////////////////////////////////////////////////////////*/\n\n/// @notice Calculates the binary exponent of x using the binary fraction method.\n/// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693.\n/// @param x The exponent as an unsigned 192.64-bit fixed-point number.\n/// @return result The result as an unsigned 60.18-decimal fixed-point number.\n/// @custom:smtchecker abstract-function-nondet\nfunction exp2(uint256 x) pure returns (uint256 result) {\n    unchecked {\n        // Start from 0.5 in the 192.64-bit fixed-point format.\n        result = 0x800000000000000000000000000000000000000000000000;\n\n        // The following logic multiplies the result by $\\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:\n        //\n        // 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.\n        // 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing\n        // a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,\n        // we know that `x & 0xFF` is also 1.\n        if (x & 0xFF00000000000000 > 0) {\n            if (x & 0x8000000000000000 > 0) {\n                result = (result * 0x16A09E667F3BCC909) >> 64;\n            }\n            if (x & 0x4000000000000000 > 0) {\n                result = (result * 0x1306FE0A31B7152DF) >> 64;\n            }\n            if (x & 0x2000000000000000 > 0) {\n                result = (result * 0x1172B83C7D517ADCE) >> 64;\n            }\n            if (x & 0x1000000000000000 > 0) {\n                result = (result * 0x10B5586CF9890F62A) >> 64;\n            }\n            if (x & 0x800000000000000 > 0) {\n                result = (result * 0x1059B0D31585743AE) >> 64;\n            }\n            if (x & 0x400000000000000 > 0) {\n                result = (result * 0x102C9A3E778060EE7) >> 64;\n            }\n            if (x & 0x200000000000000 > 0) {\n                result = (result * 0x10163DA9FB33356D8) >> 64;\n            }\n            if (x & 0x100000000000000 > 0) {\n                result = (result * 0x100B1AFA5ABCBED61) >> 64;\n            }\n        }\n\n        if (x & 0xFF000000000000 > 0) {\n            if (x & 0x80000000000000 > 0) {\n                result = (result * 0x10058C86DA1C09EA2) >> 64;\n            }\n            if (x & 0x40000000000000 > 0) {\n                result = (result * 0x1002C605E2E8CEC50) >> 64;\n            }\n            if (x & 0x20000000000000 > 0) {\n                result = (result * 0x100162F3904051FA1) >> 64;\n            }\n            if (x & 0x10000000000000 > 0) {\n                result = (result * 0x1000B175EFFDC76BA) >> 64;\n            }\n            if (x & 0x8000000000000 > 0) {\n                result = (result * 0x100058BA01FB9F96D) >> 64;\n            }\n            if (x & 0x4000000000000 > 0) {\n                result = (result * 0x10002C5CC37DA9492) >> 64;\n            }\n            if (x & 0x2000000000000 > 0) {\n                result = (result * 0x1000162E525EE0547) >> 64;\n            }\n            if (x & 0x1000000000000 > 0) {\n                result = (result * 0x10000B17255775C04) >> 64;\n            }\n        }\n\n        if (x & 0xFF0000000000 > 0) {\n            if (x & 0x800000000000 > 0) {\n                result = (result * 0x1000058B91B5BC9AE) >> 64;\n            }\n            if (x & 0x400000000000 > 0) {\n                result = (result * 0x100002C5C89D5EC6D) >> 64;\n            }\n            if (x & 0x200000000000 > 0) {\n                result = (result * 0x10000162E43F4F831) >> 64;\n            }\n            if (x & 0x100000000000 > 0) {\n                result = (result * 0x100000B1721BCFC9A) >> 64;\n            }\n            if (x & 0x80000000000 > 0) {\n                result = (result * 0x10000058B90CF1E6E) >> 64;\n            }\n            if (x & 0x40000000000 > 0) {\n                result = (result * 0x1000002C5C863B73F) >> 64;\n            }\n            if (x & 0x20000000000 > 0) {\n                result = (result * 0x100000162E430E5A2) >> 64;\n            }\n            if (x & 0x10000000000 > 0) {\n                result = (result * 0x1000000B172183551) >> 64;\n            }\n        }\n\n        if (x & 0xFF00000000 > 0) {\n            if (x & 0x8000000000 > 0) {\n                result = (result * 0x100000058B90C0B49) >> 64;\n            }\n            if (x & 0x4000000000 > 0) {\n                result = (result * 0x10000002C5C8601CC) >> 64;\n            }\n            if (x & 0x2000000000 > 0) {\n                result = (result * 0x1000000162E42FFF0) >> 64;\n            }\n            if (x & 0x1000000000 > 0) {\n                result = (result * 0x10000000B17217FBB) >> 64;\n            }\n            if (x & 0x800000000 > 0) {\n                result = (result * 0x1000000058B90BFCE) >> 64;\n            }\n            if (x & 0x400000000 > 0) {\n                result = (result * 0x100000002C5C85FE3) >> 64;\n            }\n            if (x & 0x200000000 > 0) {\n                result = (result * 0x10000000162E42FF1) >> 64;\n            }\n            if (x & 0x100000000 > 0) {\n                result = (result * 0x100000000B17217F8) >> 64;\n            }\n        }\n\n        if (x & 0xFF000000 > 0) {\n            if (x & 0x80000000 > 0) {\n                result = (result * 0x10000000058B90BFC) >> 64;\n            }\n            if (x & 0x40000000 > 0) {\n                result = (result * 0x1000000002C5C85FE) >> 64;\n            }\n            if (x & 0x20000000 > 0) {\n                result = (result * 0x100000000162E42FF) >> 64;\n            }\n            if (x & 0x10000000 > 0) {\n                result = (result * 0x1000000000B17217F) >> 64;\n            }\n            if (x & 0x8000000 > 0) {\n                result = (result * 0x100000000058B90C0) >> 64;\n            }\n            if (x & 0x4000000 > 0) {\n                result = (result * 0x10000000002C5C860) >> 64;\n            }\n            if (x & 0x2000000 > 0) {\n                result = (result * 0x1000000000162E430) >> 64;\n            }\n            if (x & 0x1000000 > 0) {\n                result = (result * 0x10000000000B17218) >> 64;\n            }\n        }\n\n        if (x & 0xFF0000 > 0) {\n            if (x & 0x800000 > 0) {\n                result = (result * 0x1000000000058B90C) >> 64;\n            }\n            if (x & 0x400000 > 0) {\n                result = (result * 0x100000000002C5C86) >> 64;\n            }\n            if (x & 0x200000 > 0) {\n                result = (result * 0x10000000000162E43) >> 64;\n            }\n            if (x & 0x100000 > 0) {\n                result = (result * 0x100000000000B1721) >> 64;\n            }\n            if (x & 0x80000 > 0) {\n                result = (result * 0x10000000000058B91) >> 64;\n            }\n            if (x & 0x40000 > 0) {\n                result = (result * 0x1000000000002C5C8) >> 64;\n            }\n            if (x & 0x20000 > 0) {\n                result = (result * 0x100000000000162E4) >> 64;\n            }\n            if (x & 0x10000 > 0) {\n                result = (result * 0x1000000000000B172) >> 64;\n            }\n        }\n\n        if (x & 0xFF00 > 0) {\n            if (x & 0x8000 > 0) {\n                result = (result * 0x100000000000058B9) >> 64;\n            }\n            if (x & 0x4000 > 0) {\n                result = (result * 0x10000000000002C5D) >> 64;\n            }\n            if (x & 0x2000 > 0) {\n                result = (result * 0x1000000000000162E) >> 64;\n            }\n            if (x & 0x1000 > 0) {\n                result = (result * 0x10000000000000B17) >> 64;\n            }\n            if (x & 0x800 > 0) {\n                result = (result * 0x1000000000000058C) >> 64;\n            }\n            if (x & 0x400 > 0) {\n                result = (result * 0x100000000000002C6) >> 64;\n            }\n            if (x & 0x200 > 0) {\n                result = (result * 0x10000000000000163) >> 64;\n            }\n            if (x & 0x100 > 0) {\n                result = (result * 0x100000000000000B1) >> 64;\n            }\n        }\n\n        if (x & 0xFF > 0) {\n            if (x & 0x80 > 0) {\n                result = (result * 0x10000000000000059) >> 64;\n            }\n            if (x & 0x40 > 0) {\n                result = (result * 0x1000000000000002C) >> 64;\n            }\n            if (x & 0x20 > 0) {\n                result = (result * 0x10000000000000016) >> 64;\n            }\n            if (x & 0x10 > 0) {\n                result = (result * 0x1000000000000000B) >> 64;\n            }\n            if (x & 0x8 > 0) {\n                result = (result * 0x10000000000000006) >> 64;\n            }\n            if (x & 0x4 > 0) {\n                result = (result * 0x10000000000000003) >> 64;\n            }\n            if (x & 0x2 > 0) {\n                result = (result * 0x10000000000000001) >> 64;\n            }\n            if (x & 0x1 > 0) {\n                result = (result * 0x10000000000000001) >> 64;\n            }\n        }\n\n        // In the code snippet below, two operations are executed simultaneously:\n        //\n        // 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1\n        // accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.\n        // 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.\n        //\n        // The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the,\n        // integer part, $2^n$.\n        result *= UNIT;\n        result >>= (191 - (x >> 64));\n    }\n}\n\n/// @notice Finds the zero-based index of the first 1 in the binary representation of x.\n///\n/// @dev See the note on \"msb\" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set\n///\n/// Each step in this implementation is equivalent to this high-level code:\n///\n/// ```solidity\n/// if (x >= 2 ** 128) {\n///     x >>= 128;\n///     result += 128;\n/// }\n/// ```\n///\n/// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here:\n/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948\n///\n/// The Yul instructions used below are:\n///\n/// - \"gt\" is \"greater than\"\n/// - \"or\" is the OR bitwise operator\n/// - \"shl\" is \"shift left\"\n/// - \"shr\" is \"shift right\"\n///\n/// @param x The uint256 number for which to find the index of the most significant bit.\n/// @return result The index of the most significant bit as a uint256.\n/// @custom:smtchecker abstract-function-nondet\nfunction msb(uint256 x) pure returns (uint256 result) {\n    // 2^128\n    assembly (\"memory-safe\") {\n        let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\n        x := shr(factor, x)\n        result := or(result, factor)\n    }\n    // 2^64\n    assembly (\"memory-safe\") {\n        let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))\n        x := shr(factor, x)\n        result := or(result, factor)\n    }\n    // 2^32\n    assembly (\"memory-safe\") {\n        let factor := shl(5, gt(x, 0xFFFFFFFF))\n        x := shr(factor, x)\n        result := or(result, factor)\n    }\n    // 2^16\n    assembly (\"memory-safe\") {\n        let factor := shl(4, gt(x, 0xFFFF))\n        x := shr(factor, x)\n        result := or(result, factor)\n    }\n    // 2^8\n    assembly (\"memory-safe\") {\n        let factor := shl(3, gt(x, 0xFF))\n        x := shr(factor, x)\n        result := or(result, factor)\n    }\n    // 2^4\n    assembly (\"memory-safe\") {\n        let factor := shl(2, gt(x, 0xF))\n        x := shr(factor, x)\n        result := or(result, factor)\n    }\n    // 2^2\n    assembly (\"memory-safe\") {\n        let factor := shl(1, gt(x, 0x3))\n        x := shr(factor, x)\n        result := or(result, factor)\n    }\n    // 2^1\n    // No need to shift x any more.\n    assembly (\"memory-safe\") {\n        let factor := gt(x, 0x1)\n        result := or(result, factor)\n    }\n}\n\n/// @notice Calculates x*y÷denominator with 512-bit precision.\n///\n/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.\n///\n/// Notes:\n/// - The result is rounded toward zero.\n///\n/// Requirements:\n/// - The denominator must not be zero.\n/// - The result must fit in uint256.\n///\n/// @param x The multiplicand as a uint256.\n/// @param y The multiplier as a uint256.\n/// @param denominator The divisor as a uint256.\n/// @return result The result as a uint256.\n/// @custom:smtchecker abstract-function-nondet\nfunction mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {\n    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n    // use the Chinese Remainder Theorem to reconstruct the 512-bit result. The result is stored in two 256\n    // variables such that product = prod1 * 2^256 + prod0.\n    uint256 prod0; // Least significant 256 bits of the product\n    uint256 prod1; // Most significant 256 bits of the product\n    assembly (\"memory-safe\") {\n        let mm := mulmod(x, y, not(0))\n        prod0 := mul(x, y)\n        prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n    }\n\n    // Handle non-overflow cases, 256 by 256 division.\n    if (prod1 == 0) {\n        unchecked {\n            return prod0 / denominator;\n        }\n    }\n\n    // Make sure the result is less than 2^256. Also prevents denominator == 0.\n    if (prod1 >= denominator) {\n        revert PRBMath_MulDiv_Overflow(x, y, denominator);\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // 512 by 256 division\n    ////////////////////////////////////////////////////////////////////////////\n\n    // Make division exact by subtracting the remainder from [prod1 prod0].\n    uint256 remainder;\n    assembly (\"memory-safe\") {\n        // Compute remainder using the mulmod Yul instruction.\n        remainder := mulmod(x, y, denominator)\n\n        // Subtract 256 bit number from 512-bit number.\n        prod1 := sub(prod1, gt(remainder, prod0))\n        prod0 := sub(prod0, remainder)\n    }\n\n    unchecked {\n        // Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow\n        // because the denominator cannot be zero at this point in the function execution. The result is always >= 1.\n        // For more detail, see https://cs.stackexchange.com/q/138556/92363.\n        uint256 lpotdod = denominator & (~denominator + 1);\n        uint256 flippedLpotdod;\n\n        assembly (\"memory-safe\") {\n            // Factor powers of two out of denominator.\n            denominator := div(denominator, lpotdod)\n\n            // Divide [prod1 prod0] by lpotdod.\n            prod0 := div(prod0, lpotdod)\n\n            // Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.\n            // `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.\n            // However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693\n            flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)\n        }\n\n        // Shift in bits from prod1 into prod0.\n        prod0 |= prod1 * flippedLpotdod;\n\n        // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n        // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n        // four bits. That is, denominator * inv = 1 mod 2^4.\n        uint256 inverse = (3 * denominator) ^ 2;\n\n        // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n        // in modular arithmetic, doubling the correct bits in each step.\n        inverse *= 2 - denominator * inverse; // inverse mod 2^8\n        inverse *= 2 - denominator * inverse; // inverse mod 2^16\n        inverse *= 2 - denominator * inverse; // inverse mod 2^32\n        inverse *= 2 - denominator * inverse; // inverse mod 2^64\n        inverse *= 2 - denominator * inverse; // inverse mod 2^128\n        inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n        // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n        // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n        // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n        // is no longer required.\n        result = prod0 * inverse;\n    }\n}\n\n/// @notice Calculates x*y÷1e18 with 512-bit precision.\n///\n/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.\n///\n/// Notes:\n/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.\n/// - The result is rounded toward zero.\n/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:\n///\n/// $$\n/// \\begin{cases}\n///     x * y = MAX\\_UINT256 * UNIT \\\\\n///     (x * y) \\% UNIT \\geq \\frac{UNIT}{2}\n/// \\end{cases}\n/// $$\n///\n/// Requirements:\n/// - Refer to the requirements in {mulDiv}.\n/// - The result must fit in uint256.\n///\n/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.\n/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.\n/// @return result The result as an unsigned 60.18-decimal fixed-point number.\n/// @custom:smtchecker abstract-function-nondet\nfunction mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {\n    uint256 prod0;\n    uint256 prod1;\n    assembly (\"memory-safe\") {\n        let mm := mulmod(x, y, not(0))\n        prod0 := mul(x, y)\n        prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n    }\n\n    if (prod1 == 0) {\n        unchecked {\n            return prod0 / UNIT;\n        }\n    }\n\n    if (prod1 >= UNIT) {\n        revert PRBMath_MulDiv18_Overflow(x, y);\n    }\n\n    uint256 remainder;\n    assembly (\"memory-safe\") {\n        remainder := mulmod(x, y, UNIT)\n        result :=\n            mul(\n                or(\n                    div(sub(prod0, remainder), UNIT_LPOTD),\n                    mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))\n                ),\n                UNIT_INVERSE\n            )\n    }\n}\n\n/// @notice Calculates x*y÷denominator with 512-bit precision.\n///\n/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.\n///\n/// Notes:\n/// - The result is rounded toward zero.\n///\n/// Requirements:\n/// - Refer to the requirements in {mulDiv}.\n/// - None of the inputs can be `type(int256).min`.\n/// - The result must fit in int256.\n///\n/// @param x The multiplicand as an int256.\n/// @param y The multiplier as an int256.\n/// @param denominator The divisor as an int256.\n/// @return result The result as an int256.\n/// @custom:smtchecker abstract-function-nondet\nfunction mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {\n    if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {\n        revert PRBMath_MulDivSigned_InputTooSmall();\n    }\n\n    // Get hold of the absolute values of x, y and the denominator.\n    uint256 xAbs;\n    uint256 yAbs;\n    uint256 dAbs;\n    unchecked {\n        xAbs = x < 0 ? uint256(-x) : uint256(x);\n        yAbs = y < 0 ? uint256(-y) : uint256(y);\n        dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);\n    }\n\n    // Compute the absolute value of x*y÷denominator. The result must fit in int256.\n    uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);\n    if (resultAbs > uint256(type(int256).max)) {\n        revert PRBMath_MulDivSigned_Overflow(x, y);\n    }\n\n    // Get the signs of x, y and the denominator.\n    uint256 sx;\n    uint256 sy;\n    uint256 sd;\n    assembly (\"memory-safe\") {\n        // \"sgt\" is the \"signed greater than\" assembly instruction and \"sub(0,1)\" is -1 in two's complement.\n        sx := sgt(x, sub(0, 1))\n        sy := sgt(y, sub(0, 1))\n        sd := sgt(denominator, sub(0, 1))\n    }\n\n    // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.\n    // If there are, the result should be negative. Otherwise, it should be positive.\n    unchecked {\n        result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);\n    }\n}\n\n/// @notice Calculates the square root of x using the Babylonian method.\n///\n/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n///\n/// Notes:\n/// - If x is not a perfect square, the result is rounded down.\n/// - Credits to OpenZeppelin for the explanations in comments below.\n///\n/// @param x The uint256 number for which to calculate the square root.\n/// @return result The result as a uint256.\n/// @custom:smtchecker abstract-function-nondet\nfunction sqrt(uint256 x) pure returns (uint256 result) {\n    if (x == 0) {\n        return 0;\n    }\n\n    // For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.\n    //\n    // We know that the \"msb\" (most significant bit) of x is a power of 2 such that we have:\n    //\n    // $$\n    // msb(x) <= x <= 2*msb(x)$\n    // $$\n    //\n    // We write $msb(x)$ as $2^k$, and we get:\n    //\n    // $$\n    // k = log_2(x)\n    // $$\n    //\n    // Thus, we can write the initial inequality as:\n    //\n    // $$\n    // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\\\\n    // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\\\\n    // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}\n    // $$\n    //\n    // Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit.\n    uint256 xAux = uint256(x);\n    result = 1;\n    if (xAux >= 2 ** 128) {\n        xAux >>= 128;\n        result <<= 64;\n    }\n    if (xAux >= 2 ** 64) {\n        xAux >>= 64;\n        result <<= 32;\n    }\n    if (xAux >= 2 ** 32) {\n        xAux >>= 32;\n        result <<= 16;\n    }\n    if (xAux >= 2 ** 16) {\n        xAux >>= 16;\n        result <<= 8;\n    }\n    if (xAux >= 2 ** 8) {\n        xAux >>= 8;\n        result <<= 4;\n    }\n    if (xAux >= 2 ** 4) {\n        xAux >>= 4;\n        result <<= 2;\n    }\n    if (xAux >= 2 ** 2) {\n        result <<= 1;\n    }\n\n    // At this point, `result` is an estimation with at least one bit of precision. We know the true value has at\n    // most 128 bits, since it is the square root of a uint256. Newton's method converges quadratically (precision\n    // doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of\n    // precision into the expected uint128 result.\n    unchecked {\n        result = (result + x / result) >> 1;\n        result = (result + x / result) >> 1;\n        result = (result + x / result) >> 1;\n        result = (result + x / result) >> 1;\n        result = (result + x / result) >> 1;\n        result = (result + x / result) >> 1;\n        result = (result + x / result) >> 1;\n\n        // If x is not a perfect square, round the result toward zero.\n        uint256 roundedResult = x / result;\n        if (result >= roundedResult) {\n            result = roundedResult;\n        }\n    }\n}\n"
      },
      "contracts/common/access/OrigamiElevatedAccess.sol": {
        "content": "pragma solidity 0.8.19;\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Origami (common/access/OrigamiElevatedAccessBase.sol)\n\nimport { OrigamiElevatedAccessBase } from \"contracts/common/access/OrigamiElevatedAccessBase.sol\";\n\n/**\n * @notice Inherit to add Owner roles for DAO elevated access.\n */ \nabstract contract OrigamiElevatedAccess is OrigamiElevatedAccessBase {\n    constructor(address initialOwner) {\n        _init(initialOwner);\n    }\n}\n"
      },
      "contracts/common/access/OrigamiElevatedAccessBase.sol": {
        "content": "pragma solidity 0.8.19;\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Origami (common/access/OrigamiElevatedAccessBase.sol)\n\nimport { IOrigamiElevatedAccess } from \"contracts/interfaces/common/access/IOrigamiElevatedAccess.sol\";\nimport { CommonEventsAndErrors } from \"contracts/libraries/CommonEventsAndErrors.sol\";\n\n/**\n * @notice Inherit to add Owner roles for DAO elevated access.\n */ \nabstract contract OrigamiElevatedAccessBase is IOrigamiElevatedAccess {\n    /**\n     * @notice The address of the current owner.\n     */ \n    address public override owner;\n\n    /**\n     * @notice Explicit approval for an address to execute a function.\n     * allowedCaller => function selector => true/false\n     */\n    mapping(address => mapping(bytes4 => bool)) public override explicitFunctionAccess;\n\n    /// @dev Track proposed owner\n    address private _proposedNewOwner;\n\n    function _init(address initialOwner) internal {\n        if (owner != address(0)) revert CommonEventsAndErrors.InvalidAccess();\n        if (initialOwner == address(0)) revert CommonEventsAndErrors.InvalidAddress(address(0));\n        owner = initialOwner;\n    }\n\n    /**\n     * @notice Proposes a new Owner.\n     * Can only be called by the current owner\n     */\n    function proposeNewOwner(address account) external override onlyElevatedAccess {\n        if (account == address(0)) revert CommonEventsAndErrors.InvalidAddress(account);\n        emit NewOwnerProposed(owner, _proposedNewOwner, account);\n        _proposedNewOwner = account;\n    }\n\n    /**\n     * @notice Caller accepts the role as new Owner.\n     * Can only be called by the proposed owner\n     */\n    function acceptOwner() external override {\n        if (msg.sender != _proposedNewOwner) revert CommonEventsAndErrors.InvalidAccess();\n\n        emit NewOwnerAccepted(owner, msg.sender);\n        owner = msg.sender;\n        delete _proposedNewOwner;\n    }\n\n    /**\n     * @notice Grant `allowedCaller` the rights to call the function selectors in the access list.\n     * @dev fnSelector == bytes4(keccak256(\"fn(argType1,argType2,...)\"))\n     */\n    function setExplicitAccess(address allowedCaller, ExplicitAccess[] calldata access) external override onlyElevatedAccess {\n        if (allowedCaller == address(0)) revert CommonEventsAndErrors.InvalidAddress(allowedCaller);\n        ExplicitAccess memory _access;\n        for (uint256 i; i < access.length; ++i) {\n            _access = access[i];\n            emit ExplicitAccessSet(allowedCaller, _access.fnSelector, _access.allowed);\n            explicitFunctionAccess[allowedCaller][_access.fnSelector] = _access.allowed;\n        }\n    }\n\n    function isElevatedAccess(address caller, bytes4 fnSelector) internal view returns (bool) {\n        return (\n            caller == owner || \n            explicitFunctionAccess[caller][fnSelector]\n        );\n    }\n\n    /**\n     * @notice The owner is allowed to call, or if explicit access has been given to the caller.\n     * @dev Important: Only for use when called from an *external* contract. \n     * If a function with this modifier is called internally then the `msg.sig` \n     * will still refer to the top level externally called function.\n     */\n    modifier onlyElevatedAccess() {\n        if (!isElevatedAccess(msg.sender, msg.sig)) revert CommonEventsAndErrors.InvalidAccess();\n        _;\n    }\n}\n"
      },
      "contracts/common/borrowAndLend/OrigamiMorphoBorrowAndLend.sol": {
        "content": "pragma solidity 0.8.19;\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Origami (common/borrowAndLend/OrigamiMorphoBorrowAndLend.sol)\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport { \n    IMorpho,\n    Id as MorphoMarketId,\n    MarketParams as MorphoMarketParams\n} from \"@morpho-org/morpho-blue/src/interfaces/IMorpho.sol\";\nimport { IOracle as IMorphoOracle } from \"@morpho-org/morpho-blue/src/interfaces/IOracle.sol\";\nimport { ORACLE_PRICE_SCALE as MORPHO_ORACLE_PRICE_SCALE } from \"@morpho-org/morpho-blue/src/libraries/ConstantsLib.sol\";\nimport { IMorphoSupplyCollateralCallback } from \"@morpho-org/morpho-blue/src/interfaces/IMorphoCallbacks.sol\";\nimport { MorphoBalancesLib } from \"@morpho-org/morpho-blue/src/libraries/periphery/MorphoBalancesLib.sol\";\nimport { MorphoLib } from \"@morpho-org/morpho-blue/src/libraries/periphery/MorphoLib.sol\";\nimport { MarketParamsLib } from \"@morpho-org/morpho-blue/src/libraries/MarketParamsLib.sol\";\n\nimport { IOrigamiSwapper } from \"contracts/interfaces/common/swappers/IOrigamiSwapper.sol\";\nimport { IOrigamiMorphoBorrowAndLend } from \"contracts/interfaces/common/borrowAndLend/IOrigamiMorphoBorrowAndLend.sol\";\nimport { CommonEventsAndErrors } from \"contracts/libraries/CommonEventsAndErrors.sol\";\nimport { OrigamiElevatedAccess } from \"contracts/common/access/OrigamiElevatedAccess.sol\";\nimport { OrigamiMath } from \"contracts/libraries/OrigamiMath.sol\";\n\n/**\n * @notice An Origami abstraction over a borrow/lend money market for\n * a single `supplyToken` and a single `borrowToken`.\n * This is a Morpho specific interface\n */\ncontract OrigamiMorphoBorrowAndLend is IOrigamiMorphoBorrowAndLend, IMorphoSupplyCollateralCallback, OrigamiElevatedAccess {\n    using SafeERC20 for IERC20;\n    using MorphoBalancesLib for IMorpho;\n    using MorphoLib for IMorpho;\n    using MarketParamsLib for MorphoMarketParams;\n    using OrigamiMath for uint256;\n\n    /**\n     * @notice The morpho singleton contract\n     */\n    IMorpho public immutable override morpho;\n\n    /**\n     * @notice The token supplied as collateral\n     */\n    IERC20 private immutable _supplyToken;\n    \n    /**\n     * @notice The token which is borrowed\n     */\n    IERC20 private immutable _borrowToken;\n\n    /**\n     * @notice The Morpho oracle used for the target market\n     */\n    address public override immutable morphoMarketOracle;\n\n    /**\n     * @notice The Morpho Interest Rate Model used for the target market\n     */\n    address public override immutable morphoMarketIrm;\n\n    /**\n     * @notice The Morpho Liquidation LTV for the target market\n     */\n    uint96 public override immutable morphoMarketLltv;\n\n    /**\n     * @notice The derived Morpho market ID given the market parameters\n     */\n    MorphoMarketId public override immutable marketId;\n\n    /**\n     * @notice The approved owner of the borrow/lend position\n     */\n    address public override positionOwner;\n\n    /**\n     * @notice The max LTV we will allow when borrowing or withdrawing collateral.\n     * @dev The morpho LTV is the liquidation LTV only, we don't want to allow up to that limit\n     */\n    uint256 public override maxSafeLtv;\n    \n    /**\n     * @notice The swapper for `borrowToken` <--> `supplyToken`\n     */\n    IOrigamiSwapper public override swapper;\n\n    /**\n     * @dev Factor when converting the Morpho LTV (1e18) to an Origami Assets/Liabilities (1e18)\n     */\n    uint256 private constant LTV_TO_AL_FACTOR = 1e36;\n\n    /// @dev internal serialization of callback data for increasing leverage\n    struct IncreaseLeverageData {\n        /// @dev The amount of new `borrowToken` to borrow\n        uint256 borrowAmount;\n\n        /// @dev The encoded swap data for `borrowToken` to `supplyToken`\n        bytes swapData;\n    }\n\n    /// @dev internal serialization of callback data for decreasing leverage\n    struct DecreaseLeverageData {\n        /// @dev The amount of `supplyToken` to withdraw from collateral\n        uint256 withdrawCollateralAmount;\n\n        /// @dev The encoded swap data for `supplyToken` to `borrowToken`\n        bytes swapData;\n    }\n    \n    constructor(\n        address _initialOwner,\n        address __supplyToken,\n        address __borrowToken,\n        address _morphoAddress,\n        address _morphoMarketOracle, \n        address _morphoMarketIrm,\n        uint96 _morphoMarketLltv,\n        uint256 _maxSafeLtv\n    ) OrigamiElevatedAccess(_initialOwner) {\n        _supplyToken = IERC20(__supplyToken);\n        _borrowToken = IERC20(__borrowToken);\n        \n        morpho = IMorpho(_morphoAddress);\n\n        morphoMarketOracle = _morphoMarketOracle;\n        morphoMarketIrm = _morphoMarketIrm;\n        morphoMarketLltv = _morphoMarketLltv;\n\n        if (_maxSafeLtv >= morphoMarketLltv) revert CommonEventsAndErrors.InvalidParam();\n        maxSafeLtv = _maxSafeLtv;\n\n        marketId = getMarketParams().id();\n\n        // Verify that the market is valid\n        if (morpho.lastUpdate(marketId) == 0) revert CommonEventsAndErrors.InvalidParam();\n\n        // Approve the supply and borrow to the Morpho singleton upfront\n        _supplyToken.forceApprove(_morphoAddress, type(uint256).max);\n        _borrowToken.forceApprove(_morphoAddress, type(uint256).max);\n    }\n\n    /**\n     * @notice Set the position owner who can borrow/lend via this contract\n     */\n    function setPositionOwner(address account) external override onlyElevatedAccess {\n        positionOwner = account;\n        emit PositionOwnerSet(account);\n    }\n\n    /**\n     * @notice Set the max LTV we will allow when borrowing or withdrawing collateral.\n     * @dev The morpho LTV is the liquidation LTV only, we don't want to allow up to that limit\n     * so we set a more restrictive 'safe' LTV'\n     */\n    function setMaxSafeLtv(uint256 _maxSafeLtv) external override onlyElevatedAccess {\n        if (_maxSafeLtv >= morphoMarketLltv) revert CommonEventsAndErrors.InvalidParam();\n        maxSafeLtv = _maxSafeLtv;\n        emit MaxSafeLtvSet(_maxSafeLtv);\n    }\n    \n    /**\n     * @notice Set the swapper responsible for `borrowToken` <--> `supplyToken` swaps\n     */\n    function setSwapper(address _swapper) external override onlyElevatedAccess {\n        if (_swapper == address(0)) revert CommonEventsAndErrors.InvalidAddress(_swapper);\n\n        // Update the approval's for both `supplyToken` and `borrowToken`\n        address _oldSwapper = address(swapper);\n        if (_oldSwapper != address(0)) {\n            _supplyToken.forceApprove(_oldSwapper, 0);\n            _borrowToken.forceApprove(_oldSwapper, 0);\n        }\n        _supplyToken.forceApprove(_swapper, type(uint256).max);\n        _borrowToken.forceApprove(_swapper, type(uint256).max);\n\n        emit SwapperSet(_swapper);\n        swapper = IOrigamiSwapper(_swapper);\n    }\n\n    /**\n     * @notice Supply tokens as collateral\n     */\n    function supply(\n        uint256 supplyAmount\n    ) external override onlyPositionOwnerOrElevated {\n        _supply(supplyAmount, getMarketParams(), \"\");\n    }\n\n    /**\n     * @notice Withdraw collateral tokens to recipient\n     * @dev Set `withdrawAmount` to type(uint256).max in order to withdraw the whole balance\n     */\n    function withdraw(\n        uint256 withdrawAmount, \n        address recipient\n    ) external override onlyPositionOwnerOrElevated returns (uint256 amountWithdrawn) {\n        amountWithdrawn = _withdraw(withdrawAmount, recipient, getMarketParams());\n    }\n\n    /**\n     * @notice Borrow tokens and send to recipient\n     */\n    function borrow(\n        uint256 borrowAmount, \n        address recipient\n    ) external override onlyPositionOwnerOrElevated {\n        _borrow(borrowAmount, recipient, getMarketParams());\n    }\n\n    /**\n     * @notice Repay debt. \n     * @dev If `repayAmount` is set higher than the actual outstanding debt balance, it will be capped\n     * to that outstanding debt balance\n     * `debtRepaidAmount` return parameter will be capped to the outstanding debt balance.\n     * Any surplus debtTokens (if debt fully repaid) will remain in this contract\n     */\n    function repay(\n        uint256 repayAmount\n    ) external override onlyPositionOwnerOrElevated returns (uint256 debtRepaidAmount) {\n        debtRepaidAmount = _repay(repayAmount, getMarketParams(), \"\");\n    }\n\n    /**\n     * @notice Repay debt and withdraw collateral in one step\n     * @dev If `repayAmount` is set higher than the actual outstanding debt balance, it will be capped\n     * to that outstanding debt balance\n     * Set `withdrawAmount` to type(uint256).max in order to withdraw the whole balance\n     * `debtRepaidAmount` return parameter will be capped to the outstanding debt amount.\n     * Any surplus debtTokens (if debt fully repaid) will remain in this contract\n     */\n    function repayAndWithdraw(\n        uint256 repayAmount, \n        uint256 withdrawAmount, \n        address recipient\n    ) external override onlyPositionOwnerOrElevated returns (uint256 debtRepaidAmount, uint256 withdrawnAmount) {\n        MorphoMarketParams memory marketParams = getMarketParams();\n        debtRepaidAmount = _repay(repayAmount, marketParams, \"\");\n        withdrawnAmount = _withdraw(withdrawAmount, recipient, marketParams);\n    }\n\n    /**\n     * @notice Supply collateral and borrow in one step\n     */\n    function supplyAndBorrow(\n        uint256 supplyAmount, \n        uint256 borrowAmount, \n        address recipient\n    ) external override onlyPositionOwnerOrElevated {\n        MorphoMarketParams memory marketParams = getMarketParams();\n        _supply(supplyAmount, marketParams, \"\");\n        _borrow(borrowAmount, recipient, marketParams);\n    }\n\n    /**\n     * @notice Increase the leverage of the existing position, by supplying `supplyToken` as collateral\n     * and borrowing `borrowToken` and swapping that back to `supplyToken`\n     * @dev The totalCollateralSupplied may include any surplus after swapping from the debt to collateral\n     */\n    function increaseLeverage(\n        uint256 supplyAmount,\n        uint256 borrowAmount,\n        bytes memory swapData,\n        uint256 supplyCollateralSurplusThreshold\n    ) external override onlyPositionOwnerOrElevated returns (uint256 totalCollateralSupplied) {\n        MorphoMarketParams memory marketParams = getMarketParams();\n        _supply(\n            supplyAmount,\n            marketParams,\n            abi.encode(IncreaseLeverageData(\n                borrowAmount,\n                swapData\n            ))\n        );\n        totalCollateralSupplied = supplyAmount;\n\n        // There may be a suplus of `supplyToken` in this contract after the leverage increase\n        // If over the threshold, supply any surplus back in as collateral to morpho\n        uint256 surplusAfterLeverage = _supplyToken.balanceOf(address(this));\n        if (surplusAfterLeverage > supplyCollateralSurplusThreshold) {\n            _supply(surplusAfterLeverage, marketParams, \"\");\n            totalCollateralSupplied = totalCollateralSupplied + surplusAfterLeverage;\n        }\n    }\n\n    /**\n     * @notice Callback called when a supply of collateral occurs in Morpho.\n     * @dev The callback is called only if data is not empty.\n     * @param supplyAmount The amount of supplied collateral.\n     * @param data Arbitrary data passed to the `supplyCollateral` function.\n     */\n    function onMorphoSupplyCollateral(uint256 supplyAmount, bytes calldata data) external override {\n        if (msg.sender != address(morpho)) revert CommonEventsAndErrors.InvalidAccess();\n        IncreaseLeverageData memory decoded = abi.decode(data, (IncreaseLeverageData));\n\n        MorphoMarketParams memory marketParams = getMarketParams();\n\n        // Perform the borrow\n        _borrow(decoded.borrowAmount, address(this), marketParams);\n\n        // Swap from [borrowToken] to [supplyToken]\n        // The expected amount of [supplyToken] received after swapping from [borrowToken]\n        // needs to at least cover the supplyAmount\n        uint256 collateralReceived = swapper.execute(_borrowToken, decoded.borrowAmount, _supplyToken, decoded.swapData);\n        if (collateralReceived < supplyAmount) {\n            revert CommonEventsAndErrors.Slippage(supplyAmount, collateralReceived);\n        }\n    }\n\n    /**\n     * @notice Decrease the leverage of the existing position, by repaying `borrowToken`\n     * and withdrawing `supplyToken` collateral then swapping that back to `borrowToken`\n     */\n    function decreaseLeverage(\n        uint256 repayAmount,\n        uint256 withdrawCollateralAmount,\n        bytes memory swapData,\n        uint256 repaySurplusThreshold\n    ) external override onlyPositionOwnerOrElevated returns (\n        uint256 debtRepaidAmount, \n        uint256 surplusDebtRepaid\n    ) {\n        MorphoMarketParams memory marketParams = getMarketParams();\n        debtRepaidAmount = _repay(\n            repayAmount, \n            marketParams,\n            abi.encode(DecreaseLeverageData(\n                withdrawCollateralAmount,\n                swapData\n            ))\n        );\n\n        // There may be a suplus of `borrowToken` in this contract after the delverage\n        // If over the threshold, repay any surplus back to morpho\n        uint256 surplusAfterDeleverage = _borrowToken.balanceOf(address(this));\n        if (surplusAfterDeleverage > repaySurplusThreshold) {\n            surplusDebtRepaid = _repay(surplusAfterDeleverage, marketParams, \"\");\n        }\n    }\n\n    /**\n     * @notice Callback called when a repayment occurs.\n     * @dev The callback is called only if data is not empty.\n     * @param repayAmount The amount of repaid assets.\n     * @param data Arbitrary data passed to the `repay` function.\n     */\n    function onMorphoRepay(uint256 repayAmount, bytes calldata data) external {\n        if (msg.sender != address(morpho)) revert CommonEventsAndErrors.InvalidAccess();\n        DecreaseLeverageData memory decoded = abi.decode(data, (DecreaseLeverageData));\n\n        MorphoMarketParams memory marketParams = getMarketParams();\n\n        // Withdraw collateral\n        uint256 _amountWithdrawn = _withdraw(decoded.withdrawCollateralAmount, address(this), marketParams);\n        if (_amountWithdrawn != decoded.withdrawCollateralAmount) {\n            revert CommonEventsAndErrors.InvalidAmount(address(_supplyToken), decoded.withdrawCollateralAmount);\n        }\n        \n        // Swap from [supplyToken] to [borrowToken]\n        // The expected amount of [borrowToken] received after swapping from [supplyToken]\n        // needs to at least cover the repayAmount\n        uint256 borrowTokenReceived = swapper.execute(_supplyToken, decoded.withdrawCollateralAmount, _borrowToken, decoded.swapData);\n        if (borrowTokenReceived < repayAmount) {\n            revert CommonEventsAndErrors.Slippage(repayAmount, borrowTokenReceived);\n        }\n    }\n\n    /**\n     * @notice Recover accidental donations.\n     * @dev Does not allow for recovery of supplyToken or borrowToken if there is an outstanding\n     * morpho debt on this pool\n     * @param token Token to recover\n     * @param to Recipient address\n     * @param amount Amount to recover\n     */\n    function recoverToken(address token, address to, uint256 amount) external onlyElevatedAccess {\n        if (debtBalance() != 0) {\n            if (token == address(_supplyToken) || token == address(_borrowToken)) {\n                revert CommonEventsAndErrors.InvalidToken(token);\n            }\n        }\n        emit CommonEventsAndErrors.TokenRecovered(to, token, amount);\n        IERC20(token).safeTransfer(to, amount);\n    }\n        \n    /**\n     * @notice The Morpho market parameters\n     */\n    function getMarketParams() public override view returns (MorphoMarketParams memory) {\n        return MorphoMarketParams({\n            loanToken: address(_borrowToken),\n            collateralToken: address(_supplyToken),\n            oracle: morphoMarketOracle,\n            irm: morphoMarketIrm,\n            lltv: morphoMarketLltv\n        });\n    }\n\n    /**\n     * @notice The token supplied as collateral\n     */\n    function supplyToken() public override view returns (address) {\n        return address(_supplyToken);\n    }\n    \n    /**\n     * @notice The token which is borrowed\n     */\n    function borrowToken() public override view returns (address) {\n        return address(_borrowToken);\n    }\n\n    /**\n     * @notice The current (manually tracked) balance of tokens supplied\n     */\n    function suppliedBalance() public override view returns (uint256) {\n        return morpho.collateral(marketId, address(this));\n    }\n\n    /**\n     * @notice The current debt balance of tokens borrowed\n     */\n    function debtBalance() public override view returns (uint256) {\n        return morpho.expectedBorrowAssets(getMarketParams(), address(this));\n    }\n\n    /**\n     * @notice Whether a given Assets/Liabilities Ratio is safe, given the upstream\n     * money market parameters\n     */\n    function isSafeAlRatio(uint256 alRatio) external override view returns (bool) {\n        return alRatio >= LTV_TO_AL_FACTOR / maxSafeLtv;\n    }\n\n    /**\n     * @notice How many `supplyToken` are available to withdraw from collateral\n     * from the entire protocol, assuming this contract has fully paid down its debt\n     */\n    function availableToWithdraw() external override view returns (uint256) {\n        // The collateral (for borrows) never gets used as they are siloed markets,\n        // this contracts collateral is always available to be withdrawn.\n        // There's no morpho metric for the entire collateral supplied, instead\n        // this just returns our collateral - so the same as `suppliedBalance()`\n        return suppliedBalance();\n    }\n\n    /**\n     * @notice How many `borrowToken` are available to borrow\n     * from the entire protocol\n     */\n    function availableToBorrow() external override view returns (uint256) {\n        uint256 totalSupplyAssets = morpho.totalSupplyAssets(marketId);\n        uint256 totalBorrowAssets = morpho.totalBorrowAssets(marketId);\n        return totalSupplyAssets > totalBorrowAssets ? totalSupplyAssets - totalBorrowAssets : 0;\n    }\n\n    /**\n     * @notice How much more capacity is available to supply\n     */\n    function availableToSupply() external override pure returns (\n        uint256 supplyCap,\n        uint256 available\n    ) {\n        return (\n            type(uint256).max,\n            type(uint256).max\n        );\n    }\n\n    /**\n     * @notice Returns the curent Morpho position data\n     */\n    function debtAccountData() external override view returns (\n        uint256 collateral,\n        uint256 collateralPrice,\n        uint256 borrowed,\n        uint256 maxBorrow,\n        uint256 currentLtv,\n        uint256 healthFactor\n    ) {\n        // supplyToken decimals\n        collateral = suppliedBalance();\n        // `36 + borrowToken decimals - supplyToken decimals` decimals of precision.\n        collateralPrice = IMorphoOracle(morphoMarketOracle).price();\n        // borrowToken decimals\n        borrowed = debtBalance();\n        \n        uint256 _collateralInBorrowTerms = collateral.mulDiv(\n            collateralPrice, \n            MORPHO_ORACLE_PRICE_SCALE, \n            OrigamiMath.Rounding.ROUND_DOWN\n        );\n\n        maxBorrow = _collateralInBorrowTerms.mulDiv(\n            morphoMarketLltv,\n            1e18,\n            OrigamiMath.Rounding.ROUND_DOWN\n        );\n        \n        if (borrowed == 0) {\n            healthFactor = type(uint256).max;\n        } else {\n            currentLtv = borrowed.mulDiv(\n                1e18,\n                _collateralInBorrowTerms,\n                OrigamiMath.Rounding.ROUND_UP\n            );\n            healthFactor = maxBorrow.mulDiv(1e18, borrowed, OrigamiMath.Rounding.ROUND_DOWN);\n        }\n    }\n\n    function _supply(uint256 supplyAmount, MorphoMarketParams memory marketParams, bytes memory data) internal {\n        morpho.supplyCollateral(marketParams, supplyAmount, address(this), data);\n    }\n\n    function _withdraw(uint256 withdrawAmount, address recipient, MorphoMarketParams memory marketParams) internal returns (uint256 amountWithdrawn) {\n        // If `withdrawAmount` == uint256.max, then set the the current supplied collateral balance\n        amountWithdrawn = withdrawAmount == type(uint256).max ? suppliedBalance() : withdrawAmount;\n        morpho.withdrawCollateral(marketParams, amountWithdrawn, address(this), recipient);\n    }\n\n    function _borrow(uint256 borrowAmount, address recipient, MorphoMarketParams memory marketParams) internal {\n        (uint256 assetsBorrowed,) = morpho.borrow(\n            marketParams, borrowAmount, 0, address(this), recipient\n        );\n        if (assetsBorrowed != borrowAmount) revert CommonEventsAndErrors.InvalidAmount(address(_borrowToken), assetsBorrowed);\n    }\n    \n    function _repay(uint256 repayAmount, MorphoMarketParams memory marketParams, bytes memory data) internal returns (uint256 debtRepaidAmount) {\n        uint256 _debtBalance = debtBalance();\n\n        if (_debtBalance != 0) {\n            // If the repayment amount is more than the current balance, then repay 100% of the debt.\n            if (repayAmount > _debtBalance) {\n                // Calculate the current morpho shares owed, and repay via the shares (not amount)\n                uint256 _repayShares = morpho.position(marketId, address(this)).borrowShares;\n                (debtRepaidAmount, ) = morpho.repay(marketParams, 0, _repayShares, address(this), data);\n            } else {\n                // Repay via the amount (not shares)\n                (debtRepaidAmount, ) = morpho.repay(marketParams, repayAmount, 0, address(this), data);\n            }                          \n        }\n    }\n\n    /**\n     * @dev Only the positionOwner or Elevated Access is allowed to call.\n     */\n    modifier onlyPositionOwnerOrElevated() {\n        if (msg.sender != address(positionOwner)) {\n            if (!isElevatedAccess(msg.sender, msg.sig)) revert CommonEventsAndErrors.InvalidAccess();\n        }\n        _;\n    }\n}\n"
      },
      "contracts/interfaces/common/access/IOrigamiElevatedAccess.sol": {
        "content": "pragma solidity 0.8.19;\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Origami (interfaces/common/access/IOrigamiElevatedAccess.sol)\n\n/**\n * @notice Inherit to add Owner roles for DAO elevated access.\n */ \ninterface IOrigamiElevatedAccess {\n    event ExplicitAccessSet(address indexed account, bytes4 indexed fnSelector, bool indexed value);\n\n    event NewOwnerProposed(address indexed oldOwner, address indexed oldProposedOwner, address indexed newProposedOwner);\n    event NewOwnerAccepted(address indexed oldOwner, address indexed newOwner);\n\n    struct ExplicitAccess {\n        bytes4 fnSelector;\n        bool allowed;\n    }\n\n    /**\n     * @notice The address of the current owner.\n     */ \n    function owner() external returns (address);\n\n    /**\n     * @notice Explicit approval for an address to execute a function.\n     * allowedCaller => function selector => true/false\n     */\n    function explicitFunctionAccess(address contractAddr, bytes4 functionSelector) external returns (bool);\n\n    /**\n     * @notice Proposes a new Owner.\n     * Can only be called by the current owner\n     */\n    function proposeNewOwner(address account) external;\n\n    /**\n     * @notice Caller accepts the role as new Owner.\n     * Can only be called by the proposed owner\n     */\n    function acceptOwner() external;\n\n    /**\n     * @notice Grant `allowedCaller` the rights to call the function selectors in the access list.\n     * @dev fnSelector == bytes4(keccak256(\"fn(argType1,argType2,...)\"))\n     */\n    function setExplicitAccess(address allowedCaller, ExplicitAccess[] calldata access) external;\n}\n"
      },
      "contracts/interfaces/common/borrowAndLend/IOrigamiBorrowAndLend.sol": {
        "content": "pragma solidity 0.8.19;\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Origami (interfaces/common/borrowAndLend/IOrigamiBorrowAndLend.sol)\n\n/**\n * @notice An Origami abstraction over a borrow/lend money market for\n * a single `supplyToken` and a single `borrowToken`, for a given `positionOwner`\n */\ninterface IOrigamiBorrowAndLend {\n    event PositionOwnerSet(address indexed account);\n    event SurplusDebtReclaimed(uint256 amount, address indexed recipient);\n\n    /**\n     * @notice Set the position owner who can borrow/lend via this contract\n     */\n    function setPositionOwner(address account) external;\n\n    /**\n     * @notice Supply tokens as collateral\n     */\n    function supply(\n        uint256 supplyAmount\n    ) external;\n\n    /**\n     * @notice Withdraw collateral tokens to recipient\n     * @dev Set `withdrawAmount` to type(uint256).max in order to withdraw the whole balance\n     */\n    function withdraw(\n        uint256 withdrawAmount, \n        address recipient\n    ) external returns (uint256 amountWithdrawn);\n\n    /**\n     * @notice Borrow tokens and send to recipient\n     */\n    function borrow(\n        uint256 borrowAmount,\n        address recipient\n    ) external;\n\n    /**\n     * @notice Repay debt. \n     * @dev If `repayAmount` is set higher than the actual outstanding debt balance, it will be capped\n     * to that outstanding debt balance\n     * `debtRepaidAmount` return parameter will be capped to the outstanding debt balance.\n     * Any surplus debtTokens (if debt fully repaid) will remain in this contract\n     */\n    function repay(\n        uint256 repayAmount\n    ) external returns (uint256 debtRepaidAmount);\n\n    /**\n     * @notice Repay debt and withdraw collateral in one step\n     * @dev If `repayAmount` is set higher than the actual outstanding debt balance, it will be capped\n     * to that outstanding debt balance\n     * Set `withdrawAmount` to type(uint256).max in order to withdraw the whole balance\n     * `debtRepaidAmount` return parameter will be capped to the outstanding debt amount.\n     * Any surplus debtTokens (if debt fully repaid) will remain in this contract\n     */\n    function repayAndWithdraw(\n        uint256 repayAmount, \n        uint256 withdrawAmount, \n        address recipient\n    ) external returns (\n        uint256 debtRepaidAmount,\n        uint256 withdrawnAmount\n    );\n\n    /**\n     * @notice Supply collateral and borrow in one step\n     */\n    function supplyAndBorrow(\n        uint256 supplyAmount, \n        uint256 borrowAmount, \n        address recipient\n    ) external;\n\n    /**\n     * @notice The approved owner of the borrow/lend position\n     */\n    function positionOwner() external view returns (address);\n\n    /**\n     * @notice The token supplied as collateral\n     */\n    function supplyToken() external view returns (address);\n\n    /**\n     * @notice The token which is borrowed\n     */\n    function borrowToken() external view returns (address);\n\n    /**\n     * @notice The current (manually tracked) balance of tokens supplied\n     */\n    function suppliedBalance() external view returns (uint256);\n\n    /**\n     * @notice The current debt balance of tokens borrowed\n     */\n    function debtBalance() external view returns (uint256);\n\n    /**\n     * @notice Whether a given Assets/Liabilities Ratio is safe, given the upstream\n     * money market parameters\n     */\n    function isSafeAlRatio(uint256 alRatio) external view returns (bool);\n\n    /**\n     * @notice How many `supplyToken` are available to withdraw from collateral\n     * from the entire protocol, assuming this contract has fully paid down its debt\n     */\n    function availableToWithdraw() external view returns (uint256);\n\n    /**\n     * @notice How much more capacity is available to supply\n     */\n    function availableToSupply() external view returns (\n        uint256 supplyCap,\n        uint256 available\n    );\n\n    /**\n     * @notice How many `borrowToken` are available to borrow\n     * from the entire protocol\n     */\n    function availableToBorrow() external view returns (uint256);\n}"
      },
      "contracts/interfaces/common/borrowAndLend/IOrigamiMorphoBorrowAndLend.sol": {
        "content": "pragma solidity 0.8.19;\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Origami (interfaces/common/borrowAndLend/IOrigamiMorphoBorrowAndLend.sol)\n\nimport { IOrigamiBorrowAndLend } from \"contracts/interfaces/common/borrowAndLend/IOrigamiBorrowAndLend.sol\";\nimport { IMorpho, Id as MorphoMarketId, MarketParams as MorphoMarketParams } from \"@morpho-org/morpho-blue/src/interfaces/IMorpho.sol\";\nimport { IOrigamiSwapper } from \"contracts/interfaces/common/swappers/IOrigamiSwapper.sol\";\n\n/**\n * @notice An Origami abstraction over a borrow/lend money market for\n * a single `supplyToken` and a single `borrowToken`.\n * This is a Morpho specific interface\n */\ninterface IOrigamiMorphoBorrowAndLend is IOrigamiBorrowAndLend {\n    event MaxSafeLtvSet(uint256 _maxSafeLtv);\n    event SwapperSet(address indexed swapper);\n\n    /**\n     * @notice Set the max LTV we will allow when borrowing or withdrawing collateral.\n     * @dev The morpho LTV is the liquidation LTV only, we don't want to allow up to that limit\n     */\n    function setMaxSafeLtv(uint256 _maxSafeLtv) external;\n\n    /**\n     * @notice Set the swapper responsible for `borrowToken` <--> `supplyToken` swaps\n     */\n    function setSwapper(address _swapper) external;\n\n    /**\n     * @notice Increase the leverage of the existing position, by supplying `supplyToken` as collateral\n     * and borrowing `borrowToken` and swapping that back to `supplyToken`\n     * @dev The totalCollateralSupplied may include any surplus after swapping from the debt to collateral\n     */\n    function increaseLeverage(\n        uint256 supplyCollateralAmount,\n        uint256 borrowAmount,\n        bytes memory swapData,\n        uint256 supplyCollateralSurplusThreshold\n    ) external returns (uint256 totalCollateralSupplied);\n\n    /**\n     * @notice Decrease the leverage of the existing position, by repaying `borrowToken`\n     * and withdrawing `supplyToken` collateral then swapping that back to `borrowToken`\n     */\n    function decreaseLeverage(\n        uint256 repayAmount,\n        uint256 withdrawCollateralAmount,\n        bytes memory swapData,\n        uint256 repaySurplusThreshold\n    ) external returns  (\n        uint256 debtRepaidAmount, \n        uint256 surplusDebtRepaid\n    );\n\n    /**\n     * @notice The morpho singleton contract\n     */\n    function morpho() external view returns (IMorpho);\n\n    /**\n     * @notice The Morpho oracle used for the target market\n     */\n    function morphoMarketOracle() external view returns (address);\n\n    /**\n     * @notice The Morpho Interest Rate Model used for the target market\n     */\n    function morphoMarketIrm() external view returns (address);\n\n    /**\n     * @notice The Morpho Liquidation LTV for the target market\n     */\n    function morphoMarketLltv() external view returns (uint96);\n\n    /**\n     * @notice The Morpho market parameters\n     */\n    function getMarketParams() external view returns (MorphoMarketParams memory);\n\n    /**\n     * @notice The derived Morpho market ID given the market parameters\n     */\n    function marketId() external view returns (MorphoMarketId);\n\n    /**\n     * @notice The max LTV we will allow when borrowing or withdrawing collateral.\n     * @dev The morpho LTV is the liquidation LTV only, we don't want to allow up to that limit\n     */\n    function maxSafeLtv() external view returns (uint256);\n    \n    /**\n     * @notice The swapper for `borrowToken` <--> `supplyToken`\n     */\n    function swapper() external view returns (IOrigamiSwapper);\n\n    /**\n     * @notice Returns the curent Morpho position data\n     */\n    function debtAccountData() external view returns (\n        uint256 collateral,\n        uint256 collateralPrice,\n        uint256 borrowed,\n        uint256 maxBorrow,\n        uint256 currentLtv,\n        uint256 healthFactor\n    );\n}"
      },
      "contracts/interfaces/common/swappers/IOrigamiSwapper.sol": {
        "content": "pragma solidity 0.8.19;\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Origami (interfaces/common/swappers/IOrigamiSwapper.sol)\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @notice An on chain swapper contract to integrate with the 1Inch router | 0x proxy, \n * possibly others which obtain quote calldata offchain and then execute via a low level call\n * to perform the swap onchain\n */\ninterface IOrigamiSwapper {\n    error UnknownSwapError(bytes result);\n    error InvalidSwap();\n\n    event Swap(address indexed sellToken, uint256 sellTokenAmount, address indexed buyToken, uint256 buyTokenAmount);\n\n    /**\n     * @notice Pull tokens from sender then execute the swap\n     */\n    function execute(\n        IERC20 sellToken, \n        uint256 sellTokenAmount, \n        IERC20 buyToken,\n        bytes memory swapData\n    ) external returns (uint256 buyTokenAmount);\n}\n"
      },
      "contracts/libraries/CommonEventsAndErrors.sol": {
        "content": "pragma solidity 0.8.19;\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Origami (libraries/CommonEventsAndErrors.sol)\n\n/// @notice A collection of common events and errors thrown within the Origami contracts\nlibrary CommonEventsAndErrors {\n    error InsufficientBalance(address token, uint256 required, uint256 balance);\n    error InvalidToken(address token);\n    error InvalidParam();\n    error InvalidAddress(address addr);\n    error InvalidAmount(address token, uint256 amount);\n    error ExpectedNonZero();\n    error Slippage(uint256 minAmountExpected, uint256 actualAmount);\n    error IsPaused();\n    error UnknownExecuteError(bytes returndata);\n    error InvalidAccess();\n    error BreachedMaxTotalSupply(uint256 totalSupply, uint256 maxTotalSupply);\n\n    event TokenRecovered(address indexed to, address indexed token, uint256 amount);\n}\n"
      },
      "contracts/libraries/OrigamiMath.sol": {
        "content": "pragma solidity 0.8.19;\n// SPDX-License-Identifier: AGPL-3.0-or-later\n// Origami (libraries/OrigamiMath.sol)\n\nimport { mulDiv as prbMulDiv, PRBMath_MulDiv_Overflow } from \"@prb/math/src/Common.sol\";\nimport { CommonEventsAndErrors } from \"contracts/libraries/CommonEventsAndErrors.sol\";\n\n/**\n * @notice Utilities to operate on fixed point math multipliation and division\n * taking rounding into consideration\n */\nlibrary OrigamiMath {\n    enum Rounding {\n        ROUND_DOWN,\n        ROUND_UP\n    }\n\n    uint256 public constant BASIS_POINTS_DIVISOR = 10_000;\n\n    function scaleUp(uint256 amount, uint256 scalar) internal pure returns (uint256) {\n        // Special case for scalar == 1, as it's common for token amounts to not need\n        // scaling if decimal places are the same\n        return scalar == 1 ? amount : amount * scalar;\n    }\n\n    function scaleDown(\n        uint256 amount, \n        uint256 scalar, \n        Rounding roundingMode\n    ) internal pure returns (uint256 result) {\n        // Special case for scalar == 1, as it's common for token amounts to not need\n        // scaling if decimal places are the same\n        unchecked {\n            if (scalar == 1) {\n                result = amount;\n            } else if (roundingMode == Rounding.ROUND_DOWN) {\n                result = amount / scalar;\n            } else {\n                // ROUND_UP uses the same logic as OZ Math.ceilDiv()\n                result = amount == 0 ? 0 : (amount - 1) / scalar + 1;\n            }\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision,\n     * rounding up\n     */\n    function mulDiv(\n        uint256 x, \n        uint256 y, \n        uint256 denominator,\n        Rounding roundingMode\n    ) internal pure returns (uint256 result) {\n        result = prbMulDiv(x, y, denominator);\n        if (roundingMode == Rounding.ROUND_UP) {\n            if (mulmod(x, y, denominator) != 0) {\n                if (result < type(uint256).max) {\n                    unchecked {\n                        result = result + 1;\n                    }\n                } else {\n                    revert PRBMath_MulDiv_Overflow(x, y, denominator);\n                }\n            }\n        }\n    }\n\n    function subtractBps(\n        uint256 inputAmount, \n        uint256 basisPoints,\n        Rounding roundingMode\n    ) internal pure returns (uint256 result) {\n        uint256 numeratorBps;\n        unchecked {\n            numeratorBps = BASIS_POINTS_DIVISOR - basisPoints;\n        }\n\n        result = basisPoints < BASIS_POINTS_DIVISOR\n            ? mulDiv(\n                inputAmount,\n                numeratorBps, \n                BASIS_POINTS_DIVISOR, \n                roundingMode\n            ) : 0;\n    }\n\n    function addBps(\n        uint256 inputAmount,\n        uint256 basisPoints,\n        Rounding roundingMode\n    ) internal pure returns (uint256 result) {\n        uint256 numeratorBps;\n        unchecked {\n            numeratorBps = BASIS_POINTS_DIVISOR + basisPoints;\n        }\n\n        // Round up for max amounts out expected\n        result = mulDiv(\n            inputAmount,\n            numeratorBps, \n            BASIS_POINTS_DIVISOR, \n            roundingMode\n        );\n    }\n\n    /**\n     * @notice Split the `inputAmount` into two parts based on the `basisPoints` fraction.\n     * eg: 3333 BPS (33.3%) can be used to split an input amount of 600 into: (result=400, removed=200).\n     * @dev The rounding mode is applied to the `result`\n     */\n    function splitSubtractBps(\n        uint256 inputAmount, \n        uint256 basisPoints,\n        Rounding roundingMode\n    ) internal pure returns (uint256 result, uint256 removed) {\n        result = subtractBps(inputAmount, basisPoints, roundingMode);\n        unchecked {\n            removed = inputAmount - result;\n        }\n    }\n\n    /**\n     * @notice Reverse the fractional amount of an input.\n     * eg: For 3333 BPS (33.3%) and the remainder=400, the result is 600\n     */\n    function inverseSubtractBps(\n        uint256 remainderAmount, \n        uint256 basisPoints,\n        Rounding roundingMode\n    ) internal pure returns (uint256 result) {\n        if (basisPoints == 0) return remainderAmount; // gas shortcut for 0\n        if (basisPoints >= BASIS_POINTS_DIVISOR) revert CommonEventsAndErrors.InvalidParam();\n\n        uint256 denominatorBps;\n        unchecked {\n            denominatorBps = BASIS_POINTS_DIVISOR - basisPoints;\n        }\n        result = mulDiv(\n            remainderAmount,\n            BASIS_POINTS_DIVISOR, \n            denominatorBps, \n            roundingMode\n        );\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 10000
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}