Skip to content
Verified contractExactBUSL-1.1

FluidLimitsAuthDex

Address0x1e1fca3cc4436aae73e9c97ea0e1584c749db300
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.21

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.21+commit.d9974bed
Language
solidity
Optimization
Yes, 10,000,000 runs
EVM version
paris
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,454,471
Creation transaction
0x599a63248f…4f448f8d96

contracts/config/limitsAuthDex/main.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

import { DexSlotsLink } from "../../libraries/dexSlotsLink.sol";
import { DexCalcs } from "../../libraries/dexCalcs.sol";
import { IFluidDexT1 } from "../../protocols/dex/interfaces/iDexT1.sol";
import { IFluidDexT1Admin } from "../../protocols/dex/interfaces/iDexT1Admin.sol";
import { IFluidAuthGate, IFluidAuthGateLiquidity, FluidAuthLevels } from "../authGate/interfaces/iAuthGate.sol";
import { BasicValidations } from "../../libraries/utils/basicValidations.sol";
import { Structs as AdminModuleStructs } from "../../protocols/dex/poolT1/adminModule/structs.sol";
import { BigMathMinified } from "../../libraries/bigMathMinified.sol";
import { Error } from "../error.sol";
import { ErrorTypes } from "../errorTypes.sol";

abstract contract Events {
    /// @notice emitted when multisig successfully changes the withdrawal limit
    event LogSetWithdrawalLimit(address dex, address user, uint256 newLimit);

    /// @notice emitted when multisig changes the withdrawal limit config
    event LogSetUserWithdrawLimit(address dex, address user, uint256 baseLimit);

    /// @notice emitted when multisig changes the borrow limit config
    event LogSetUserBorrowLimits(address dex, address user, uint256 baseLimit, uint256 maxLimit);

    /// @notice emitted when multisig changes the max borrow shares
    event LogSetMaxBorrowShares(address dex, uint256 maxBorrowShares);

    /// @notice emitted when multisig changes the max supply shares
    event LogSetMaxSupplyShares(address dex, uint256 maxSupplyShares);

    /// @notice emitted when a limits update re-instated a side pause that the pool config update had lifted
    event LogRePauseUser(address dex, address user, bool supply, bool borrow);
}

abstract contract Constants is FluidAuthLevels {
    uint256 internal constant X14 = 0x3fff;
    uint256 internal constant X18 = 0x3ffff;
    uint256 internal constant X24 = 0xffffff;

    uint256 internal constant DEFAULT_EXPONENT_SIZE = 8;
    uint256 internal constant DEFAULT_EXPONENT_MASK = 0xFF;

    /// @dev Set this to 20 for a +/-20% limit
    uint256 internal constant MAX_PERCENT_CHANGE = 20;

    /// @notice auth gate resolving multisig/governance identity; MID-level auths pass `onlyAuthLevelMid`.
    IFluidAuthGate public immutable AUTH_GATE;

    uint256 internal constant COOLDOWN_PERIOD = 4 days;
}

abstract contract Variables is Constants {
    // dex => user => lastUpdateTime for cooldown checks
    mapping(address => mapping(address => uint256)) public lastUpdateTime;
}

