Skip to content
Verified contractExactGPL-2.0-or-later

LotusLens

Address0x3a4d499dec5c87d3c0ddb50ddafb55df1fabb9db
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.28

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
GPL-2.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,429,748
Creation transaction
0x56bc6ff8b8…212e5ef0f5

src/lens/LotusLens.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

import {FixedPointMathLib} from "solady/src/utils/FixedPointMathLib.sol";

import {Id, ILotus, MarketParams, Position, Tranche, TrancheConfig} from "../interfaces/ILotus.sol";
import {IOracle} from "../interfaces/IOracle.sol";
import {ILotusLens, IRiskEngineBorrowUtilizationPreview, IRiskEnginePreview} from "./interfaces/ILotusLens.sol";
import {WAD, ORACLE_PRICE_SCALE} from "../libraries/ConstantsLib.sol";
import {LotusErrorsLib} from "../libraries/LotusErrorsLib.sol";
import {MarketParamsLib} from "../libraries/MarketParamsLib.sol";

/// @title LotusLens
/// @notice Read helper for Lotus tranche rates, analytics, and borrow capacity.
contract LotusLens is ILotusLens {
    using FixedPointMathLib for uint256;
    using MarketParamsLib for MarketParams;

    /// @inheritdoc ILotusLens
    ILotus public immutable override LOTUS;

    /// @param lotus The Lotus core contract queried by this lens.
    constructor(ILotus lotus) {
        if (address(lotus) == address(0)) revert LotusErrorsLib.ZeroAddress();
        LOTUS = lotus;
    }

    /// @inheritdoc ILotusLens
    function accrueInterestAndReturnMaxBorrow(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        address borrower,
        bytes calldata riskEngineData
    ) external override returns (uint256 borrowed, uint256 maxBorrow) {
        LOTUS.accrueInterest(marketParams, riskEngineData);
        return LOTUS.getMaxBorrowAndBorrowed(marketParams, trancheIndex, borrower);
    }

    /// @inheritdoc ILotusLens
    function accrueInterestAndReturnBorrowLimit(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        address borrower,
        bytes calldata riskEngineData
    ) external override returns (uint256 borrowed, uint256 borrowLimit) {
        LOTUS.accrueInterest(marketParams, riskEngineData);
        return getBorrowLimitAndBorrowed(marketParams, trancheIndex, borrower);
    }

    /// @inheritdoc ILotusLens
    /// @dev Mirrors Lotus's buffered health check: `getMaxBorrowAndBorrowed` validates the market and tranche and
    /// supplies `borrowed`; the limit is recomputed with the buffered LLTV using Lotus's rounding.
    function getBorrowLimitAndBorrowed(MarketParams memory marketParams, uint256 trancheIndex, address borrower)
        public
        view
        override
        returns (uint256 borrowed, uint256 borrowLimit)
    {
        (borrowed,) = LOTUS.getMaxBorrowAndBorrowed(marketParams, trancheIndex, borrower);

        Id id = marketParams.id();
        TrancheConfig memory config = LOTUS.getTrancheConfig(id, trancheIndex);
        Position memory position = LOTUS.getPosition(id, borrower, trancheIndex);
        uint256 borrowLimitLltv = uint256(config.lltv).mulWad(WAD - LOTUS.borrowLtvBuffer());
        borrowLimit = uint256(position.collateral).mulDiv(IOracle(config.oracle).price(), ORACLE_PRICE_SCALE)
            .mulWad(borrowLimitLltv);
    }

    /// @inheritdoc ILotusLens
    function getPositions(Id id, address user) external view returns (Position[] memory userPositions) {
        uint256 numTranches = LOTUS.getNumMarketTranches(id);
        userPositions = new Position[](numTranches);
        for (uint256 i; i < numTranches; ++i) {
            userPositions[i] = LOTUS.getPosition(id, user, i);
        }
    }

    /// @inheritdoc ILotusLens
    /// @dev This helper only supports markets whose risk engine implements `IRiskEnginePreview`.
    function previewTrancheSupplyRate(Id id, uint256 trancheIndex)
        external
        view
        override
        returns (uint256 trancheSupplyRate)
    {
        return previewTrancheSupplyRate(id, trancheIndex, bytes(""));
    }

    /// @inheritdoc ILotusLens
    /// @dev Cascades per-second borrow interest from tranche 0 (most senior) through supply-utilization ratios at each
    /// tranche to derive the absorbed rate at `trancheIndex`, then applies the fee.
    /// @dev This helper only supports markets whose risk engine implements `IRiskEnginePreview`.
    /// @dev `riskEngineData` is forwarded to preview helpers for engines that depend on call-time config.
    function previewTrancheSupplyRate(Id id, uint256 trancheIndex, bytes memory riskEngineData)
        public
        view
        override
        returns (uint256 trancheSupplyRate)
    {
        (Tranche[] memory tranches, Tranche memory targetTranche, IRiskEnginePreview engine) =
            _getValidatedPreviewContext(id, trancheIndex);
        if (targetTranche.supplyAssets == 0) return 0;
        return _previewTrancheSupplyRate(id, trancheIndex, tranches, targetTranche, engine, riskEngineData);
    }

    /// @inheritdoc ILotusLens
    function previewTrancheAnalytics(Id id, uint256 trancheIndex)
        external
        view
        override
        returns (TranchePreview memory preview)
    {
        return previewTrancheAnalytics(id, trancheIndex, bytes(""));
    }

    /// @inheritdoc ILotusLens
    function previewTrancheAnalytics(Id id, uint256 trancheIndex, bytes memory riskEngineData)
        public
        view
        override
        returns (TranchePreview memory preview)
    {
        (Tranche[] memory tranches, Tranche memory targetTranche, IRiskEnginePreview engine) =
            _getValidatedPreviewContext(id, trancheIndex);

        preview.borrowRate = engine.previewTrancheBorrowRate(id, trancheIndex, riskEngineData);
        preview.supplyUtilization = engine.previewTrancheSupplyUtilization(id, trancheIndex, riskEngineData);
        preview.supplyRate =
            _previewTrancheSupplyRate(id, trancheIndex, tranches, targetTranche, engine, riskEngineData);

        (bool success, bytes memory data) = address(engine)
            .staticcall(
                abi.encodeCall(
                    IRiskEngineBorrowUtilizationPreview.previewTrancheBorrowUtilization,
                    (id, trancheIndex, riskEngineData)
                )
            );
        if (success && data.length >= 32) {
            preview.hasBorrowUtilization = true;
            preview.borrowUtilization = abi.decode(data, (uint256));
        }
    }

    function _getValidatedPreviewContext(Id id, uint256 trancheIndex)
        internal
        view
        returns (Tranche[] memory tranches, Tranche memory targetTranche, IRiskEnginePreview engine)
    {
        tranches = LOTUS.getMarketTranches(id);
        uint256 numTranches = tranches.length;
        if (numTranches == 0) revert LotusErrorsLib.MarketNotCreated(id);
        if (trancheIndex >= numTranches) revert LotusErrorsLib.InvalidTrancheIndex(trancheIndex);
        targetTranche = tranches[trancheIndex];
        engine = IRiskEnginePreview(LOTUS.getMarketParams(id).riskEngine);
        return (tranches, targetTranche, engine);
    }

    function _previewTrancheSupplyRate(
        Id id,
        uint256 trancheIndex,
        Tranche[] memory tranches,
        Tranche memory targetTranche,
        IRiskEnginePreview engine,
        bytes memory riskEngineData
    ) internal view returns (uint256 trancheSupplyRate) {
        if (targetTranche.supplyAssets == 0) return 0;

        uint256 cascadingRatePerSecond;
        for (uint256 i = 0; i <= trancheIndex;) {
            if (tranches[i].borrowAssets != 0) {
                uint256 borrowRate = engine.previewTrancheBorrowRate(id, i, riskEngineData);
                cascadingRatePerSecond += uint256(tranches[i].borrowAssets).mulWad(borrowRate);
            }

            if (cascadingRatePerSecond != 0) {
                uint256 supplyUtil = engine.previewTrancheSupplyUtilization(id, i, riskEngineData);
                uint256 absorbedRate = cascadingRatePerSecond.mulWad(supplyUtil);

                if (i == trancheIndex) {
                    if (absorbedRate == 0) return 0;
                    trancheSupplyRate = absorbedRate.divWad(targetTranche.supplyAssets).mulWad(WAD - targetTranche.fee);
                    return trancheSupplyRate;
                }

                cascadingRatePerSecond -= absorbedRate;
            }

            unchecked {
                ++i;
            }
        }
    }
}

