Перейти к содержимому
Проверенный контрактТочноеMIT

OwnerPegResponsiveExponentialIrmFactory

Адрес0xe8aeb4c25c419cadece85eecfa6c5ca3bf1186c7
Баланс

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.28

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.28+commit.7893614a
Язык
solidity
Оптимизация
Да, 100 прогонов
Версия EVM
cancun
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 378 876
Транзакция создания
0xd48fee1059…aff12018b6

contracts/deployments/ethereum-mainnet/OwnerPegResponsiveExponentialIrmFactory.sol

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

import {PegResponsiveExponentialIrmConfig} from "@alto/lending/interfaces/IPegResponsiveExponentialIrm.sol";
import {PegResponsiveExponentialIrm} from "@alto/lending/irm/PegResponsiveExponentialIrm.sol";
import {AltoOwnable2Step, Ownable} from "@alto/utils/AltoOwnable2Step.sol";

/// @title Owner Peg Responsive Exponential Interest Rate Model Factory
/// @author GPM
/// @custom:contact [email protected]
/// @notice Deterministically deploys PegResponsiveExponentialIrms owned by the factory owner.
/// @dev A newly deployed IRM has a permissionless, one-time `setMarket`. Deploy it and wire it to its market
///      atomically so another account cannot consume that initialization first.
contract OwnerPegResponsiveExponentialIrmFactory is AltoOwnable2Step {
    struct Deployment {
        address irm;
        address owner;
        address pegOracle;
    }

    address public pegOracle;

    mapping(address market => mapping(uint256 version => Deployment)) public deployments;

    event SetPegOracle(address indexed oldPegOracle, address indexed newPegOracle);
    event PegResponsiveExponentialIrmDeployed(
        address indexed market, address indexed irm, address indexed owner, address pegOracle, uint256 version
    );

    constructor(address initialOwner, address initialPegOracle) Ownable(initialOwner) {
        _setPegOracle(initialPegOracle);
    }

    /// @notice Changes the peg oracle used for future IRM deployments.
    function setPegOracle(address newPegOracle) external onlyOwner {
        _setPegOracle(newPegOracle);
    }

    /// @notice Deploys one IRM for a market version, or returns an exact prior deployment.
    function deploy(address market, uint256 version, PegResponsiveExponentialIrmConfig calldata config)
        external
        onlyOwner
        returns (address irm)
    {
        require(market != address(0), "Invalid market");

        address irmOwner = owner();
        Deployment memory existing = deployments[market][version];
        if (existing.irm != address(0)) {
            _validateExisting(
                existing, _predictIrmAddress(market, version, existing.pegOracle, config, irmOwner), irmOwner
            );
            return existing.irm;
        }

        address currentPegOracle = pegOracle;
        irm = address(new PegResponsiveExponentialIrm{salt: _salt(market, version)}(currentPegOracle, config, irmOwner));
        deployments[market][version] = Deployment(irm, irmOwner, currentPegOracle);

        emit PegResponsiveExponentialIrmDeployed(market, irm, irmOwner, currentPegOracle, version);
    }

    function predictIrmAddress(address market, uint256 version, PegResponsiveExponentialIrmConfig memory config)
        public
        view
        returns (address)
    {
        require(market != address(0), "Invalid market");

        address irmOwner = owner();
        Deployment memory existing = deployments[market][version];
        if (existing.irm != address(0)) {
            _validateExisting(
                existing, _predictIrmAddress(market, version, existing.pegOracle, config, irmOwner), irmOwner
            );
            return existing.irm;
        }

        return _predictIrmAddress(market, version, pegOracle, config, irmOwner);
    }

    function _setPegOracle(address newPegOracle) private {
        require(newPegOracle != address(0), "Invalid peg oracle");
        emit SetPegOracle(pegOracle, newPegOracle);
        pegOracle = newPegOracle;
    }

    function _predictIrmAddress(
        address market,
        uint256 version,
        address oracle,
        PegResponsiveExponentialIrmConfig memory config,
        address irmOwner
    ) private view returns (address) {
        bytes32 initCodeHash = keccak256(
            abi.encodePacked(type(PegResponsiveExponentialIrm).creationCode, abi.encode(oracle, config, irmOwner))
        );

        return address(
            uint160(
                uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), _salt(market, version), initCodeHash)))
            )
        );
    }

    function _validateExisting(Deployment memory existing, address expectedIrm, address irmOwner) private view {
        require(existing.irm == expectedIrm && existing.owner == irmOwner, "Version already used");
        require(existing.irm.code.length != 0 && Ownable(existing.irm).owner() == irmOwner, "Invalid deployment");
    }

    function _salt(address market, uint256 version) private pure returns (bytes32) {
        return keccak256(abi.encode(market, version));
    }
}

contracts/lending/interfaces/IIrm.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

enum IRMType {
    FIXED_RATE, // FixedRateIrm
    ADAPTIVE_CURVE, // AdaptiveCurveIrm
    PEG_RESPONSIVE_EXPONENTIAL // PegResponsiveExponentialIrm
}

interface IIrm {
    /// @notice Error thrown when the caller is not the market
    error IrmUnauthorized();

    /// @notice Error thrown when the market is already set
    error IrmMarketAlreadySet();

    /// @notice Error thrown when the market is not set
    error IrmMarketNotSet();

    /// @notice Error thrown when the parameters are invalid
    error IrmInvalidParams();

    /// @notice The type of the IRM
    /// @dev This is used to identify the type of the IRM during indexing
    function IRM_TYPE() external view returns (IRMType);

    /// @notice Sets the market for the IRM
    /// @param _market The market to set
    /// @dev This function has to be called first time by the market to set up the IRM
    function setMarket(address _market) external;

    /// @notice Called when the market is paused
    /// @param _paused The new paused state
    /// @dev This function is function is used when market of this IRM is paused/unpaused.
    /// Pausing market should also pause the accrual of interest.
    function onMarketPause(bool _paused) external;

    /// @notice Updates interest rate the the latest value
    /// @param totalSupply Total amount of assets supplied to the markets
    /// @param totalBorrowed Total amount of assets borrowed from the markets
    /// @return new interest rate in second percent yield (SPY), new interest since last update
    function updateInterestRate(uint256 totalSupply, uint256 totalBorrowed) external returns (uint256, uint256);

    /// @notice Performs compuutation of the interest rate without mutating state
    /// @param totalSupply Total amount of assets supplied to the markets
    /// @param totalBorrowed Total amount of assets borrowed from the markets
    /// @return new interest rate in second percent yield (SPY), new interest since last update
    function updateInterestRateView(uint256 totalSupply, uint256 totalBorrowed) external view returns (uint256, uint256);
}

contracts/lending/interfaces/IMarket.sol

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

import {IAuth} from "@alto/utils/interfaces/IAuth.sol";
import {IPausable} from "@alto/utils/interfaces/IPausable.sol";

/// @notice The type of the market
enum MarketType {
    BORROW, // AltoBorrowMarket
    MINT, // AltoMintMarket
    DAO_MINT, // AltoDaoMintMarket
    CREDIT_MINT // AltoConvexCreditLineMarket
}

/// @notice Struct that represents the balance of a token
struct Balance {
    uint128 assets;
    uint128 shares;
}

/// @notice Struct that represents the position of a user
struct Position {
    uint128 supplyShares;
    uint128 borrowShares;
    uint128 collateralAssets;
}

/// @notice Struct that represents the parameters for initializing a base market
struct BaseMarketInitParams {
    /// @notice The address of the borrow token.
    address borrowToken;
    /// @notice The address of the collateral token.
    address collateralToken;
    /// @notice The address of the IRM contract.
    address irm;
    /// @notice The address of the owner.
    address owner;
    /// @notice The address initially authorized to pause and freeze the market.
    address emergencyAdmin;
    /// @notice The address of the oracle contract.
    address oracle;
    /// @notice The max LTV for the market.
    uint256 maxLtv;
    /// @notice The address of the fee recipient.
    address feeRecipient;
    /// @notice The address of the liquidation engine.
    address liquidationEngine;
}

/// @notice Struct that represents the parameters for initializing a borrow market
struct BorrowMarketInitParams {
    /// @notice The parameters for initializing a base market.
    BaseMarketInitParams baseMarketInitParams;
    /// @notice The initial borrow opening fee.
    uint256 initialBorrowOpeningFee;
    /// @notice The maximum amount of assets that can be supplied to the market.
    uint128 supplyCapAssets;
    /// @notice The initial interest fee.
    uint256 initialInterestFee;
}

