Skip to content
Verified contractExactBUSL-1.1

FluidPauseAuthDex

Address0x735ba3772c2ccc0b92ff6993bd71da88236c1495
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
24,765,029
Creation transaction
0x23c94dd9ce…18eaad095d

contracts/config/pauseAuth/pauseAuthDex.sol

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

// ==================== FluidPauseAuthDex ====================
//
// Executes pause/unpause operations at the DEX layer on behalf of FluidPauseAuth.
//
// ACCESS:
//   - Only callable by the FluidPauseAuth main contract (set once via setPauseAuthContract).
//
// CAPABILITIES:
//   - pauseSwapAndArbitrage / unpauseSwapAndArbitrage (by DEX ID) — toggles bit 255 of dexVariables2.
//   - pauseVault / unpauseVault (by vault ID) — pauses vault as user on its connected DEX supply/borrow sides.
//   - pauseSmartLending / unpauseSmartLending (by DEX ID) — pauses smart lending as supply-side user on DEX.
//   - pauseUser / unpauseUser — direct pass-through to DEX admin.
//
// BEHAVIOR:
//   - Does NOT emit operational events. Returns structured data so FluidPauseAuth can emit unified events.
//   - Pre-reads DEX storage (dexVariables2, userSupplyData, userBorrowData) to skip already-in-state ops.
//
// DEPLOYMENT:
//   - Must be set as **global auth** (or per-dex auth) on Fluid DEX Factory.
//   - FluidPauseAuth address set post-deployment via setPauseAuthContract (locked once set).
// =============================================================

import { IFluidLiquidity } from "../../liquidity/interfaces/iLiquidity.sol";
import { IFluidVaultFactory } from "../../protocols/vault/interfaces/iVaultFactory.sol";
import { IFluidDexFactory } from "../../protocols/dex/interfaces/iDexFactory.sol";
import { IFluidVault } from "../../protocols/vault/interfaces/iVault.sol";
import { FluidProtocolTypes } from "../../libraries/fluidProtocolTypes.sol";
import { DexSlotsLink } from "../../libraries/dexSlotsLink.sol";
import { Error } from "../error.sol";
import { ErrorTypes } from "../errorTypes.sol";

interface IFluidDexFactoryVerifier {
    function isDex(address dex_) external view returns (bool);
}

interface IFluidDexT1Admin {
    function pauseSwapAndArbitrage() external;
    function unpauseSwapAndArbitrage() external;
    function pauseUser(address user_, bool pauseSupply_, bool pauseBorrow_) external;
    function unpauseUser(address user_, bool unpauseSupply_, bool unpauseBorrow_) external;
    function readFromStorage(bytes32 slot_) external view returns (uint256);
}

interface IFluidSmartLendingFactory {
    function getSmartLendingAddress(uint256 dexId_) external view returns (address);
}

abstract contract Events {
    event LogSetPauseAuthContract(address indexed pauseAuthContract);
}

abstract contract Constants {
    IFluidLiquidity public immutable LIQUIDITY;
    IFluidVaultFactory public immutable VAULT_FACTORY;
    IFluidDexFactory public immutable DEX_FACTORY;
    IFluidSmartLendingFactory public immutable SMART_LENDING_FACTORY;

    /// @notice Team multisig allowed to trigger admin methods.
    address public constant TEAM_MULTISIG = 0x4F6F977aCDD1177DCD81aB83074855EcB9C2D49e;
}

abstract contract Variables is Constants {
    /// @notice FluidPauseAuth main contract. Set once by multisig, then permanently locked.
    address public pauseAuthContract;
}