lib/solady/src/utils/FixedPointMathLib.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error ExpOverflow();

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error FactorialOverflow();

    /// @dev The operation failed, due to an overflow.
    error RPowOverflow();

    /// @dev The mantissa is too big to fit.
    error MantissaOverflow();

    /// @dev The operation failed, due to an multiplication overflow.
    error MulWadFailed();

    /// @dev The operation failed, due to an multiplication overflow.
    error SMulWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error DivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error SDivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error MulDivFailed();

    /// @dev The division failed, as the denominator is zero.
    error DivFailed();

    /// @dev The full precision multiply-divide operation failed, either due
    /// to the result being larger than 256 bits, or a division by a zero.
    error FullMulDivFailed();

    /// @dev The output is undefined, as the input is less-than-or-equal to zero.
    error LnWadUndefined();

    /// @dev The input outside the acceptable domain.
    error OutOfDomain();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The scalar of ETH and most ERC20s.
    uint256 internal constant WAD = 1e18;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              SIMPLIFIED FIXED POINT OPERATIONS             */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if gt(x, div(not(0), y)) {
                if y {
                    mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
            if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up.
    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if iszero(eq(div(z, y), x)) {
                if y {
                    mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
    function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
            if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, WAD)
            // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
            if iszero(mul(y, eq(sdiv(z, WAD), x))) {
                mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up.
    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
            if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
    function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `x` to the power of `y`.
    /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
    /// Note: This function is an approximation.
    function powWad(int256 x, int256 y) internal pure returns (int256) {
        // Using `ln(x)` means `x` must be greater than 0.
        return expWad((lnWad(x) * y) / int256(WAD));
    }

    /// @dev Returns `exp(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    /// Note: This function is an approximation. Monotonically increasing.
    function expWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            // When the result is less than 0.5 we return zero.
            // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
            if (x <= -41446531673892822313) return r;

            /// @solidity memory-safe-assembly
            assembly {
                // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                if iszero(slt(x, 135305999368893231589)) {
                    mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                    revert(0x1c, 0x04)
                }
            }

            // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
            // for more intermediate precision and a binary basis. This base conversion
            // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
            x = (x << 78) / 5 ** 18;

            // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
            // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
            // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
            int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
            x = x - k * 54916777467707473351141471128;

            // `k` is in the range `[-61, 195]`.

            // Evaluate using a (6, 7)-term rational approximation.
            // `p` is made monic, we'll multiply by a scale factor later.
            int256 y = x + 1346386616545796478920950773328;
            y = ((y * x) >> 96) + 57155421227552351082224309758442;
            int256 p = y + x - 94201549194550492254356042504812;
            p = ((p * y) >> 96) + 28719021644029726153956944680412240;
            p = p * x + (4385272521454847904659076985693276 << 96);

            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
            int256 q = x - 2855989394907223263936484059900;
            q = ((q * x) >> 96) + 50020603652535783019961831881945;
            q = ((q * x) >> 96) - 533845033583426703283633433725380;
            q = ((q * x) >> 96) + 3604857256930695427073651918091429;
            q = ((q * x) >> 96) - 14423608567350463180887372962807573;
            q = ((q * x) >> 96) + 26449188498355588339934803723976023;

            /// @solidity memory-safe-assembly
            assembly {
                // Div in assembly because solidity adds a zero check despite the unchecked.
                // The q polynomial won't have zeros in the domain as all its roots are complex.
                // No scaling is necessary because p is already `2**96` too large.
                r := sdiv(p, q)
            }

            // r should be in the range `(0.09, 0.25) * 2**96`.

            // We now need to multiply r by:
            // - The scale factor `s ≈ 6.031367120`.
            // - The `2**k` factor from the range reduction.
            // - The `1e18 / 2**96` factor for base conversion.
            // We do this all at once, with an intermediate result in `2**213`
            // basis, so the final right shift is always by a positive amount.
            r = int256(
                (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
            );
        }
    }

    /// @dev Returns `ln(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    /// Note: This function is an approximation. Monotonically increasing.
    function lnWad(int256 x) internal pure returns (int256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
            // We do this by multiplying by `2**96 / 10**18`. But since
            // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
            // and add `ln(2**96 / 10**18)` at the end.

            // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // We place the check here for more optimal stack operations.
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                revert(0x1c, 0x04)
            }
            // forgefmt: disable-next-item
            r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x := shr(159, shl(r, x))

            // Evaluate using a (8, 8)-term rational approximation.
            // `p` is made monic, we will multiply by a scale factor later.
            // forgefmt: disable-next-item
            let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                sar(96, mul(add(43456485725739037958740375743393,
                sar(96, mul(add(24828157081833163892658089445524,
                sar(96, mul(add(3273285459638523848632254066296,
                    x), x))), x))), x)), 11111509109440967052023855526967)
            p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
            p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
            p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.

            // `q` is monic by convention.
            let q := add(5573035233440673466300451813936, x)
            q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
            q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
            q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
            q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
            q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
            q := add(909429971244387300277376558375, sar(96, mul(x, q)))

            // `p / q` is in the range `(0, 0.125) * 2**96`.

            // Finalization, we need to:
            // - Multiply by the scale factor `s = 5.549…`.
            // - Add `ln(2**96 / 10**18)`.
            // - Add `k * ln(2)`.
            // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.

            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already `2**96` too large.
            p := sdiv(p, q)
            // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
            p := mul(1677202110996718588342820967067443963516166, p)
            // Add `ln(2) * k * 5**18 * 2**192`.
            // forgefmt: disable-next-item
            p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
            // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
            p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
            // Base conversion: mul `2**18 / 2**192`.
            r := sar(174, p)
        }
    }

    /// @dev Returns `W_0(x)`, denominated in `WAD`.
    /// See: https://en.wikipedia.org/wiki/Lambert_W_function
    /// a.k.a. Product log function. This is an approximation of the principal branch.
    /// Note: This function is an approximation. Monotonically increasing.
    function lambertW0Wad(int256 x) internal pure returns (int256 w) {
        // forgefmt: disable-next-item
        unchecked {
            if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
            (int256 wad, int256 p) = (int256(WAD), x);
            uint256 c; // Whether we need to avoid catastrophic cancellation.
            uint256 i = 4; // Number of iterations.
            if (w <= 0x1ffffffffffff) {
                if (-0x4000000000000 <= w) {
                    i = 1; // Inputs near zero only take one step to converge.
                } else if (w <= -0x3ffffffffffffff) {
                    i = 32; // Inputs near `-1/e` take very long to converge.
                }
            } else if (uint256(w >> 63) == uint256(0)) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Inline log2 for more performance, since the range is small.
                    let v := shr(49, w)
                    let l := shl(3, lt(0xff, v))
                    l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                        0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                    w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                    c := gt(l, 60)
                    i := add(2, add(gt(l, 53), c))
                }
            } else {
                int256 ll = lnWad(w = lnWad(w));
                /// @solidity memory-safe-assembly
                assembly {
                    // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                    w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                    i := add(3, iszero(shr(68, x)))
                    c := iszero(shr(143, x))
                }
                if (c == uint256(0)) {
                    do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                        int256 e = expWad(w);
                        /// @solidity memory-safe-assembly
                        assembly {
                            let t := mul(w, div(e, wad))
                            w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                        }
                        if (p <= w) break;
                        p = w;
                    } while (--i != uint256(0));
                    /// @solidity memory-safe-assembly
                    assembly {
                        w := sub(w, sgt(w, 2))
                    }
                    return w;
                }
            }
            do { // Otherwise, use Halley's for faster convergence.
                int256 e = expWad(w);
                /// @solidity memory-safe-assembly
                assembly {
                    let t := add(w, wad)
                    let s := sub(mul(w, e), mul(x, wad))
                    w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                }
                if (p <= w) break;
                p = w;
            } while (--i != c);
            /// @solidity memory-safe-assembly
            assembly {
                w := sub(w, sgt(w, 2))
            }
            // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
            // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
            if (c == uint256(0)) return w;
            int256 t = w | 1;
            /// @solidity memory-safe-assembly
            assembly {
                x := sdiv(mul(x, wad), t)
            }
            x = (t * (wad + lnWad(x)));
            /// @solidity memory-safe-assembly
            assembly {
                w := sdiv(x, add(wad, t))
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  GENERAL NUMBER UTILITIES                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `a * b == x * y`, with full precision.
    function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
        internal
        pure
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
    function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // 512-bit multiply `[p1 p0] = x * y`.
            // Compute the product mod `2**256` and mod `2**256 - 1`
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that `product = p1 * 2**256 + p0`.

            // Temporarily use `z` as `p0` to save gas.
            z := mul(x, y) // Lower 256 bits of `x * y`.
            for {} 1 {} {
                // If overflows.
                if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                    let mm := mulmod(x, y, not(0))
                    let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.

                    /*------------------- 512 by 256 division --------------------*/

                    // Make division exact by subtracting the remainder from `[p1 p0]`.
                    let r := mulmod(x, y, d) // Compute remainder using mulmod.
                    let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
                    // Make sure `z` is less than `2**256`. Also prevents `d == 0`.
                    // Placing the check here seems to give more optimal stack operations.
                    if iszero(gt(d, p1)) {
                        mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    d := div(d, t) // Divide `d` by `t`, which is a power of two.
                    // Invert `d mod 2**256`
                    // Now that `d` is an odd number, it has an inverse
                    // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                    // Compute the inverse by starting with a seed that is correct
                    // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                    let inv := xor(2, mul(3, d))
                    // Now use Newton-Raphson iteration to improve the precision.
                    // Thanks to Hensel's lifting lemma, this also works in modular
                    // arithmetic, doubling the correct bits in each step.
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                    z :=
                        mul(
                            // Divide [p1 p0] by the factors of two.
                            // Shift in bits from `p1` into `p0`. For this we need
                            // to flip `t` such that it is `2**256 / t`.
                            or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
                            mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
                        )
                    break
                }
                z := div(z, d)
                break
            }
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
    /// Performs the full 512 bit calculation regardless.
    function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            let mm := mulmod(x, y, not(0))
            let p1 := sub(mm, add(z, lt(mm, z)))
            let t := and(d, sub(0, d))
            let r := mulmod(x, y, d)
            d := div(d, t)
            let inv := xor(2, mul(3, d))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            z :=
                mul(
                    or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
                    mul(sub(2, mul(d, inv)), inv)
                )
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Uniswap-v3-core under MIT license:
    /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
    function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        z = fullMulDiv(x, y, d);
        /// @solidity memory-safe-assembly
        assembly {
            if mulmod(x, y, d) {
                z := add(z, 1)
                if iszero(z) {
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
    /// Throws if result overflows a uint256.
    /// Credit to Philogy under MIT license:
    /// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
    function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Temporarily use `z` as `p0` to save gas.
            z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
            for {} 1 {} {
                if iszero(or(iszero(x), eq(div(z, x), y))) {
                    let k := and(n, 0xff) // `n`, cleaned.
                    let mm := mulmod(x, y, not(0))
                    let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
                    //         |      p1     |      z     |
                    // Before: | p1_0 ¦ p1_1 | z_0  ¦ z_1 |
                    // Final:  |   0  ¦ p1_0 | p1_1 ¦ z_0 |
                    // Check that final `z` doesn't overflow by checking that p1_0 = 0.
                    if iszero(shr(k, p1)) {
                        z := add(shl(sub(256, k), p1), shr(k, z))
                        break
                    }
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
                z := shr(and(n, 0xff), z)
                break
            }
        }
    }

    /// @dev Returns `floor(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
            if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(z, d)
        }
    }

    /// @dev Returns `ceil(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
            if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(z, d))), div(z, d))
        }
    }

    /// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
    function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
        /// @solidity memory-safe-assembly
        assembly {
            let g := n
            let r := mod(a, n)
            for { let y := 1 } 1 {} {
                let q := div(g, r)
                let t := g
                g := r
                r := sub(t, mul(r, q))
                let u := x
                x := y
                y := sub(u, mul(y, q))
                if iszero(r) { break }
            }
            x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
        }
    }

    /// @dev Returns `ceil(x / d)`.
    /// Reverts if `d` is zero.
    function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(d) {
                mstore(0x00, 0x65244e4e) // `DivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(x, d))), div(x, d))
        }
    }

    /// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Returns `max(0, x - y)`.
    function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Returns `min(2 ** 256 - 1, x + y)`.
    function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(sub(0, lt(add(x, y), x)), add(x, y))
        }
    }

    /// @dev Returns `min(2 ** 256 - 1, x * y)`.
    function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, address x, address y) internal pure returns (address z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `x != 0 ? x : y`, without branching.
    function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(x)))
        }
    }

    /// @dev Returns `x != bytes32(0) ? x : y`, without branching.
    function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(x)))
        }
    }

    /// @dev Returns `x != address(0) ? x : y`, without branching.
    function coalesce(address x, address y) internal pure returns (address z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(shl(96, x))))
        }
    }

    /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
    /// Reverts if the computation overflows.
    function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
            if x {
                z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                let half := shr(1, b) // Divide `b` by 2.
                // Divide `y` by 2 every iteration.
                for { y := shr(1, y) } y { y := shr(1, y) } {
                    let xx := mul(x, x) // Store x squared.
                    let xxRound := add(xx, half) // Round to the nearest number.
                    // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                    if or(lt(xxRound, xx), shr(128, x)) {
                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                    // If `y` is odd:
                    if and(y, 1) {
                        let zx := mul(z, x) // Compute `z * x`.
                        let zxRound := add(zx, half) // Round to the nearest number.
                        // If `z * x` overflowed or `zx + half` overflowed:
                        if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                            // Revert if `x` is non-zero.
                            if x {
                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                revert(0x1c, 0x04)
                            }
                        }
                        z := div(zxRound, b) // Return properly scaled `zxRound`.
                    }
                }
            }
        }
    }

    /// @dev Returns the square root of `x`, rounded down.
    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
            // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffffff, shr(r, x))))
            z := shl(shr(1, r), z)

            // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
            // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
            // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
            // That's not possible if `x < 256` but we can just verify those cases exhaustively.

            // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
            // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
            // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.

            // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
            // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
            // with largest error when `s = 1` and when `s = 256` or `1/256`.

            // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
            // Then we can estimate `sqrt(y)` using
            // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.

            // There is no overflow risk here since `y < 2**136` after the first branch above.
            z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If `x+1` is a perfect square, the Babylonian method cycles between
            // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            z := sub(z, lt(div(x, z), z))
        }
    }

    /// @dev Returns the cube root of `x`, rounded down.
    /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
    /// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
    /// Formally verified by xuwinnie:
    /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
    function cbrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // Makeshift lookup table to nudge the approximate log2 result.
            z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
            // Newton-Raphson's.
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            // Round down.
            z := sub(z, lt(div(x, mul(z, z)), z))
        }
    }

    /// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
    function sqrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
            z = (1 + sqrt(x)) * 10 ** 9;
            z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
        }
        /// @solidity memory-safe-assembly
        assembly {
            z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
        }
    }

    /// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
    /// Formally verified by xuwinnie:
    /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
    function cbrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
            z = (1 + cbrt(x)) * 10 ** 12;
            z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
        }
        /// @solidity memory-safe-assembly
        assembly {
            let p := x
            for {} 1 {} {
                if iszero(shr(229, p)) {
                    if iszero(shr(199, p)) {
                        p := mul(p, 100000000000000000) // 10 ** 17.
                        break
                    }
                    p := mul(p, 100000000) // 10 ** 8.
                    break
                }
                if iszero(shr(249, p)) { p := mul(p, 100) }
                break
            }
            let t := mulmod(mul(z, z), z, p)
            z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
        }
    }

    /// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
    function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
        if (x == y) return x;
        uint256 p = rawMul(x, y);
        if (y == rawDiv(p, x)) return sqrt(p);
        for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
            if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
        }
    }

    /// @dev Returns the factorial of `x`.
    function factorial(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := 1
            if iszero(lt(x, 58)) {
                mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                revert(0x1c, 0x04)
            }
            for {} x { x := sub(x, 1) } { z := mul(z, x) }
        }
    }

    /// @dev Returns the log2 of `x`.
    /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
    /// Returns 0 if `x` is zero.
    function log2(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020504060203020504030106050205030304010505030400000000))
        }
    }

    /// @dev Returns the log2 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log2Up(uint256 x) internal pure returns (uint256 r) {
        r = log2(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(r, 1), x))
        }
    }

    /// @dev Returns the log10 of `x`.
    /// Returns 0 if `x` is zero.
    function log10(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(x, 100000000000000000000000000000000000000)) {
                x := div(x, 100000000000000000000000000000000000000)
                r := 38
            }
            if iszero(lt(x, 100000000000000000000)) {
                x := div(x, 100000000000000000000)
                r := add(r, 20)
            }
            if iszero(lt(x, 10000000000)) {
                x := div(x, 10000000000)
                r := add(r, 10)
            }
            if iszero(lt(x, 100000)) {
                x := div(x, 100000)
                r := add(r, 5)
            }
            r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
        }
    }

    /// @dev Returns the log10 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log10Up(uint256 x) internal pure returns (uint256 r) {
        r = log10(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(exp(10, r), x))
        }
    }

    /// @dev Returns the log256 of `x`.
    /// Returns 0 if `x` is zero.
    function log256(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(shr(3, r), lt(0xff, shr(r, x)))
        }
    }

    /// @dev Returns the log256 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log256Up(uint256 x) internal pure returns (uint256 r) {
        r = log256(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(shl(3, r), 1), x))
        }
    }

    /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
    /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
    function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
        /// @solidity memory-safe-assembly
        assembly {
            mantissa := x
            if mantissa {
                if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                    mantissa := div(mantissa, 1000000000000000000000000000000000)
                    exponent := 33
                }
                if iszero(mod(mantissa, 10000000000000000000)) {
                    mantissa := div(mantissa, 10000000000000000000)
                    exponent := add(exponent, 19)
                }
                if iszero(mod(mantissa, 1000000000000)) {
                    mantissa := div(mantissa, 1000000000000)
                    exponent := add(exponent, 12)
                }
                if iszero(mod(mantissa, 1000000)) {
                    mantissa := div(mantissa, 1000000)
                    exponent := add(exponent, 6)
                }
                if iszero(mod(mantissa, 10000)) {
                    mantissa := div(mantissa, 10000)
                    exponent := add(exponent, 4)
                }
                if iszero(mod(mantissa, 100)) {
                    mantissa := div(mantissa, 100)
                    exponent := add(exponent, 2)
                }
                if iszero(mod(mantissa, 10)) {
                    mantissa := div(mantissa, 10)
                    exponent := add(exponent, 1)
                }
            }
        }
    }

    /// @dev Convenience function for packing `x` into a smaller number using `sci`.
    /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
    /// The `exponent` will be in bits [0..6] (the lower 7 bits).
    /// Use `SafeCastLib` to safely ensure that the `packed` number is small
    /// enough to fit in the desired unsigned integer type:
    /// ```
    ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
    /// ```
    function packSci(uint256 x) internal pure returns (uint256 packed) {
        (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
        /// @solidity memory-safe-assembly
        assembly {
            if shr(249, x) {
                mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                revert(0x1c, 0x04)
            }
            packed := or(shl(7, x), packed)
        }
    }

    /// @dev Convenience function for unpacking a packed number from `packSci`.
    function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
        unchecked {
            unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
        }
    }

    /// @dev Returns the average of `x` and `y`. Rounds towards zero.
    function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = (x & y) + ((x ^ y) >> 1);
        }
    }

    /// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
    function avg(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = (x >> 1) + (y >> 1) + (x & y & 1);
        }
    }

    /// @dev Returns the absolute value of `x`.
    function abs(int256 x) internal pure returns (uint256 z) {
        unchecked {
            z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(int256 x, int256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), slt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), gt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), sgt(y, x)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(uint256 x, uint256 minValue, uint256 maxValue)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
        }
    }

    /// @dev Returns greatest common divisor of `x` and `y`.
    function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            for { z := x } y {} {
                let t := y
                y := mod(z, y)
                z := t
            }
        }
    }

    /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
    /// with `t` clamped between `begin` and `end` (inclusive).
    /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
    /// If `begins == end`, returns `t <= begin ? a : b`.
    function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
        internal
        pure
        returns (uint256)
    {
        if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
        if (t <= begin) return a;
        if (t >= end) return b;
        unchecked {
            if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
            return a - fullMulDiv(a - b, t - begin, end - begin);
        }
    }

    /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
    /// with `t` clamped between `begin` and `end` (inclusive).
    /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
    /// If `begins == end`, returns `t <= begin ? a : b`.
    function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
        internal
        pure
        returns (int256)
    {
        if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
        if (t <= begin) return a;
        if (t >= end) return b;
        // forgefmt: disable-next-item
        unchecked {
            if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
                uint256(t - begin), uint256(end - begin)));
            return int256(uint256(a) - fullMulDiv(uint256(a - b),
                uint256(t - begin), uint256(end - begin)));
        }
    }

    /// @dev Returns if `x` is an even number. Some people may need this.
    function isEven(uint256 x) internal pure returns (bool) {
        return x & uint256(1) == uint256(0);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   RAW NUMBER OPERATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(x, y)
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mod(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := smod(x, y)
        }
    }

    /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
    function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := addmod(x, y, d)
        }
    }

    /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
    function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mulmod(x, y, d)
        }
    }
}