/// @notice Struct that represents the parameters for initializing a mint market
struct MintMarketInitParams {
    /// @notice The parameters for initializing a base market.
    BaseMarketInitParams baseMarketInitParams;
    /// @notice The debt ceiling of mint market.
    uint256 debtCeiling;
    /// @notice The initial borrow opening fee.
    uint256 initialBorrowOpeningFee;
}

interface IMarketErrors {
    /// @notice Error thrown when the input is invalid
    error AltoBaseMarketInvalidInput();

    /// @notice Error thrown when the user is trying to remove more collateral then allowed
    error AltoBaseMarketInsufficientUserCollateral();

    /// @notice Error thrown when the user is trying to borrow more than they are allowed
    error AltoBaseMarketBorrowingTooMuch();

    /// @notice Error thrown when the market has insufficient liquidity for the borrow
    error AltoBaseMarketInsufficientMarketLiquidity();

    /// @notice Error thrown when executor is not allowed to perform the action on behalf of another user
    error AltoBaseMarketUnauthorized();
}

interface IMarketEvents {
    /// @notice Emitted when the IRM contract is set
    /// @param oldAddr The address of the old IRM contract
    /// @param newAddr The address of the new IRM contract
    event SetIrm(address indexed oldAddr, address indexed newAddr);

    /// @notice Emitted when the oracle contract is set
    /// @param oldAddr The address of the old oracle contract
    /// @param newAddr The address of the new oracle contract
    event SetOracle(address indexed oldAddr, address indexed newAddr);

    /// @notice Emitted when the max LTV is set
    /// @param oldMaxLtv The address of the old max LTV
    /// @param newMaxLtv The address of the new max LTV
    event SetMaxLtv(uint256 oldMaxLtv, uint256 newMaxLtv);

    /// @notice Emitted when the liquidation engine is set
    /// @param oldLiquidationEngine The address of the old liquidation engine
    /// @param newLiquidationEngine The address of the new liquidation engine
    event SetLiquidationEngine(address indexed oldLiquidationEngine, address indexed newLiquidationEngine);

    /// @notice Emitted when the fee recipient is set
    /// @param oldAddr The address of the old fee recipient
    /// @param newAddr The address of the new fee recipient
    event SetFeeRecipient(address indexed oldAddr, address indexed newAddr);

    /// @notice Emitted when the authorized callback is set
    /// @param callback The address of the authorized callback
    /// @param isAuthorized If set to true, the callback contract will be allowed as an authorized callback.
    /// If set to false, the callback contract will be disallowed as an authorized callback.
    event SetAuthorizedCallback(address indexed callback, bool isAuthorized);

    /// @notice Emitted when the authorized liquidation periphery is set
    /// @param periphery The address of the authorized liquidation periphery
    /// @param isAuthorized If set to true, the liquidation periphery will be allowed as an authorized liquidation periphery.
    /// If set to false, the liquidation periphery will be disallowed as an authorized liquidation periphery.
    event SetAuthorizedLiquidationPeriphery(address indexed periphery, bool isAuthorized);

    /// @notice Emitted when a user supplies tokens to the lending market
    /// @param caller The address of the caller who is supplying tokens
    /// @param onBehalf The address of the user who is receiving the ownership of supplied tokens
    /// @param assets The amount of assets supplied
    /// @param shares The amount of shares minted
    event AddSupply(address indexed caller, address indexed onBehalf, uint256 assets, uint256 shares);

    /// @notice Emitted when a user withdraws tokens from the lending market
    /// @param caller The address of the caller who is withdrawing tokens on behalf
    /// @param onBehalf The address of the user who is the owner of withdrawn tokens
    /// @param receiver The address of the user who is receiving the withdrawn tokens
    /// @param assets The amount of assets withdrawn
    /// @param shares The amount of shares burned
    event RemoveSupply(
        address indexed caller, address indexed onBehalf, address indexed receiver, uint256 assets, uint256 shares
    );

    /// @notice Emitted when a user borrows tokens from the lending market
    /// @param caller The address of the caller who is borrowing tokens
    /// @param onBehalf The address of the user who is the owner of borrowed tokens
    /// @param receiver The address of the user who is receiving the borrowed tokens
    /// @param assets The amount of assets borrowed
    /// @param shares The amount of shares minted
    /// @param feeAmount The amount of assets paid as opening fee
    /// @param feeSupplyShares The amount of supply shares given to the fee recipient
    event Borrow(
        address indexed caller,
        address indexed onBehalf,
        address indexed receiver,
        uint256 assets,
        uint256 shares,
        uint256 feeAmount,
        uint256 feeSupplyShares
    );

    /// @notice Emitted when a user repays borrowed tokens
    /// @param caller The address of the caller who is repaying tokens
    /// @param onBehalf The address of the user who is the owner of the borrow position
    /// @param assets The amount of assets repaid
    /// @param shares The amount of shares burned
    event Repay(address indexed caller, address indexed onBehalf, uint256 assets, uint256 shares);

    /// @notice Emitted when a user deposits collateral
    /// @param caller The address of the caller who is supplying collateral
    /// @param onBehalf The address of the user who is the owner of supplied collateral
    /// @param amount The amount of collateral supplied
    event AddCollateral(address indexed caller, address indexed onBehalf, uint256 amount);

    /// @notice Emitted when a user withdraws collateral
    /// @param caller The address of the caller who is withdrawing collateral
    /// @param onBehalf The address of the owner of collateral being withdrawn
    /// @param receiver The address of the user who is receiving the withdrawn collateral
    /// @param amount The amount of collateral withdrawn
    event RemoveCollateral(address indexed caller, address indexed onBehalf, address indexed receiver, uint256 amount);

    /// @notice Emitted when interest is accrued
    /// @param borrowRate The average rate
    /// @param interest The amount of interest accrued
    /// @param totalBorrowAssets The total borrow assets
    /// @param totalSupplyAssets The total supply assets
    event AccrueInterest(uint256 borrowRate, uint256 interest, uint128 totalBorrowAssets, uint128 totalSupplyAssets);

    // add liquidation event
    /// @notice Emitted when a liquidation occurs
    /// @param user The address of the user whose position was liquidated
    /// @param liquidator The address of the liquidator
    /// @param liquidatedCollateral The amount of collateral that was liquidated
    /// @param protocolFee The amount of protocol fee credited to the fee recipient
    /// @param repaidBorrow The amount of borrow tokens that were repaid
    /// @param repaidBorrowShares The amount of borrow shares that were repaid
    /// @param badDebtClearedAssets The amount of bad debt cleared
    /// @param badDebtClearedShares The amount of bad debt shares cleared
    event Liquidation(
        address indexed user,
        address liquidator,
        uint256 liquidatedCollateral,
        uint256 protocolFee,
        uint256 repaidBorrow,
        uint256 repaidBorrowShares,
        uint256 badDebtClearedAssets,
        uint256 badDebtClearedShares
    );

    /// @notice Emitted when a liquidation is performed through governance
    /// @param user The address of the user whose position was liquidated
    /// @param liquidator The address of the liquidator
    /// @param liquidatedCollateral The amount of collateral that was seized
    /// @param badDebtClearedAssets The amount of bad debt cleared
    /// @param badDebtClearedShares The amount of bad debt shares cleared
    event GovernanceLiquidation(
        address indexed user,
        address liquidator,
        uint256 liquidatedCollateral,
        uint256 badDebtClearedAssets,
        uint256 badDebtClearedShares
    );
}

interface IMarketBase is IMarketErrors, IMarketEvents, IAuth, IPausable {
    /// @notice The type of the market.
    function MARKET_TYPE() external view returns (MarketType);

    /// @notice The address of the borrow token.
    function borrowToken() external view returns (address);

    /// @notice The address of the collateral token.
    function collateralToken() external view returns (address);

    /// @notice Authorized contracts to be called by `borrow` and `removeCollateral`.
    /// @dev This is used to allow for leverage and deleverage.
    function authorizedCallbacks(address callback) external view returns (bool);

    /// @notice Authorized contracts to be called during liquidation.
    function authorizedLiquidationPeriphery(address periphery) external view returns (bool);

    /// @notice Contract used for Interest Rate Model calculation when market needs to accrue interest.
    function irm() external view returns (address);

    /// @notice Oracle used to determine the collateral to borrow price.
    function oracle() external view returns (address);