contract FluidLimitsAuthDex is Variables, Error, Events, BasicValidations {
    modifier onlyAuthLevelMid() {
        AUTH_GATE.requireAuthLevelMid(msg.sender);
        _;
    }

    constructor(address authGate_) validAddress(authGate_) {
        if (IFluidAuthGateLiquidity(authGate_).LIQUIDITY() == address(0)) {
            revert FluidConfigError(ErrorTypes.LimitsAuth__InvalidParams);
        }
        AUTH_GATE = IFluidAuthGate(authGate_);
    }

    /// @notice Sets the withdrawal limit for a specific user at a dex
    /// @param dex_ The address of the dex
    /// @param user_ The address of the user for which to set the withdrawal limit
    /// @param newLimit_ The new withdrawal limit to be set
    function setWithdrawalLimit(address dex_, address user_, uint256 newLimit_) external onlyAuthLevelMid {
        IFluidDexT1Admin(dex_).updateUserWithdrawalLimit(user_, newLimit_);
        emit LogSetWithdrawalLimit(dex_, user_, newLimit_);
    }

    /// @notice Sets the user withdraw base limit at a specific dex for a user (vault) without restrictions.
    ///         `updateUserSupplyConfigs` force-re-enables the user's supply side on the pool, so if that side was
    ///         paused it is re-paused within the same transaction, emitting `LogRePauseUser`.
    /// @param dex_ The address of the dex at which to set the user withdraw limit
    /// @param user_ The address of the user for which to set the user withdraw limit
    /// @param baseLimit_ The base limit for the user supply; must be non-zero.
    /// @param skipMaxPercentChangeCheck_ allow full range of limit check. Keep to false by default to have additional human error check.
    function setUserWithdrawLimit(
        address dex_,
        address user_,
        uint256 baseLimit_,
        bool skipMaxPercentChangeCheck_
    ) external onlyAuthLevelMid {
        if (baseLimit_ == 0) {
            revert FluidConfigError(ErrorTypes.LimitsAuth__InvalidParams);
        }

        AdminModuleStructs.UserSupplyConfig[] memory userSupplyConfigs = new AdminModuleStructs.UserSupplyConfig[](1);
        userSupplyConfigs[0] = getUserSupplyConfig(dex_, user_);

        if (userSupplyConfigs[0].user == address(0)) {
            // user is not defined yet
            revert FluidConfigError(ErrorTypes.LimitsAuth__UserNotDefinedYet);
        }

        if (!skipMaxPercentChangeCheck_) {
            _validateWithinMaxPercentChange(userSupplyConfigs[0].baseWithdrawalLimit, baseLimit_);
        }

        userSupplyConfigs[0].baseWithdrawalLimit = baseLimit_;

        bool wasPaused_ = _isSidePaused(dex_, user_, DexSlotsLink.DEX_USER_SUPPLY_MAPPING_SLOT);

        IFluidDexT1Admin(dex_).updateUserSupplyConfigs(userSupplyConfigs);

        emit LogSetUserWithdrawLimit(dex_, user_, userSupplyConfigs[0].baseWithdrawalLimit);

        if (wasPaused_) {
            // hard call: a failed re-pause must revert rather than leave the side open
            IFluidDexT1Admin(dex_).pauseUser(user_, true, false);

            emit LogRePauseUser(dex_, user_, true, false);
        }
    }

    /// @notice Sets the user borrow limits at a specific dex for a user (vault), with time and max percent change restrictions.
    ///         `updateUserBorrowConfigs` force-re-enables the user's borrow side on the pool, so if that side was
    ///         paused it is re-paused within the same transaction, emitting `LogRePauseUser`.
    /// @param dex_ The address of the dex at which to set the user borrow limit
    /// @param user_ The address of the user for which to set the user borrow limit
    /// @param baseLimit_ The base limit for the user borrow. Set to 0 to keep current value.
    /// @param maxLimit_ The max limit for the user borrow. Set to 0 to keep current value.
    function setUserBorrowLimits(
        address dex_,
        address user_,
        uint256 baseLimit_,
        uint256 maxLimit_
    ) external onlyAuthLevelMid {
        if (baseLimit_ == 0 && maxLimit_ == 0) {
            revert FluidConfigError(ErrorTypes.LimitsAuth__InvalidParams);
        }

        AdminModuleStructs.UserBorrowConfig[] memory userBorrowConfigs = new AdminModuleStructs.UserBorrowConfig[](1);
        userBorrowConfigs[0] = getUserBorrowConfig(dex_, user_);

        if (userBorrowConfigs[0].user == address(0)) {
            // user is not defined yet
            revert FluidConfigError(ErrorTypes.LimitsAuth__UserNotDefinedYet);
        }

        _validateLastUpdateTime(lastUpdateTime[dex_][user_]);

        if (baseLimit_ != 0) {
            _validateWithinMaxPercentChange(userBorrowConfigs[0].baseDebtCeiling, baseLimit_);
            userBorrowConfigs[0].baseDebtCeiling = baseLimit_;
        }

        if (maxLimit_ != 0) {
            _validateWithinMaxPercentChange(userBorrowConfigs[0].maxDebtCeiling, maxLimit_);
            userBorrowConfigs[0].maxDebtCeiling = maxLimit_;
        }

        lastUpdateTime[dex_][user_] = block.timestamp;

        bool wasPaused_ = _isSidePaused(dex_, user_, DexSlotsLink.DEX_USER_BORROW_MAPPING_SLOT);

        IFluidDexT1Admin(dex_).updateUserBorrowConfigs(userBorrowConfigs);

        emit LogSetUserBorrowLimits(
            dex_,
            user_,
            userBorrowConfigs[0].baseDebtCeiling,
            userBorrowConfigs[0].maxDebtCeiling
        );

        if (wasPaused_) {
            // hard call: a failed re-pause must revert rather than leave the side open
            IFluidDexT1Admin(dex_).pauseUser(user_, false, true);

            emit LogRePauseUser(dex_, user_, false, true);
        }
    }

    /// @notice Sets the max borrow shares of a DEX. To update max supply and max borrow shares at once within same coolDown, use setMaxShares.
    /// @param dex_ The address of the dex at which to set the max borrow shares
    /// @param maxBorrowShares_ The max borrow shares.
    /// @param confirmLiquidityLimitsCoverCap_  Reminder to manually confirm that the limits for the dex at liquidity layer cover the cap.
    function setMaxBorrowShares(
        address dex_,
        uint256 maxBorrowShares_,
        bool confirmLiquidityLimitsCoverCap_
    ) external onlyAuthLevelMid {
        _validateSetDexShares(dex_, confirmLiquidityLimitsCoverCap_);
        _setMaxBorrowShares(dex_, maxBorrowShares_);
    }

    /// @notice Sets the max supply shares of a DEX. To update max supply and max borrow shares at once within same coolDown, use setMaxShares.
    /// @param dex_ The address of the dex at which to set the max supply shares
    /// @param maxSupplyShares_ The max supply shares.
    /// @param confirmLiquidityLimitsCoverCap_  Reminder to manually confirm that the limits for the dex at liquidity layer cover the cap.
    function setMaxSupplyShares(
        address dex_,
        uint256 maxSupplyShares_,
        bool confirmLiquidityLimitsCoverCap_
    ) external onlyAuthLevelMid {
        _validateSetDexShares(dex_, confirmLiquidityLimitsCoverCap_);
        _setMaxSupplyShares(dex_, maxSupplyShares_);
    }

    /// @notice Sets both max borrow shares and max supply shares of a DEX at once.
    /// @param dex_ The address of the dex at which to set the max shares
    /// @param maxSupplyShares_ The max supply shares.
    /// @param maxBorrowShares_ The max borrow shares.
    /// @param confirmLiquidityLimitsCoverCap_  Reminder to manually confirm that the limits for the dex at liquidity layer cover the cap.
    function setMaxShares(
        address dex_,
        uint256 maxSupplyShares_,
        uint256 maxBorrowShares_,
        bool confirmLiquidityLimitsCoverCap_
    ) external onlyAuthLevelMid {
        _validateSetDexShares(dex_, confirmLiquidityLimitsCoverCap_);
        _setMaxSupplyShares(dex_, maxSupplyShares_);
        _setMaxBorrowShares(dex_, maxBorrowShares_);
    }

    ////////////////////////////////// INTERNAL HELPERS ////////////////////////////////////////////////////////

    /// @dev Validates parameters for setting DEX shares.
    function _validateSetDexShares(address dex_, bool confirmLiquidityLimitsCoverCap_) internal {
        if (!confirmLiquidityLimitsCoverCap_) {
            revert FluidConfigError(ErrorTypes.LimitsAuth__InvalidParams);
        }

        _validateLastUpdateTime(lastUpdateTime[dex_][dex_]);
        lastUpdateTime[dex_][dex_] = block.timestamp;
    }

    /// @dev Sets the max borrow shares for a DEX.
    function _setMaxBorrowShares(address dex_, uint256 maxBorrowShares_) internal {
        uint256 currentMaxBorrowShares_ = getMaxBorrowShares(dex_);
        _validateWithinMaxPercentChange(currentMaxBorrowShares_, maxBorrowShares_);

        IFluidDexT1Admin(dex_).updateMaxBorrowShares(maxBorrowShares_);

        emit LogSetMaxBorrowShares(dex_, maxBorrowShares_);
    }

    /// @dev Sets the max supply shares for a DEX.
    function _setMaxSupplyShares(address dex_, uint256 maxSupplyShares_) internal {
        uint256 currentMaxSupplyShares_ = getMaxSupplyShares(dex_);
        _validateWithinMaxPercentChange(currentMaxSupplyShares_, maxSupplyShares_);

        IFluidDexT1Admin(dex_).updateMaxSupplyShares(maxSupplyShares_);

        emit LogSetMaxSupplyShares(dex_, maxSupplyShares_);
    }

    /// @dev Validates that the new limit is within the allowed max percent change.
    function _validateWithinMaxPercentChange(uint256 oldLimit_, uint256 newLimit_) internal pure {
        uint256 maxDelta = (oldLimit_ * MAX_PERCENT_CHANGE) / 100; // 20% of oldLimit_

        if (newLimit_ > oldLimit_ && (newLimit_ - oldLimit_) > maxDelta) {
            revert FluidConfigError(ErrorTypes.LimitsAuth__ExceedAllowedPercentageChange);
        } else if (newLimit_ < oldLimit_ && (oldLimit_ - newLimit_) > maxDelta) {
            revert FluidConfigError(ErrorTypes.LimitsAuth__ExceedAllowedPercentageChange);
        }
    }

    /// @dev Reads bit 0 of the user's packed word at `mappingSlot_` (supply or borrow) on `dex_`. A configured user
    ///      has non-zero data, and bit 0 == 0 there means that whole side is paused.
    function _isSidePaused(address dex_, address user_, uint256 mappingSlot_) internal view returns (bool) {
        uint256 userData_ = IFluidDexT1(dex_).readFromStorage(
            DexSlotsLink.calculateMappingStorageSlot(mappingSlot_, user_)
        );

        return userData_ > 0 && userData_ & 1 == 0;
    }

    /// @dev Validates that the cooldown period has passed since the last update.
    function _validateLastUpdateTime(uint256 lastUpdateTime_) internal view {
        if (block.timestamp - lastUpdateTime_ < COOLDOWN_PERIOD) {
            revert FluidConfigError(ErrorTypes.LimitsAuth__CoolDownPending);
        }
    }

    ////////////////////////////////// GETTERS ////////////////////////////////////////////////////////

    /// @notice Get the max borrow shares of a DEX
    /// @param dex_ The address of the DEX
    /// @return The max borrow shares
    function getMaxBorrowShares(address dex_) public view returns (uint) {
        return IFluidDexT1(dex_).readFromStorage(bytes32(DexSlotsLink.DEX_TOTAL_BORROW_SHARES_SLOT)) >> 128;
    }

    /// @notice Get the max supply shares of a DEX
    /// @param dex_ The address of the DEX
    /// @return The max supply shares
    function getMaxSupplyShares(address dex_) public view returns (uint) {
        return IFluidDexT1(dex_).readFromStorage(bytes32(DexSlotsLink.DEX_TOTAL_SUPPLY_SHARES_SLOT)) >> 128;
    }

    /// @notice Returns the user supply config for a given dex and user.
    function getUserSupplyConfig(
        address dex_,
        address user_
    ) public view returns (AdminModuleStructs.UserSupplyConfig memory userSupplyConfigs_) {
        uint256 userSupply_ = IFluidDexT1(dex_).readFromStorage(
            DexSlotsLink.calculateMappingStorageSlot(DexSlotsLink.DEX_USER_SUPPLY_MAPPING_SLOT, user_)
        );

        if (userSupply_ > 0) {
            userSupplyConfigs_ = AdminModuleStructs.UserSupplyConfig({
                user: user_,
                baseWithdrawalLimit: BigMathMinified.fromBigNumber(
                    (userSupply_ >> DexSlotsLink.BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT) & X18,
                    DEFAULT_EXPONENT_SIZE,
                    DEFAULT_EXPONENT_MASK
                ),
                expandPercent: (userSupply_ >> DexSlotsLink.BITS_USER_SUPPLY_EXPAND_PERCENT) & X14,
                expandDuration: (userSupply_ >> DexSlotsLink.BITS_USER_SUPPLY_EXPAND_DURATION) & X24
            });
        }
    }

    /// @notice Returns the user borrow config for a given dex and user.
    function getUserBorrowConfig(
        address dex_,
        address user_
    ) public view returns (AdminModuleStructs.UserBorrowConfig memory userBorrowConfigs_) {
        uint256 userBorrow_ = IFluidDexT1(dex_).readFromStorage(
            DexSlotsLink.calculateMappingStorageSlot(DexSlotsLink.DEX_USER_BORROW_MAPPING_SLOT, user_)
        );

        if (userBorrow_ > 0) {
            userBorrowConfigs_ = AdminModuleStructs.UserBorrowConfig({
                user: user_,
                baseDebtCeiling: BigMathMinified.fromBigNumber(
                    (userBorrow_ >> DexSlotsLink.BITS_USER_BORROW_BASE_BORROW_LIMIT) & X18,
                    DEFAULT_EXPONENT_SIZE,
                    DEFAULT_EXPONENT_MASK
                ),
                maxDebtCeiling: BigMathMinified.fromBigNumber(
                    (userBorrow_ >> DexSlotsLink.BITS_USER_BORROW_MAX_BORROW_LIMIT) & X18,
                    DEFAULT_EXPONENT_SIZE,
                    DEFAULT_EXPONENT_MASK
                ),
                expandPercent: (userBorrow_ >> DexSlotsLink.BITS_USER_BORROW_EXPAND_PERCENT) & X14,
                expandDuration: (userBorrow_ >> DexSlotsLink.BITS_USER_BORROW_EXPAND_DURATION) & X24
            });
        }
    }
}

contracts/config/authGate/interfaces/iAuthGate.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.36;

/// @notice inherit to use the `SECURITY_LEVEL_*` constants by name.
/// @dev spaced values so future levels can slot in without renumbering consumers; checks use `>=`.
abstract contract FluidAuthLevels {
    uint256 internal constant SECURITY_LEVEL_LOW = 1;
    uint256 internal constant SECURITY_LEVEL_MID = 5;
    uint256 internal constant SECURITY_LEVEL_HIGH = 10;
    uint256 internal constant SECURITY_LEVEL_CRITICAL = 15;
    uint256 internal constant SECURITY_LEVEL_MAX = 20;
}