src/access/TwoStepOwnable.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

/// @title ITwoStepOwnable
/// @notice Two-step ownership interface. Host interfaces extend this so the mixin implements it once.
interface ITwoStepOwnable {
    /// @notice Emitted when a two-step ownership transfer is started.
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /// @notice Emitted when ownership changes (accept or renounce).
    event OwnerUpdated(address indexed newOwner);

    /// @notice Caller is not the owner.
    error NotOwner();

    /// @notice Caller is not the pending owner.
    error NotPendingOwner();

    /// @notice The current owner.
    function owner() external view returns (address);

    /// @notice The pending owner of a two-step transfer.
    function pendingOwner() external view returns (address);

    /// @notice Starts a two-step ownership transfer. The new owner must call `acceptOwnership`.
    function transferOwnership(address newOwner) external;

    /// @notice Completes a two-step ownership transfer. Callable only by the pending owner.
    function acceptOwnership() external;

    /// @notice Renounces ownership, setting the owner to the zero address.
    function renounceOwnership() external;
}

/// @title TwoStepOwnable
/// @notice Two-step ownership transfer with a separate renounce, mirroring OpenZeppelin's Ownable2Step.
/// @dev ERC-7201 namespaced storage so this composes with upgradeable and non-upgradeable hosts, and
///      alongside a TwoStepOperator role, with no storage-layout clashes. Seed the initial owner from the
///      host constructor or initializer via `_initializeOwner`.
abstract contract TwoStepOwnable is ITwoStepOwnable {
    /// @custom:storage-location erc7201:lotus.storage.TwoStepOwnable
    struct OwnableStorage {
        address owner;
        address pendingOwner;
    }

    // keccak256(abi.encode(uint256(keccak256("lotus.storage.TwoStepOwnable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant _STORAGE = 0xfaec8a094acaf62210bd0812262aaaff8760ca5d3f50907b79cda40ef2806d00;

    function _ownableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := _STORAGE
        }
    }

    modifier onlyOwner() {
        if (msg.sender != _ownableStorage().owner) revert NotOwner();
        _;
    }

    /// @inheritdoc ITwoStepOwnable
    function owner() public view virtual override returns (address) {
        return _ownableStorage().owner;
    }

    /// @inheritdoc ITwoStepOwnable
    function pendingOwner() public view virtual override returns (address) {
        return _ownableStorage().pendingOwner;
    }

    /// @inheritdoc ITwoStepOwnable
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        OwnableStorage storage $ = _ownableStorage();
        $.pendingOwner = newOwner;
        emit OwnershipTransferStarted($.owner, newOwner);
    }

    /// @inheritdoc ITwoStepOwnable
    function acceptOwnership() public virtual override {
        if (msg.sender != _ownableStorage().pendingOwner) revert NotPendingOwner();
        _setOwner(msg.sender);
    }

    /// @inheritdoc ITwoStepOwnable
    function renounceOwnership() public virtual override onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Seeds the owner. Call once from the host constructor or initializer.
    function _initializeOwner(address initialOwner) internal {
        _setOwner(initialOwner);
    }

    function _setOwner(address newOwner) internal {
        OwnableStorage storage $ = _ownableStorage();
        $.owner = newOwner;
        delete $.pendingOwner;
        emit OwnerUpdated(newOwner);
    }
}