    /// @notice Max position's LTV for the market.
    /// @dev This is used to determine the max amount of borrow that can be taken for a given collateral.
    function maxLtv() external view returns (uint256);

    /// @notice function to calculate the borrow opening fee while borrowing
    /// @dev The implementation used to calculate the borrow opening fee may differ for AltoBorrowMarket and AltoMintMarket
    /// @dev This function will be implemented by the AltoBorrowMarket and AltoMintMarket
    function borrowOpeningFee() external view returns (uint256);

    /// @notice Address that receives the opening fee
    /// @dev This is used to send the opening fee to the fee recipient
    function feeRecipient() external view returns (address);

    /// @notice Setter of the IRM contract for the market
    /// @dev This setter accrues the interest using the previous IRM contract and sets up the new IRM contract.
    /// This can be also used to disable the interest accrual by setting the IRM to zero address.
    /// @param irm The address of the new IRM contract
    /// @param skipAccrueInterest If set to true, the interest accrual will be skipped. This is useful when IRM
    /// has improper setup and accruing interest would either revert or cause unwanted interest rate calculation.
    function setIrm(address irm, bool skipAccrueInterest) external;

    /// @notice setter of the oracle contract for the market
    function setOracle(address oracle) external;

    /// @notice setter of the max LTV for the market
    /// @dev This will be used in rare scenarios - usually when increasing the max LTV to avoid
    /// This should always be considered to be used in tandem with `setLiquidationConfiguration` as
    /// liquidation calculation depends on the max LTV.
    function setMaxLtv(uint256 maxLtv) external;

    /// @notice Setter of the fee recipient for the market.
    function setFeeRecipient(address feeRecipient) external;

    /// @notice Function to set an authorized callback contract.
    /// @param callback The address of the callback contract
    /// @param isAuthorized If set to true, the callback contract will be allowed as an authorized callback.
    /// If set to false, the callback contract will be disallowed as an authorized callback.
    /// @dev This is used to allow for leverage and deleverage.
    function setAuthorizedCallback(address callback, bool isAuthorized) external;

    /// @notice Function to set an authorized liquidation periphery contract.
    /// @param periphery The address of the liquidation periphery contract
    /// @param isAuthorized If set to true, the liquidation periphery contract will be allowed as an authorized liquidation periphery.
    /// If set to false, the liquidation periphery contract will be disallowed as an authorized liquidation periphery.
    function setAuthorizedLiquidationPeriphery(address periphery, bool isAuthorized) external;

    /// @notice Function to supply the borrow token to the market and make it available for borrowing.
    /// @param assets The amount of assets supplied
    /// @param shares The amount of shares to supply
    /// @param onBehalf The address of the user who will become the owner of the supply position
    /// @return assets The amount of assets supplied
    /// @return shares The amount of shares supplied
    /// @dev This increases the `totalSupply` of the market and the `supplyShares` of the `onBehalf` user.
    /// @dev Either assets or shares can be provided but not both.
    /// Providing `assets` will supply exact amount of assets to the market on behalf of `onBehalf`.
    /// Providing `shares` will supply shares to the market on behalf of `onBehalf`. `assets` should be used in majority
    /// of the cases. Specifying `shares` may end up depositing more or less assets than expected because of the
    /// slippage. See AltoAdapter.sol for an example on how to handle slippage.
    function addSupply(uint256 assets, uint256 shares, address onBehalf) external returns (uint256, uint256);

    /// @notice Function to remove the borrow token from the market, make it unavailable for borrowing and remove the shares.
    /// @param assets The amount of assets to remove
    /// @param shares The amount of shares to remove
    /// @param onBehalf The address of the user who is the owner of the supply position
    /// @param receiver The address of the user who is receiving the withdrawn assets
    /// @return assets The amount of assets withdrawn
    /// @return shares The amount of shares withdrawn
    /// @dev This decreases the `totalSupply` of the market and the `supplyShares` of the `onBehalf` user.
    /// @dev Either assets or shares can be provided but not both.
    /// Providing `assets` will remove exact amount of assets from the market on behalf of `onBehalf`.
    /// Providing `shares` will remove shares from the market on behalf of `onBehalf`. `assets` should be used in majority
    /// of the cases. Specifying `shares` may end up withdrawing more or less assets than expected because of the
    /// slippage. But, in the case of when user wants to withdraw all their assets, `shares` should be used.
    /// See AltoAdapter.sol for an example on how to handle slippage.
    /// @dev This function will revert if there are currenly not enough assets in the market to remove. This can
    /// happen if utilization is high or trying to withdraw more than globally available for borrow in the market.
    function removeSupply(uint256 assets, uint256 shares, address onBehalf, address receiver)
        external
        returns (uint256, uint256);

    /// @notice Function to deposit collateral token to the market as a collateral for borrowing.
    /// @param assets The amount of collateral supplied
    /// @param onBehalf The address of the user who will become the owner of the collateral position
    /// @return assets The amount of collateral supplied
    /// @dev This increases the `totalCollateral` of the market and the `collateralAssets` of the `onBehalf` user.
    function addCollateral(uint256 assets, address onBehalf) external returns (uint256);

    /// @notice Function to withdraw collateral token from the market and make it unavailable to be used as collateral
    /// for borrowing.
    /// @param assets The amount of collateral to remove
    /// @param onBehalf The address of the user who is the owner of the collateral position
    /// @param receiver The address of the user who is receiving the withdrawn collateral
    /// @param swapParams ABI-encoded swap parameter (see `SwapParams` struct for details)
    /// @return assets The amount of collateral withdrawn
    /// @dev This decreases the `totalCollateral` of the market and the `collateralAssets` of the `onBehalf` user.
    /// @dev This function will revert if this would leave `onBehalf`'s position insolvent after the withdrawal.
    /// @dev When `swapParams` is provided `receiver` should be an authorized callback contract implementing `IRemoveCollateralCallback`.
    /// This is used to allow for deleverage. Authorized callback contracts would be able to perform a swap and
    /// prepare enough funds to repay `onBehalf`'s position using collateral.
    function removeCollateral(uint256 assets, address onBehalf, address receiver, bytes calldata swapParams)
        external
        returns (uint256);

    /// @notice Function to borrow the borrow token from the market.
    /// @param assets The amount of assets to borrow
    /// @param shares The amount of shares to borrow
    /// @param onBehalf The address of the user who will become the owner of the borrow position
    /// @param receiver The address of the user who is receiving the borrowed tokens
    /// @param swapParams ABI-encoded swap parameter (see `SwapParams` struct for details)
    /// @return assets The amount of assets borrowed
    /// @return shares The amount of shares borrowed
    /// @return openingFeeAssets The amount of opening borrow fee paid for this borrow
    /// @dev This increases the `totalBorrowed` of the market and the `borrowShares` of the `onBehalf` user.
    /// @dev Either assets or shares can be provided but not both.
    /// Providing `assets` will borrow exact amount of assets from the market on behalf of `onBehalf`.
    /// Providing `shares` will borrow shares from the market on behalf of `onBehalf`. `assets` should be used in majority
    /// of the cases. Specifying `shares` may end up borrowing more or less assets than expected because of the
    /// slippage. See AltoAdapter.sol for an example on how to handle slippage.
    /// @dev When `swapParams` is provided `receiver` should be an authorized callback contract implementing `IBorrowCallback`.
    /// This is used to allow for leverage. Authorized callback contracts would be able to perform a swap and
    /// prepare enough collateral to borrow `assets` from the market.
    /// @dev This function can only borrow up to to the max LTV of the market for given collateral by `onBehalf`.
    function borrow(uint256 assets, uint256 shares, address onBehalf, address receiver, bytes calldata swapParams)
        external
        returns (uint256, uint256, uint256);

    /// @notice Function to repay the borrow token to the market.
    /// @param assets The amount of assets to repay
    /// @param shares The amount of shares to repay
    /// @param onBehalf The address of the user who is the owner of the borrow position
    /// @return assets The amount of assets repaid
    /// @return shares The amount of shares burned
    /// @dev This decreases the `totalBorrowed` of the market and the `borrowShares` of the `onBehalf` user.
    /// @dev Either assets or shares can be provided but not both.
    /// Providing `assets` will repay exact amount of assets from the market on behalf of `onBehalf`.
    /// Providing `shares` will repay shares from the market on behalf of `onBehalf`. `assets` should be used in majority
    /// of the cases. Specifying `shares` may end up repaying more or less assets than expected because of the
    /// slippage. But in the case of when user wants to repay all of their borrowed assets, `shares` should be used.
    /// See AltoAdapter.sol for an example on how to handle slippage.
    /// @dev This function will revert if `onBehalf`'s position is not solvent after the repayment.
    function repay(uint256 assets, uint256 shares, address onBehalf) external returns (uint256, uint256);