interface IFluidAuthGate {
    function governance() external view returns (address);

    function isGovernance(address addr_) external view returns (bool);

    function authLevel(address addr_) external view returns (uint256);

    /// @notice reverts `Access__Unauthorized` unless `authLevel(addr_)` is non-zero and
    ///         >= `minSecurityLevel_`. `SECURITY_LEVEL_MAX` is governance-only.
    function requireAuthLevel(address addr_, uint256 minSecurityLevel_) external view;

    function requireAuthLevelLow(address addr_) external view;

    function requireAuthLevelMid(address addr_) external view;

    function requireAuthLevelHigh(address addr_) external view;

    function requireAuthLevelCritical(address addr_) external view;

    function requireAuthLevelMax(address addr_) external view;
}

/// @notice the gate inherits `LIQUIDITY` as a public immutable, so its getter can't sit in `IFluidAuthGate`
interface IFluidAuthGateLiquidity {
    function LIQUIDITY() external view returns (address);
}

contracts/config/error.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

contract Error {
    error FluidConfigError(uint256 errorId_);
}

contracts/config/errorTypes.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

library ErrorTypes {
    /***********************************|
    |    ExpandPercentConfigHandler     | 
    |__________________________________*/

    /// @notice thrown when an input address is zero
    uint256 internal constant ExpandPercentConfigHandler__AddressZero = 100001;

    /// @notice thrown when an unauthorized `msg.sender` calls a protected method
    uint256 internal constant ExpandPercentConfigHandler__Unauthorized = 100002;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant ExpandPercentConfigHandler__InvalidParams = 100003;

    /// @notice thrown when no update is currently needed
    uint256 internal constant ExpandPercentConfigHandler__NoUpdate = 100004;

    /// @notice thrown when slot is not used, e.g. when borrow token is 0 there is no borrow data
    uint256 internal constant ExpandPercentConfigHandler__SlotDoesNotExist = 100005;

    /***********************************|
    |      EthenaRateConfigHandler      | 
    |__________________________________*/

    /// @notice thrown when an input address is zero
    uint256 internal constant EthenaRateConfigHandler__AddressZero = 100011;

    /// @notice thrown when an unauthorized `msg.sender` calls a protected method
    uint256 internal constant EthenaRateConfigHandler__Unauthorized = 100012;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant EthenaRateConfigHandler__InvalidParams = 100013;

    /// @notice thrown when no update is currently needed
    uint256 internal constant EthenaRateConfigHandler__NoUpdate = 100014;

    /***********************************|
    |       MaxBorrowConfigHandler      | 
    |__________________________________*/

    /// @notice thrown when an input address is zero
    uint256 internal constant MaxBorrowConfigHandler__AddressZero = 100021;

    /// @notice thrown when an unauthorized `msg.sender` calls a protected method
    uint256 internal constant MaxBorrowConfigHandler__Unauthorized = 100022;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant MaxBorrowConfigHandler__InvalidParams = 100023;

    /// @notice thrown when no update is currently needed
    uint256 internal constant MaxBorrowConfigHandler__NoUpdate = 100024;

    /***********************************|
    |       BufferRateConfigHandler     | 
    |__________________________________*/

    /// @notice thrown when an input address is zero
    uint256 internal constant BufferRateConfigHandler__AddressZero = 100031;

    /// @notice thrown when an unauthorized `msg.sender` calls a protected method
    uint256 internal constant BufferRateConfigHandler__Unauthorized = 100032;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant BufferRateConfigHandler__InvalidParams = 100033;

    /// @notice thrown when no update is currently needed
    uint256 internal constant BufferRateConfigHandler__NoUpdate = 100034;

    /// @notice thrown when rate data version is not supported
    uint256 internal constant BufferRateConfigHandler__RateVersionUnsupported = 100035;

    /***********************************|
    |          FluidRatesAuth           | 
    |__________________________________*/

    /// @notice thrown when a rate or kink change exceeds the allowed delta
    uint256 internal constant RatesAuth__AllowedDeltaExceeded = 100041;

    // 100042 (RatesAuth__Unauthorized) retired: the auth gate reverts `Access__Unauthorized` instead.
    // Still emitted by legacy deployed FluidRatesAuth versions.

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant RatesAuth__InvalidParams = 100043;

    /// @notice thrown when cooldown is not yet expired
    uint256 internal constant RatesAuth__CooldownLeft = 100044;

    /// @notice thrown when version is invalid
    uint256 internal constant RatesAuth__InvalidVersion = 100045;

    /// @notice thrown when the resolved rate config equals the current one, which would burn the cooldown for nothing
    uint256 internal constant RatesAuth__NoChange = 100046;

    /***********************************|
    |       LiquidityTokenAuth          | 
    |__________________________________*/

    /// @notice thrown when an unauthorized `msg.sender` calls a protected method
    uint256 internal constant LiquidityTokenAuth__Unauthorized = 100051;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant LiquidityTokenAuth_AlreadyInitialized = 100052;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant LiquidityTokenAuth__InvalidParams = 100053;

    /***********************************|
    |       CollectRevenueAuth          | 
    |__________________________________*/

    /// @notice thrown when an unauthorized `msg.sender` calls a protected method
    uint256 internal constant CollectRevenueAuth__Unauthorized = 100061;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant CollectRevenueAuth__InvalidParams = 100062;

    /***********************************|
    |       FluidWithdrawLimitAuth      | 
    |__________________________________*/

    /// @notice thrown when an unauthorized `msg.sender` calls a protected method
    uint256 internal constant WithdrawLimitAuth__NoUserSupply = 100071;

    /// @notice thrown when an unauthorized `msg.sender` calls a protected method
    uint256 internal constant WithdrawLimitAuth__Unauthorized = 100072;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant WithdrawLimitAuth__InvalidParams = 100073;

    /// @notice thrown when no more withdrawal limit can be set for the day
    uint256 internal constant WithdrawLimitAuth__DailyLimitReached = 100074;

    /// @notice thrown when no more withdrawal limit can be set for the hour
    uint256 internal constant WithdrawLimitAuth__HourlyLimitReached = 100075;

    /// @notice thrown when the withdrawal limit and userSupply difference exceeds 5%
    uint256 internal constant WithdrawLimitAuth__ExcessPercentageDifference = 100076;

    /***********************************|
    |       DexFeeHandler               | 
    |__________________________________*/

    /// @notice thrown when fee update is not required
    uint256 internal constant DexFeeHandler__FeeUpdateNotRequired = 100081;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant DexFeeHandler__InvalidParams = 100082;

    /// @notice thrown when an unauthorized `msg.sender` calls
    uint256 internal constant DexFeeHandler__Unauthorized = 100083;

    /***********************************|
    |           RangeAuthDex            | 
    |__________________________________*/

    uint256 internal constant RangeAuthDex__InvalidParams = 100091;
    uint256 internal constant RangeAuthDex__CooldownLeft = 100092;
    // 100093 (RangeAuthDex__Unauthorized) retired: the auth gate reverts `Access__Unauthorized` instead.
    // Still emitted by legacy deployed FluidRangeAuthDex versions.
    uint256 internal constant RangeAuthDex__ExceedAllowedPercentageChange = 100094;
    uint256 internal constant RangeAuthDex__InvalidShiftTime = 100095;
    uint256 internal constant RangeAuthDex__NoChange = 100096;

    /***********************************|
    |           FluidLimitsAuth         | 
    |__________________________________*/

    uint256 internal constant LimitsAuth__InvalidParams = 100101;
    uint256 internal constant LimitsAuth__Unauthorized = 100102;
    uint256 internal constant LimitsAuth__UserNotDefinedYet = 100103;
    uint256 internal constant LimitsAuth__ExceedAllowedPercentageChange = 100104;
    uint256 internal constant LimitsAuth__CoolDownPending = 100105;

    /***********************************|
    |          DexFeeAuth               | 
    |__________________________________*/

    /// @notice thrown when an unauthorized `msg.sender` calls
    uint256 internal constant DexFeeAuth__Unauthorized = 100111;

    /***********************************|
    |       VaultFeeRewardsAuth         | 
    |__________________________________*/

    /// @notice thrown when an unauthorized `msg.sender` calls
    uint256 internal constant VaultFeeRewardsAuth__Unauthorized = 100121;
    /// @notice thrown when magnifier or rate is being updated for a non matching vault type
    uint256 internal constant VaultFeeRewardsAuth__InvalidVaultType = 100122;

    /***********************************|
    |          FluidPauseAuth           | 
    |__________________________________*/

    /// @notice thrown when an unauthorized `msg.sender` calls a protected method
    uint256 internal constant PauseAuth__Unauthorized = 100131;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant PauseAuth__InvalidParams = 100132;

    /***********************************|
    |        FluidPauseAuthDex          | 
    |__________________________________*/

    /// @notice thrown when an unauthorized `msg.sender` calls a protected method
    uint256 internal constant PauseAuthDex__Unauthorized = 100141;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant PauseAuthDex__InvalidParams = 100142;

    /// @notice thrown when only one operation of a DEX side is requested; DEX user pause is side-level
    uint256 internal constant PauseAuthDex__PartialSideNotSupported = 100143;

    /***********************************|
    |      PaybackOnBehalfAuth          | 
    |__________________________________*/

    /// @notice thrown when an unauthorized `msg.sender` calls
    uint256 internal constant PaybackOnBehalfAuth__Unauthorized = 100151;

    /// @notice thrown when invalid params are passed into a method
    uint256 internal constant PaybackOnBehalfAuth__InvalidParams = 100152;

    /***********************************|
    |       PauseAuthOracleV2           | 
    |__________________________________*/

    /// @notice thrown when `msg.sender` is not the pause auth contract
    uint256 internal constant PauseAuthOracleV2__Unauthorized = 100161;

    /// @notice thrown when `setPauseAuthContract` was already called, or the auth gate is bound to another Liquidity
    uint256 internal constant PauseAuthOracleV2__InvalidParams = 100162;
}