src/interfaces/ILotus.sol

// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;

import {IRiskEngine} from "./IRiskEngine.sol";
import {ITwoStepOwnable} from "../access/TwoStepOwnable.sol";

type Id is bytes32;

/// @notice Core market parameters shared across all tranches.
struct MarketParams {
    /// @notice Loan token shared across all tranches.
    address loanToken;
    /// @notice Risk engine for the market, shared across all tranches.
    address riskEngine;
    /// @notice Liquidation module for the market, shared across all tranches.
    address liquidationModule;
    /// @notice keccak256 hash of abi-encoded TrancheConfig array.
    bytes32 trancheConfigsHash;
}

/// @notice Per-tranche configuration stored separately from core params.
struct TrancheConfig {
    /// @notice Collateral token accepted by this tranche.
    address collateralToken;
    /// @notice Oracle used to price this tranche's collateral token.
    address oracle;
    /// @notice Liquidation loan-to-value threshold for this tranche, in wad.
    uint128 lltv;
}

/// @notice Per-tranche user position state.
/// @dev Warning: The `supplyShares` for the protocol `feeRecipient` is accurate as of the last interest accrual.
struct Position {
    /// @notice Supply shares for this tranche.
    uint256 supplyShares;
    /// @notice Borrow shares for this tranche.
    uint128 borrowShares;
    /// @notice Collateral amount for this tranche.
    uint128 collateral;
    /// @notice Size-weighted timestamp of this position's outstanding borrow.
    uint64 borrowTs;
}

/// @notice Aggregate accounting state for one market tranche.
/// @dev Warning: The `supplyAssets` and `borrowAssets` are accurate as of the last interest accrual.
/// @dev Warning: The `supplyShares` does not include supply shares to be issued to the `feeRecipient` during the next
/// interest accrual.
/// @dev `supplyShares` is `uint256`: bad debt reduces `supplyAssets` without reducing `supplyShares`, so a wiped
/// tranche's collapsed share price can mint far more than `uint128` shares. Asset fields stay `uint128` because they
/// only ever hold real token amounts. Layout (3 slots): `supplyAssets | fee | lastUpdate`, `supplyShares`,
/// `borrowAssets | borrowShares`, so supply, borrow and accrual each write at most two slots per tranche.
struct Tranche {
    /// @notice Total amount of assets supplied at this tranche.
    uint128 supplyAssets;
    /// @notice Protocol fee taken from interest accrued at this tranche.
    uint64 fee;
    /// @notice Last timestamp when interest was accrued for this tranche.
    uint64 lastUpdate;
    /// @notice Total supply shares for this tranche.
    uint256 supplyShares;
    /// @notice Total borrow assets for only the current tranche.
    uint128 borrowAssets;
    /// @notice Total borrow shares for only the current tranche.
    uint128 borrowShares;
}

/// @notice EIP-712 authorization payload.
struct Authorization {
    /// @notice Account granting or revoking authorization.
    address authorizer;
    /// @notice Account receiving or losing authorization.
    address authorized;
    /// @notice Whether authorization is granted or revoked.
    bool isAuthorized;
    /// @notice Authorizer nonce consumed by this payload.
    uint256 nonce;
    /// @notice Timestamp after which the signature is invalid.
    uint256 deadline;
}

/// @notice ECDSA signature fields for EIP-712 authorization payloads.
struct Signature {
    /// @notice ECDSA recovery id.
    uint8 v;
    /// @notice ECDSA r value.
    bytes32 r;
    /// @notice ECDSA s value.
    bytes32 s;
}

/// @title ILotus
/// @notice Interface for the Lotus core lending protocol.
interface ILotus is ITwoStepOwnable {
    /// @notice Emitted when the protocol is globally paused.
    event GlobalPaused();

    /// @notice Emitted when the protocol is globally unpaused.
    /// @param unpausedAt The timestamp at which the global pause was released.
    event GlobalUnpaused(uint64 unpausedAt);

    /// @notice Emitted when a single market is paused.
    /// @param id The market id.
    event MarketPaused(Id indexed id);

    /// @notice Emitted when a single market is unpaused.
    /// @param id The market id.
    event MarketUnpaused(Id indexed id);

    /// @notice Emitted when a token's flash loan fee is updated.
    /// @param token The token whose flash loan fee was updated.
    /// @param newFee The new flash loan fee in WAD.
    event FlashLoanFeeUpdated(address indexed token, uint64 newFee);

    /// @notice Emitted when an LLTV is enabled.
    /// @param lltv The enabled liquidation LTV ratio.
    event LltvEnabled(uint256 indexed lltv);

    /// @notice Emitted after aggregate accounting state changes for a tranche.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @param supplyAssets Total supplied assets after the change.
    /// @param supplyShares Total supply shares after the change.
    /// @param borrowAssets Total borrowed assets after the change.
    /// @param borrowShares Total borrow shares after the change.
    event TrancheStateUpdated(
        Id indexed id,
        uint256 indexed trancheIndex,
        uint256 supplyAssets,
        uint256 supplyShares,
        uint256 borrowAssets,
        uint256 borrowShares
    );

    /// @notice Emitted when interest is added to a tranche's aggregate borrow balance.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @param borrowInterest The amount added to aggregate borrow assets.
    event BorrowInterestAccrued(Id indexed id, uint256 indexed trancheIndex, uint256 borrowInterest);

    /// @notice Emitted when interest is distributed to a tranche's suppliers.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @param supplyInterest The amount added to aggregate supply assets.
    /// @param feeShares The supply shares minted to the protocol fee recipient.
    event SupplyInterestDistributed(
        Id indexed id, uint256 indexed trancheIndex, uint256 supplyInterest, uint256 feeShares
    );

    /// @notice Emitted when bad debt is allocated to a tranche's suppliers.
    /// @param id The market id.
    /// @param originTrancheIndex The tranche where the defaulted borrow position originated.
    /// @param absorbingTrancheIndex The tranche whose aggregate supply assets absorb the loss.
    /// @param assetsReduced The amount removed from the absorbing tranche's supply assets.
    event BadDebtAllocated(
        Id indexed id, uint256 indexed originTrancheIndex, uint256 indexed absorbingTrancheIndex, uint256 assetsReduced
    );

    /// @notice Emitted when a bad-debt event arms the borrow cooldown on the tranches junior to its origin.
    /// @param id The market id.
    /// @param originTrancheIndex The tranche where the bad debt originated.
    /// @param cooldownUntil Latest resulting expiry among the affected junior tranches, or the event's own expiry
    /// if there are no junior tranches. Each tranche accumulates its own remaining window, capped at
    /// `MIN_BORROW_DURATION` from now.
    event BorrowCooldownArmed(Id indexed id, uint256 indexed originTrancheIndex, uint64 cooldownUntil);

    /// @notice Emitted when the owner clears a tranche's borrow cooldown.
    /// @param id The market id.
    /// @param trancheIndex The tranche whose cooldown was cleared.
    event BorrowCooldownCleared(Id indexed id, uint256 indexed trancheIndex);

    /// @notice Emitted when the owner sets a borrower's exemption from the repay cooldown.
    /// @param account The borrower.
    /// @param exempt Whether `account` is exempt.
    event BorrowCooldownExemptSet(address indexed account, bool exempt);

    /// @return domainSeparator The EIP-712 domain separator for Lotus.
    function DOMAIN_SEPARATOR() external view returns (bytes32 domainSeparator);

    /// @notice Minimum size-weighted age a borrow position needs to be repaid while its tranche's cooldown is armed.
    function MIN_BORROW_DURATION() external view returns (uint256);

    /// @notice Bad debt, as a WAD fraction of cascade supply, at which the borrow cooldown arms for the full duration.
    function FULL_COOLDOWN_BAD_DEBT_RATIO() external view returns (uint256);

    /* OWNER FUNCTIONS */

    /// @notice The Lotus fee recipient for all markets, tranches, and flash loans.
    /// @dev The `feeRecipient` receives tranche fees during interest accrual via supply shares.
    /// @return recipient The protocol fee recipient.
    function feeRecipient() external view returns (address recipient);

    /// @notice Global relative buffer below each tranche's LLTV that caps new borrows and collateral withdrawals.
    /// @dev `borrow` and `withdrawCollateral` require the position to stay within `lltv * (WAD - borrowLtvBuffer) / WAD`.
    /// Liquidation eligibility and every other health computation keep using the plain LLTV, so a fresh position
    /// cannot become liquidatable through interest alone until its debt grows past the buffer.
    /// @return buffer The buffer in WAD, in [`MIN_BORROW_LTV_BUFFER`, `MAX_BORROW_LTV_BUFFER`].
    function borrowLtvBuffer() external view returns (uint64 buffer);

    /// @notice The Lotus flash loan fee for `token`, in WAD.
    /// @param token The token to quote the configured flash loan fee for.
    /// @return fee The flash loan fee rate applied to `token`.
    function flashLoanFee(address token) external view returns (uint64 fee);

    /// @notice Sets the protocol interest fee for a specific tranche in a market.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to set the fee for.
    /// @param newFee The new fee to set.
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    function setFee(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint64 newFee,
        bytes calldata riskEngineData
    ) external;

    /// @notice Sets the Lotus fee recipient.
    /// @param newFeeRecipient The new Lotus fee recipient.
    function setFeeRecipient(address newFeeRecipient) external;

    /// @notice Sets the Lotus flash loan fee for `token`.
    /// @param token The token to configure the flash loan fee for.
    /// @param newFee The new flash loan fee, in WAD.
    function setFlashLoanFee(address token, uint64 newFee) external;