    /// @notice Function to accrue interest for the market.
    /// @dev This function is called by the market when it needs to accrue interest.
    /// It increases the `totalBorrowed` and `totalSupply` assets of the market.
    /// @dev If `irm` is set to zero address, this function does nothing.
    function accrueInterest() external;

    /// @notice Function to liquidate an insolvent position.
    /// @param borrower The address of the borrower being liquidated
    /// @param callbackData Additional data for the liquidator contract
    /// @param liquidationData Additional data for the liquidation engine
    /// @dev If caller(msg.sender) is an authorized liquidation periphery, then liquidationData needs to be abi.encode(originalLiquidator, originalLiquidationData)
    /// @dev originalLiquidationData will be passed to the liquidation engine
    /// @dev originalLiquidator will be used for checks of priority liquidation
    /// @dev if caller is not authorized liquidation periphery, then liquidationData will be passed directly to the liquidation engine
    /// @return repaidBorrow The amount of borrow token repaid
    /// @return repaidBorrowShares The amount of borrow shares repaid
    /// @return protocolFee The amount of protocol credited to the fee recipient
    /// @dev This function will calculate the liquidation amount and fee by itself. Liquidator
    /// can't specify the amount of assets to repay.
    /// @dev This function will revert if `borrower`'s position is not insolvent on not tagged.
    /// @dev When `data` is provided `msg.sender` should be a contract implementing `ILiquidateCallback`.
    /// This is used to perform a potential swap and to enough funds to repay the `borrower`'s position.
    /// @dev Position has to be first tagged for liquidation using `tagLiquidablePosition` function.
    /// This will start the timer in which the position can be liquidated in by the `priorityLiquidator` first.
    /// Afterwards, if `priorityLiquidationGracePeriod` expired and position is not liquidated,
    /// the liqudator that tagged the position can liquidate it. If `taggerLiquidationGracePeriod` expired
    /// and position is not liquidated, anyone can liquidate it. If position becomes solvent and is not liquidated
    /// after it was tagged, the tag will expire in `liquidationWindowTag` seconds after the tag was set.
    /// @dev The underlying liquidation logic is well described in the docs.
    function liquidate(address borrower, bytes calldata callbackData, bytes calldata liquidationData)
        external
        returns (uint256, uint256, uint256);

    /// @notice Function to liquidate an insolvent position which is not possible to liquidate using normal liquidation
    /// @dev Governance liquidation seizes full collateral of liquidated user and offsets the debt of the protocol
    /// generating bad debt
    /// @dev Market's liquidation engine should be reviewed before running this to ensure what implications does it have on the liquidation engine.
    /// governanceLiquidate​ is not aware of liquidation engine.
    /// @dev No fees are charged for this liquidation for the simplicity of implementation
    /// @dev This function will only be used if normal liquidation reverts caused by its complexity
    /// @param borrower The address of the borrower being liquidated
    /// @param skipAccrueInterest Whether to skip interest accrual before liquidation
    /// @return sizedCollateral The amount of collateral that was seized
    /// @return badDebtAmount The amount of borrow token that was offset
    function governanceLiquidate(address borrower, bool skipAccrueInterest) external returns (uint256, uint256);

    /// @notice Function to set the liquidation engine for the market.
    /// @param liquidationEngine The address of the liquidation engine
    function setLiquidationEngine(address liquidationEngine) external;

    /// @notice Address of the liquidation engine for the market.
    /// @return The address of the liquidation engine for the market.
    function liquidationEngine() external view returns (address);
}

interface IMarket is IMarketBase {
    /// @notice State of the user's position in market.
    /// @param user The address of the user whose position is being queried
    function position(address user) external view returns (Position memory);

    /// @notice Total supply of borrow token of the market provided by the lenders.
    function totalSupply() external view returns (Balance memory);

    /// @notice Total borrowed assets of the market currently borrowed.
    function totalBorrowed() external view returns (Balance memory);
}

interface IMarketStaticTypes is IMarketBase {
    /// @notice State of the user's position in market.
    /// @param user The address of the user whose position is being queried
    function position(address user)
        external
        view
        returns (uint128 supplyShares, uint128 borrowShares, uint128 collateralAssets);

    /// @notice Total supply of borrow token of the market provided by the lenders.
    function totalSupply() external view returns (uint128 assets, uint128 shares);

    /// @notice Total borrowed assets of the market currently borrowed.
    function totalBorrowed() external view returns (uint128 assets, uint128 shares);
}

contracts/lending/interfaces/IPegResponsiveExponentialIrm.sol

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

import {IIrm} from "@alto/lending/interfaces/IIrm.sol";

/// @notice Parameters for the price-to-rate curve, recovery confirmation,
/// and oracle freshness.
/// @dev Each rate is a continuously compounded SPY value, not an annual
/// percentage yield. Prices and `doublingDistance` use 1e18 precision.
struct PegResponsiveExponentialIrmConfig {
    /// @dev Price at or above which the raw curve returns `baseRate`.
    uint256 recoveryPrice;
    /// @dev Price below which the raw curve grows exponentially.
    uint256 stressPrice;
    /// @dev Minimum SPY rate returned at or above `recoveryPrice`. May be zero.
    uint256 baseRate;
    /// @dev SPY rate returned at `stressPrice` and stress-mode rate floor. Must be nonzero.
    uint256 stressRate;
    /// @dev Extreme safety ceiling for the SPY rate.
    uint256 maxRate;
    /// @dev Price decline below `stressPrice` that doubles `stressRate`.
    /// The stressed curve is `stressRate * 2 ** (depeg / doublingDistance)`.
    /// For example, 0.0025e18 maps 7.5% at $0.995 to 30% at $0.990.
    uint256 doublingDistance;
    /// @dev Minimum block-time delay between qualifying recovery observations.
    /// This confirms sampled recovery, not a continuously healthy price.
    uint48 recoveryDelay;
    /// @dev Maximum permitted age of an oracle observation.
    /// If this exceeds recoveryDelay, one observation can start and complete recovery,
    /// so recovery can be confirmed without new pool activity.
    /// Setting it below recoveryDelay only requires a newer observation at completion.
    /// It does not prove continuous health or resist manipulation.
    uint48 maxOracleAge;
}

/// @notice Internal cached state of the interest rate model.
struct IRState {
    /// @dev SPY rate that will accrue during the next interval.
    uint256 borrowRate;
    /// @dev Timestamp through which interest has been accrued.
    uint48 lastUpdate;
    /// @dev Timestamp at which the current recovery confirmation began.
    uint48 recoveryStartedAt;
    /// @dev Whether the controller is enforcing the stress-rate floor.
    bool stressMode;
}

interface IPegResponsiveExponentialIrmErrors {
    /// @notice Error thrown when the peg oracle address is invalid
    error PegResponsiveExponentialIrmInvalidOracle();

    /// @notice Error thrown when price thresholds are invalid
    error PegResponsiveExponentialIrmInvalidPriceConfig();

    /// @notice Error thrown when configured rates are invalid
    error PegResponsiveExponentialIrmInvalidRateConfig();

    /// @notice Error thrown when controller timing or curve parameters are invalid
    error PegResponsiveExponentialIrmInvalidControllerConfig();
}

interface IPegResponsiveExponentialIrmEvents {
    /// @notice Emitted when the peg oracle changes.
    event SetPegOracle(address indexed oldPegOracle, address indexed newPegOracle);

    /// @notice Emitted when the IRM configuration changes.
    event SetIrmConfig(PegResponsiveExponentialIrmConfig newConfig);

    /// @notice Emitted when stress-mode or recovery-confirmation state changes.
    event StressStateUpdated(bool stressMode, uint48 recoveryStartedAt, uint256 priceWad);

    /// @notice Emitted after a checkpoint or owner input change refreshes the rate.
    event BorrowRateUpdated(uint256 prev, uint256 curr, uint256 priceWad, uint48 observedAt, bool oracleValid);

    /// @notice Emitted when the interest rate state has been updated.
    event IRStateUpdated(IRState newIRState);
}