contracts/libraries/bigMathMinified.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.36;

/// @title library that represents a number in BigNumber(coefficient and exponent) format to store in smaller bits.
/// @notice the number is divided into two parts: a coefficient and an exponent. This comes at a cost of losing some precision
/// at the end of the number because the exponent simply fills it with zeroes. This precision is oftentimes negligible and can
/// result in significant gas cost reduction due to storage space reduction.
/// Also note, a valid big number is as follows: if the exponent is > 0, then coefficient last bits should be occupied to have max precision.
/// @dev roundUp is more like a increase 1, which happens everytime for the same number.
/// roundDown simply sets trailing digits after coefficientSize to zero (floor), only once for the same number.
library BigMathMinified {
    /// @dev constants to use for `roundUp` input param to increase readability
    bool internal constant ROUND_DOWN = false;
    bool internal constant ROUND_UP = true;

    /// @dev converts `normal` number to BigNumber with `exponent` and `coefficient` (or precision).
    /// e.g.:
    /// 5035703444687813576399599 (normal) = (coefficient[32bits], exponent[8bits])[40bits]
    /// 5035703444687813576399599 (decimal) => 10000101010010110100000011111011110010100110100000000011100101001101001101011101111 (binary)
    ///                                     => 10000101010010110100000011111011000000000000000000000000000000000000000000000000000
    ///                                                                        ^-------------------- 51(exponent) -------------- ^
    /// coefficient = 1000,0101,0100,1011,0100,0000,1111,1011               (2236301563)
    /// exponent =                                            0011,0011     (51)
    /// bigNumber =   1000,0101,0100,1011,0100,0000,1111,1011,0011,0011     (572493200179)
    ///
    /// @param normal number which needs to be converted into Big Number
    /// @param coefficientSize at max how many bits of precision there should be (64 = uint64 (64 bits precision))
    /// @param exponentSize at max how many bits of exponent there should be (8 = uint8 (8 bits exponent))
    /// @param roundUp signals if result should be rounded down or up
    /// @return bigNumber converted bigNumber (coefficient << exponent)
    function toBigNumber(
        uint256 normal,
        uint256 coefficientSize,
        uint256 exponentSize,
        bool roundUp
    ) internal pure returns (uint256 bigNumber) {
        assembly {
            let lastBit_
            let number_ := normal
            if gt(number_, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
                number_ := shr(0x80, number_)
                lastBit_ := 0x80
            }
            if gt(number_, 0xFFFFFFFFFFFFFFFF) {
                number_ := shr(0x40, number_)
                lastBit_ := add(lastBit_, 0x40)
            }
            if gt(number_, 0xFFFFFFFF) {
                number_ := shr(0x20, number_)
                lastBit_ := add(lastBit_, 0x20)
            }
            if gt(number_, 0xFFFF) {
                number_ := shr(0x10, number_)
                lastBit_ := add(lastBit_, 0x10)
            }
            if gt(number_, 0xFF) {
                number_ := shr(0x8, number_)
                lastBit_ := add(lastBit_, 0x8)
            }
            if gt(number_, 0xF) {
                number_ := shr(0x4, number_)
                lastBit_ := add(lastBit_, 0x4)
            }
            if gt(number_, 0x3) {
                number_ := shr(0x2, number_)
                lastBit_ := add(lastBit_, 0x2)
            }
            if gt(number_, 0x1) {
                lastBit_ := add(lastBit_, 1)
            }
            if gt(number_, 0) {
                lastBit_ := add(lastBit_, 1)
            }
            if lt(lastBit_, coefficientSize) {
                // for throw exception
                lastBit_ := coefficientSize
            }
            let exponent := sub(lastBit_, coefficientSize)
            let coefficient := shr(exponent, normal)
            if and(roundUp, gt(exponent, 0)) {
                // rounding up is only needed if exponent is > 0, as otherwise the coefficient fully holds the original number
                coefficient := add(coefficient, 1)
                if eq(shl(coefficientSize, 1), coefficient) {
                    // case were coefficient was e.g. 111, with adding 1 it became 1000 (in binary) and coefficientSize 3 bits
                    // final coefficient would exceed it's size. -> reduce coefficent to 100 and increase exponent by 1.
                    coefficient := shl(sub(coefficientSize, 1), 1)
                    exponent := add(exponent, 1)
                }
            }
            if iszero(lt(exponent, shl(exponentSize, 1))) {
                // if exponent is >= exponentSize, the normal number is too big to fit within
                // BigNumber with too small sizes for coefficient and exponent
                revert(0, 0)
            }
            bigNumber := shl(exponentSize, coefficient)
            bigNumber := add(bigNumber, exponent)
        }
    }

    /// @dev get `normal` number from `bigNumber`, `exponentSize` and `exponentMask`
    function fromBigNumber(
        uint256 bigNumber,
        uint256 exponentSize,
        uint256 exponentMask
    ) internal pure returns (uint256 normal) {
        assembly {
            let coefficient := shr(exponentSize, bigNumber)
            let exponent := and(bigNumber, exponentMask)
            normal := shl(exponent, coefficient)
        }
    }

    /// @dev gets the most significant bit `lastBit` of a `normal` number (length of given number of binary format).
    /// e.g.
    /// 5035703444687813576399584 = 10000101010010110100000011111011110010100110100000000011100101001101001101011100000
    /// lastBit =                   ^---------------------------------   83   ----------------------------------------^
    function mostSignificantBit(uint256 normal) internal pure returns (uint lastBit) {
        assembly {
            let number_ := normal
            if gt(normal, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
                number_ := shr(0x80, number_)
                lastBit := 0x80
            }
            if gt(number_, 0xFFFFFFFFFFFFFFFF) {
                number_ := shr(0x40, number_)
                lastBit := add(lastBit, 0x40)
            }
            if gt(number_, 0xFFFFFFFF) {
                number_ := shr(0x20, number_)
                lastBit := add(lastBit, 0x20)
            }
            if gt(number_, 0xFFFF) {
                number_ := shr(0x10, number_)
                lastBit := add(lastBit, 0x10)
            }
            if gt(number_, 0xFF) {
                number_ := shr(0x8, number_)
                lastBit := add(lastBit, 0x8)
            }
            if gt(number_, 0xF) {
                number_ := shr(0x4, number_)
                lastBit := add(lastBit, 0x4)
            }
            if gt(number_, 0x3) {
                number_ := shr(0x2, number_)
                lastBit := add(lastBit, 0x2)
            }
            if gt(number_, 0x1) {
                lastBit := add(lastBit, 1)
            }
            if gt(number_, 0) {
                lastBit := add(lastBit, 1)
            }
        }
    }

    /// @dev gets the least significant bit `firstBit` of a `normal` number (position of rightmost 1 in binary format).
    /// e.g.
    /// 5035703444687813576399584 = 10000101010010110100000011111011110010100110100000000011100101001101001101011100000
    /// firstBit =                                                                                               ^-6--^
    function leastSignificantBit(uint256 normal) internal pure returns (uint firstBit) {
        assembly {
            // If number is 0, revert as there is no least significant bit
            if iszero(normal) {
                revert(0, 0)
            }

            // Find first set bit using binary search
            let number_ := normal
            firstBit := 0

            // Check if lower 128 bits are all zero
            if iszero(and(number_, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) {
                number_ := shr(0x80, number_)
                firstBit := 0x80
            }
            // Check if lower 64 bits are all zero
            if iszero(and(number_, 0xFFFFFFFFFFFFFFFF)) {
                number_ := shr(0x40, number_)
                firstBit := add(firstBit, 0x40)
            }
            // Check if lower 32 bits are all zero
            if iszero(and(number_, 0xFFFFFFFF)) {
                number_ := shr(0x20, number_)
                firstBit := add(firstBit, 0x20)
            }
            // Check if lower 16 bits are all zero
            if iszero(and(number_, 0xFFFF)) {
                number_ := shr(0x10, number_)
                firstBit := add(firstBit, 0x10)
            }
            // Check if lower 8 bits are all zero
            if iszero(and(number_, 0xFF)) {
                number_ := shr(0x8, number_)
                firstBit := add(firstBit, 0x8)
            }
            // Check if lower 4 bits are all zero
            if iszero(and(number_, 0xF)) {
                number_ := shr(0x4, number_)
                firstBit := add(firstBit, 0x4)
            }
            // Check if lower 2 bits are all zero
            if iszero(and(number_, 0x3)) {
                number_ := shr(0x2, number_)
                firstBit := add(firstBit, 0x2)
            }
            // Check if lowest bit is zero
            if iszero(and(number_, 0x1)) {
                firstBit := add(firstBit, 1)
            }
            // Add 1 to match the 1-based position counting
            firstBit := add(firstBit, 1)
        }
    }
}

contracts/libraries/dexCalcs.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.36;

import { BigMathMinified } from "./bigMathMinified.sol";
import { DexSlotsLink } from "./dexSlotsLink.sol";

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// @DEV ATTENTION: ON ANY CHANGES HERE, MAKE SURE THAT LOGIC IN VAULTS WILL STILL BE VALID.
// SOME CODE THERE ASSUMES DEXCALCS == LIQUIDITYCALCS.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

/// @notice implements calculation methods used for Fluid Dex such as updated withdrawal / borrow limits.
library DexCalcs {
    // constants used for BigMath conversion from and to storage
    uint256 internal constant DEFAULT_EXPONENT_SIZE = 8;
    uint256 internal constant DEFAULT_EXPONENT_MASK = 0xFF;

    uint256 internal constant FOUR_DECIMALS = 1e4;
    uint256 internal constant X14 = 0x3fff;
    uint256 internal constant X18 = 0x3ffff;
    uint256 internal constant X24 = 0xffffff;
    uint256 internal constant X33 = 0x1ffffffff;
    uint256 internal constant X64 = 0xffffffffffffffff;

    ///////////////////////////////////////////////////////////////////////////
    //////////                      CALC LIMITS                       /////////
    ///////////////////////////////////////////////////////////////////////////

    /// @dev calculates withdrawal limit before an operate execution:
    /// amount of user supply that must stay supplied (not amount that can be withdrawn).
    /// i.e. if user has supplied 100m and can withdraw 5M, this method returns the 95M, not the withdrawable amount 5M
    /// @param userSupplyData_ user supply data packed uint256 from storage
    /// @param userSupply_ current user supply amount already extracted from `userSupplyData_` and converted from BigMath
    /// @return currentWithdrawalLimit_ current withdrawal limit updated for expansion since last interaction.
    ///         returned value is in raw for with interest mode, normal amount for interest free mode!
    function calcWithdrawalLimitBeforeOperate(
        uint256 userSupplyData_,
        uint256 userSupply_
    ) internal view returns (uint256 currentWithdrawalLimit_) {
        // @dev must support handling the case where timestamp is 0 (config is set but no interactions yet).
        // first tx where timestamp is 0 will enter `if (lastWithdrawalLimit_ == 0)` because lastWithdrawalLimit_ is not set yet.
        // returning max withdrawal allowed, which is not exactly right but doesn't matter because the first interaction must be
        // a deposit anyway. Important is that it would not revert.

        // Note the first time a deposit brings the user supply amount to above the base withdrawal limit, the active limit
        // is the fully expanded limit immediately.

        // extract last set withdrawal limit
        uint256 lastWithdrawalLimit_ = (userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_PREVIOUS_WITHDRAWAL_LIMIT) &
            X64;
        lastWithdrawalLimit_ =
            (lastWithdrawalLimit_ >> DEFAULT_EXPONENT_SIZE) <<
            (lastWithdrawalLimit_ & DEFAULT_EXPONENT_MASK);
        if (lastWithdrawalLimit_ == 0) {
            // withdrawal limit is not activated. Max withdrawal allowed
            return 0;
        }

        uint256 maxWithdrawableLimit_;
        uint256 temp_;
        unchecked {
            // extract max withdrawable percent of user supply and
            // calculate maximum withdrawable amount expandPercentage of user supply at full expansion duration elapsed
            // e.g.: if 10% expandPercentage, meaning 10% is withdrawable after full expandDuration has elapsed.

            // userSupply_ needs to be at least 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
            maxWithdrawableLimit_ =
                (((userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_EXPAND_PERCENT) & X14) * userSupply_) /
                FOUR_DECIMALS;

            // time elapsed since last withdrawal limit was set (in seconds)
            // @dev last process timestamp is guaranteed to exist for withdrawal, as a supply must have happened before.
            // last timestamp can not be > current timestamp
            temp_ = block.timestamp - ((userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_LAST_UPDATE_TIMESTAMP) & X33);
        }
        // calculate withdrawable amount of expandPercent that is elapsed of expandDuration.
        // e.g. if 60% of expandDuration has elapsed, then user should be able to withdraw 6% of user supply, down to 94%.
        // Note: no explicit check for this needed, it is covered by setting minWithdrawalLimit_ if needed.
        temp_ =
            (maxWithdrawableLimit_ * temp_) /
            // extract expand duration: After this, decrement won't happen (user can withdraw 100% of withdraw limit)
            ((userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_EXPAND_DURATION) & X24); // expand duration can never be 0
        // calculate expanded withdrawal limit: last withdrawal limit - withdrawable amount.
        // Note: withdrawable amount here can grow bigger than userSupply if timeElapsed is a lot bigger than expandDuration,
        // which would cause the subtraction `lastWithdrawalLimit_ - withdrawableAmount_` to revert. In that case, set 0
        // which will cause minimum (fully expanded) withdrawal limit to be set in lines below.
        unchecked {
            // underflow explicitly checked & handled
            currentWithdrawalLimit_ = lastWithdrawalLimit_ > temp_ ? lastWithdrawalLimit_ - temp_ : 0;
            // calculate minimum withdrawal limit: minimum amount of user supply that must stay supplied at full expansion.
            // subtraction can not underflow as maxWithdrawableLimit_ is a percentage amount (<=100%) of userSupply_
            temp_ = userSupply_ - maxWithdrawableLimit_;
        }
        // if withdrawal limit is decreased below minimum then set minimum
        // (e.g. when more than expandDuration time has elapsed)
        if (temp_ > currentWithdrawalLimit_) {
            currentWithdrawalLimit_ = temp_;
        }
    }

    /// @dev calculates withdrawal limit after an operate execution:
    /// amount of user supply that must stay supplied (not amount that can be withdrawn).
    /// i.e. if user has supplied 100m and can withdraw 5M, this method returns the 95M, not the withdrawable amount 5M
    /// @param userSupplyData_ user supply data packed uint256 from storage
    /// @param userSupply_ current user supply amount already extracted from `userSupplyData_` and added / subtracted with the executed operate amount
    /// @param newWithdrawalLimit_ current withdrawal limit updated for expansion since last interaction, result from `calcWithdrawalLimitBeforeOperate`
    /// @return withdrawalLimit_ updated withdrawal limit that should be written to storage. returned value is in
    ///                          raw for with interest mode, normal amount for interest free mode!
    function calcWithdrawalLimitAfterOperate(
        uint256 userSupplyData_,
        uint256 userSupply_,
        uint256 newWithdrawalLimit_
    ) internal pure returns (uint256) {
        // temp_ => base withdrawal limit. below this, maximum withdrawals are allowed
        uint256 temp_ = (userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT) & X18;
        temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);

        // if user supply is below base limit then max withdrawals are allowed
        if (userSupply_ < temp_) {
            return 0;
        }
        // temp_ => withdrawal limit expandPercent (is in 1e2 decimals)
        temp_ = (userSupplyData_ >> DexSlotsLink.BITS_USER_SUPPLY_EXPAND_PERCENT) & X14;
        unchecked {
            // temp_ => minimum withdrawal limit: userSupply - max withdrawable limit (userSupply * expandPercent))
            // userSupply_ needs to be at least 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
            // subtraction can not underflow as maxWithdrawableLimit_ is a percentage amount (<=100%) of userSupply_
            temp_ = userSupply_ - ((userSupply_ * temp_) / FOUR_DECIMALS);
        }
        // if new (before operation) withdrawal limit is less than minimum limit then set minimum limit.
        // e.g. can happen on new deposits. withdrawal limit is instantly fully expanded in a scenario where
        // increased deposit amount outpaces withrawals.
        if (temp_ > newWithdrawalLimit_) {
            return temp_;
        }
        return newWithdrawalLimit_;
    }

    /// @dev calculates borrow limit before an operate execution:
    /// total amount user borrow can reach (not borrowable amount in current operation).
    /// i.e. if user has borrowed 50M and can still borrow 5M, this method returns the total 55M, not the borrowable amount 5M
    /// @param userBorrowData_ user borrow data packed uint256 from storage
    /// @param userBorrow_ current user borrow amount already extracted from `userBorrowData_`
    /// @return currentBorrowLimit_ current borrow limit updated for expansion since last interaction. returned value is in
    ///                             raw for with interest mode, normal amount for interest free mode!
    function calcBorrowLimitBeforeOperate(
        uint256 userBorrowData_,
        uint256 userBorrow_
    ) internal view returns (uint256 currentBorrowLimit_) {
        // @dev must support handling the case where timestamp is 0 (config is set but no interactions yet) -> base limit.
        // first tx where timestamp is 0 will end up with maxExpansionLimit_ = 0 because userBorrow = 0, so maxExpandedBorrowLimit_ = 0,
        // so currentBorrowLimit_ = 0, so it will enter currentBorrowLimit_ < temp_ when checking against base limit as expected.

        // temp_ = extract borrow expand percent (is in 1e2 decimals)
        uint256 temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_EXPAND_PERCENT) & X14;

        uint256 maxExpansionLimit_;
        uint256 maxExpandedBorrowLimit_;
        unchecked {
            // calculate max expansion limit: Max amount limit can expand to since last interaction
            // userBorrow_ needs to be at least 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
            maxExpansionLimit_ = ((userBorrow_ * temp_) / FOUR_DECIMALS);

            // calculate max borrow limit: Max point limit can increase to since last interaction
            maxExpandedBorrowLimit_ = userBorrow_ + maxExpansionLimit_;
        }

        // time elapsed since last borrow limit was set (in seconds)
        unchecked {
            // temp_ = timeElapsed_ (last timestamp can not be > current timestamp)
            temp_ = block.timestamp - ((userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_LAST_UPDATE_TIMESTAMP) & X33); // extract last update timestamp
        }

        // currentBorrowLimit_ = expandedBorrowableAmount + extract last set borrow limit
        currentBorrowLimit_ =
            // calculate borrow limit expansion since last interaction for `expandPercent` that is elapsed of `expandDuration`.
            // divisor is extract expand duration (after this, full expansion to expandPercentage happened).
            ((maxExpansionLimit_ * temp_) /
                ((userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_EXPAND_DURATION) & X24)) + // expand duration can never be 0
            //  extract last set borrow limit
            BigMathMinified.fromBigNumber(
                (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_PREVIOUS_BORROW_LIMIT) & X64,
                DEFAULT_EXPONENT_SIZE,
                DEFAULT_EXPONENT_MASK
            );

        // if timeElapsed is bigger than expandDuration, new borrow limit would be > max expansion,
        // so set to `maxExpandedBorrowLimit_` in that case.
        // also covers the case where last process timestamp = 0 (timeElapsed would simply be very big)
        if (currentBorrowLimit_ > maxExpandedBorrowLimit_) {
            currentBorrowLimit_ = maxExpandedBorrowLimit_;
        }

        // temp_ = extract base borrow limit, if current limit is below this, then set base limit as current limit
        temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_BASE_BORROW_LIMIT) & X18;
        temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);
        if (currentBorrowLimit_ < temp_) {
            return temp_;
        }

        // temp_ = extract hard max borrow limit. Above this user can never borrow (not expandable above)
        temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_MAX_BORROW_LIMIT) & X18;
        temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);
        if (currentBorrowLimit_ > temp_) {
            return temp_;
        }
    }

    /// @dev calculates borrow limit after an operate execution:
    /// total amount user borrow can reach (not borrowable amount in current operation).
    /// i.e. if user has borrowed 50M and can still borrow 5M, this method returns the total 55M, not the borrowable amount 5M
    /// @param userBorrowData_ user borrow data packed uint256 from storage
    /// @param userBorrow_ current user borrow amount already extracted from `userBorrowData_` and added / subtracted with the executed operate amount
    /// @param newBorrowLimit_ current borrow limit updated for expansion since last interaction, result from `calcBorrowLimitBeforeOperate`
    /// @return borrowLimit_ updated borrow limit that should be written to storage.
    ///                      returned value is in raw for with interest mode, normal amount for interest free mode!
    function calcBorrowLimitAfterOperate(
        uint256 userBorrowData_,
        uint256 userBorrow_,
        uint256 newBorrowLimit_
    ) internal pure returns (uint256 borrowLimit_) {
        // temp_ = extract borrow expand percent
        uint256 temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_EXPAND_PERCENT) & X14; // (is in 1e2 decimals)

        unchecked {
            // borrowLimit_ = calculate maximum borrow limit at full expansion.
            // userBorrow_ needs to be at least 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
            borrowLimit_ = userBorrow_ + ((userBorrow_ * temp_) / FOUR_DECIMALS);
        }

        // temp_ = extract base borrow limit
        temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_BASE_BORROW_LIMIT) & X18;
        temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);

        if (borrowLimit_ < temp_) {
            // below base limit, borrow limit is always base limit
            return temp_;
        }
        // temp_ = extract hard max borrow limit. Above this user can never borrow (not expandable above)
        temp_ = (userBorrowData_ >> DexSlotsLink.BITS_USER_BORROW_MAX_BORROW_LIMIT) & X18;
        temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);

        // make sure fully expanded borrow limit is not above hard max borrow limit
        if (borrowLimit_ > temp_) {
            borrowLimit_ = temp_;
        }
        // if new borrow limit (from before operate) is > max borrow limit, set max borrow limit.
        // (e.g. on a repay shrinking instantly to fully expanded borrow limit from new borrow amount. shrinking is instant)
        if (newBorrowLimit_ > borrowLimit_) {
            return borrowLimit_;
        }
        return newBorrowLimit_;
    }
}