    /// @notice Sets the global borrow LTV buffer.
    /// @dev Reverts if `newBuffer` equals the current buffer or is outside
    /// [`MIN_BORROW_LTV_BUFFER`, `MAX_BORROW_LTV_BUFFER`].
    /// @param newBuffer The new relative buffer below each tranche's LLTV, in WAD.
    function setBorrowLtvBuffer(uint64 newBuffer) external;

    /// @notice Enables `riskEngine` for Lotus markets.
    /// @param riskEngine The risk engine to enable.
    function enableRiskEngine(address riskEngine) external;

    /// @notice Enables `lltv` for Lotus markets.
    /// @param lltv The LLTV to enable.
    function enableLltv(uint128 lltv) external;

    /// @notice Enables `liquidationModule` for Lotus markets.
    /// @param liquidationModule The liquidation module to enable.
    function enableLiquidationModule(address liquidationModule) external;

    /// @notice Enables a module manager who can enable risk engines and liquidation modules.
    /// @param manager The module manager address.
    function enableModuleManager(address manager) external;

    /// @notice Disables a module manager.
    /// @param manager The module manager address.
    function disableModuleManager(address manager) external;

    /// @notice Sets or clears the market hook configuration.
    /// @param marketParams The market parameters (used to derive market id).
    /// @param hook The hook contract address (zero address to disable hooks).
    /// @param permissions The permissions bitmap indicating which hooks are implemented.
    function setMarketHook(MarketParams memory marketParams, address hook, uint256 permissions) external;

    /* PAUSE */

    /// @notice Pauses or unpauses state-changing operations. Owner only.
    /// @dev When `global` is true, applies to every market across the protocol and `marketParams`
    /// is ignored. When `global` is false, applies to the single market identified by
    /// `marketParams`; forbidden while globally paused. Unpausing (in either scope) records the
    /// moment so the lazy per-market sync skips interest accrual over the pause window.
    /// Interest from the last pre-pause interaction up to the pause is not captured by the lazy
    /// sync. Operators who need that interest realized must call `accrueInterest` before pausing;
    /// it cannot be recovered during a pause, because accrual reverts while paused, or after
    /// unpause, because the sync skips directly to the unpause timestamp. This preserves
    /// emergency-pause availability when accrual itself depends on a broken oracle or risk engine
    /// and could revert.
    /// @param marketParams The market parameters (ignored when `global` is true).
    /// @param global Whether to set the global-pause flag (true) or the per-market flag (false).
    /// @param paused The new pause state.
    function setPaused(MarketParams memory marketParams, bool global, bool paused) external;

    /// @notice Clears a tranche's borrow cooldown once no young borrow in it needs gating. Clear-only: never arms.
    /// @param id The market id.
    /// @param trancheIndex The tranche to clear.
    function clearBorrowCooldown(Id id, uint256 trancheIndex) external;

    /// @notice Exempts `account`'s positions from the repay cooldown, whoever calls repay on its behalf.
    /// @param account The borrower (repay's `onBehalf`).
    /// @param exempt Whether `account` is exempt.
    function setBorrowCooldownExempt(address account, bool exempt) external;

    /* MARKET CREATION */

    /// @notice Creates a new Lotus market.
    /// @dev Lotus settlement assumes exact token receipt on inbound transfers.
    /// @dev Do not configure fee-on-transfer or other transfer-shortfall loan or collateral tokens.
    /// @dev `marketParams.trancheConfigsHash` is recomputed from `tranches`, returned, and used as input into the
    /// market id calculation; any caller-supplied value is ignored.
    /// @param marketParams The core market parameters (loan token, risk engine, liquidation module).
    /// @param tranches The per-tranche configuration array.
    /// @param riskEngineParams The parameters for the risk engine.
    /// @param liquidationParams The parameters for the liquidation module.
    /// @return id The id of the created market (derived from the recomputed `marketParams`).
    /// @return trancheConfigsHash The tranche config hash recomputed from `tranches`.
    function createMarket(
        MarketParams memory marketParams,
        TrancheConfig[] memory tranches,
        bytes calldata riskEngineParams,
        bytes calldata liquidationParams
    ) external returns (Id id, bytes32 trancheConfigsHash);

    /* LENDER FUNCTIONS */

    /// @notice Supplies assets to a specific tranche in the market.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to supply to.
    /// @param assets The amount of assets to supply (use 0 if supplying by shares).
    /// @param shares The amount of shares to supply (use 0 if supplying by assets).
    /// @param onBehalf The address to supply on behalf of.
    /// @param data Arbitrary data to pass to the callback (if any).
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    /// @return suppliedAssets The actual amount of assets supplied.
    /// @return suppliedShares The actual amount of shares supplied.
    function supply(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes calldata data,
        bytes calldata riskEngineData
    ) external returns (uint256 suppliedAssets, uint256 suppliedShares);

    /// @notice Withdraws assets from a specific tranche in the market.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to withdraw from.
    /// @param assets The amount of assets to withdraw (use 0 if withdrawing by shares).
    /// @param shares The amount of shares to withdraw (use 0 if withdrawing by assets).
    /// @param onBehalf The address to withdraw on behalf of.
    /// @param receiver The address to send the withdrawn assets to.
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    /// @return withdrawnAssets The actual amount of assets withdrawn.
    /// @return withdrawnShares The actual amount of shares withdrawn.
    function withdraw(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver,
        bytes calldata riskEngineData
    ) external returns (uint256 withdrawnAssets, uint256 withdrawnShares);

    /* BORROWER FUNCTIONS */

    /// @notice Borrows assets from a specific tranche in the market.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to borrow from.
    /// @param assets The amount of assets to borrow (use 0 if borrowing by shares).
    /// @param shares The amount of shares to borrow (use 0 if borrowing by assets). A borrow by shares pays out the
    /// shares' value rounded down and mints only the shares that amount costs, which can be fewer than requested.
    /// @param onBehalf The address to borrow on behalf of.
    /// @param receiver The address to send the borrowed assets to.
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    /// @return borrowedAssets The actual amount of assets borrowed.
    /// @return borrowedShares The actual amount of shares borrowed.
    function borrow(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver,
        bytes calldata riskEngineData
    ) external returns (uint256 borrowedAssets, uint256 borrowedShares);

    /// @notice Repays borrowed assets for a specific tranche in the market with callback support.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to repay to.
    /// @param assets The amount of assets to repay (use 0 if repaying by shares).
    /// @param shares The amount of shares to repay (use 0 if repaying by assets). A partial repay by shares burns at
    /// least the shares its charged assets are worth, capped at the position, which can be more than requested.
    /// @param onBehalf The address to repay on behalf of.
    /// @param data Arbitrary data to pass to the callback (if any).
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    /// @return repaidAssets The actual amount of assets repaid.
    /// @return repaidShares The actual amount of shares repaid.
    function repay(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes calldata data,
        bytes calldata riskEngineData
    ) external returns (uint256 repaidAssets, uint256 repaidShares);

    /// @notice Supplies collateral to a specific tranche in the market with callback support.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to supply collateral to.
    /// @param assets The amount of collateral assets to supply.
    /// @param onBehalf The address to supply collateral on behalf of.
    /// @param data Arbitrary data to pass to the callback (if any).
    function supplyCollateral(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        address onBehalf,
        bytes calldata data
    ) external;

    /// @notice Withdraws collateral from a specific tranche in the market.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to withdraw collateral from.
    /// @param assets The amount of collateral assets to withdraw.
    /// @param onBehalf The address to withdraw collateral on behalf of.
    /// @param receiver The address to send the withdrawn collateral to.
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    function withdrawCollateral(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        address onBehalf,
        address receiver,
        bytes calldata riskEngineData
    ) external;

    /* LIQUIDATION */

    /// @notice Liquidates a borrower's position.
    /// @dev The returned `repaidAssets` is computed with rounding up to favor protocol safety.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche index of the position to liquidate.
    /// @param borrower The address of the borrower to liquidate.
    /// @param riskEngineData risk engine-specific data.
    /// @param callbackData Optional data forwarded to the liquidator callback.
    /// @param lmData Opaque liquidation-module data interpreted by the selected module.
    /// @return seizedAssets The collateral assets seized.
    /// @return repaidAssets The loan assets repaid by the liquidator.
    function liquidate(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        address borrower,
        bytes calldata riskEngineData,
        bytes calldata callbackData,
        bytes calldata lmData
    ) external returns (uint256 seizedAssets, uint256 repaidAssets);

    /* INTEREST MANAGEMENT */

    /// @notice Accrues interest for all tranches in a market.
    /// @param marketParams The market parameters.
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    function accrueInterest(MarketParams memory marketParams, bytes calldata riskEngineData) external;

    /* FLASH LOANS */

    /// @notice Returns the fee owed for borrowing `assets` of `token`.
    /// @param token The token to quote.
    /// @param assets The amount to flash loan.
    /// @return fee The flash loan fee owed on top of `assets`.
    function flashFee(address token, uint256 assets) external view returns (uint256 fee);

    /// @notice Executes a flash loan.
    /// @param token The address of the token to flash loan.
    /// @param assets The amount of assets to flash loan.
    /// @param data Arbitrary data to pass to the callback.
    function flashLoan(address token, uint256 assets, bytes calldata data) external;

    /* AUTHORIZATION */

    /// @notice Returns true if `authorized` can modify `authorizer`'s position on all markets/tranches.
    /// @param authorizer The account delegating permissions.
    /// @param authorized The account receiving delegated permissions.
    /// @return isAuthorized_ Whether `authorized` is currently approved.
    function isAuthorized(address authorizer, address authorized) external view returns (bool isAuthorized_);

    /// @notice The `authorizer`'s current nonce.
    /// @dev To prevent replay attacks with EIP-712 signatures.
    /// @param authorizer The account whose nonce is queried.
    /// @return currentNonce The current authorization nonce.
    function nonce(address authorizer) external view returns (uint256 currentNonce);

    /// @notice Sets `authorized` authorization to act on behalf of `msg.sender`.
    /// @param authorized The authorized address.
    /// @param newIsAuthorized The new authorization status.
    function setAuthorization(address authorized, bool newIsAuthorized) external;

    /// @notice Sets authorization via signature.
    /// @param authorization The authorization struct.
    /// @param signature The signature struct.
    function setAuthorizationWithSig(Authorization memory authorization, Signature calldata signature) external;

    /* VIEW FUNCTIONS */

    /// @notice Returns true if `riskEngine` is enabled for Lotus markets.
    /// @param riskEngine The risk engine to check.
    /// @return isEnabled Whether `riskEngine` is enabled.
    function isRiskEngineEnabled(address riskEngine) external view returns (bool isEnabled);