interface IPegResponsiveExponentialIrmBase is
    IIrm,
    IPegResponsiveExponentialIrmErrors,
    IPegResponsiveExponentialIrmEvents
{
    /// @notice The maximum per-second borrow rate.
    function MAX_BORROW_RATE() external view returns (uint256);

    /// @notice The maximum supported recovery price.
    function MAX_RECOVERY_PRICE() external view returns (uint256);

    /// @notice The maximum supported input to the exponential approximation.
    function MAX_EXPONENT_INPUT() external view returns (uint256);

    /// @notice Returns the active DUSD/quoteToken peg oracle.
    function pegOracle() external view returns (address);

    /// @notice Returns the market bound to this interest-rate model.
    function market() external view returns (address);

    /// @notice Checkpoints the old inputs, replaces the oracle, and refreshes the rate.
    /// @param newPegOracle The address of the new peg oracle.
    /// @dev Requirements:
    /// - Only callable by the contract owner.
    /// - New oracle address cannot be the zero address.
    /// @dev Restarts recovery confirmation. Paused and unbound markets skip accrual
    /// but still refresh the rate without changing the accrual timestamp.
    function setPegOracle(address newPegOracle) external;

    /// @notice Changes the price curve and controller configuration.
    /// @param newConfig The new IRM configuration to apply.
    /// @dev Checkpoints the old inputs before applying the new configuration and rate.
    /// Recovery confirmation restarts. An invalid observation holds the rate within
    /// the new applicable floor and cap. Paused and unbound markets skip accrual.
    /// @dev Requirements:
    /// - Only callable by the contract owner.
    /// - Configuration is validated according to `_validateConfig`.
    function setIrmConfig(PegResponsiveExponentialIrmConfig calldata newConfig) external;

    /// @notice Previews the oracle observation and rate that would be stored by a checkpoint.
    /// @return priceWad Valid DUSD/quoteToken price, or zero for an unusable observation.
    /// @return observedAt Timestamp supplied by the oracle.
    /// @return oracleValid Whether the observation passed validity and freshness checks.
    /// @return borrowRate Effective rate that would be stored for the next interval.
    function previewBorrowRate()
        external
        view
        returns (uint256 priceWad, uint48 observedAt, bool oracleValid, uint256 borrowRate);

    /// @notice Returns the raw target SPY rate for a given DUSD/quoteToken price.
    /// @param priceWad The price at which the rate will be calculated.
    /// @dev The rate curve has three regions:
    /// - At or above the recovery price: fixed at the base rate.
    /// - Between recovery and stress: linearly increases to the stress rate.
    /// - Below stress: exponentially increases, capped at the maximum rate.
    /// @dev Stress-mode hysteresis is handled separately.
    function targetBorrowRate(uint256 priceWad) external view returns (uint256 borrowRate);
}

/// @title IPegResponsiveExponentialIrm
/// @author GPM
/// @custom:contact [email protected]
/// @notice Interface for the DUSD peg-responsive interest-rate model.
interface IPegResponsiveExponentialIrm is IPegResponsiveExponentialIrmBase {
    /// @notice Returns the complete price-curve and controller configuration.
    /// @return configuration The current configuration.
    function irmConfig() external view returns (PegResponsiveExponentialIrmConfig memory configuration);

    /// @notice Returns the complete cached interest-rate controller state.
    /// @return state The cached interest-rate state.
    function irState() external view returns (IRState memory state);
}

interface IPegResponsiveExponentialIrmStaticTypes is IPegResponsiveExponentialIrmBase {
    /// @notice Returns the complete price-curve and controller configuration.
    /// @return recoveryPrice Price at or above which the raw curve returns the base rate.
    /// @return stressPrice Price below which the raw curve grows exponentially.
    /// @return baseRate Minimum SPY rate returned at or above the recovery price.
    /// @return stressRate SPY rate returned at the stress price and stress-mode rate floor.
    /// @return maxRate Extreme safety ceiling for the SPY rate.
    /// @return doublingDistance Price decline below the stress price that doubles the stress rate.
    /// @return recoveryDelay Minimum block-time delay between qualifying recovery observations.
    /// @return maxOracleAge Maximum permitted age of an oracle observation.
    function irmConfig()
        external
        view
        returns (
            uint256 recoveryPrice,
            uint256 stressPrice,
            uint256 baseRate,
            uint256 stressRate,
            uint256 maxRate,
            uint256 doublingDistance,
            uint48 recoveryDelay,
            uint48 maxOracleAge
        );

    /// @notice Returns the complete cached interest-rate controller state.
    /// @return borrowRate SPY rate that will accrue during the next interval.
    /// @return lastUpdate Timestamp through which interest has been accrued.
    /// @return recoveryStartedAt Timestamp at which the current recovery confirmation began.
    /// @return stressMode Whether the controller is enforcing the stress-rate floor.
    function irState()
        external
        view
        returns (uint256 borrowRate, uint48 lastUpdate, uint48 recoveryStartedAt, bool stressMode);
}

contracts/lending/irm/PegResponsiveExponentialIrm.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.28;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";

import {
    PegResponsiveExponentialIrmConfig,
    IRState,
    IPegResponsiveExponentialIrmBase,
    IPegResponsiveExponentialIrmStaticTypes
} from "@alto/lending/interfaces/IPegResponsiveExponentialIrm.sol";
import {IIrm, IRMType} from "@alto/lending/interfaces/IIrm.sol";
import {IMarket} from "@alto/lending/interfaces/IMarket.sol";
import {IDusdPegOracle} from "@alto/oracles/interfaces/IDusdPegOracle.sol";
import {ExpLib} from "@alto/lending/libraries/ExpLib.sol";
import {AltoOwnable2Step, Ownable} from "@alto/utils/AltoOwnable2Step.sol";
import {PAUSE_TYPE} from "@alto/utils/Constants.sol";
import {FixedPointMath, MATH_PRECISION} from "@alto/utils/FixedPointMath.sol";