contracts/libraries/dexSlotsLink.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.36;

/// @notice library that helps in reading / working with storage slot data of Fluid Dex.
/// @dev as all data for Fluid Dex is internal, any data must be fetched directly through manual
/// slot reading through this library or, if gas usage is less important, through the FluidDexResolver.
library DexSlotsLink {
    /// @dev storage slot for variables at Dex
    uint256 internal constant DEX_VARIABLES_SLOT = 0;
    /// @dev storage slot for variables2 at Dex
    uint256 internal constant DEX_VARIABLES2_SLOT = 1;
    /// @dev storage slot for total supply shares at Dex
    uint256 internal constant DEX_TOTAL_SUPPLY_SHARES_SLOT = 2;
    /// @dev storage slot for user supply mapping at Dex
    uint256 internal constant DEX_USER_SUPPLY_MAPPING_SLOT = 3;
    /// @dev storage slot for total borrow shares at Dex
    uint256 internal constant DEX_TOTAL_BORROW_SHARES_SLOT = 4;
    /// @dev storage slot for user borrow mapping at Dex
    uint256 internal constant DEX_USER_BORROW_MAPPING_SLOT = 5;
    /// @dev storage slot for range and threshold shifts at Dex
    uint256 internal constant DEX_RANGE_THRESHOLD_SHIFTS_SLOT = 7;
    /// @dev storage slot for center price shift at Dex
    uint256 internal constant DEX_CENTER_PRICE_SHIFT_SLOT = 8;

    // -------------------------------- DEPRECATED ----------------
    /// @dev storage slot for oracle mapping at Dex
    uint256 internal constant DEX_DEPRECATED_PREVIOUSLY_ORACLE_MAPPING_SLOT = 6; // unused in new deployments and oracle is not enabled on any dex

    // --------------------------------
    // @dev stacked uint256 storage slots bits position data for each:

    // UserSupplyData
    uint256 internal constant BITS_USER_SUPPLY_ALLOWED = 0;
    uint256 internal constant BITS_USER_SUPPLY_AMOUNT = 1;
    uint256 internal constant BITS_USER_SUPPLY_PREVIOUS_WITHDRAWAL_LIMIT = 65;
    uint256 internal constant BITS_USER_SUPPLY_LAST_UPDATE_TIMESTAMP = 129;
    uint256 internal constant BITS_USER_SUPPLY_EXPAND_PERCENT = 162;
    uint256 internal constant BITS_USER_SUPPLY_EXPAND_DURATION = 176;
    uint256 internal constant BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT = 200;

    // UserBorrowData
    uint256 internal constant BITS_USER_BORROW_ALLOWED = 0;
    uint256 internal constant BITS_USER_BORROW_AMOUNT = 1;
    uint256 internal constant BITS_USER_BORROW_PREVIOUS_BORROW_LIMIT = 65;
    uint256 internal constant BITS_USER_BORROW_LAST_UPDATE_TIMESTAMP = 129;
    uint256 internal constant BITS_USER_BORROW_EXPAND_PERCENT = 162;
    uint256 internal constant BITS_USER_BORROW_EXPAND_DURATION = 176;
    uint256 internal constant BITS_USER_BORROW_BASE_BORROW_LIMIT = 200;
    uint256 internal constant BITS_USER_BORROW_MAX_BORROW_LIMIT = 218;

    // --------------------------------

    /// @notice Calculating the slot ID for Dex contract for single mapping at `slot_` for `key_`
    function calculateMappingStorageSlot(uint256 slot_, address key_) internal pure returns (bytes32) {
        return keccak256(abi.encode(key_, slot_));
    }

    /// @notice Calculating the slot ID for Dex contract for double mapping at `slot_` for `key1_` and `key2_`
    function calculateDoubleMappingStorageSlot(
        uint256 slot_,
        address key1_,
        address key2_
    ) internal pure returns (bytes32) {
        bytes32 intermediateSlot_ = keccak256(abi.encode(key1_, slot_));
        return keccak256(abi.encode(key2_, intermediateSlot_));
    }
}