    /// @notice Returns true if `lltv` is enabled for Lotus markets.
    /// @param lltv The LLTV to check.
    /// @return isEnabled Whether `lltv` is enabled.
    function isLltvEnabled(uint256 lltv) external view returns (bool isEnabled);

    /// @notice Returns true if `liquidationModule` is enabled for Lotus markets.
    /// @param liquidationModule The liquidation module to check.
    /// @return isEnabled Whether `liquidationModule` is enabled.
    function isLiquidationModuleEnabled(address liquidationModule) external view returns (bool isEnabled);

    /// @notice Returns true if `manager` is a module manager.
    /// @param manager The address to check.
    /// @return Whether `manager` is a module manager.
    function isModuleManager(address manager) external view returns (bool);

    /// @notice Returns the last interest accrual time for a market.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @return timestamp The unix timestamp of last accrual for the tranche.
    function lastUpdate(Id id, uint256 trancheIndex) external view returns (uint64 timestamp);

    /// @notice Returns when a tranche's borrow cooldown lapses; while armed, only positions at least
    /// `MIN_BORROW_DURATION` old may repay.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @return The cooldown expiry timestamp, or zero if never armed.
    function borrowCooldownUntil(Id id, uint256 trancheIndex) external view returns (uint64);

    /// @notice Returns whether `account`'s positions skip the repay cooldown.
    /// @param account The borrower.
    function isBorrowCooldownExempt(address account) external view returns (bool);

    /// @notice Returns the market parameters for a given market id.
    /// @param id The market id.
    /// @return The MarketParams struct for the market.
    function getMarketParams(Id id) external view returns (MarketParams memory);

    /// @notice Returns the tranche config for a given market id and tranche index.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @return The TrancheConfig struct for the tranche.
    function getTrancheConfig(Id id, uint256 trancheIndex) external view returns (TrancheConfig memory);

    /// @notice Returns all tranche configs for a given market id.
    /// @param id The market id.
    /// @return An array of TrancheConfig structs for the market.
    function getTrancheConfigs(Id id) external view returns (TrancheConfig[] memory);

    /// @notice Returns the tranches for a given market id.
    /// @param id The market id.
    /// @return An array of Tranche structs for the market.
    function getMarketTranches(Id id) external view returns (Tranche[] memory);

    /// @notice Returns a single tranche for a given market id and tranche index.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @return The Tranche struct for the tranche.
    function getMarketTranche(Id id, uint256 trancheIndex) external view returns (Tranche memory);

    /// @notice Returns the number of tranches for a given market id.
    /// @param id The market id.
    /// @return The number of tranches in the market.
    function getNumMarketTranches(Id id) external view returns (uint256);

    /// @notice Returns the effective pause state for a market, as the interest-accrual gate sees it.
    /// @dev Lets off-chain valuation mirror accrual: when `paused`, no interest accrues over the
    /// pause window; when `unpausedAt > syncedAt`, the next accrual restarts each tranche from
    /// `unpausedAt` rather than its stale pre-pause `lastUpdate`.
    /// @param id The market id.
    /// @return paused Whether the protocol or this market is currently paused.
    /// @return unpausedAt The most recent unpause timestamp relevant to this market (global or per-market).
    /// @return syncedAt The unpause timestamp already synchronized into this market's tranche `lastUpdate` values.
    function getMarketPauseState(Id id) external view returns (bool paused, uint64 unpausedAt, uint64 syncedAt);

    /// @notice Returns the risk engine for a given market id.
    /// @param id The market id.
    /// @return The IRiskEngine contract for the market.
    function getMarketRiskEngine(Id id) external view returns (IRiskEngine);

    /// @notice Returns a user's position in a specific market tranche.
    /// @param id The market id.
    /// @param user The address of the user.
    /// @param trancheIndex The tranche index.
    /// @return The Position struct for the user in the tranche.
    function getPosition(Id id, address user, uint256 trancheIndex) external view returns (Position memory);

    /// @notice Returns the current borrowed assets and max borrowable assets for a borrower in a market tranche.
    /// @dev Accurate as of the last interest accrual.
    /// @dev Use `accrueInterest` first (or a lens helper) when post-accrual values are required.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche index.
    /// @param borrower The borrower account.
    /// @return borrowed The current borrowed assets in the tranche.
    /// @return maxBorrow The current max borrowable assets in the tranche.
    function getMaxBorrowAndBorrowed(MarketParams memory marketParams, uint256 trancheIndex, address borrower)
        external
        view
        returns (uint256 borrowed, uint256 maxBorrow);

    /// @notice Computes junior supply for a given market and tranche.
    /// @dev Accurate as of the last interest accrual.
    /// @param id The market whose junior supply is computed.
    /// @param trancheIndex The tranche whose junior supply is computed.
    /// @return The junior supply amount.
    function getJrSupply(Id id, uint256 trancheIndex) external view returns (uint256);

    /// @notice Returns risk engine-effective free supply available for withdraw or borrow.
    /// @dev Bounded by Lotus's current waterfall-backed physical ceiling and then refined by the market risk engine.
    /// @param id The market whose free supply is returned.
    /// @param trancheIndex The tranche whose free supply is returned.
    /// @return The free supply amount.
    function getFreeSupply(Id id, uint256 trancheIndex) external view returns (uint256);

    /// @notice Returns risk engine-effective free supply available for withdraw or borrow.
    /// @dev Bounded by Lotus's current waterfall-backed physical ceiling and then refined by the market risk engine.
    /// @param id The market whose free supply is returned.
    /// @param trancheIndex The tranche whose free supply is returned.
    /// @param riskEngineData Custom data to be passed to the risk engine implementation.
    /// @return The free supply amount.
    function getFreeSupply(Id id, uint256 trancheIndex, bytes calldata riskEngineData) external view returns (uint256);

    /// @notice Computes junior net supply for all tranches in a market.
    /// @dev Accurate as of the last interest accrual.
    /// @param id The market id.
    /// @return An array of junior net supply amounts for each tranche.
    function getJrNetSupply(Id id) external view returns (uint256[] memory);

    /// @notice Returns the market hook configuration (if any) for a given market id.
    /// @param id The market id.
    /// @return hook The hook contract address (zero address if disabled).
    /// @return permissions The hook permissions bitmap.
    function getMarketHookConfig(Id id) external view returns (address hook, uint256 permissions);
}

src/interfaces/IOracle.sol

// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;

/// @title IOracle
/// @notice Interface that oracles used by Lotus must implement.
/// @dev It is the user's responsibility to select markets with safe oracles.
interface IOracle {
    /// @notice Returns the price of 1 asset of collateral token quoted in 1 asset of loan token, scaled by 1e36.
    /// @dev It corresponds to the price of 10**(collateral token decimals) assets of collateral token quoted in
    /// 10**(loan token decimals) assets of loan token with `36 + loan token decimals - collateral token decimals`
    /// decimals of precision.
    /// @return oraclePrice The collateral price in loan-token terms, scaled by 1e36.
    function price() external view returns (uint256 oraclePrice);
}

src/interfaces/IRiskEngine.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {Id, Tranche} from "./ILotus.sol";

/// @notice Per-tranche accrual delta returned by cascade accrual.
struct AccrualDelta {
    /// @notice Interest added to `borrowAssets`.
    uint256 borrowInterest;
    /// @notice Interest added to `supplyAssets`.
    uint256 supplyInterest;
}

/// @notice Per-tranche bad debt reductions returned by the risk engine.
struct BadDebtDeltas {
    /// @notice Full-length array of supply asset reductions.
    uint256[] supplyReductions;
}

/// @title IRiskEngine
/// @notice The Risk Engine interface expected by Lotus protocol.
interface IRiskEngine {
    /// @notice Initializes the risk engine for a Lotus market.
    /// @param id The market id.
    /// @param riskEngineParams ABI-encoded params expected by the risk engine implementation.
    function initialize(Id id, bytes calldata riskEngineParams) external;

    /// @notice Accrues interest across all tranches with cascading distribution.
    /// @dev May update internal risk engine state (e.g. adaptive rates).
    /// @param id The market id.
    /// @param tranches The current tranche state array.
    /// @param riskEngineData Custom data to be passed to the risk engine implementation.
    /// @return deltas The per-tranche accrual deltas.
    /// @return freeSupply The risk-engine-effective withdraw/borrow liquidity across accrued tranches,
    /// bounded by Lotus's trusted physical `freeSupplyCap`.
    function accrueInterest(Id id, Tranche[] calldata tranches, bytes calldata riskEngineData)
        external
        returns (AccrualDelta[] memory deltas, uint256 freeSupply);

    /// @notice Returns the effective free supply at a tranche without accruing interest.
    /// @param id The market id.
    /// @param tranches The current tranche state array.
    /// @param trancheIndex The tranche index to query.
    /// @param riskEngineData Custom data to be passed to the risk engine implementation.
    /// @return freeSupply The risk-engine-effective withdraw/borrow liquidity at the tranche,
    /// bounded by Lotus's trusted physical `freeSupplyCap`.
    function getFreeSupply(Id id, Tranche[] calldata tranches, uint256 trancheIndex, bytes calldata riskEngineData)
        external
        view
        returns (uint256 freeSupply);

    /// @notice Distributes bad debt losses across tranches from originIndex upward.
    /// @param id The market id.
    /// @param tranches The current tranche state array.
    /// @param originTrancheIndex The tranche index where bad debt originated.
    /// @param badDebtAssets The amount of bad debt to distribute.
    /// @return deltas The per-tranche supply reductions after bad debt distribution.
    function distributeBadDebt(Id id, Tranche[] calldata tranches, uint256 originTrancheIndex, uint256 badDebtAssets)
        external
        pure
        returns (BadDebtDeltas memory deltas);

    /// @notice View-only preview of accrueInterest for off-chain estimation.
    /// @param id The market id.
    /// @param tranches The current tranche state array.
    /// @param riskEngineData Custom data to be passed to the risk engine implementation.
    /// @return deltas The preview per-tranche accrual deltas.
    /// @return freeSupply The risk-engine-effective withdraw/borrow liquidity across accrued tranches,
    /// bounded by Lotus's trusted physical `freeSupplyCap`.
    function previewAccrueInterest(Id id, Tranche[] calldata tranches, bytes calldata riskEngineData)
        external
        view
        returns (AccrualDelta[] memory deltas, uint256 freeSupply);

    /// @notice Validates that `riskEngineData` is well-formed for this engine before it is used or persisted.
    /// @dev Called on an integrating adapter's position write path so that a caller cannot associate arbitrary or
    /// oversized `riskEngineData` with a position (that data is later SLOADed and forwarded to the engine on every
    /// valuation read). Engines that ignore `riskEngineData` MUST reject any non-empty payload; engines with
    /// call-time config SHOULD validate its structure and bound its size. Reverts if the data is not acceptable.
    /// @param riskEngineData The custom data a caller wants associated with a position.
    function validateRiskEngineData(bytes calldata riskEngineData) external view;
}