/// @title Peg-Responsive Exponential Interest Rate Model
/// @author GPM
/// @custom:contact [email protected]
/// @notice Adjusts a mint market's borrow rate in response to a validated DUSD/quoteToken
/// peg price.
/// @dev This is a discrete, checkpoint-driven controller. Each update first
/// calculates interest for the elapsed interval using the previously stored
/// rate, then samples the oracle and stores a price-derived rate for the next
/// interval.
/// @dev The raw target is flat at `baseRate` above `recoveryPrice`, increases
/// linearly to `stressRate` at `stressPrice`, and increases exponentially below
/// `stressPrice` according to `doublingDistance`, subject to `maxRate`.
/// `baseRate` may be zero, in which case debt accrues no interest while the peg
/// is healthy and stress mode is inactive.
/// @dev Stress-mode hysteresis is applied separately from the raw curve. Stress
/// begins at or below `stressPrice` and keeps the effective rate at or above
/// `stressRate` until qualifying recovery checkpoints are separated by at least
/// `recoveryDelay`. This is sampled confirmation. The contract does not prove
/// continuous recovery between checkpoints.
/// @dev An unusable oracle observation holds the stored rate and stress-mode
/// status, but interrupts recovery confirmation. Observation freshness is
/// checked only when the controller is called and does not guarantee checkpoint
/// liveness.
/// @dev Owner input changes checkpoint the old inputs and refresh the rate
/// immediately. Invalid observations hold the rate within the new floor and cap.
/// @dev Prices, price distances, and rates use 1e18 fixed-point precision.
/// Rates are expressed as second percent yield (SPY). Delay and observation-age
/// parameters are expressed in seconds.
/// @dev The bound market must checkpoint immediately before pausing. Unpausing
/// resets the accrual timestamp and recovery confirmation but does not sample
/// the oracle or replace the pre-pause rate.
/// @dev `setMarket` is permissionless and one-shot. Deployment must bind the
/// intended market atomically or otherwise prevent an unintended first caller.
contract PegResponsiveExponentialIrm is AltoOwnable2Step, IPegResponsiveExponentialIrmStaticTypes {
    using FixedPointMath for uint256;
    using SafeCast for uint256;
    using SafeCast for int256;

    /// @inheritdoc IIrm
    IRMType public constant IRM_TYPE = IRMType.PEG_RESPONSIVE_EXPONENTIAL;

    /// @inheritdoc IPegResponsiveExponentialIrmBase
    uint256 public constant MAX_BORROW_RATE = 8e18 / uint256(365 days);

    /// @inheritdoc IPegResponsiveExponentialIrmBase
    uint256 public constant MAX_RECOVERY_PRICE = 1.01e18;

    /// @inheritdoc IPegResponsiveExponentialIrmBase
    /// @dev Conservative curve cap below ExpLib's clipping bound. At e^50, even
    /// a stressRate of 1 exceeds MAX_BORROW_RATE, so every positive stress rate
    /// already reaches maxRate. This is not ExpLib's numerical limit.
    uint256 public constant MAX_EXPONENT_INPUT = 50e18;

    /// @inheritdoc IPegResponsiveExponentialIrmBase
    address public pegOracle;

    /// @inheritdoc IPegResponsiveExponentialIrmStaticTypes
    PegResponsiveExponentialIrmConfig public irmConfig;

    /// @inheritdoc IPegResponsiveExponentialIrmStaticTypes
    IRState public irState;

    /// @inheritdoc IPegResponsiveExponentialIrmBase
    address public market;

    /// @notice Constructor.
    /// @param initialPegOracle Oracle returning a validated, timestamped DUSD/quoteToken price.
    /// @param initialConfig Initial curve, recovery, and oracle-freshness configuration.
    /// @param initialOwner Owner of the IRM.
    constructor(address initialPegOracle, PegResponsiveExponentialIrmConfig memory initialConfig, address initialOwner)
        Ownable(initialOwner)
    {
        if (initialPegOracle == address(0)) revert PegResponsiveExponentialIrmInvalidOracle();
        _validateConfig(initialConfig);

        pegOracle = initialPegOracle;
        irmConfig = initialConfig;
        irState.borrowRate = initialConfig.baseRate;

        emit SetPegOracle(address(0), initialPegOracle);
        emit SetIrmConfig(initialConfig);
        emit IRStateUpdated(irState);
    }

    /// @inheritdoc IIrm
    function setMarket(address newMarket) external {
        // No access control: Mirrors current IRM design. Must be deployed and
        // set in one transaction to avoid frontrunning.
        if (market != address(0)) revert IrmMarketAlreadySet();
        if (newMarket == address(0)) revert IrmInvalidParams();

        market = newMarket;
        irState.lastUpdate = block.timestamp.toUint48();

        emit IRStateUpdated(irState);
    }

    /// @inheritdoc IIrm
    function onMarketPause(bool paused) external {
        if (msg.sender != market) revert IrmUnauthorized();

        // The market checkpoints immediately before pausing. Resetting on
        // unpause prevents interest from being charged for the paused interval.
        // Recovery confirmation is also restarted because no observations were
        // processed while the market was paused.
        if (!paused) {
            irState.lastUpdate = block.timestamp.toUint48();
            _resetRecoveryConfirmation();
            emit IRStateUpdated(irState);
        }
    }

    /// @inheritdoc IIrm
    function updateInterestRateView(uint256, uint256 totalBorrowed) external view returns (uint256, uint256) {
        return _accrueInterest(totalBorrowed);
    }

    /// @inheritdoc IIrm
    /// @dev Accrues elapsed interest at the stored rate, then updates the rate for
    /// future accrual. Returns the interest and the rate used to calculate it.
    function updateInterestRate(uint256, uint256 totalBorrowed)
        external
        returns (uint256 interest, uint256 borrowRate)
    {
        if (msg.sender != market) revert IrmUnauthorized();
        (interest, borrowRate) = _accrueInterest(totalBorrowed);
        irState.lastUpdate = block.timestamp.toUint48();
        _refreshBorrowRate();

        return (interest, borrowRate);
    }

    /// @inheritdoc IPegResponsiveExponentialIrmBase
    function setPegOracle(address newPegOracle) external onlyOwner {
        if (newPegOracle == address(0)) revert PegResponsiveExponentialIrmInvalidOracle();

        _checkpointMarket();

        emit SetPegOracle(pegOracle, newPegOracle);
        pegOracle = newPegOracle;
        _resetRecoveryConfirmation();
        _refreshBorrowRate();
    }

    /// @inheritdoc IPegResponsiveExponentialIrmBase
    function setIrmConfig(PegResponsiveExponentialIrmConfig calldata newConfig) external onlyOwner {
        _validateConfig(newConfig);
        _checkpointMarket();
        irmConfig = newConfig;
        emit SetIrmConfig(newConfig);
        _resetRecoveryConfirmation();
        _refreshBorrowRate();
    }

    /// @inheritdoc IPegResponsiveExponentialIrmBase
    function previewBorrowRate()
        external
        view
        returns (uint256 priceWad, uint48 observedAt, bool oracleValid, uint256 borrowRate)
    {
        (priceWad, observedAt, oracleValid) = _readPegPrice();

        if (!oracleValid) return (priceWad, observedAt, false, irState.borrowRate);

        (bool nextStressMode,) = _nextStressState(priceWad, true);
        borrowRate = _effectiveTargetRate(priceWad, nextStressMode);

        return (priceWad, observedAt, oracleValid, borrowRate);
    }

    /// @inheritdoc IPegResponsiveExponentialIrmBase
    function targetBorrowRate(uint256 priceWad) public view returns (uint256 borrowRate) {
        PegResponsiveExponentialIrmConfig memory config = irmConfig;

        if (priceWad >= config.recoveryPrice) return config.baseRate;

        if (priceWad >= config.stressPrice) {
            uint256 position =
                Math.mulDiv(config.recoveryPrice - priceWad, MATH_PRECISION, config.recoveryPrice - config.stressPrice);
            uint256 rateIncrease = Math.mulDiv(config.stressRate - config.baseRate, position, MATH_PRECISION);

            return config.baseRate + rateIncrease;
        }

        uint256 stressDrop = config.stressPrice - priceWad;

        // Convert the price decline into the input for e^x:
        //
        //      2^n = e^(ln(2) * n)
        //
        // where n is the number of configured doubling distances below stressPrice.
        uint256 exponent =
            Math.min(Math.mulDiv(uint256(ExpLib.LN_2_INT), stressDrop, config.doublingDistance), MAX_EXPONENT_INPUT);
        uint256 multiplier = ExpLib.wExp(exponent.toInt256()).toUint256();

        return Math.min(Math.mulDiv(config.stressRate, multiplier, MATH_PRECISION), config.maxRate);
    }

    /// @dev Checkpoints the active market before an owner changes controller inputs.
    /// Does nothing when the IRM is not bound to a market or the market is paused.
    function _checkpointMarket() private {
        if (market != address(0) && !IMarket(market).paused(PAUSE_TYPE)) {
            IMarket(market).accrueInterest();
        }
    }

    /// @dev Calculates interest using the rate that was active throughout the
    /// elapsed interval.
    /// @param totalBorrowed The market's total outstanding debt before accrual.
    /// @return interest    The interest accrued since the previous update.
    /// @return borrowRate  The stored borrow rate used to calculate the interest.
    function _accrueInterest(uint256 totalBorrowed) private view returns (uint256, uint256) {
        if (market == address(0)) revert IrmMarketNotSet();

        uint256 interest = totalBorrowed.multiplyWithPrecision(
            irState.borrowRate.calculateCompoundInterest(block.timestamp - irState.lastUpdate)
        );

        return (interest, irState.borrowRate);
    }

    /// @dev Refreshes the prospective rate within the current bounds without
    /// advancing the accrual timestamp. Setters also use this while paused or unbound.
    function _refreshBorrowRate() private {
        uint256 borrowRate = irState.borrowRate;
        (uint256 priceWad, uint48 observedAt, bool oracleValid) = _readPegPrice();
        bool nextStressMode = _applyStressState(priceWad, oracleValid);
        uint256 floor = nextStressMode ? irmConfig.stressRate : irmConfig.baseRate;
        uint256 newRate = oracleValid
            ? _effectiveTargetRate(priceWad, nextStressMode)
            : Math.min(Math.max(borrowRate, floor), irmConfig.maxRate);

        irState.borrowRate = newRate;

        emit BorrowRateUpdated(borrowRate, newRate, priceWad, observedAt, oracleValid);
        emit IRStateUpdated(irState);
    }

    /// @dev Returns the controller state implied by the latest observation.
    /// Invalid observations keep stress mode active but interrupt recovery
    /// confirmation.
    /// @param priceWad The latest reported DUSD/quoteToken price, using 1e18 precision.
    /// @param oracleValid Whether the latest oracle observation is usable.
    /// @return stressMode          Whether the controller should be in stress mode.
    /// @return recoveryStartedAt   The recovery confirmation start time, or zero when inactive.
    function _nextStressState(uint256 priceWad, bool oracleValid)
        private
        view
        returns (bool stressMode, uint48 recoveryStartedAt)
    {
        IRState memory state = irState;
        PegResponsiveExponentialIrmConfig memory config = irmConfig;

        // Invalid observations preserve stress mode but interrupt recovery.
        if (!oracleValid) return (state.stressMode, 0);

        // Crossing the stress threshold enters stress mode immediately.
        if (!state.stressMode) return (priceWad <= config.stressPrice, 0);

        // Falling below the recovery threshold interrupts recovery.
        if (priceWad < config.recoveryPrice) return (true, 0);

        // The first healthy checkpoint starts recovery confirmation.
        if (state.recoveryStartedAt == 0) return (true, block.timestamp.toUint48());

        // A later healthy checkpoint exits stress once the delay has elapsed.
        if (block.timestamp - uint256(state.recoveryStartedAt) < config.recoveryDelay) {
            return (true, state.recoveryStartedAt);
        }

        return (false, 0);
    }

    /// @dev Applies and emits the stress state implied by the latest observation.
    /// @param priceWad The latest reported DUSD/quoteToken price, using 1e18 precision.
    /// @param oracleValid Whether the latest oracle observation is usable.
    /// @return stressMode Whether the controller is in stress mode after the update.
    function _applyStressState(uint256 priceWad, bool oracleValid) private returns (bool stressMode) {
        uint48 recoveryStartedAt;
        (stressMode, recoveryStartedAt) = _nextStressState(priceWad, oracleValid);
        _setStressState(stressMode, recoveryStartedAt, priceWad);
    }

    /// @dev Applies the stress-mode floor to the raw price-derived target.
    /// @param priceWad The latest valid DUSD/quoteToken price, using 1e18 precision.
    /// @param stressMode Whether the controller is currently in stress mode.
    /// @return borrowRate The price-derived target rate after applying the stress floor.
    function _effectiveTargetRate(uint256 priceWad, bool stressMode) private view returns (uint256 borrowRate) {
        uint256 targetRate = targetBorrowRate(priceWad);
        return stressMode ? Math.max(targetRate, irmConfig.stressRate) : targetRate;
    }

    /// @dev Interrupts an in-progress recovery confirmation.
    function _resetRecoveryConfirmation() private {
        _setStressState(irState.stressMode, 0, 0);
    }

    /// @dev Stores and emits a stress-state transition when either field changes.
    function _setStressState(bool stressMode, uint48 recoveryStartedAt, uint256 priceWad) private {
        if (irState.stressMode == stressMode && irState.recoveryStartedAt == recoveryStartedAt) {
            return;
        }

        irState.stressMode = stressMode;
        irState.recoveryStartedAt = recoveryStartedAt;
        emit StressStateUpdated(stressMode, recoveryStartedAt, priceWad);
    }

    /// @dev Treats reverts, invalid flags, zero/future timestamps, stale data,
    /// and zero prices as unusable.
    /// @return priceWad    The reported DUSD/quoteToken price, or zero when unusable.
    /// @return observedAt  The oracle observation timestamp, or zero when the oracle call reverts.
    /// @return valid       Whether the observation passed all validation checks.
    function _readPegPrice() private view returns (uint256 priceWad, uint48 observedAt, bool valid) {
        try IDusdPegOracle(pegOracle).getPrice() returns (
            uint256 reportedPriceWad, uint48 reportedAt, bool observationValid
        ) {
            observedAt = reportedAt;

            // Keep this order: each timestamp check relies on the prior checks
            // short-circuiting before the age subtraction.
            if (
                !observationValid || reportedPriceWad == 0 || reportedAt == 0 || uint256(reportedAt) > block.timestamp
                    || block.timestamp - uint256(reportedAt) > irmConfig.maxOracleAge
            ) {
                return (0, observedAt, false);
            }

            return (reportedPriceWad, observedAt, true);
        } catch {
            return (0, 0, false);
        }
    }

    /// @dev Reverts when curve thresholds, rates, or controller timings are
    /// outside supported bounds.
    /// @param config The IRM configuration to validate.
    function _validateConfig(PegResponsiveExponentialIrmConfig memory config) private pure {
        // stressPrice must be nonzero and strictly below recoveryPrice.
        // Equal thresholds would make the linear bridge divide by zero, while
        // reversed thresholds would invalidate the ordering of the curve regions.
        // recoveryPrice is also limited to the supported oracle price range.
        //
        // baseRate may be zero but must be no greater than stressRate.
        // stressRate must be nonzero because the exponential region scales it, and
        // strictly below maxRate so that region has room to increase. maxRate must
        // not exceed the protocol safety limit.
        //
        // doublingDistance must be nonzero to prevent division by zero.
        // recoveryDelay and maxOracleAge must be nonzero so recovery confirmation
        // and oracle freshness validation cannot be disabled accidentally.

        if (
            config.stressPrice == 0 || config.recoveryPrice > MAX_RECOVERY_PRICE
                || config.stressPrice >= config.recoveryPrice
        ) {
            revert PegResponsiveExponentialIrmInvalidPriceConfig();
        }

        if (
            config.stressRate == 0 || config.baseRate > config.stressRate || config.stressRate >= config.maxRate
                || config.maxRate > MAX_BORROW_RATE
        ) {
            revert PegResponsiveExponentialIrmInvalidRateConfig();
        }

        if (config.doublingDistance == 0 || config.recoveryDelay == 0 || config.maxOracleAge == 0) {
            revert PegResponsiveExponentialIrmInvalidControllerConfig();
        }
    }
}