/// @title   FluidPauseAuthDex
/// @notice  Executes pause/unpause operations at the DEX layer. Callable only by the main FluidPauseAuth contract.
///          Does NOT emit operational events — the main contract handles all event emission based on return values.
contract FluidPauseAuthDex is Variables, Events, Error {
    modifier validAddress(address value_) {
        if (value_ == address(0)) {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__InvalidParams);
        }
        _;
    }

    modifier onlyPauseAuthContract() {
        if (msg.sender != pauseAuthContract) {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__Unauthorized);
        }
        _;
    }

    constructor(
        address liquidity_,
        address vaultFactory_,
        address dexFactory_,
        address smartLendingFactory_
    )
        validAddress(liquidity_)
        validAddress(vaultFactory_)
        validAddress(dexFactory_)
        validAddress(smartLendingFactory_)
    {
        LIQUIDITY = IFluidLiquidity(liquidity_);
        VAULT_FACTORY = IFluidVaultFactory(vaultFactory_);
        DEX_FACTORY = IFluidDexFactory(dexFactory_);
        SMART_LENDING_FACTORY = IFluidSmartLendingFactory(smartLendingFactory_);
    }

    /// @notice Sets the FluidPauseAuth main contract address. Can only be called once (permanently locked after).
    function setPauseAuthContract(address pauseAuth_) external validAddress(pauseAuth_) {
        if (msg.sender != TEAM_MULTISIG) {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__Unauthorized);
        }
        if (pauseAuthContract != address(0)) {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__InvalidParams);
        }
        pauseAuthContract = pauseAuth_;
        emit LogSetPauseAuthContract(pauseAuth_);
    }

    // ==================== Public methods ====================

    /// @notice Pauses a vault at the DEX layer. Returns event data.
    function pauseVault(
        uint256 vaultId_,
        bool pauseSupply_,
        bool pauseBorrow_
    )
        external
        onlyPauseAuthContract
        returns (address vault_, bool actedSupply_, bool actedBorrow_, bool supplySkipped_, bool borrowSkipped_)
    {
        return _setVaultPauseState(vaultId_, pauseSupply_, pauseBorrow_, true);
    }

    /// @notice Unpauses a vault at the DEX layer. Returns event data.
    function unpauseVault(
        uint256 vaultId_,
        bool unpauseSupply_,
        bool unpauseBorrow_
    )
        external
        onlyPauseAuthContract
        returns (address vault_, bool actedSupply_, bool actedBorrow_, bool supplySkipped_, bool borrowSkipped_)
    {
        return _setVaultPauseState(vaultId_, unpauseSupply_, unpauseBorrow_, false);
    }

    /// @notice Pauses swap and arbitrage on a DEX pool. Returns event data.
    function pauseSwapAndArbitrage(
        uint256 dexId_
    ) external onlyPauseAuthContract returns (address dex_, bool alreadySet_) {
        return _setSwapPauseState(dexId_, true);
    }

    /// @notice Unpauses swap and arbitrage on a DEX pool. Returns event data.
    function unpauseSwapAndArbitrage(
        uint256 dexId_
    ) external onlyPauseAuthContract returns (address dex_, bool alreadySet_) {
        return _setSwapPauseState(dexId_, false);
    }

    /// @notice Pauses the smart lending contract on a DEX pool. Returns event data.
    function pauseSmartLending(
        uint256 dexId_
    ) external onlyPauseAuthContract returns (address dex_, address smartLending_, bool alreadySet_) {
        return _setSmartLendingPauseState(dexId_, true);
    }

    /// @notice Unpauses the smart lending contract on a DEX pool. Returns event data.
    function unpauseSmartLending(
        uint256 dexId_
    ) external onlyPauseAuthContract returns (address dex_, address smartLending_, bool alreadySet_) {
        return _setSmartLendingPauseState(dexId_, false);
    }

    /// @notice Pauses a specific user on a DEX pool. Returns the resolved dex address.
    function pauseUser(
        uint256 dexId_,
        address user_,
        bool pauseSupply_,
        bool pauseBorrow_
    ) external onlyPauseAuthContract returns (address dex_) {
        if (!pauseSupply_ && !pauseBorrow_) {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__InvalidParams);
        }
        dex_ = _getDexAddress(dexId_);
        IFluidDexT1Admin(dex_).pauseUser(user_, pauseSupply_, pauseBorrow_);
    }

    /// @notice Unpauses a specific user on a DEX pool. Returns the resolved dex address.
    function unpauseUser(
        uint256 dexId_,
        address user_,
        bool unpauseSupply_,
        bool unpauseBorrow_
    ) external onlyPauseAuthContract returns (address dex_) {
        if (!unpauseSupply_ && !unpauseBorrow_) {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__InvalidParams);
        }
        dex_ = _getDexAddress(dexId_);
        IFluidDexT1Admin(dex_).unpauseUser(user_, unpauseSupply_, unpauseBorrow_);
    }

    // ==================== Internal: shared state logic ====================

    /// @dev Shared swap & arbitrage pause/unpause logic. `wantsPaused_` == true → pause, false → unpause.
    function _setSwapPauseState(
        uint256 dexId_,
        bool wantsPaused_
    ) internal returns (address dex_, bool alreadySet_) {
        dex_ = _getDexAddress(dexId_);

        if (_isDexSwapPaused(dex_) == wantsPaused_) {
            alreadySet_ = true;
            return (dex_, alreadySet_);
        }

        if (wantsPaused_) {
            IFluidDexT1Admin(dex_).pauseSwapAndArbitrage();
        } else {
            IFluidDexT1Admin(dex_).unpauseSwapAndArbitrage();
        }
    }

    /// @dev Shared vault pause/unpause logic at DEX layer. `wantsPaused_` == true → pause, false → unpause.
    function _setVaultPauseState(
        uint256 vaultId_,
        bool supply_,
        bool borrow_,
        bool wantsPaused_
    ) internal returns (address vault_, bool actedSupply_, bool actedBorrow_, bool supplySkipped_, bool borrowSkipped_) {
        if (!supply_ && !borrow_) {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__InvalidParams);
        }

        vault_ = VAULT_FACTORY.getVaultAddress(vaultId_);
        if (vault_ == address(0)) {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__InvalidParams);
        }

        (address supplyDex_, address borrowDex_) = _getVaultDexes(vault_);
        if (supplyDex_ == address(0) && borrowDex_ == address(0)) {
            return (vault_, false, false, false, false);
        }

        bool supplyEligible_ = supply_ && supplyDex_ != address(0) && _isDexPausable(supplyDex_);
        bool borrowEligible_ = borrow_ && borrowDex_ != address(0) && _isDexPausable(borrowDex_);

        actedSupply_ = supplyEligible_ &&
            _dexUserNeedsToggle(supplyDex_, vault_, DexSlotsLink.DEX_USER_SUPPLY_MAPPING_SLOT, wantsPaused_);
        actedBorrow_ = borrowEligible_ &&
            _dexUserNeedsToggle(borrowDex_, vault_, DexSlotsLink.DEX_USER_BORROW_MAPPING_SLOT, wantsPaused_);

        if (actedSupply_ || actedBorrow_) {
            if (actedSupply_ && actedBorrow_ && supplyDex_ == borrowDex_) {
                if (wantsPaused_) {
                    IFluidDexT1Admin(supplyDex_).pauseUser(vault_, true, true);
                } else {
                    IFluidDexT1Admin(supplyDex_).unpauseUser(vault_, true, true);
                }
            } else {
                if (actedSupply_) {
                    if (wantsPaused_) {
                        IFluidDexT1Admin(supplyDex_).pauseUser(vault_, true, false);
                    } else {
                        IFluidDexT1Admin(supplyDex_).unpauseUser(vault_, true, false);
                    }
                }
                if (actedBorrow_) {
                    if (wantsPaused_) {
                        IFluidDexT1Admin(borrowDex_).pauseUser(vault_, false, true);
                    } else {
                        IFluidDexT1Admin(borrowDex_).unpauseUser(vault_, false, true);
                    }
                }
            }
        }

        supplySkipped_ = supplyEligible_ && !actedSupply_;
        borrowSkipped_ = borrowEligible_ && !actedBorrow_;
    }

    /// @dev Shared smart lending pause/unpause logic. `wantsPaused_` == true → pause, false → unpause.
    function _setSmartLendingPauseState(
        uint256 dexId_,
        bool wantsPaused_
    ) internal returns (address dex_, address smartLending_, bool alreadySet_) {
        dex_ = _getDexAddress(dexId_);

        smartLending_ = SMART_LENDING_FACTORY.getSmartLendingAddress(dexId_);
        if (smartLending_ == address(0)) {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__InvalidParams);
        }

        if (!_dexUserNeedsToggle(dex_, smartLending_, DexSlotsLink.DEX_USER_SUPPLY_MAPPING_SLOT, wantsPaused_)) {
            alreadySet_ = true;
            return (dex_, smartLending_, alreadySet_);
        }

        if (wantsPaused_) {
            IFluidDexT1Admin(dex_).pauseUser(smartLending_, true, false);
        } else {
            IFluidDexT1Admin(dex_).unpauseUser(smartLending_, true, false);
        }
    }

    // ==================== Internal: DEX helpers ====================

    /// @dev Resolves DEX address from factory. Reverts if not found.
    function _getDexAddress(uint256 dexId_) internal view returns (address dex_) {
        dex_ = DEX_FACTORY.getDexAddress(dexId_);
        if (dex_ == address(0)) {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__InvalidParams);
        }
    }

    /// @dev Returns whether a DEX address is a deployed DEX that can be interacted with.
    function _isDexPausable(address dex_) internal view returns (bool) {
        if (dex_ == address(0)) {
            return false;
        }
        try IFluidDexFactoryVerifier(address(DEX_FACTORY)).isDex(dex_) returns (bool isDex_) {
            return isDex_;
        } catch {
            return false;
        }
    }

    /// @dev Returns whether swap & arbitrage is currently paused on a DEX.
    function _isDexSwapPaused(address dex_) internal view returns (bool) {
        // dexVariables2: Last 1 bit => 255 => Pause swap & arbitrage. 1 = paused, 0 = not paused.
        uint256 dexVariables2_ = IFluidDexT1Admin(dex_).readFromStorage(bytes32(DexSlotsLink.DEX_VARIABLES2_SLOT));
        return (dexVariables2_ >> 255) == 1;
    }

    /// @dev Checks whether a user side on a DEX needs toggling. Returns true if the user is defined
    ///      and not already in the desired state.
    function _dexUserNeedsToggle(
        address dex_,
        address user_,
        uint256 mappingSlot_,
        bool wantsPaused_
    ) internal view returns (bool) {
        bytes32 slot_ = DexSlotsLink.calculateMappingStorageSlot(mappingSlot_, user_);
        // _userSupplyData / _userBorrowData: First 1 bit => 0 => is user allowed? 0 = not allowed (paused), 1 = allowed (unpaused)
        uint256 data_ = IFluidDexT1Admin(dex_).readFromStorage(slot_);
        if (data_ == 0) {
            return false;
        }
        bool isUnpaused_ = data_ & 1 == 1;
        return wantsPaused_ ? isUnpaused_ : !isUnpaused_;
    }

    /// @dev Returns whether `vault_` is a T1 vault. Falls back to true on revert (older vaults without TYPE()).
    function _isVaultT1(address vault_) internal view returns (bool) {
        try IFluidVault(vault_).TYPE() returns (uint256 type_) {
            return type_ == FluidProtocolTypes.VAULT_T1_TYPE;
        } catch {
            return true;
        }
    }

    /// @dev Resolves a vault to its connected supply-side and borrow-side DEX addresses. Reverts if unresolvable.
    ///      Returns `address(0)` for sides that go through Liquidity instead of a DEX.
    ///      T1 vaults always use Liquidity directly, so both returned values are `address(0)`.
    function _getVaultDexes(address vault_) internal view returns (address supplyDex_, address borrowDex_) {
        if (_isVaultT1(vault_)) {
            return (address(0), address(0));
        }

        try IFluidVault(vault_).constantsView() returns (IFluidVault.ConstantViews memory cv_) {
            if (cv_.supply != address(LIQUIDITY)) {
                supplyDex_ = cv_.supply;
            }
            if (cv_.borrow != address(LIQUIDITY)) {
                borrowDex_ = cv_.borrow;
            }
        } catch {
            revert FluidConfigError(ErrorTypes.PauseAuthDex__InvalidParams);
        }
    }
}