contracts/libraries/errorTypes.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.36;

library LibsErrorTypes {
    /***********************************|
    |         LiquidityCalcs            | 
    |__________________________________*/

    /// @notice thrown when supply or borrow exchange price is zero at calc token data (token not configured yet)
    uint256 internal constant LiquidityCalcs__ExchangePriceZero = 70001;

    /// @notice thrown when rate data is set to a version that is not implemented
    uint256 internal constant LiquidityCalcs__UnsupportedRateVersion = 70002;

    /// @notice thrown when the calculated borrow rate turns negative. This should never happen.
    uint256 internal constant LiquidityCalcs__BorrowRateNegative = 70003;

    /***********************************|
    |           SafeTransfer            | 
    |__________________________________*/

    /// @notice thrown when safe transfer from for an ERC20 fails
    uint256 internal constant SafeTransfer__TransferFromFailed = 71001;

    /// @notice thrown when safe transfer for an ERC20 fails
    uint256 internal constant SafeTransfer__TransferFailed = 71002;

    /***********************************|
    |         BasicValidations          | 
    |__________________________________*/

    /// @notice thrown when a passed address is the zero address
    uint256 internal constant BasicValidations__AddressZero = 72001;

    /***********************************|
    |           SafeApprove             | 
    |__________________________________*/

    /// @notice thrown when safe approve from for an ERC20 fails
    uint256 internal constant SafeApprove__ApproveFailed = 81001;
}