contracts/lending/libraries/ExpLib.sol

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

import {MATH_PRECISION} from "@alto/utils/FixedPointMath.sol";

int256 constant MATH_PRECISION_INT = int256(MATH_PRECISION);

/// @title ExpLib
/// @author GPM
/// @author Adapted from Morpho Labs (https://github.com/morpho-org/morpho-blue-irm)
/// @custom:contact [email protected]
/// @notice Library to approximate the exponential function.
library ExpLib {
    /// @dev ln(2).
    int256 internal constant LN_2_INT = 0.693147180559945309 ether;

    /// @dev ln(1e-18).
    int256 internal constant LN_WEI_INT = -41.446531673892822312 ether;

    /// @dev Above this bound, `wExp` is clipped to avoid overflowing when multiplied with 1 ether.
    /// @dev This upper bound corresponds to: ln(type(int256).max / 1e36) (scaled by MATH_PRECISION_INT, floored).
    int256 internal constant WEXP_UPPER_BOUND = 93.859467695000404319 ether;

    /// @dev The value of wExp(`WEXP_UPPER_BOUND`).
    int256 internal constant WEXP_UPPER_VALUE = 57716089161558943949701069502944508345128.422502756744429568 ether;

    /// @dev Returns an approximation of exp.
    function wExp(int256 x) internal pure returns (int256) {
        unchecked {
            // If x < ln(1e-18) then exp(x) < 1e-18 so it is rounded to zero.
            if (x < LN_WEI_INT) return 0;
            // `wExp` is clipped to avoid overflowing when multiplied with 1 ether.
            if (x >= WEXP_UPPER_BOUND) return WEXP_UPPER_VALUE;

            // Decompose x as x = q * ln(2) + r with q an integer and -ln(2)/2 <= r <= ln(2)/2.
            // q = x / ln(2) rounded half toward zero.
            int256 roundingAdjustment = (x < 0) ? -(LN_2_INT / 2) : (LN_2_INT / 2);
            // Safe unchecked because x is bounded.
            int256 q = (x + roundingAdjustment) / LN_2_INT;
            // Safe unchecked because |q * ln(2) - x| <= ln(2)/2.
            int256 r = x - q * LN_2_INT;

            // Compute e^r with a 2nd-order Taylor polynomial.
            // Safe unchecked because |r| < 1e18.
            int256 expR = MATH_PRECISION_INT + r + (r * r) / MATH_PRECISION_INT / 2;

            // Return e^x = 2^q * e^r.
            if (q >= 0) return expR << uint256(q);
            else return expR >> uint256(-q);
        }
    }
}

contracts/oracles/interfaces/IDusdPegOracle.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