src/lens/interfaces/ILotusLens.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {Id, ILotus, MarketParams, Position} from "../../interfaces/ILotus.sol";

/// @title IRiskEnginePreview
/// @notice Optional preview surface used by this lens for the currently shipped preview-capable risk engines.
/// @dev Markets need not implement this to satisfy Lotus core. Deploy a family-specific lens if future engines omit
/// these helpers.
interface IRiskEnginePreview {
    /// @notice Returns the current borrow rate implied by a risk engine for a tranche.
    /// @param id The market whose borrow rate is previewed.
    /// @param trancheIndex The tranche whose borrow rate is previewed.
    /// @param riskEngineData Risk engine-specific data for engines that depend on call-time config.
    /// @return trancheBorrowRate The borrow rate in wad per second.
    function previewTrancheBorrowRate(Id id, uint256 trancheIndex, bytes calldata riskEngineData)
        external
        view
        returns (uint256 trancheBorrowRate);

    /// @notice Returns the supply-utilization ratio used for cascading borrow interest into a tranche.
    /// @param id The market whose supply utilization is previewed.
    /// @param trancheIndex The tranche whose supply utilization is previewed.
    /// @param riskEngineData Risk engine-specific data for engines that depend on call-time config.
    /// @return trancheSupplyUtilization The supply-utilization ratio in wad.
    function previewTrancheSupplyUtilization(Id id, uint256 trancheIndex, bytes calldata riskEngineData)
        external
        view
        returns (uint256 trancheSupplyUtilization);
}

/// @title IRiskEngineBorrowUtilizationPreview
/// @notice Optional borrow-utilization preview used by current non-fixed preview-capable risk engines.
interface IRiskEngineBorrowUtilizationPreview {
    /// @notice Returns the borrow-utilization ratio reported by a risk engine for a tranche.
    /// @param id The market whose borrow utilization is previewed.
    /// @param trancheIndex The tranche whose borrow utilization is previewed.
    /// @param riskEngineData Risk engine-specific data for engines that depend on call-time config.
    /// @return trancheBorrowUtilization The borrow-utilization ratio in wad.
    function previewTrancheBorrowUtilization(Id id, uint256 trancheIndex, bytes calldata riskEngineData)
        external
        view
        returns (uint256 trancheBorrowUtilization);
}

/// @title ILotusLens
/// @notice Read helpers and accrue-then-read helpers for Lotus markets.
/// @dev Keeps helper-oriented accrue-and-query flows out of Lotus core entry points.
interface ILotusLens {
    /// @notice Aggregated risk-engine and derived-rate analytics for one tranche.
    struct TranchePreview {
        /// @notice Whether `borrowUtilization` was available from the risk engine.
        bool hasBorrowUtilization;
        /// @notice Borrow-utilization ratio in wad, or zero when unavailable.
        uint256 borrowUtilization;
        /// @notice Borrow rate in wad per second.
        uint256 borrowRate;
        /// @notice Supply-utilization ratio in wad.
        uint256 supplyUtilization;
        /// @notice Net supply rate in wad per second after cascading and fees.
        uint256 supplyRate;
    }

    /// @return The Lotus core contract queried by this lens.
    function LOTUS() external view returns (ILotus);

    /// @notice Accrues market interest, then returns the borrower's current borrowed amount and LLTV-based max borrow.
    /// @dev `maxBorrow` is the liquidation threshold (plain LLTV). New borrows and collateral withdrawals are capped
    /// lower, by `borrowLtvBuffer`; use `accrueInterestAndReturnBorrowLimit` for the amount a borrower can reach.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche whose borrower state is queried after accrual.
    /// @param borrower The borrower account to query.
    /// @param riskEngineData Risk engine-specific data passed through to Lotus accrual.
    /// @return borrowed The borrower's current borrowed amount after accrual.
    /// @return maxBorrow The borrower's current LLTV-based max borrow after accrual.
    function accrueInterestAndReturnMaxBorrow(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        address borrower,
        bytes calldata riskEngineData
    ) external returns (uint256 borrowed, uint256 maxBorrow);

    /// @notice Accrues market interest, then returns the borrower's current borrowed amount and buffered borrow limit.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche whose borrower state is queried after accrual.
    /// @param borrower The borrower account to query.
    /// @param riskEngineData Risk engine-specific data passed through to Lotus accrual.
    /// @return borrowed The borrower's current borrowed amount after accrual.
    /// @return borrowLimit The most `borrow` / `withdrawCollateral` may leave outstanding after accrual.
    function accrueInterestAndReturnBorrowLimit(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        address borrower,
        bytes calldata riskEngineData
    ) external returns (uint256 borrowed, uint256 borrowLimit);

    /// @notice Returns the borrower's borrowed amount and the borrow limit enforced by `borrow` and
    /// `withdrawCollateral`: collateral value times `lltv * (WAD - borrowLtvBuffer) / WAD`, rounded as in Lotus.
    /// @dev Accurate as of the last interest accrual. Liquidation still uses the plain LLTV.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche to query.
    /// @param borrower The borrower account to query.
    /// @return borrowed The borrower's current borrowed amount.
    /// @return borrowLimit The most `borrow` / `withdrawCollateral` may leave outstanding.
    function getBorrowLimitAndBorrowed(MarketParams memory marketParams, uint256 trancheIndex, address borrower)
        external
        view
        returns (uint256 borrowed, uint256 borrowLimit);

    /// @notice Returns the net per-second supply rate for a tranche, including cascaded interest.
    /// @param id The market whose supply rate is previewed.
    /// @param trancheIndex The tranche whose supply rate is previewed.
    /// @return trancheSupplyRate The net per-second supply rate in wad.
    function previewTrancheSupplyRate(Id id, uint256 trancheIndex) external view returns (uint256 trancheSupplyRate);

    /// @notice Returns the net per-second supply rate for a tranche, including cascaded interest.
    /// @dev `riskEngineData` is forwarded to preview helpers for engines that depend on call-time config.
    /// @param id The market whose supply rate is previewed.
    /// @param trancheIndex The tranche whose supply rate is previewed.
    /// @param riskEngineData Risk engine-specific data forwarded to preview helpers.
    /// @return trancheSupplyRate The net per-second supply rate in wad.
    function previewTrancheSupplyRate(Id id, uint256 trancheIndex, bytes memory riskEngineData)
        external
        view
        returns (uint256 trancheSupplyRate);

    /// @notice Returns the preview analytics currently exposed by preview-capable risk engines for a tranche.
    /// @param id The market whose tranche analytics are previewed.
    /// @param trancheIndex The tranche whose analytics are previewed.
    /// @return preview Aggregated preview analytics for off-chain consumers.
    function previewTrancheAnalytics(Id id, uint256 trancheIndex) external view returns (TranchePreview memory preview);

    /// @notice Returns the preview analytics currently exposed by preview-capable risk engines for a tranche.
    /// @dev `riskEngineData` is forwarded to preview helpers for engines that depend on call-time config.
    /// `borrowUtilization` is optional and is populated only when the risk engine implements
    /// `IRiskEngineBorrowUtilizationPreview`; `supplyRate` is derived from the borrow-rate and supply-utilization
    /// preview helpers.
    /// @param id The market whose tranche analytics are previewed.
    /// @param trancheIndex The tranche whose analytics are previewed.
    /// @param riskEngineData Risk engine-specific data forwarded to preview helpers.
    /// @return preview Aggregated preview analytics for off-chain consumers.
    function previewTrancheAnalytics(Id id, uint256 trancheIndex, bytes memory riskEngineData)
        external
        view
        returns (TranchePreview memory preview);

    /// @notice Returns all tranche positions for a user in a given market.
    /// @param id The market id.
    /// @param user The address of the user.
    /// @return userPositions An array of Position structs indexed by tranche.
    function getPositions(Id id, address user) external view returns (Position[] memory userPositions);
}

src/libraries/ConstantsLib.sol

// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;

/// @dev The WAD constant (1e18) for fixed-point arithmetic.
uint256 constant WAD = 1e18;

/// @dev The oracle price scale.
uint256 constant ORACLE_PRICE_SCALE = 1e36;

/// @dev The maximum protocol interest fee for a tranche (25% in WAD).
uint64 constant MAX_FEE = 0.25e18;

/// @dev Minimum raw asset units that a partial repay must settle (full position closes are exempt).
/// @dev Rejects one-unit dust repays. On its own the floor does not stop `borrowShares` inflation, since a borrow of
/// @dev any size can be paired with a repay settling exactly the floor; Lotus prevents that by having borrows mint and
/// @dev partial repays burn shares in line with the assets they move.
uint256 constant MIN_PARTIAL_REPAY_ASSETS = 2;

/// @dev The maximum flash loan fee for a token (25% in WAD).
uint64 constant MAX_FLASH_LOAN_FEE = 0.25e18;

/// @dev Maximum allowed borrow rate per second in WAD (~500% APY continuous).
/// Computed as ln(6) / 365 days ~= 5.6816320054e-8, scaled by 1e18.
uint256 constant MAX_BORROW_RATE_PER_SECOND = 56_816_320_054;

/// @dev Maximum allowed slope (rate change per utilization unit), per second in WAD.
/// Aligns with the maximum rate ceiling to prevent extreme steepness.
uint256 constant MAX_SLOPE_PER_SECOND = MAX_BORROW_RATE_PER_SECOND;

/// @dev Minimum liquidation incentive (1.0x) and maximum (1.15x) in WAD.
uint256 constant MIN_LIQUIDATION_INCENTIVE = 1e18;
uint256 constant MAX_LIQUIDATION_INCENTIVE = 1.15e18;

/// @dev The minimum borrow LTV buffer (0.5% in WAD). Covers about one day of interest at `MAX_BORROW_RATE_PER_SECOND`,
/// @dev i.e. `MIN_COOLDOWN_DURATION`.
uint64 constant MIN_BORROW_LTV_BUFFER = 0.005e18;

/// @dev The maximum borrow LTV buffer (25% in WAD). The buffer is relative: a tranche's borrow limit is
/// @dev `lltv * (WAD - borrowLtvBuffer) / WAD`.
uint64 constant MAX_BORROW_LTV_BUFFER = 0.25e18;

/// @dev Maximum configurable health liquidation discount in WAD (25%),
/// equivalent to a ~1.33x maximum liquidation effect.
/// Must remain strictly below 100% to keep discount factor positive.
uint256 constant MAX_HEALTH_LIQUIDATION_DISCOUNT = 0.25e18;