contracts/libraries/utils/basicValidations.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.36;

import { LibsErrorTypes as ErrorTypes } from "../errorTypes.sol";

/// @notice basic input validation modifiers for inheriting contracts.
abstract contract BasicValidations {
    error FluidBasicValidationsError(uint256 errorId_);

    modifier validAddress(address value_) {
        if (!_isValidAddress(value_)) {
            revert FluidBasicValidationsError(ErrorTypes.BasicValidations__AddressZero);
        }
        _;
    }

    function _isValidAddress(address value_) internal pure returns (bool) {
        return value_ != address(0);
    }
}

contracts/protocols/dex/interfaces/iDexT1.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.21 <=0.8.36;

interface IFluidDexT1 {
    error FluidDexError(uint256 errorId);

    /// @notice used to simulate swap to find the output amount
    error FluidDexSwapResult(uint256 amountOut);

    error FluidDexPerfectLiquidityOutput(uint256 token0Amt, uint token1Amt);

    error FluidDexSingleTokenOutput(uint256 tokenAmt);

    error FluidDexLiquidityOutput(uint256 shares);

    error FluidDexPricesAndExchangeRates(PricesAndExchangePrice pex_);

    /// @notice returns the dex id
    function DEX_ID() external view returns (uint256);

    /// @notice pool code version; reverts on pools deployed before 1.1.0
    function VERSION() external view returns (string memory);

    /// @notice reads uint256 data `result_` from storage at a bytes32 storage `slot_` key.
    function readFromStorage(bytes32 slot_) external view returns (uint256 result_);

    struct Implementations {
        address shift;
        address admin;
        address colOperations;
        address debtOperations;
        address perfectOperationsAndSwapOut; // unused, kept for compatibility purposes
    }

    struct ConstantViews {
        uint256 dexId;
        address liquidity;
        address factory;
        Implementations implementations;
        address deployerContract;
        address token0;
        address token1;
        bytes32 supplyToken0Slot;
        bytes32 borrowToken0Slot;
        bytes32 supplyToken1Slot;
        bytes32 borrowToken1Slot;
        bytes32 exchangePriceToken0Slot;
        bytes32 exchangePriceToken1Slot;
        uint256 oracleMapping;
    }

    struct ConstantViews2 {
        uint token0NumeratorPrecision;
        uint token0DenominatorPrecision;
        uint token1NumeratorPrecision;
        uint token1DenominatorPrecision;
    }

    struct PricesAndExchangePrice {
        uint lastStoredPrice; // last stored price in 1e27 decimals
        uint centerPrice; // last stored price in 1e27 decimals
        uint upperRange; // price at upper range in 1e27 decimals
        uint lowerRange; // price at lower range in 1e27 decimals
        uint geometricMean; // geometric mean of upper range & lower range in 1e27 decimals
        uint supplyToken0ExchangePrice;
        uint borrowToken0ExchangePrice;
        uint supplyToken1ExchangePrice;
        uint borrowToken1ExchangePrice;
    }

    struct CollateralReserves {
        uint token0RealReserves;
        uint token1RealReserves;
        uint token0ImaginaryReserves;
        uint token1ImaginaryReserves;
    }

    struct DebtReserves {
        uint token0Debt;
        uint token1Debt;
        uint token0RealReserves;
        uint token1RealReserves;
        uint token0ImaginaryReserves;
        uint token1ImaginaryReserves;
    }

    function getCollateralReserves(
        uint geometricMean_,
        uint upperRange_,
        uint lowerRange_,
        uint token0SupplyExchangePrice_,
        uint token1SupplyExchangePrice_
    ) external view returns (CollateralReserves memory c_);

    function getDebtReserves(
        uint geometricMean_,
        uint upperRange_,
        uint lowerRange_,
        uint token0BorrowExchangePrice_,
        uint token1BorrowExchangePrice_
    ) external view returns (DebtReserves memory d_);

    // reverts with FluidDexPricesAndExchangeRates(pex_);
    function getPricesAndExchangePrices() external;

    function constantsView() external view returns (ConstantViews memory constantsView_);

    function constantsView2() external view returns (ConstantViews2 memory constantsView2_);

    struct Oracle {
        uint twap1by0; // TWAP price
        uint lowestPrice1by0; // lowest price point
        uint highestPrice1by0; // highest price point
        uint twap0by1; // TWAP price
        uint lowestPrice0by1; // lowest price point
        uint highestPrice0by1; // highest price point
    }

    /// @dev This function allows users to swap a specific amount of input tokens for output tokens
    /// @param swap0to1_ Direction of swap. If true, swaps token0 for token1; if false, swaps token1 for token0
    /// @param amountIn_ The exact amount of input tokens to swap
    /// @param amountOutMin_ The minimum amount of output tokens the user is willing to accept
    /// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with amountOut_
    /// @return amountOut_ The amount of output tokens received from the swap
    function swapIn(
        bool swap0to1_,
        uint256 amountIn_,
        uint256 amountOutMin_,
        address to_
    ) external payable returns (uint256 amountOut_);

    /// @dev Swap tokens with perfect amount in and callback functionality
    /// @param swap0to1_ Direction of swap. If true, swaps token0 for token1; if false, swaps token1 for token0
    /// @param amountIn_ The exact amount of tokens to swap in
    /// @param amountOutMin_ The minimum amount of tokens to receive after swap
    /// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with amountOut_
    /// @return amountOut_ The amount of output tokens received from the swap
    function swapInWithCallback(
        bool swap0to1_,
        uint256 amountIn_,
        uint256 amountOutMin_,
        address to_
    ) external payable returns (uint256 amountOut_);

    /// @dev Swap tokens with perfect amount out
    /// @param swap0to1_ Direction of swap. If true, swaps token0 for token1; if false, swaps token1 for token0
    /// @param amountOut_ The exact amount of tokens to receive after swap
    /// @param amountInMax_ Maximum amount of tokens to swap in
    /// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with amountIn_
    /// @return amountIn_ The amount of input tokens used for the swap
    function swapOut(
        bool swap0to1_,
        uint256 amountOut_,
        uint256 amountInMax_,
        address to_
    ) external payable returns (uint256 amountIn_);

    /// @dev Swap tokens with perfect amount out and callback functionality
    /// @param swap0to1_ Direction of swap. If true, swaps token0 for token1; if false, swaps token1 for token0
    /// @param amountOut_ The exact amount of tokens to receive after swap
    /// @param amountInMax_ Maximum amount of tokens to swap in
    /// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with amountIn_
    /// @return amountIn_ The amount of input tokens used for the swap
    function swapOutWithCallback(
        bool swap0to1_,
        uint256 amountOut_,
        uint256 amountInMax_,
        address to_
    ) external payable returns (uint256 amountIn_);

    /// @dev Deposit tokens in equal proportion to the current pool ratio
    /// @param shares_ The number of shares to mint
    /// @param maxToken0Deposit_ Maximum amount of token0 to deposit
    /// @param maxToken1Deposit_ Maximum amount of token1 to deposit
    /// @param estimate_ If true, function will revert with estimated deposit amounts without executing the deposit
    /// @return token0Amt_ Amount of token0 deposited
    /// @return token1Amt_ Amount of token1 deposited
    function depositPerfect(
        uint shares_,
        uint maxToken0Deposit_,
        uint maxToken1Deposit_,
        bool estimate_
    ) external payable returns (uint token0Amt_, uint token1Amt_);

    /// @dev This function allows users to withdraw a perfect amount of collateral liquidity
    /// @param shares_ The number of shares to withdraw
    /// @param minToken0Withdraw_ The minimum amount of token0 the user is willing to accept
    /// @param minToken1Withdraw_ The minimum amount of token1 the user is willing to accept
    /// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with token0Amt_ & token1Amt_
    /// @return token0Amt_ The amount of token0 withdrawn
    /// @return token1Amt_ The amount of token1 withdrawn
    function withdrawPerfect(
        uint shares_,
        uint minToken0Withdraw_,
        uint minToken1Withdraw_,
        address to_
    ) external returns (uint token0Amt_, uint token1Amt_);

    /// @dev This function allows users to borrow tokens in equal proportion to the current debt pool ratio
    /// @param shares_ The number of shares to borrow
    /// @param minToken0Borrow_ Minimum amount of token0 to borrow
    /// @param minToken1Borrow_ Minimum amount of token1 to borrow
    /// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with token0Amt_ & token1Amt_
    /// @return token0Amt_ Amount of token0 borrowed
    /// @return token1Amt_ Amount of token1 borrowed
    function borrowPerfect(
        uint shares_,
        uint minToken0Borrow_,
        uint minToken1Borrow_,
        address to_
    ) external returns (uint token0Amt_, uint token1Amt_);

    /// @dev This function allows users to pay back borrowed tokens in equal proportion to the current debt pool ratio
    /// @param shares_ The number of shares to pay back
    /// @param maxToken0Payback_ Maximum amount of token0 to pay back
    /// @param maxToken1Payback_ Maximum amount of token1 to pay back
    /// @param estimate_ If true, function will revert with estimated payback amounts without executing the payback
    /// @return token0Amt_ Amount of token0 paid back
    /// @return token1Amt_ Amount of token1 paid back
    function paybackPerfect(
        uint shares_,
        uint maxToken0Payback_,
        uint maxToken1Payback_,
        bool estimate_
    ) external payable returns (uint token0Amt_, uint token1Amt_);