/// @notice Common interface for timestamped DUSD peg-price observations.
interface IDusdPegOracle {
    /// @notice Returns the current DUSD/quoteToken price and associated metadata.
    /// @return priceWad DUSD/quoteToken price using 1e18 precision.
    /// @return observedAt Timestamp represented by the observation.
    /// @return valid Whether the observation passed the oracle's checks.
    function getPrice() external view returns (uint256 priceWad, uint48 observedAt, bool valid);
}

contracts/utils/AltoOwnable2Step.sol

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

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title Alto Ownable 2 Step
 * @author GPM
 * @custom:contact [email protected]
 * @notice This contract extends Ownable2Step contract from OpenZeppelin, with a way to bypass the 2 steps ownership transfer.
 */
abstract contract AltoOwnable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /// @notice This function is used to transfer ownership of the contract to a new account without the 2 steps ownership transfer.
    /// @param newOwner The address of the new owner.
    /// @dev This is useful in deployment scripts and should be used with caution.
    function transferOwnershipSkip2Step(address newOwner) public virtual onlyOwner {
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

contracts/utils/Constants.sol

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

bytes32 constant PAUSE_TYPE = keccak256("PAUSE_TYPE");

bytes32 constant RESCUE_TYPE = keccak256("RESCUE_TYPE");

bytes32 constant FROZEN_TYPE = keccak256("FROZEN_TYPE");

contracts/utils/FixedPointMath.sol

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

uint256 constant MATH_PRECISION = 1e18;

/// @title FixedPointMath
/// @author GPM
/// @custom:contact [email protected]
/// @notice Library for fixed point arithmetic.
library FixedPointMath {
    /// @dev Multiplies two numbers and divides by MATH_PRECISION, rounding down.
    function multiplyWithPrecision(uint256 multiplicand, uint256 multiplier) internal pure returns (uint256) {
        return (multiplicand * multiplier) / MATH_PRECISION;
    }

    /// @dev Multiplies two numbers and divides by MATH_PRECISION, rounding up.
    function multiplyWithPrecisionUp(uint256 multiplicand, uint256 multiplier) internal pure returns (uint256) {
        return Math.ceilDiv(multiplicand * multiplier, MATH_PRECISION);
    }

    /// @dev Divides a number by another using MATH_PRECISION, rounding up.
    function divideWithPrecisionUp(uint256 numerator, uint256 denominator) internal pure returns (uint256) {
        return Math.ceilDiv(numerator * MATH_PRECISION, denominator);
    }

    /// @dev Divides a number by another using MATH_PRECISION, rounding down.
    function divideWithPrecisionDown(uint256 numerator, uint256 denominator) internal pure returns (uint256) {
        return (numerator * MATH_PRECISION) / denominator;
    }

    /// @dev Multiplies numerator by multiplier and divides by denominator rounding division result up or down based on roundUp parameter.
    /// @dev numerator * multiplier / denominator rounding division result.
    function divideWithRounding(uint256 numerator, uint256 multiplier, uint256 denominator, bool roundUp)
        internal
        pure
        returns (uint256)
    {
        if (roundUp) {
            return Math.ceilDiv(numerator * multiplier, denominator);
        }
        return (numerator * multiplier) / denominator;
    }

    /// @dev Multiplies numerator by multiplier and divides by denominator rounding division result up or down based on half up rule.
    /// @dev numerator * multiplier / denominator rounding division result.
    function divideWithRoundingHalfUp(uint256 numerator, uint256 multiplier, uint256 denominator)
        internal
        pure
        returns (uint256)
    {
        return (numerator * multiplier + denominator / 2) / denominator;
    }

    /// @dev Calculates compound interest using Taylor series approximation.
    function calculateCompoundInterest(uint256 rate, uint256 periods) internal pure returns (uint256) {
        uint256 linearTerm = rate * periods;
        uint256 quadraticTerm = (linearTerm * linearTerm) / (2 * MATH_PRECISION);
        uint256 cubicTerm = (quadraticTerm * linearTerm) / (3 * MATH_PRECISION);

        uint256 result = linearTerm + quadraticTerm + cubicTerm;

        // Add fourth term when rate * periods exceeds 0.2e18 for improved accuracy
        if (linearTerm > 0.2e18) {
            uint256 quarticTerm = (cubicTerm * linearTerm) / (4 * MATH_PRECISION);

            // Check for overflow before adding the fourth term
            if (result <= type(uint256).max - quarticTerm) {
                result += quarticTerm;
            }
        }

        // Cap the result to prevent downstream uint128 overflows in interest calculations
        // Max safe value is approximately 1e20 to allow for reasonable multiplication with borrower amounts
        uint256 maxSafeResult = 1e20;
        if (result > maxSafeResult) {
            result = maxSafeResult;
        }

        return result;
    }
}

contracts/utils/interfaces/IAuth.sol

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

struct Authorization {
    address owner;
    address spender;
    bool isAuthorizedStatus;
    uint256 nonce;
    uint256 deadline;
}

struct Signature {
    uint8 v;
    bytes32 r;
    bytes32 s;
}

interface IAuth {
    /// @notice Emitted when the authorization is set.
    /// @param caller The address of the caller.
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @param isAuthorized The authorization status.
    event SetAuthorization(address indexed caller, address indexed owner, address indexed spender, bool isAuthorized);

    /// @notice Emitted when the nonce is incremented.
    /// @param caller The address of the caller.
    /// @param owner The address of the owner.
    /// @param nonce The nonce.
    event IncrementNonce(address indexed caller, address indexed owner, uint256 nonce);

    /// @notice Error thrown when the authorization is already set.
    error AuthAuthorizationAlreadySet();

    /// @notice Error thrown when the signature's deadline expired.
    error AuthSignatureExpired();

    /// @notice Error thrown when the nonce is invalid.
    error AuthInvalidNonce();

    /// @notice Error thrown when the signature is invalid because of various reasons.
    error AuthInvalidSignature();

    /// @dev Returns whether the sender is authorized to manage `owner`'s positions.
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @return isAuthorized Whether the sender is authorized to manage `owner`'s positions.
    function isAuthorized(address owner, address spender) external view returns (bool);

    /// @dev Returns the nonce for the owner.
    /// @param owner The address of the owner.
    /// @return nonce The nonce for the owner.
    function nonce(address owner) external view returns (uint256);

    /// @dev Sets the authorization for `spender` to `isAuthorizedStatus`.
    /// @param spender The address to set the authorization for.
    /// @param isAuthorizedStatus The authorization status to set.
    function setAuthorization(address spender, bool isAuthorizedStatus) external;

    /// @dev Sets the authorization for `spender` to `isAuthorizedStatus` status using a signature.
    /// @param authData The authorization to set.
    /// @param sigData The signature of the owner.
    function setAuthorizationWithSignature(Authorization memory authData, Signature calldata sigData) external;
}

contracts/utils/interfaces/IPausable.sol

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

interface IPausable {
    event PauserUpdated(address indexed pauser, bytes32 pauseType, bool status);
    event Paused(address indexed pauser, bytes32 pauseType, bool paused);

    error Unauthorized(address pauser, bytes32 pauseType);
    error IsPaused(bytes32 pauseType);
    error StateNotChanged(bytes32 pauseType, bool currentState, bool newState);

    function paused(bytes32 pauseType) external view returns (bool);
    function setPauser(address pauser, bytes32 pauseType, bool status) external;
    function pause(bytes32 pauseType, bool _paused) external;
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the 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.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}
Настройки компилятораПоказать
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "deployments/=contracts/deployments/",
    "@morpho-org/bundler3/=lib/bundler3/src/",
    "@bundler3/=lib/bundler3/",
    "@morpho-org/irm/=lib/morpho-blue-irm/src/",
    "@alto-test/=test/",
    "@alto/=contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@chainlink/=lib/chainlink-evm/",
    "@erc4626-tests/=lib/erc4626-tests/",
    "@layerzerolabs/=node_modules/@layerzerolabs/",
    "bundler3/=lib/bundler3/",
    "chainlink-evm/=lib/chainlink-evm/",
    "ds-test/=lib/morpho-blue-irm/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/bundler3/lib/permit2/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "morpho-blue-irm/=lib/morpho-blue-irm/src/",
    "morpho-blue/=lib/bundler3/lib/morpho-blue/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/bundler3/lib/openzeppelin-contracts/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "permit2/=lib/bundler3/lib/permit2/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/",
    "solmate/=lib/morpho-blue-irm/lib/solmate/src/",
    "v3-core/=lib/v3-core/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.