/// @dev Inclusive bounds on the borrow-cooldown `MIN_BORROW_DURATION` immutable. A zero duration would disable the
/// @dev cooldown; an excessive one would lock honest borrowers out of `repay` and, at extreme values, overflow the
/// @dev cooldown arming arithmetic.
uint256 constant MIN_COOLDOWN_DURATION = 1 days;
uint256 constant MAX_COOLDOWN_DURATION = 7 days;

/// @dev The EIP-712 typeHash for EIP712Domain.
bytes32 constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");

/// @dev The EIP-712 typeHash for Authorization.
bytes32 constant AUTHORIZATION_TYPEHASH =
    keccak256("Authorization(address authorizer,address authorized,bool isAuthorized,uint256 nonce,uint256 deadline)");

src/libraries/LotusErrorsLib.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {Id} from "../interfaces/ILotus.sol";

/// @title LotusErrorsLib
/// @notice Library for Lotus errors.
library LotusErrorsLib {
    /* GENERAL ERRORS */

    /// @notice Zero address provided for a required argument.
    error ZeroAddress();

    /// @notice Non-zero value is required but zero is provided.
    error ZeroValue();

    /// @notice Mutually dependent inputs are inconsistent.
    error InconsistentInput();

    /// @notice Caller is not the owner.
    error NotOwner();

    /// @notice Caller is neither the owner nor a module manager.
    error NotOwnerOrModuleManager();

    /* ASSET AMOUNT ERRORS */

    /// @notice Withdrawal resolves to zero assets.
    error InvalidZeroAssetWithdrawal();

    /// @notice Borrow resolves to zero assets.
    error InvalidZeroAssetBorrow();

    /// @notice Supply resolves to zero shares.
    error InvalidZeroShareSupply();

    /// @notice Repay resolves to zero shares.
    error InvalidZeroShareRepay();

    /// @notice Partial repay settles fewer than the minimum required assets.
    error InsufficientRepayAssets(uint256 assets);

    /* OWNER ERRORS */

    /// @notice Owner is already set to the requested address.
    /// @param owner The owner that is already set.
    error OwnerAlreadySet(address owner);

    /// @notice Caller is not the pending owner.
    error NotPendingOwner();

    /// @notice Fee is already set to the requested value.
    /// @param id The market whose fee is already set.
    /// @param trancheIndex The tranche whose fee is already set.
    /// @param fee The fee that is already set.
    error FeeAlreadySet(Id id, uint256 trancheIndex, uint64 fee);

    /// @notice Fee exceeds protocol bounds.
    /// @param fee The invalid fee value.
    error InvalidFee(uint64 fee);

    /// @notice Fee recipient is already set to the requested address.
    /// @param feeRecipient The fee recipient that is already set.
    error FeeRecipientAlreadySet(address feeRecipient);

    /// @notice Fee recipient is the zero address or the Lotus contract itself.
    /// @param feeRecipient The invalid fee recipient.
    error InvalidFeeRecipient(address feeRecipient);

    /// @notice Token flash-loan fee is already set to the requested value.
    /// @param token The token whose flash loan fee is already set.
    /// @param fee The flash loan fee that is already set.
    error FlashLoanFeeAlreadySet(address token, uint64 fee);

    /// @notice Borrow LTV buffer is outside [`MIN_BORROW_LTV_BUFFER`, `MAX_BORROW_LTV_BUFFER`].
    /// @param buffer The rejected buffer, in WAD.
    error InvalidBorrowLtvBuffer(uint256 buffer);

    /// @notice Borrow LTV buffer is already set to the requested value.
    /// @param buffer The current buffer, in WAD.
    error BorrowLtvBufferAlreadySet(uint256 buffer);

    /// @notice Risk engine is already enabled.
    /// @param riskEngine The risk engine that is already enabled.
    error RiskEngineAlreadyEnabled(address riskEngine);

    /// @notice LLTV is outside valid bounds.
    /// @param lltv The invalid LLTV value.
    error InvalidLltv(uint256 lltv);

    /// @notice LLTV is already enabled.
    /// @param lltv The LLTV that is already enabled.
    error LltvAlreadyEnabled(uint256 lltv);

    /* MARKET LIFECYCLE ERRORS */

    /// @notice Market already exists.
    /// @param id The market id that already exists.
    error MarketAlreadyExists(Id id);

    /// @notice Market has not been created.
    /// @param id The market id that does not exist.
    error MarketNotCreated(Id id);

    /// @notice Market references a risk engine that is not enabled.
    /// @param riskEngine The risk engine that is not enabled.
    error RiskEngineNotEnabled(address riskEngine);

    /// @notice Market references an LLTV that is not enabled.
    /// @param lltv The LLTV that is not enabled.
    error LltvNotEnabled(uint256 lltv);

    /// @notice Tranche index is out of bounds.
    /// @param trancheIndex The tranche index that is out of bounds.
    error InvalidTrancheIndex(uint256 trancheIndex);

    /* LIQUIDITY ERRORS */

    /// @notice Available liquidity is insufficient for an operation.
    /// @param assets The amount of assets that is not available.
    error InsufficientLiquidity(uint256 assets);

    /// @notice Operation makes the position unhealthy.
    /// @param assets The operation amount that caused the unhealthy state.
    error UnhealthyAfter(uint256 assets);

    /// @notice Liquidation is attempted on a non-underwater borrower.
    /// @param borrower The borrower that is not underwater.
    error NotUnderwater(address borrower);

    /// @notice `repaidShares` exceeds the borrower's debt shares.
    /// @param repaidShares The amount of shares attempting to be repaid.
    /// @param borrowerShares The borrower's actual borrow shares.
    error ExcessiveRepay(uint256 repaidShares, uint256 borrowerShares);

    /// @notice Flash loan callback returned an unexpected selector.
    /// @param expected The selector expected from the callback.
    /// @param received The selector actually returned by the callback.
    error InvalidFlashLoanCallbackResponse(bytes4 expected, bytes4 received);

    /// @notice `seizedAssets` exceeds the borrower's collateral.
    /// @param seizedAssets The amount of assets attempting to be seized.
    /// @param borrowerCollateral The borrower's actual collateral.
    error ExcessiveSeizure(uint256 seizedAssets, uint256 borrowerCollateral);

    /* AUTHORIZATION ERRORS */

    /// @notice Caller is not authorized for the operation.
    error Unauthorized();

    /// @notice Authorization is already set to the requested value.
    error AuthorizationAlreadySet();

    /// @notice Signature deadline has passed.
    error SignatureExpired();

    /// @notice Signature nonce is invalid.
    error InvalidNonce();

    /// @notice Signature recovery or signer validation failed.
    error InvalidSignature();

    /* LIQUIDATION MODULE ERRORS */

    /// @notice Caller is not Lotus.
    error NotLotus();

    /// @notice Liquidation module is already enabled.
    /// @param module The liquidation module that is already enabled.
    error LiquidationModuleAlreadyEnabled(address module);

    /// @notice Liquidation module is not enabled.
    /// @param module The liquidation module that is not enabled.
    error LiquidationModuleNotEnabled(address module);

    /// @notice Module manager is already enabled.
    /// @param manager The module manager that is already enabled.
    error ModuleManagerAlreadyEnabled(address manager);

    /// @notice Module manager is not enabled.
    /// @param manager The module manager that is not enabled.
    error ModuleManagerNotEnabled(address manager);

    /// @notice Oracle collateral price is zero.
    error InvalidCollateralPrice();

    /// @notice Repay attempted on a position younger than `MIN_BORROW_DURATION` while its tranche's cooldown is armed.
    /// @param cooldownUntil Timestamp at which the tranche's borrow cooldown lapses.
    error BorrowTooYoung(uint64 cooldownUntil);

    /// @notice Constructor borrow-cooldown config is out of bounds: `minBorrowDuration` must lie in
    /// [`MIN_COOLDOWN_DURATION`, `MAX_COOLDOWN_DURATION`] and `fullCooldownBadDebtRatio` in (0, `WAD`].
    error InvalidBorrowCooldownConfig();

    /* DELTA VALIDATION ERRORS */

    /// @notice Risk engine delta array length does not match Lotus expectations.
    error DeltaLengthMismatch();

    /// @notice Risk engine reports borrow interest above Lotus's maximum allowed envelope.
    error BorrowInterestTooHigh();

    /// @notice Risk engine reports non-zero borrow interest when no interest can accrue.
    error UnexpectedBorrowInterest();

    /// @notice Risk engine reports free supply above Lotus's waterfall-backed liquidity cap.
    error FreeSupplyExceedsPhysical();

    /// @notice Risk engine over-distributes cascading interest to suppliers.
    error InterestDirectionViolation();

    /// @notice Full accrual leaves unexpected interest undistributed.
    error UnexpectedCarryForward();

    /// @notice Bad debt reductions flow below the origin tranche.
    error BadDebtDirectionViolation();

    /// @notice Bad debt reduction exceeds a tranche's supply assets.
    error ExcessiveBadDebtReduction();

    /// @notice Bad debt reductions do not exactly match realized bad debt.
    error BadDebtTotalMismatch();

    /// @notice Lotus is reentered during the guarded risk engine external call window.
    error RiskEngineCallReentrancy();

    /* PAUSE ERRORS */

    /// @notice Operation attempted while the protocol is globally paused.
    error ProtocolPaused();

    /// @notice Operation attempted on a paused market.
    /// @param id The paused market id.
    error MarketIsPaused(Id id);

    /// @notice Protocol is already paused.
    error AlreadyPaused();

    /// @notice Protocol is not paused.
    error NotPaused();
}

src/libraries/MarketParamsLib.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {Id, MarketParams, TrancheConfig} from "../interfaces/ILotus.sol";

/// @title MarketParamsLib
/// @notice Helpers for deriving and transforming Lotus market parameter structs.
library MarketParamsLib {
    /// @dev Computes the unique id for a given `MarketParams` struct.
    function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
        marketParamsId = Id.wrap(
            keccak256(
                abi.encode(
                    marketParams.loanToken,
                    marketParams.riskEngine,
                    marketParams.liquidationModule,
                    marketParams.trancheConfigsHash
                )
            )
        );
    }

    /// @dev Computes `trancheConfigsHash` from a tranche configuration array.
    function computeTrancheConfigsHash(TrancheConfig[] memory tranches) internal pure returns (bytes32) {
        // forge-lint: disable-next-item(asm-keccak256)
        return keccak256(abi.encode(tranches));
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "solady/=lib/solady/",
    "bundler3/=lib/bundler3/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/bundler3/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "morpho-blue/=lib/bundler3/lib/morpho-blue/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "prb-math/=lib/prb-math/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.