    /// @dev This function allows users to deposit tokens in any proportion into the col pool
    /// @param token0Amt_ The amount of token0 to deposit
    /// @param token1Amt_ The amount of token1 to deposit
    /// @param minSharesAmt_ The minimum amount of shares the user expects to receive
    /// @param estimate_ If true, function will revert with estimated shares without executing the deposit
    /// @return shares_ The amount of shares minted for the deposit
    function deposit(
        uint token0Amt_,
        uint token1Amt_,
        uint minSharesAmt_,
        bool estimate_
    ) external payable returns (uint shares_);

    /// @dev This function allows users to withdraw tokens in any proportion from the col pool
    /// @param token0Amt_ The amount of token0 to withdraw
    /// @param token1Amt_ The amount of token1 to withdraw
    /// @param maxSharesAmt_ The maximum number of shares the user is willing to burn
    /// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with shares_
    /// @return shares_ The number of shares burned for the withdrawal
    function withdraw(
        uint token0Amt_,
        uint token1Amt_,
        uint maxSharesAmt_,
        address to_
    ) external returns (uint shares_);

    /// @dev This function allows users to borrow tokens in any proportion from the debt pool
    /// @param token0Amt_ The amount of token0 to borrow
    /// @param token1Amt_ The amount of token1 to borrow
    /// @param maxSharesAmt_ The maximum amount of shares the user is willing to receive
    /// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with shares_
    /// @return shares_ The amount of borrow shares minted to represent the borrowed amount
    function borrow(uint token0Amt_, uint token1Amt_, uint maxSharesAmt_, address to_) external returns (uint shares_);

    /// @dev This function allows users to payback tokens in any proportion to the debt pool
    /// @param token0Amt_ The amount of token0 to payback
    /// @param token1Amt_ The amount of token1 to payback
    /// @param minSharesAmt_ The minimum amount of shares the user expects to burn
    /// @param estimate_ If true, function will revert with estimated shares without executing the payback
    /// @return shares_ The amount of borrow shares burned for the payback
    function payback(
        uint token0Amt_,
        uint token1Amt_,
        uint minSharesAmt_,
        bool estimate_
    ) external payable returns (uint shares_);

    /// @dev This function allows users to withdraw their collateral with perfect shares in one token
    /// @param shares_ The number of shares to burn for withdrawal
    /// @param minToken0_ The minimum amount of token0 the user expects to receive (set to 0 if withdrawing in token1)
    /// @param minToken1_ The minimum amount of token1 the user expects to receive (set to 0 if withdrawing in token0)
    /// @param to_ Recipient of swapped tokens. If to_ == address(0) then out tokens will be sent to msg.sender. If to_ == ADDRESS_DEAD then function will revert with withdrawAmt_
    /// @return withdrawAmt_ The amount of tokens withdrawn in the chosen token
    function withdrawPerfectInOneToken(
        uint shares_,
        uint minToken0_,
        uint minToken1_,
        address to_
    ) external returns (uint withdrawAmt_);

    /// @dev This function allows users to payback their debt with perfect shares in one token
    /// @param shares_ The number of shares to burn for payback
    /// @param maxToken0_ The maximum amount of token0 the user is willing to pay (set to 0 if paying back in token1)
    /// @param maxToken1_ The maximum amount of token1 the user is willing to pay (set to 0 if paying back in token0)
    /// @param estimate_ If true, the function will revert with the estimated payback amount without executing the payback
    /// @return paybackAmt_ The amount of tokens paid back in the chosen token
    function paybackPerfectInOneToken(
        uint shares_,
        uint maxToken0_,
        uint maxToken1_,
        bool estimate_
    ) external payable returns (uint paybackAmt_);

    /// @dev the oracle assumes last set price of pool till the next swap happens.
    /// There's a possibility that during that time some interest is generated hence the last stored price is not the 100% correct price for the whole duration
    /// but the difference due to interest will be super low so this difference is ignored
    /// For example 2 swaps happened 10min (600 seconds) apart and 1 token has 10% higher interest than other.
    /// then that token will accrue about 10% * 600 / secondsInAYear = ~0.0002%
    /// @param secondsAgos_ array of seconds ago for which TWAP is needed. If user sends [10, 30, 60] then twaps_ will return [10-0, 30-10, 60-30]
    /// @return twaps_ twap price, lowest price (aka minima) & highest price (aka maxima) between secondsAgo checkpoints
    /// @return currentPrice_ price of pool after the most recent swap
    function oraclePrice(uint[] memory secondsAgos_) external view returns (Oracle[] memory twaps_, uint currentPrice_);
}

contracts/protocols/dex/interfaces/iDexT1Admin.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.36;

import { Structs as AdminModuleStructs } from "../poolT1/adminModule/structs.sol";

/// @title Fluid DEX T1 Admin Interface
/// @notice Admin module methods exposed by DEX T1 pools through the pool fallback. Callable only by
///         DEX factory auths (global or per-dex).
/// @dev older config contracts keep identical local declarations; migrate them here when next touched.
interface IFluidDexT1Admin {
    function updateUserSupplyConfigs(AdminModuleStructs.UserSupplyConfig[] memory userSupplyConfigs_) external;

    function updateUserBorrowConfigs(AdminModuleStructs.UserBorrowConfig[] memory userBorrowConfigs_) external;

    /// @notice sets a new withdrawal limit as the current limit for a certain user
    /// @param user_ user address for which to update the withdrawal limit
    /// @param newLimit_ new limit until which user supply can decrease to.
    ///                  Important: input in raw. Must account for exchange price in input param calculation.
    ///                  Note any limit that is < max expansion or > current user supply will set max expansion limit or
    ///                  current user supply as limit respectively.
    ///                  - set 0 to make maximum possible withdrawable: instant full expansion, and if that goes
    ///                  below base limit then fully down to 0.
    ///                  - set type(uint256).max to make current withdrawable 0 (sets current user supply as limit).
    function updateUserWithdrawalLimit(address user_, uint256 newLimit_) external;

    function updateMaxSupplyShares(uint256 maxSupplyShares_) external;

    function updateMaxBorrowShares(uint256 maxBorrowShares_) external;

    /// @notice side-level: both operations of a paused side are blocked.
    function pauseUser(address user_, bool pauseSupply_, bool pauseBorrow_) external;

    function unpauseUser(address user_, bool unpauseSupply_, bool unpauseBorrow_) external;

    function pauseSwapAndArbitrage() external;

    function unpauseSwapAndArbitrage() external;

    function updateFeeAndRevenueCut(uint256 fee_, uint256 revenueCut_) external;

    function updateRangePercents(uint256 upperPercent_, uint256 lowerPercent_, uint256 shiftTime_) external;

    function updateThresholdPercent(
        uint256 upperThresholdPercent_,
        uint256 lowerThresholdPercent_,
        uint256 thresholdShiftTime_,
        uint256 shiftTime_
    ) external;
}

contracts/protocols/dex/poolT1/adminModule/structs.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

abstract contract Structs {
    struct InitializeVariables {
        bool smartCol;
        uint token0ColAmt;
        bool smartDebt;
        uint token0DebtAmt;
        uint centerPrice;
        uint fee;
        uint revenueCut;
        uint upperPercent;
        uint lowerPercent;
        uint upperShiftThreshold;
        uint lowerShiftThreshold;
        uint thresholdShiftTime;
        uint centerPriceAddress;
        uint hookAddress;
        uint maxCenterPrice;
        uint minCenterPrice;
    }

    /// @notice struct to set user supply & withdrawal config
    struct UserSupplyConfig {
        ///
        /// @param user address
        address user;
        ///
        /// @param expandPercent withdrawal limit expand percent. in 1e2: 100% = 10_000; 1% = 100
        /// Also used to calculate rate at which withdrawal limit should decrease (instant).
        uint256 expandPercent;
        ///
        /// @param expandDuration withdrawal limit expand duration in seconds.
        /// used to calculate rate together with expandPercent
        uint256 expandDuration;
        ///
        /// @param baseWithdrawalLimit base limit, below this, user can withdraw the entire amount.
        /// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token:
        /// with interest -> raw, without interest -> normal
        uint256 baseWithdrawalLimit;
    }

    /// @notice struct to set user borrow & payback config
    struct UserBorrowConfig {
        ///
        /// @param user address
        address user;
        ///
        /// @param expandPercent debt limit expand percent. in 1e2: 100% = 10_000; 1% = 100
        /// Also used to calculate rate at which debt limit should decrease (instant).
        uint256 expandPercent;
        ///
        /// @param expandDuration debt limit expand duration in seconds.
        /// used to calculate rate together with expandPercent
        uint256 expandDuration;
        ///
        /// @param baseDebtCeiling base borrow limit. until here, borrow limit remains as baseDebtCeiling
        /// (user can borrow until this point at once without stepped expansion). Above this, automated limit comes in place.
        /// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token:
        /// with interest -> raw, without interest -> normal
        uint256 baseDebtCeiling;
        ///
        /// @param maxDebtCeiling max borrow ceiling, maximum amount the user can borrow.
        /// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token:
        /// with interest -> raw, without interest -> normal
        uint256 maxDebtCeiling;
    }
}
Compiler settingsShow
{
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 10000000,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.