@openzeppelin/contracts/token/ERC721/IERC721.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

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 no update is currently needed
    uint256 internal constant RatesAuth__NoUpdate = 100041;

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

    /// @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;

    /***********************************|
    |       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;
    uint256 internal constant RangeAuthDex__Unauthorized = 100093;
    uint256 internal constant RangeAuthDex__ExceedAllowedPercentageChange = 100094;
    uint256 internal constant RangeAuthDex__InvalidShiftTime = 100095;

    /***********************************|
    |           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;

    /***********************************|
    |      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;
}

contracts/infiniteProxy/interfaces/iProxy.sol

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

interface IProxy {
    function setAdmin(address newAdmin_) external;

    function setDummyImplementation(address newDummyImplementation_) external;

    function addImplementation(address implementation_, bytes4[] calldata sigs_) external;

    function removeImplementation(address implementation_) external;

    function getAdmin() external view returns (address);

    function getDummyImplementation() external view returns (address);

    function getImplementationSigs(address impl_) external view returns (bytes4[] memory);

    function getSigsImplementation(bytes4 sig_) external view returns (address);

    function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
}

contracts/libraries/dexSlotsLink.sol

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

/// @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/fluidProtocolTypes.sol

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

interface IFluidProtocol {
    function TYPE() external view returns (uint256);
}

/// @notice implements helper methods to filter Fluid protocols by a certain type
library FluidProtocolTypes {
    uint256 internal constant VAULT_T1_TYPE = 10000; // VaultT1 borrow protocol type vaults
    uint256 internal constant VAULT_T2_SMART_COL_TYPE = 20000; // DEX protocol type vault
    uint256 internal constant VAULT_T3_SMART_DEBT_TYPE = 30000; // DEX protocol type vault
    uint256 internal constant VAULT_T4_SMART_COL_SMART_DEBT_TYPE = 40000; // DEX protocol type vault

    /// @dev filters input `addresses_` by protocol `type_`. Input addresses must be actual Fluid protocols, otherwise
    ///      they would be wrongly assumed to be VaultT1 even if they are not Fluid VaultT1 smart contracts.
    ///      `type_` must be a listed constant type of this library.
    ///      Example usage is to filter all vault addresses at the Vault factory by a certain type, e.g. to not include
    ///      DEX protocol type vaults.
    function filterBy(address[] memory addresses_, uint256 type_) internal view returns (address[] memory filtered_) {
        uint256 curType_;
        uint256 filteredProtocols_ = addresses_.length;
        for (uint256 i; i < addresses_.length; ) {
            try IFluidProtocol(addresses_[i]).TYPE() returns (uint256 protocolType_) {
                curType_ = protocolType_;
            } catch {
                curType_ = VAULT_T1_TYPE;
            }

            if (curType_ != type_) {
                addresses_[i] = address(0);
                --filteredProtocols_;
            }

            unchecked {
                ++i;
            }
        }

        filtered_ = new address[](filteredProtocols_);
        uint256 index_;
        unchecked {
            for (uint256 i; i < addresses_.length; ) {
                if (addresses_[i] != address(0)) {
                    filtered_[index_] = addresses_[i];
                    ++index_;
                }
                ++i;
            }
        }
    }
}

contracts/liquidity/adminModule/structs.sol

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

abstract contract Structs {
    struct AddressBool {
        address addr;
        bool value;
    }

    struct AddressUint256 {
        address addr;
        uint256 value;
    }

    /// @notice struct to set borrow rate data for version 1
    struct RateDataV1Params {
        ///
        /// @param token for rate data
        address token;
        ///
        /// @param kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100
        /// utilization below kink usually means slow increase in rate, once utilization is above kink borrow rate increases fast
        uint256 kink;
        ///
        /// @param rateAtUtilizationZero desired borrow rate when utilization is zero. in 1e2: 100% = 10_000; 1% = 100
        /// i.e. constant minimum borrow rate
        /// e.g. at utilization = 0.01% rate could still be at least 4% (rateAtUtilizationZero would be 400 then)
        uint256 rateAtUtilizationZero;
        ///
        /// @param rateAtUtilizationKink borrow rate when utilization is at kink. in 1e2: 100% = 10_000; 1% = 100
        /// e.g. when rate should be 7% at kink then rateAtUtilizationKink would be 700
        uint256 rateAtUtilizationKink;
        ///
        /// @param rateAtUtilizationMax borrow rate when utilization is maximum at 100%. in 1e2: 100% = 10_000; 1% = 100
        /// e.g. when rate should be 125% at 100% then rateAtUtilizationMax would be 12_500
        uint256 rateAtUtilizationMax;
    }

    /// @notice struct to set borrow rate data for version 2
    struct RateDataV2Params {
        ///
        /// @param token for rate data
        address token;
        ///
        /// @param kink1 first kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100
        /// utilization below kink 1 usually means slow increase in rate, once utilization is above kink 1 borrow rate increases faster
        uint256 kink1;
        ///
        /// @param kink2 second kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100
        /// utilization below kink 2 usually means slow / medium increase in rate, once utilization is above kink 2 borrow rate increases fast
        uint256 kink2;
        ///
        /// @param rateAtUtilizationZero desired borrow rate when utilization is zero. in 1e2: 100% = 10_000; 1% = 100
        /// i.e. constant minimum borrow rate
        /// e.g. at utilization = 0.01% rate could still be at least 4% (rateAtUtilizationZero would be 400 then)
        uint256 rateAtUtilizationZero;
        ///
        /// @param rateAtUtilizationKink1 desired borrow rate when utilization is at first kink. in 1e2: 100% = 10_000; 1% = 100
        /// e.g. when rate should be 7% at first kink then rateAtUtilizationKink would be 700
        uint256 rateAtUtilizationKink1;
        ///
        /// @param rateAtUtilizationKink2 desired borrow rate when utilization is at second kink. in 1e2: 100% = 10_000; 1% = 100
        /// e.g. when rate should be 7% at second kink then rateAtUtilizationKink would be 1_200
        uint256 rateAtUtilizationKink2;
        ///
        /// @param rateAtUtilizationMax desired borrow rate when utilization is maximum at 100%. in 1e2: 100% = 10_000; 1% = 100
        /// e.g. when rate should be 125% at 100% then rateAtUtilizationMax would be 12_500
        uint256 rateAtUtilizationMax;
    }

    /// @notice struct to set token config
    struct TokenConfig {
        ///
        /// @param token address
        address token;
        ///
        /// @param fee charges on borrower's interest. in 1e2: 100% = 10_000; 1% = 100
        uint256 fee;
        ///
        /// @param threshold on when to update the storage slot. in 1e2: 100% = 10_000; 1% = 100
        uint256 threshold;
        ///
        /// @param maxUtilization maximum allowed utilization. in 1e2: 100% = 10_000; 1% = 100
        ///                       set to 100% to disable and have default limit of 100% (avoiding SLOAD).
        uint256 maxUtilization;
    }

    /// @notice struct to set user supply & withdrawal config
    struct UserSupplyConfig {
        ///
        /// @param user address
        address user;
        ///
        /// @param token address
        address token;
        ///
        /// @param mode: 0 = without interest. 1 = with interest
        uint8 mode;
        ///
        /// @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 token address
        address token;
        ///
        /// @param mode: 0 = without interest. 1 = with interest
        uint8 mode;
        ///
        /// @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;
    }
}

contracts/liquidity/interfaces/iLiquidity.sol

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

import { IProxy } from "../../infiniteProxy/interfaces/iProxy.sol";
import { Structs as AdminModuleStructs } from "../adminModule/structs.sol";

interface IFluidLiquidityAdmin {
    /// @notice adds/removes auths. Auths generally could be contracts which can have restricted actions defined on contract.
    ///         auths can be helpful in reducing governance overhead where it's not needed.
    /// @param authsStatus_ array of structs setting allowed status for an address.
    ///                     status true => add auth, false => remove auth
    function updateAuths(AdminModuleStructs.AddressBool[] calldata authsStatus_) external;

    /// @notice adds/removes guardians. Only callable by Governance.
    /// @param guardiansStatus_ array of structs setting allowed status for an address.
    ///                         status true => add guardian, false => remove guardian
    function updateGuardians(AdminModuleStructs.AddressBool[] calldata guardiansStatus_) external;

    /// @notice changes the revenue collector address (contract that is sent revenue). Only callable by Governance.
    /// @param revenueCollector_  new revenue collector address
    function updateRevenueCollector(address revenueCollector_) external;

    /// @notice changes current status, e.g. for pausing or unpausing all user operations. Only callable by Auths.
    /// @param newStatus_ new status
    ///        status = 2 -> pause, status = 1 -> resume.
    function changeStatus(uint256 newStatus_) external;

    /// @notice                  update tokens rate data version 1. Only callable by Auths.
    /// @param tokensRateData_   array of RateDataV1Params with rate data to set for each token
    function updateRateDataV1s(AdminModuleStructs.RateDataV1Params[] calldata tokensRateData_) external;

    /// @notice                  update tokens rate data version 2. Only callable by Auths.
    /// @param tokensRateData_   array of RateDataV2Params with rate data to set for each token
    function updateRateDataV2s(AdminModuleStructs.RateDataV2Params[] calldata tokensRateData_) external;

    /// @notice updates token configs: fee charge on borrowers interest & storage update utilization threshold.
    ///         Only callable by Auths.
    /// @param tokenConfigs_ contains token address, fee & utilization threshold
    function updateTokenConfigs(AdminModuleStructs.TokenConfig[] calldata tokenConfigs_) external;

    /// @notice updates user classes: 0 is for new protocols, 1 is for established protocols.
    ///         Only callable by Auths.
    /// @param userClasses_ struct array of uint256 value to assign for each user address
    function updateUserClasses(AdminModuleStructs.AddressUint256[] calldata userClasses_) external;

    /// @notice sets user supply configs per token basis. Eg: with interest or interest-free and automated limits.
    ///         Only callable by Auths.
    ///         Resets decay limit to 0.
    /// @param userSupplyConfigs_ struct array containing user supply config, see `UserSupplyConfig` struct for more info
    function updateUserSupplyConfigs(AdminModuleStructs.UserSupplyConfig[] memory userSupplyConfigs_) external;

    /// @notice sets a new withdrawal limit as the current limit for a certain user. Resets decay limit to 0
    /// @param user_ user address for which to update the withdrawal limit
    /// @param token_ token 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_, address token_, uint256 newLimit_) external;

    /// @notice setting user borrow configs per token basis. Eg: with interest or interest-free and automated limits.
    ///         Only callable by Auths.
    /// @param userBorrowConfigs_ struct array containing user borrow config, see `UserBorrowConfig` struct for more info
    function updateUserBorrowConfigs(AdminModuleStructs.UserBorrowConfig[] memory userBorrowConfigs_) external;

    /// @notice pause operations for a particular user in class 0 (class 1 users can't be paused by guardians).
    /// Only callable by Guardians.
    /// @param user_          address of user to pause operations for
    /// @param supplyTokens_  token addresses to pause withdrawals for
    /// @param borrowTokens_  token addresses to pause borrowings for
    function pauseUser(address user_, address[] calldata supplyTokens_, address[] calldata borrowTokens_) external;

    /// @notice unpause operations for a particular user in class 0 (class 1 users can't be paused by guardians).
    /// Only callable by Guardians.
    /// @param user_          address of user to unpause operations for
    /// @param supplyTokens_  token addresses to unpause withdrawals for
    /// @param borrowTokens_  token addresses to unpause borrowings for
    function unpauseUser(address user_, address[] calldata supplyTokens_, address[] calldata borrowTokens_) external;

    /// @notice pause all operations for the given tokens by setting bit 255 of exchangePricesAndConfig.
    /// Only callable by Guardians.
    /// @param tokens_ token addresses to pause
    function pauseTokens(address[] calldata tokens_) external;

    /// @notice unpause operations for the given tokens by clearing bit 255 of exchangePricesAndConfig.
    /// Only callable by Guardians.
    /// @param tokens_ token addresses to unpause
    function unpauseTokens(address[] calldata tokens_) external;

    /// @notice         collects revenue for tokens to configured revenueCollector address.
    /// @param tokens_  array of tokens to collect revenue for
    /// @dev            Note that this can revert if token balance is < revenueAmount (utilization > 100%)
    function collectRevenue(address[] calldata tokens_) external;

    /// @notice gets the current updated exchange prices for n tokens and updates all prices, rates related data in storage.
    /// @param tokens_ tokens to update exchange prices for
    /// @return supplyExchangePrices_ new supply rates of overall system for each token
    /// @return borrowExchangePrices_ new borrow rates of overall system for each token
    function updateExchangePrices(
        address[] calldata tokens_
    ) external returns (uint256[] memory supplyExchangePrices_, uint256[] memory borrowExchangePrices_);
}

interface IFluidLiquidityLogic is IFluidLiquidityAdmin {
    /// @notice Single function which handles supply, withdraw, borrow & payback
    /// @param token_ address of token (0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native)
    /// @param supplyAmount_ if +ve then supply, if -ve then withdraw, if 0 then nothing
    /// @param borrowAmount_ if +ve then borrow, if -ve then payback, if 0 then nothing
    /// @param withdrawTo_ if withdrawal then to which address
    /// @param borrowTo_ if borrow then to which address
    /// @param callbackData_ callback data passed to `liquidityCallback` method of protocol
    /// @return memVar3_ updated supplyExchangePrice
    /// @return memVar4_ updated borrowExchangePrice
    /// @dev to trigger skipping in / out transfers (gas optimization):
    /// -  ` callbackData_` MUST be encoded so that "from" address is the last 20 bytes in the last 32 bytes slot,
    ///     also for native token operations where liquidityCallback is not triggered!
    ///     from address must come at last position if there is more data. I.e. encode like:
    ///     abi.encode(otherVar1, otherVar2, FROM_ADDRESS). Note dynamic types used with abi.encode come at the end
    ///     so if dynamic types are needed, you must use abi.encodePacked to ensure the from address is at the end.
    /// -   this "from" address must match withdrawTo_ or borrowTo_ and must be == `msg.sender`
    /// -   `callbackData_` must in addition to the from address as described above include bytes32 SKIP_TRANSFERS
    ///     in the slot before (bytes 32 to 63)
    /// -   `msg.value` must be 0.
    /// -   Amounts must be either:
    ///     -  supply(+) == borrow(+), withdraw(-) == payback(-).
    ///     -  Liquidity must be on the winning side (deposit < borrow OR payback < withdraw).
    function operate(
        address token_,
        int256 supplyAmount_,
        int256 borrowAmount_,
        address withdrawTo_,
        address borrowTo_,
        bytes calldata callbackData_
    ) external payable returns (uint256 memVar3_, uint256 memVar4_);

    /// @notice Same as `operate` but executes against `onBehalf_`'s position instead of msg.sender's.
    ///         Only callable by auths or governance. Token transfers still come from msg.sender:
    ///         native token uses msg.value, while ERC20 still pulls funds via msg.sender.liquidityCallback().
    ///         Only supply (+ve supplyAmount) and payback (-ve borrowAmount) are allowed; no withdrawals or borrows.
    ///         Bypasses user pause status: deposits and paybacks can be made even when the target user is paused.
    /// @param onBehalf_ the address (protocol) whose position to operate on. Must be != address(0)
    ///                   and must have a configured position (via admin) for the given token.
    /// @param token_ address of token (0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native)
    /// @param supplyAmount_ if +ve then supply, if 0 then nothing. Must be >= 0.
    /// @param borrowAmount_ if -ve then payback, if 0 then nothing. Must be <= 0.
    ///                      At least one of supplyAmount_ or borrowAmount_ must be non-zero.
    /// @param callbackData_ must be empty (length 0). Custom callbackData-powered transfer shortcuts like
    ///                      SKIP_TRANSFERS / NET_TRANSFERS are not supported for onBehalfOf.
    /// @return memVar3_ updated supplyExchangePrice
    /// @return memVar4_ updated borrowExchangePrice
    function operateOnBehalfOf(
        address onBehalf_,
        address token_,
        int256 supplyAmount_,
        int256 borrowAmount_,
        bytes calldata callbackData_
    ) external payable returns (uint256 memVar3_, uint256 memVar4_);
}

interface IFluidLiquidity is IProxy, IFluidLiquidityLogic {}

contracts/protocols/dex/interfaces/iDexFactory.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface IFluidDexFactory {
    /// @notice Global auth is auth for all dexes
    function isGlobalAuth(address auth_) external view returns (bool);

    /// @notice Dex auth is auth for a specific dex
    function isDexAuth(address vault_, address auth_) external view returns (bool);

    /// @notice Total dexes deployed.
    function totalDexes() external view returns (uint256);

    /// @notice Compute dexAddress
    function getDexAddress(uint256 dexId_) external view returns (address);

    /// @notice read uint256 `result_` for a storage `slot_` key
    function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
}

contracts/protocols/vault/interfaces/iVault.sol

//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

/// @notice common Fluid vaults interface, some methods only available for vaults > T1 (type, simulateLiquidate, rebalance is different)
interface IFluidVault {
    /// @notice returns the vault id
    function VAULT_ID() external view returns (uint256);

    /// @notice returns the vault id
    function TYPE() external view returns (uint256);

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

    struct Tokens {
        address token0;
        address token1;
    }

    struct ConstantViews {
        address liquidity;
        address factory;
        address operateImplementation;
        address adminImplementation;
        address secondaryImplementation;
        address deployer; // address which deploys oracle
        address supply; // either liquidity layer or DEX protocol
        address borrow; // either liquidity layer or DEX protocol
        Tokens supplyToken; // if smart collateral then address of token0 & token1 else just supply token address at token0 and token1 as empty
        Tokens borrowToken; // if smart debt then address of token0 & token1 else just borrow token address at token0 and token1 as empty
        uint256 vaultId;
        uint256 vaultType;
        bytes32 supplyExchangePriceSlot; // if smart collateral then slot is from DEX protocol else from liquidity layer
        bytes32 borrowExchangePriceSlot; // if smart debt then slot is from DEX protocol else from liquidity layer
        bytes32 userSupplySlot; // if smart collateral then slot is from DEX protocol else from liquidity layer
        bytes32 userBorrowSlot; // if smart debt then slot is from DEX protocol else from liquidity layer
    }

    /// @notice returns all Vault constants
    function constantsView() external view returns (ConstantViews memory constantsView_);

    /// @notice fetches the latest user position after a liquidation
    function fetchLatestPosition(
        int256 positionTick_,
        uint256 positionTickId_,
        uint256 positionRawDebt_,
        uint256 tickData_
    )
        external
        view
        returns (
            int256, // tick
            uint256, // raw debt
            uint256, // raw collateral
            uint256, // branchID_
            uint256 // branchData_
        );

    /// @notice calculates the updated vault exchange prices
    function updateExchangePrices(
        uint256 vaultVariables2_
    )
        external
        view
        returns (
            uint256 liqSupplyExPrice_,
            uint256 liqBorrowExPrice_,
            uint256 vaultSupplyExPrice_,
            uint256 vaultBorrowExPrice_
        );

    /// @notice calculates the updated vault exchange prices and writes them to storage
    function updateExchangePricesOnStorage()
        external
        returns (
            uint256 liqSupplyExPrice_,
            uint256 liqBorrowExPrice_,
            uint256 vaultSupplyExPrice_,
            uint256 vaultBorrowExPrice_
        );

    /// @notice returns the liquidity contract address
    function LIQUIDITY() external view returns (address);

    error FluidLiquidateResult(uint256 colLiquidated, uint256 debtLiquidated);

    function rebalance(
        int colToken0MinMax_,
        int colToken1MinMax_,
        int debtToken0MinMax_,
        int debtToken1MinMax_
    ) external payable returns (int supplyAmt_, int borrowAmt_);

    /// @notice reverts with FluidLiquidateResult
    function simulateLiquidate(uint debtAmt_, bool absorb_) external;
}

contracts/protocols/vault/interfaces/iVaultFactory.sol

//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import { IERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";

interface IFluidVaultFactory is IERC721Enumerable {
    /// @notice Minting an NFT Vault for the user
    function mint(uint256 vaultId_, address user_) external returns (uint256 tokenId_);

    /// @notice returns owner of Vault which is also an NFT
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /// @notice Global auth is auth for all vaults
    function isGlobalAuth(address auth_) external view returns (bool);

    /// @notice Vault auth is auth for a specific vault
    function isVaultAuth(address vault_, address auth_) external view returns (bool);

    /// @notice Total vaults deployed.
    function totalVaults() external view returns (uint256);

    /// @notice Compute vaultAddress
    function getVaultAddress(uint256 vaultId) external view returns (address);

    /// @notice read uint256 `result_` for a storage `slot_` key
    function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
}
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.