LevvaPoolAdapter

Description:

Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "contracts/adapters/levvaPool/LevvaPoolAdapter.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {AdapterBase} from "../AdapterBase.sol";

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IAdapterCallback} from "../../interfaces/IAdapterCallback.sol";
import {IExternalPositionAdapter} from "../../interfaces/IExternalPositionAdapter.sol";
import {ILevvaVault} from "../../interfaces/ILevvaVault.sol";
import {IEulerPriceOracle} from "../../interfaces/IEulerPriceOracle.sol";
import {ILevvaPool} from "./interfaces/ILevvaPool.sol";
import {Asserts} from "../../libraries/Asserts.sol";
import {FP96} from "./FP96.sol";

/// @title Adapter for interaction with Levva pools (Marginly protocol)
/// @notice Should be deployed for each vault
contract LevvaPoolAdapter is AdapterBase, IExternalPositionAdapter {
    using Asserts for address;

    bytes4 public constant getAdapterId = bytes4(keccak256("LevvaPoolAdapter"));

    using FP96 for FP96.FixedPoint;
    using SafeERC20 for IERC20;
    using Math for uint256;

    uint256 private constant SECONDS_IN_YEAR_X96 = 2500250661360148260042022567123353600;
    uint24 private constant ONE = 1e6;

    address private immutable i_vault;
    address[] private s_pools;
    mapping(address => uint256) private s_poolPosition;

    error LevvaPoolAdapter__NotAuthorized();
    error LevvaPoolAdapter__OracleNotExists(address base, address quote);
    error LevvaPoolAdapter__WrongLevvaPoolMode();
    error LevvaPoolAdapter__NotSupported();
    error LevvaPoolAdapter__NoPool();

    event PoolAdded(address indexed pool);
    event PoolRemoved(address indexed pool);
    event LevvaPoolDeposit(
        address indexed vault, address indexed pool, address indexed token, uint256 amount, int256 positionAmount
    );
    event LevvaPoolLong(address indexed vault, address indexed pool, uint256 amount);
    event LevvaPoolShort(address indexed vault, address indexed pool, uint256 amount);
    event LevvaPoolClosePosition(address indexed vault, address indexed pool);
    event LevvaPoolSellCollateral(address indexed vault, address indexed pool);
    event LevvaPoolWithdraw(address indexed vault, address indexed pool, address indexed asset, uint256 amount);

    constructor(address vault) {
        vault.assertNotZeroAddress();
        i_vault = vault;
    }

    modifier onlyVault() {
        _onlyVault();
        _;
    }

    function supportsInterface(bytes4 interfaceId) public pure override returns (bool) {
        return super.supportsInterface(interfaceId) || interfaceId == type(IExternalPositionAdapter).interfaceId;
    }

    /// @notice Deposits an amount into a Marginly pool
    /// @param asset The asset to deposit
    /// @param amount The amount to deposit
    /// @param positionAmount Position amount
    /// @param amountInQuote If 'positionAmount' in in quote token
    /// @param pool The pool to deposit into
    /// @param limitPriceX96 The limit price for the position
    /// @param swapCallData The swap call data
    function deposit(
        address asset,
        uint256 amount,
        int256 positionAmount,
        bool amountInQuote,
        address pool,
        uint256 limitPriceX96,
        uint256 swapCallData
    ) external onlyVault {
        _deposit(asset, amount, positionAmount, amountInQuote, pool, limitPriceX96, swapCallData);
    }

    /// @notice Deposits all amount except given amount into a Marginly pool
    function depositAllExcept(
        address asset,
        uint256 except,
        int256 positionAmount,
        bool amountInQuote,
        address pool,
        uint256 limitPriceX96,
        uint256 swapCallData
    ) external onlyVault {
        uint256 amount = IERC20(asset).balanceOf(msg.sender) - except;
        _deposit(asset, amount, positionAmount, amountInQuote, pool, limitPriceX96, swapCallData);
    }

    ///@notice Opens a long position
    ///@param amount The amount to open a long position
    /// @param amountInQuote If 'amount' in in quote token
    ///@param pool The pool to open a long position in
    ///@param limitPriceX96 The limit price for the position
    ///@param swapCallData The swap call data
    function long(uint256 amount, bool amountInQuote, address pool, uint256 limitPriceX96, uint256 swapCallData)
        external
        onlyVault
    {
        ILevvaPool(pool).execute(
            ILevvaPool.CallType.Long, amount, int256(0), limitPriceX96, amountInQuote, address(0), swapCallData
        );

        // long - quoteToken in debt, check oracle for quoteToken
        _assertOracleExists(ILevvaPool(pool).quoteToken(), ILevvaVault(msg.sender).asset());

        emit LevvaPoolLong(msg.sender, pool, amount);
    }

    ///@notice Opens a short position
    ///@param amount The amount to open a short position
    /// @param amountInQuote If 'amount' in in quote token
    ///@param pool The pool to open a short position in
    ///@param limitPriceX96 The limit price for the position
    ///@param swapCallData The swap call data
    function short(uint256 amount, bool amountInQuote, address pool, uint256 limitPriceX96, uint256 swapCallData)
        external
        onlyVault
    {
        ILevvaPool(pool).execute(
            ILevvaPool.CallType.Short, amount, int256(0), limitPriceX96, amountInQuote, address(0), swapCallData
        );

        // short - baseToken in debt, check oracle for baseToken
        _assertOracleExists(ILevvaPool(pool).baseToken(), ILevvaVault(msg.sender).asset());

        emit LevvaPoolShort(msg.sender, pool, amount);
    }

    ///@notice Closes a position
    ///@param pool The pool to close a position in
    ///@param withdrawal If withdrawal of remaining collateral is required
    ///@param limitPriceX96 The limit price for the position
    ///@param swapCallData The swap call data
    function closePosition(address pool, bool withdrawal, uint256 limitPriceX96, uint256 swapCallData)
        external
        onlyVault
    {
        address asset;
        if (withdrawal) {
            ILevvaPool.Position memory position = ILevvaPool(pool).positions(address(this));
            asset = position._type == ILevvaPool.PositionType.Long
                ? ILevvaPool(pool).baseToken()
                : ILevvaPool(pool).quoteToken();
        }

        ILevvaPool(pool).execute(
            ILevvaPool.CallType.ClosePosition, 0, int256(0), limitPriceX96, withdrawal, address(0), swapCallData
        );
        emit LevvaPoolClosePosition(msg.sender, pool);

        if (withdrawal) {
            uint256 amount = IERC20(asset).balanceOf(address(this));
            IERC20(asset).safeTransfer(msg.sender, amount);
            _removePool(pool);

            emit LevvaPoolWithdraw(msg.sender, pool, asset, amount);
        }
    }

    ///@notice Sell position collateral
    ///@param pool The pool to sell collateral in
    ///@param withdrawal If withdrawal of remaining collateral is required
    ///@param limitPriceX96 The limit price for collateral sale
    ///@param swapCallData The swap call data
    function sellCollateral(address pool, bool withdrawal, uint256 limitPriceX96, uint256 swapCallData)
        external
        onlyVault
    {
        address asset;
        if (withdrawal) {
            ILevvaPool.Position memory position = ILevvaPool(pool).positions(address(this));
            asset = position._type == ILevvaPool.PositionType.Long
                ? ILevvaPool(pool).quoteToken()
                : ILevvaPool(pool).baseToken();
        }

        ILevvaPool(pool).execute(
            ILevvaPool.CallType.SellCollateral, 0, int256(0), limitPriceX96, withdrawal, address(0), swapCallData
        );
        emit LevvaPoolSellCollateral(msg.sender, pool);

        if (withdrawal) {
            uint256 amount = IERC20(asset).balanceOf(address(this));
            IERC20(asset).safeTransfer(msg.sender, amount);
            _removePool(pool);

            emit LevvaPoolWithdraw(msg.sender, pool, asset, amount);
        }
    }

    /// @notice Withdraws an amount from pool
    /// @param asset The asset to withdraw
    /// @param amount The amount to withdraw
    /// @param pool The pool to withdraw from
    function withdraw(address asset, uint256 amount, address pool) external onlyVault returns (uint256 amountOut) {
        ILevvaPool.CallType callType = ILevvaPool(pool).quoteToken() == asset
            ? ILevvaPool.CallType.WithdrawQuote
            : ILevvaPool.CallType.WithdrawBase;

        ILevvaPool(pool).execute(callType, amount, int256(0), 0, false, address(0), 0);
        amountOut = IERC20(asset).balanceOf(address(this));
        IERC20(asset).safeTransfer(msg.sender, amountOut);

        ILevvaPool.Position memory position = ILevvaPool(pool).positions(address(this));
        if (position._type == ILevvaPool.PositionType.Uninitialized) {
            _removePool(pool);
        }

        emit LevvaPoolWithdraw(msg.sender, pool, asset, amountOut);
    }

    /// @notice Withdraws an amount when pool in emergency mode
    /// @param pool The pool to withdraw from
    function emergencyWithdraw(address pool) external onlyVault {
        ILevvaPool.Position memory position = ILevvaPool(pool).positions(address(this));
        ILevvaPool.Mode mode = ILevvaPool(pool).mode();

        IERC20 asset;
        if (mode == ILevvaPool.Mode.ShortEmergency) {
            if (position._type == ILevvaPool.PositionType.Short) {
                _removePool(pool);
                return;
            }
            asset = IERC20(ILevvaPool(pool).baseToken());
        } else if (mode == ILevvaPool.Mode.LongEmergency) {
            if (position._type == ILevvaPool.PositionType.Long) {
                _removePool(pool);
                return;
            }
            asset = IERC20(ILevvaPool(pool).quoteToken());
        } else {
            revert LevvaPoolAdapter__WrongLevvaPoolMode();
        }

        ILevvaPool(pool).execute(ILevvaPool.CallType.EmergencyWithdraw, 0, int256(0), 0, false, address(0), 0);

        uint256 amount = asset.balanceOf(address(this));
        asset.safeTransfer(msg.sender, amount);

        position = ILevvaPool(pool).positions(address(this));
        if (position._type == ILevvaPool.PositionType.Uninitialized) {
            _removePool(pool);
        }

        emit LevvaPoolWithdraw(msg.sender, pool, address(asset), amount);
    }

    /// @notice Returns managed assets by the vault in adapter Protocol
    function getManagedAssets() external view returns (address[] memory assets, uint256[] memory amounts) {
        uint256 length = s_pools.length;
        assets = new address[](length);
        amounts = new uint256[](length);

        for (uint256 i; i < length;) {
            ILevvaPool pool = ILevvaPool(s_pools[i]);
            ILevvaPool.Position memory position = pool.positions(address(this));

            if (position._type == ILevvaPool.PositionType.Short || position.discountedBaseAmount == 0) {
                //isQuote
                assets[i] = pool.quoteToken();
                uint256 discountedBaseDebt =
                    position._type == ILevvaPool.PositionType.Short ? position.discountedBaseAmount : 0;
                amounts[i] = _estimateCollateral(pool, true, position.discountedQuoteAmount, discountedBaseDebt);
            } else {
                assets[i] = pool.baseToken();
                uint256 discountedQuoteDebt =
                    position._type == ILevvaPool.PositionType.Long ? position.discountedQuoteAmount : 0;
                amounts[i] = _estimateCollateral(pool, false, position.discountedBaseAmount, discountedQuoteDebt);
            }

            unchecked {
                ++i;
            }
        }
    }

    /// @notice Returns debt assets managed by the vault in adapter Protocol
    function getDebtAssets() external view returns (address[] memory assets, uint256[] memory amounts) {
        uint256 length = s_pools.length;
        assets = new address[](length);
        amounts = new uint256[](length);

        for (uint256 i; i < length;) {
            ILevvaPool pool = ILevvaPool(s_pools[i]);
            ILevvaPool.Position memory position = pool.positions(address(this));

            if (position._type == ILevvaPool.PositionType.Long) {
                assets[i] = pool.quoteToken();
                amounts[i] = _estimateDebtCoeff(pool, true).mul(position.discountedQuoteAmount);
            } else if (position._type == ILevvaPool.PositionType.Short) {
                assets[i] = pool.baseToken();
                amounts[i] = _estimateDebtCoeff(pool, false).mul(position.discountedBaseAmount);
            }

            unchecked {
                ++i;
            }
        }
    }

    /// @notice Returns the vault address
    function getVault() external view returns (address) {
        return i_vault;
    }

    /// @notice Returns all connected pools
    function getPools() external view returns (address[] memory pools) {
        return s_pools;
    }

    /// @notice Returns position of pool
    function getPoolPosition(address pool) external view returns (uint256) {
        return s_poolPosition[pool];
    }

    function _onlyVault() private view {
        if (msg.sender != i_vault) {
            revert LevvaPoolAdapter__NotAuthorized();
        }
    }

    function _addPool(address pool) internal {
        if (s_poolPosition[pool] != 0) {
            return;
        }

        s_pools.push(pool);
        s_poolPosition[pool] = s_pools.length;

        emit PoolAdded(pool);
    }

    function _removePool(address pool) internal {
        uint256 poolPosition = s_poolPosition[pool];
        if (poolPosition == 0) {
            revert LevvaPoolAdapter__NoPool();
        }

        uint256 poolIndex = poolPosition - 1;
        uint256 poolsLastIndex = s_pools.length - 1;

        if (poolIndex != poolsLastIndex) {
            address replacement = s_pools[poolsLastIndex];
            s_pools[poolIndex] = replacement;
            s_poolPosition[replacement] = poolIndex + 1;
        }

        s_pools.pop();
        delete s_poolPosition[pool];

        emit PoolRemoved(pool);
    }

    /// @dev A little modified MarginlyPool.accruedInterest() function
    /// @dev https://github.com/eq-lab/marginly/blob/main/packages/contracts/contracts/MarginlyPool.sol#L1019
    /// @dev Instead of calling MarginlyPool.reinit() we make calculations on our side
    /// @dev Reinit simulation without margin calls
    function _estimateCollateral(ILevvaPool pool, bool isQuote, uint256 discountedCollateral, uint256 discountedDebt)
        private
        view
        returns (uint256)
    {
        uint256 secondsPassed = block.timestamp - pool.lastReinitTimestampSeconds();

        if (isQuote) {
            FP96.FixedPoint memory quoteCollateralCoeff = pool.quoteCollateralCoeff();
            FP96.FixedPoint memory quoteDelevCoeff = pool.quoteDelevCoeff();

            uint256 currentQuoteCollateral =
                quoteCollateralCoeff.mul(discountedCollateral) - quoteDelevCoeff.mul(discountedDebt);
            if (secondsPassed == 0) {
                return currentQuoteCollateral;
            }

            FP96.FixedPoint memory quoteAccruedInterestFactor = _estimateQuoteAccruedInterestFactor(pool, secondsPassed);
            uint256 realQuoteDebtDelta =
                quoteAccruedInterestFactor.sub(FP96.one()).mul(pool.quoteDebtCoeff().mul(pool.discountedQuoteDebt()));
            uint256 realQuoteCollateral = quoteCollateralCoeff.mul(pool.discountedQuoteCollateral())
                - quoteDelevCoeff.mul(pool.discountedBaseDebt());

            FP96.FixedPoint memory factor = FP96.one().add(FP96.fromRatio(realQuoteDebtDelta, realQuoteCollateral));

            return factor.mul(currentQuoteCollateral);
        } else {
            FP96.FixedPoint memory baseCollateralCoeff = pool.baseCollateralCoeff();
            FP96.FixedPoint memory baseDelevCoeff = pool.baseDelevCoeff();
            uint256 currentBaseCollateral =
                baseCollateralCoeff.mul(discountedCollateral) - baseDelevCoeff.mul(discountedDebt);

            if (secondsPassed == 0) {
                return currentBaseCollateral;
            }

            FP96.FixedPoint memory baseAccruedInterestFactor = _estimateBaseAccruedInterestFactor(pool, secondsPassed);
            uint256 realBaseDebtDelta =
                baseAccruedInterestFactor.sub(FP96.one()).mul(pool.baseDebtCoeff().mul(pool.discountedBaseDebt()));
            uint256 realBaseCollateral = baseCollateralCoeff.mul(pool.discountedBaseCollateral())
                - baseDelevCoeff.mul(pool.discountedQuoteDebt());

            FP96.FixedPoint memory factor = FP96.one().add(FP96.fromRatio(realBaseDebtDelta, realBaseCollateral));

            return factor.mul(currentBaseCollateral);
        }
    }

    function _estimateDebtCoeff(ILevvaPool pool, bool isLong) private view returns (FP96.FixedPoint memory) {
        uint256 secondsPassed = block.timestamp - pool.lastReinitTimestampSeconds();
        if (secondsPassed == 0) {
            return isLong ? pool.quoteDebtCoeff() : pool.baseDebtCoeff();
        }

        if (isLong) {
            return pool.quoteDebtCoeff().mul(_estimateQuoteAccruedInterestFactor(pool, secondsPassed));
        } else {
            return pool.baseDebtCoeff().mul(_estimateBaseAccruedInterestFactor(pool, secondsPassed));
        }
    }

    function _assertOracleExists(address base, address quote) internal view {
        IEulerPriceOracle eulerOracle = IEulerPriceOracle(ILevvaVault(msg.sender).oracle());
        if (
            _callOracle(eulerOracle, _getOneToken(base), base, quote) == 0
                && _callOracle(eulerOracle, _getOneToken(quote), quote, base) == 0
        ) revert LevvaPoolAdapter__OracleNotExists(base, quote);
    }

    function _getOneToken(address token) private view returns (uint256) {
        return 10 ** IERC20Metadata(token).decimals();
    }

    function _callOracle(IEulerPriceOracle eulerOracle, uint256 baseAmount, address baseToken, address quoteToken)
        private
        view
        returns (uint256)
    {
        return eulerOracle.getQuote(baseAmount, baseToken, quoteToken);
    }

    function _estimateQuoteAccruedInterestFactor(ILevvaPool pool, uint256 secondsPassed)
        private
        view
        returns (FP96.FixedPoint memory)
    {
        FP96.FixedPoint memory systemLeverage = FP96.FixedPoint({inner: pool.longLeverageX96()});
        return _estimateAccruedInterestFactor(pool, secondsPassed, systemLeverage);
    }

    function _estimateBaseAccruedInterestFactor(ILevvaPool pool, uint256 secondsPassed)
        private
        view
        returns (FP96.FixedPoint memory)
    {
        FP96.FixedPoint memory systemLeverage = FP96.FixedPoint({inner: pool.shortLeverageX96()});
        return _estimateAccruedInterestFactor(pool, secondsPassed, systemLeverage);
    }

    function _estimateAccruedInterestFactor(
        ILevvaPool pool,
        uint256 secondsPassed,
        FP96.FixedPoint memory systemLeverage
    ) private view returns (FP96.FixedPoint memory) {
        ILevvaPool.MarginlyParams memory params = pool.params();
        FP96.FixedPoint memory secondsInYear = FP96.FixedPoint({inner: SECONDS_IN_YEAR_X96});

        FP96.FixedPoint memory onePlusIR =
            FP96.fromRatio(params.interestRate, ONE).mul(systemLeverage).div(secondsInYear).add(FP96.one());
        FP96.FixedPoint memory accruedRateDt = FP96.powTaylor(onePlusIR, secondsPassed);

        FP96.FixedPoint memory onePlusFee = FP96.fromRatio(params.fee, ONE).div(secondsInYear).add(FP96.one());
        FP96.FixedPoint memory feeDt = FP96.powTaylor(onePlusFee, secondsPassed);

        return accruedRateDt.mul(feeDt);
    }

    function _deposit(
        address asset,
        uint256 amount,
        int256 positionAmount,
        bool amountInQuote,
        address pool,
        uint256 limitPriceX96,
        uint256 swapCallData
    ) private {
        address quoteToken = ILevvaPool(pool).quoteToken();
        ILevvaPool.CallType callType =
            asset == quoteToken ? ILevvaPool.CallType.DepositQuote : ILevvaPool.CallType.DepositBase;

        //Both token deposits not supported
        ILevvaPool.Position memory position = ILevvaPool(pool).positions(address(this));
        if (position._type == ILevvaPool.PositionType.Lend) {
            if (position.discountedBaseAmount != 0) {
                if (callType == ILevvaPool.CallType.DepositQuote) revert LevvaPoolAdapter__NotSupported();
            } else {
                if (callType == ILevvaPool.CallType.DepositBase) revert LevvaPoolAdapter__NotSupported();
            }
        }

        if (callType == ILevvaPool.CallType.DepositQuote && positionAmount < 0) {
            // depositQuote and long
            _assertOracleExists(quoteToken, ILevvaVault(msg.sender).asset());
        } else if (callType == ILevvaPool.CallType.DepositBase && positionAmount < 0) {
            // depositBase and short
            _assertOracleExists(ILevvaPool(pool).baseToken(), ILevvaVault(msg.sender).asset());
        }

        IAdapterCallback(msg.sender).adapterCallback(address(this), asset, amount);

        IERC20(asset).forceApprove(address(pool), amount);
        ILevvaPool(pool).execute(
            callType, amount, positionAmount, limitPriceX96, amountInQuote, address(0), swapCallData
        );

        _addPool(pool);

        emit LevvaPoolDeposit(msg.sender, pool, asset, amount, positionAmount);
    }
}
"
    },
    "contracts/adapters/AdapterBase.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {IERC165} from "@openzeppelin/contracts/interfaces/IERC165.sol";
import {IAdapter} from "../interfaces/IAdapter.sol";

abstract contract AdapterBase is IERC165, IAdapter {
    /// @notice Implementation of ERC165, supports IAdapter and IERC165
    /// @param interfaceId interface identifier
    function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) {
        return interfaceId == type(IAdapter).interfaceId || interfaceId == type(IERC165).interfaceId;
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/math/Math.sol": {
      "content": "// 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/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
  

Tags:
ERC20, ERC165, Proxy, Mintable, Swap, Yield, Upgradeable, Factory, Oracle|addr:0x1b5b052c8d26f041992e141e0126e4c32b2b9cb5|verified:true|block:23517443|tx:0x30a4114a1183ce768907149e32992af82520cc2c8da343f7ed796790ddcc6ff5|first_check:1759747399

Submitted on: 2025-10-06 12:43:20

Comments

Log in to comment.

No comments yet.