Skip to content
Verified contractPartialUNLICENSED

Provisioner

Address0x74c4a66ce4f4779b11e7c63d42e51eeef3a80d11
Balance

0 ETH

 

Transactions

271

 

Compiler

solc 0.8.29

 

Same code

5 more contracts

 

Details

Compiler
solc 0.8.29+commit.ab55807c
Language
solidity
Optimization
Yes, 100,000 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
23,971,333
Creation transaction
0x8da0ba49dc…ee79b88441

28 files

src/core/Provisioner.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

import { IERC20 } from "@oz/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@oz/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuardTransient } from "@oz/utils/ReentrancyGuardTransient.sol";

import { Math } from "@oz/utils/math/Math.sol";
import { BitMaps } from "@oz/utils/structs/BitMaps.sol";
import { Authority } from "@solmate/auth/Auth.sol";
import { Auth2Step } from "src/core/Auth2Step.sol";

import {
    AUTO_PRICE_FIXED_PRICE_FLAG,
    DEPOSIT_REDEEM_FLAG,
    MAX_DEPOSIT_REFUND_TIMEOUT,
    MAX_SECONDS_TO_DEADLINE,
    MIN_DEPOSIT_MULTIPLIER,
    MIN_REDEEM_MULTIPLIER,
    ONE_IN_BPS,
    ONE_UNIT
} from "src/core/Constants.sol";
import { Request, RequestType, TokenDetails } from "src/core/Types.sol";
import { IMultiDepositorVault } from "src/core/interfaces/IMultiDepositorVault.sol";
import { IPriceAndFeeCalculator } from "src/core/interfaces/IPriceAndFeeCalculator.sol";
import { IProvisioner } from "src/core/interfaces/IProvisioner.sol";

/// @title Provisioner
/// @notice Entry and exit point for {MultiDepositorVault}. Handles all deposits and redemptions
/// Uses {IPriceAndFeeCalculator} to convert between tokens and vault units. Supports both sync and async deposits; only
/// async redeems. Manages deposit caps, refund timeouts, and request replay protection. All assets must flow through
/// this contract to enter or exit the vault. Sync deposits are processed instantly, but stay refundable for a period of
/// time. Async requests can either be solved by authorized solvers, going through the vault, or directly by anyone
/// willing to pay units (for deposits) or tokens (for redeems), pocketing the solver tip, always paid in tokens
contract Provisioner is IProvisioner, Auth2Step, ReentrancyGuardTransient {
    using SafeERC20 for IERC20;
    using BitMaps for BitMaps.BitMap;

    ////////////////////////////////////////////////////////////
    //                         Immutables                     //
    ////////////////////////////////////////////////////////////

    /// @notice The price and fee calculator contract
    IPriceAndFeeCalculator public immutable PRICE_FEE_CALCULATOR;

    /// @notice The multi depositor vault contract
    address public immutable MULTI_DEPOSITOR_VAULT;

    ////////////////////////////////////////////////////////////
    //                         Storage                        //
    ////////////////////////////////////////////////////////////

    /// @notice Mapping of token to token details
    mapping(IERC20 token => TokenDetails details) public tokensDetails;

    /// @notice Maximum total value of deposits in numeraire terms
    uint256 public depositCap;

    /// @notice Time period in seconds during which sync deposits can be refunded
    uint256 public depositRefundTimeout;

    /// @notice Mapping of active sync deposit hashes
    /// @dev True if a sync deposit is active with the hashed parameters
    mapping(bytes32 syncDepositHash => bool exists) public syncDepositHashes;

    /// @notice Mapping of async deposit hash to its existence
    /// @dev True if deposit request exists, false if it was refunded or solved
    mapping(bytes32 asyncDepositHash => bool exists) public asyncDepositHashes;

    /// @notice Mapping of async redeem hash to its existence
    /// @dev True if redeem request exists, false if it was refunded or solved
    mapping(bytes32 asyncRedeemHash => bool exists) public asyncRedeemHashes;

    /// @notice Mapping of user address to timestamp until which their units are locked
    mapping(address user => uint256 unitsLockedUntil) public userUnitsRefundableUntil;

    ////////////////////////////////////////////////////////////
    //                       Modifiers                        //
    ////////////////////////////////////////////////////////////

    /// @notice Ensures the caller is not the vault
    modifier anyoneButVault() {
        // Requirements: check that the caller is not the vault
        require(msg.sender != MULTI_DEPOSITOR_VAULT, Aera__CallerIsVault());
        _;
    }

    constructor(
        IPriceAndFeeCalculator priceAndFeeCalculator,
        address multiDepositorVault,
        address owner_,
        Authority authority_
    ) Auth2Step(owner_, authority_) {
        // Requirements: immutables are not zero addresses
        require(address(priceAndFeeCalculator) != address(0), Aera__ZeroAddressPriceAndFeeCalculator());
        require(multiDepositorVault != address(0), Aera__ZeroAddressMultiDepositorVault());

        // Effects: set immutables
        PRICE_FEE_CALCULATOR = priceAndFeeCalculator;
        MULTI_DEPOSITOR_VAULT = multiDepositorVault;
    }

    ////////////////////////////////////////////////////////////
    //              Public / External Functions               //
    ////////////////////////////////////////////////////////////

    /// @inheritdoc IProvisioner
    function deposit(IERC20 token, uint256 tokensIn, uint256 minUnitsOut)
        external
        anyoneButVault
        returns (uint256 unitsOut)
    {
        // Requirements: token amount and min units out are positive
        require(tokensIn != 0, Aera__TokensInZero());
        require(minUnitsOut != 0, Aera__MinUnitsOutZero());

        // Requirements: sync deposits are enabled
        TokenDetails storage tokenDetails = _requireSyncDepositsEnabled(token);

        // Interactions: convert token amount to units out
        unitsOut = _tokensToUnitsFloorIfActive(token, tokensIn, tokenDetails.depositMultiplier);
        // Requirements: units out meets min units out
        require(unitsOut >= minUnitsOut, Aera__MinUnitsOutNotMet());
        // Requirements + interactions: convert new total units to numeraire and check against deposit cap
        _requireDepositCapNotExceeded(unitsOut);

        // Effects + interactions: sync deposit
        _syncDeposit(token, tokensIn, unitsOut);
    }

    /// @inheritdoc IProvisioner
    function mint(IERC20 token, uint256 unitsOut, uint256 maxTokensIn)
        external
        anyoneButVault
        returns (uint256 tokensIn)
    {
        // Requirements: tokens and units amount are positive
        require(unitsOut != 0, Aera__UnitsOutZero());
        require(maxTokensIn != 0, Aera__MaxTokensInZero());

        // Requirements: sync deposits are enabled
        TokenDetails storage tokenDetails = _requireSyncDepositsEnabled(token);

        // Requirements + interactions: convert new total units to numeraire and check against deposit cap
        _requireDepositCapNotExceeded(unitsOut);
        // Interactions: convert units to tokens
        tokensIn = _unitsToTokensCeilIfActive(token, unitsOut, tokenDetails.depositMultiplier);
        // Requirements: token in is less than or equal to max tokens in
        require(tokensIn <= maxTokensIn, Aera__MaxTokensInExceeded());

        // Effects + interactions: sync deposit
        _syncDeposit(token, tokensIn, unitsOut);
    }

    /// @inheritdoc IProvisioner
    function refundDeposit(
        address sender,
        IERC20 token,
        uint256 tokenAmount,
        uint256 unitsAmount,
        uint256 refundableUntil
    ) external requiresAuth {
        // Requirements: refundable timestamp is in the future
        require(refundableUntil >= block.timestamp, Aera__RefundPeriodExpired());

        bytes32 depositHash = _getDepositHash(sender, token, tokenAmount, unitsAmount, refundableUntil);
        // Requirements: hash has been set
        require(syncDepositHashes[depositHash], Aera__DepositHashNotFound());
        // Effects: unset hash as used
        syncDepositHashes[depositHash] = false;

        // Interactions: exit vault
        IMultiDepositorVault(MULTI_DEPOSITOR_VAULT).exit(sender, token, tokenAmount, unitsAmount, sender);

        // Log emit deposit refunded event
        emit DirectDepositRefunded(depositHash);
    }

    /// @inheritdoc IProvisioner
    function requestDeposit(
        IERC20 token,
        uint256 tokensIn,
        uint256 minUnitsOut,
        uint256 solverTip,
        uint256 deadline,
        uint256 maxPriceAge,
        bool isFixedPrice
    ) external anyoneButVault {
        // Requirements: token amount and min units out are positive, deadline is in the future, deadline is not too far
        // in the future, async deposits are enabled, vault is not paused in the PriceAndFeeCalculator
        require(tokensIn != 0, Aera__TokensInZero());
        require(minUnitsOut != 0, Aera__MinUnitsOutZero());
        require(deadline > block.timestamp, Aera__DeadlineInPast());
        unchecked {
            require(deadline - block.timestamp <= MAX_SECONDS_TO_DEADLINE, Aera__DeadlineTooFarInFuture());
        }
        require(tokensDetails[token].asyncDepositEnabled, Aera__AsyncDepositDisabled());
        require(!PRICE_FEE_CALCULATOR.isVaultPaused(MULTI_DEPOSITOR_VAULT), Aera__PriceAndFeeCalculatorVaultPaused());
        require(solverTip == 0 || !isFixedPrice, Aera__FixedPriceSolverTipNotAllowed());

        // Interactions: transfer tokens from sender to provisioner
        token.safeTransferFrom(msg.sender, address(this), tokensIn);

        RequestType requestType = isFixedPrice ? RequestType.DEPOSIT_FIXED_PRICE : RequestType.DEPOSIT_AUTO_PRICE;

        bytes32 depositHash = _getRequestHashParams(
            token, msg.sender, requestType, tokensIn, minUnitsOut, solverTip, deadline, maxPriceAge
        );
        // Requirements: hash has not been used
        require(!asyncDepositHashes[depositHash], Aera__HashCollision());
        // Effects: set hash as used
        asyncDepositHashes[depositHash] = true;

        // Log emit deposit requested event
        emit DepositRequested(
            msg.sender, token, tokensIn, minUnitsOut, solverTip, deadline, maxPriceAge, isFixedPrice, depositHash
        );
    }

    /// @inheritdoc IProvisioner
    function requestRedeem(
        IERC20 token,
        uint256 unitsIn,
        uint256 minTokensOut,
        uint256 solverTip,
        uint256 deadline,
        uint256 maxPriceAge,
        bool isFixedPrice
    ) external anyoneButVault {
        // Requirements: units amount is positive, min token out is positive, deadline is in the future, deadline is not
        // too far in the future, async withdrawals are enabled, vault is not paused in the PriceAndFeeCalculator
        require(unitsIn != 0, Aera__UnitsInZero());
        require(minTokensOut != 0, Aera__MinTokenOutZero());
        require(deadline > block.timestamp, Aera__DeadlineInPast());
        unchecked {
            require(deadline - block.timestamp <= MAX_SECONDS_TO_DEADLINE, Aera__DeadlineTooFarInFuture());
        }
        require(tokensDetails[token].asyncRedeemEnabled, Aera__AsyncRedeemDisabled());
        require(!PRICE_FEE_CALCULATOR.isVaultPaused(MULTI_DEPOSITOR_VAULT), Aera__PriceAndFeeCalculatorVaultPaused());
        require(solverTip == 0 || !isFixedPrice, Aera__FixedPriceSolverTipNotAllowed());

        // Interactions: transfer units from sender to provisioner
        IERC20(MULTI_DEPOSITOR_VAULT).safeTransferFrom(msg.sender, address(this), unitsIn);

        RequestType requestType = isFixedPrice ? RequestType.REDEEM_FIXED_PRICE : RequestType.REDEEM_AUTO_PRICE;

        bytes32 redeemHash = _getRequestHashParams(
            token, msg.sender, requestType, minTokensOut, unitsIn, solverTip, deadline, maxPriceAge
        );
        // Requirements: hash has not been used
        require(!asyncRedeemHashes[redeemHash], Aera__HashCollision());
        // Effects: set hash as used
        asyncRedeemHashes[redeemHash] = true;

        // Log emit redeem requested event
        emit RedeemRequested(
            msg.sender, token, minTokensOut, unitsIn, solverTip, deadline, maxPriceAge, isFixedPrice, redeemHash
        );
    }

    /// @inheritdoc IProvisioner
    function refundRequest(IERC20 token, Request calldata request) external nonReentrant {
        // Requirements: deadline is in the past or authorized
        require(
            request.deadline < block.timestamp || isAuthorized(msg.sender, msg.sig),
            Aera__DeadlineInFutureAndUnauthorized()
        );

        bytes32 requestHash = _getRequestHash(token, request);

        if (_isRequestTypeDeposit(request.requestType)) {
            // Requirements: hash has been set
            require(asyncDepositHashes[requestHash], Aera__HashNotFound());
            // Effects: unset hash as used
            asyncDepositHashes[requestHash] = false;
            // Interactions: transfer tokens from provisioner to sender
            token.safeTransfer(request.user, request.tokens);
            // Log emit deposit refunded event
            emit DepositRefunded(requestHash);
        } else {
            // Requirements: hash has been set
            require(asyncRedeemHashes[requestHash], Aera__HashNotFound());
            // Effects: unset hash as used
            asyncRedeemHashes[requestHash] = false;
            // Interactions: transfer units from provisioner to sender
            IERC20(MULTI_DEPOSITOR_VAULT).safeTransfer(request.user, request.units);
            // Log emit redeem refunded event
            emit RedeemRefunded(requestHash);
        }
    }

    /// @inheritdoc IProvisioner
    // solhint-disable code-complexity
    function solveRequestsVault(IERC20 token, Request[] calldata requests) external requiresAuth nonReentrant {
        // Interactions: get price age
        uint256 priceAge = PRICE_FEE_CALCULATOR.getVaultsPriceAge(MULTI_DEPOSITOR_VAULT);

        uint256 solverTip;
        Request calldata request;

        uint256 length = requests.length;
        TokenDetails memory tokenDetails = tokensDetails[token];
        bool depositsExist;
        for (uint256 i = 0; i < length; i++) {
            request = requests[i];
            if (_isRequestTypeDeposit(request.requestType)) {
                // Requirements: async deposit is enabled
                if (!tokenDetails.asyncDepositEnabled) {
                    // Log emit async deposit disabled event
                    emit AsyncDepositDisabled(i);
                    continue;
                }

                if (!depositsExist) {
                    depositsExist = true;
                    token.forceApprove(MULTI_DEPOSITOR_VAULT, type(uint256).max);
                }

                if (_isRequestTypeAutoPrice(request.requestType)) {
                    // Requirements + Effects + Interactions: solve auto price deposit
                    solverTip +=
                        _solveDepositVaultAutoPrice(token, tokenDetails.depositMultiplier, request, priceAge, i);
                } else {
                    // Requirements + Effects + Interactions: solve fixed price deposit
                    solverTip +=
                        _solveDepositVaultFixedPrice(token, tokenDetails.depositMultiplier, request, priceAge, i);
                }
            } else {
                // Requirements: async redeem is enabled
                if (!tokenDetails.asyncRedeemEnabled) {
                    // Log emit async redeem disabled event
                    emit AsyncRedeemDisabled(i);
                    continue;
                }

                if (_isRequestTypeAutoPrice(request.requestType)) {
                    // Requirements + Effects + Interactions: solve auto price redeem
                    solverTip += _solveRedeemVaultAutoPrice(token, tokenDetails.redeemMultiplier, request, priceAge, i);
                } else {
                    // Requirements + Effects + Interactions: solve fixed price redeem
                    solverTip += _solveRedeemVaultFixedPrice(token, tokenDetails.redeemMultiplier, request, priceAge, i);
                }
            }
        }

        if (solverTip != 0) {
            // Interactions: transfer solver tip from provisioner to sender
            token.safeTransfer(msg.sender, solverTip);
        }

        if (depositsExist) {
            // Interactions: set approval to 0
            token.forceApprove(MULTI_DEPOSITOR_VAULT, 0);
        }
    }

    /// @inheritdoc IProvisioner
    function solveRequestsDirect(IERC20 token, Request[] calldata requests) external nonReentrant {
        // Requirements: vault is not paused in the priceAndFeeCalculator
        require(!PRICE_FEE_CALCULATOR.isVaultPaused(MULTI_DEPOSITOR_VAULT), Aera__PriceAndFeeCalculatorVaultPaused());

        uint256 length = requests.length;
        TokenDetails storage tokenDetails = tokensDetails[token];
        for (uint256 i = 0; i < length; i++) {
            if (_isRequestTypeDeposit(requests[i].requestType)) {
                // Requirements: async deposit is enabled
                require(tokenDetails.asyncDepositEnabled, Aera__AsyncDepositDisabled());
                // Requirements: direct deposits can only solve fixed price requests
                require(!_isRequestTypeAutoPrice(requests[i].requestType), Aera__AutoPriceSolveNotAllowed());
                // Requirements + Effects + Interactions: solve direct deposit
                _solveDepositDirect(token, requests[i]);
            } else {
                // Requirements: async redeem is enabled
                require(tokenDetails.asyncRedeemEnabled, Aera__AsyncRedeemDisabled());
                // Requirements: direct redeems can only solve fixed price requests
                require(!_isRequestTypeAutoPrice(requests[i].requestType), Aera__AutoPriceSolveNotAllowed());
                // Requirements + Effects + Interactions: solve direct redeem
                _solveRedeemDirect(token, requests[i]);
            }
        }
    }

    /// @inheritdoc IProvisioner
    function setDepositDetails(uint256 depositCap_, uint256 depositRefundTimeout_) external requiresAuth {
        // Requirements: deposit cap is not zero
        require(depositCap_ != 0, Aera__DepositCapZero());
        // Requirements: deposit refund timeout does not exceed the safety cap
        require(depositRefundTimeout_ <= MAX_DEPOSIT_REFUND_TIMEOUT, Aera__MaxDepositRefundTimeoutExceeded());

        // Effects: set deposit cap and refund timeout
        depositCap = depositCap_;
        depositRefundTimeout = depositRefundTimeout_;

        // Log emit deposit details updated event
        emit DepositDetailsUpdated(depositCap_, depositRefundTimeout_);
    }

    /// @inheritdoc IProvisioner
    function setTokenDetails(IERC20 token, TokenDetails calldata details) external requiresAuth {
        // Requirements: check that the token is not the vault’s own unit token
        require(address(token) != MULTI_DEPOSITOR_VAULT, Aera__InvalidToken());

        uint256 depositMultiplier = details.depositMultiplier;
        // Requirements: deposit multiplier is greater than or equal to min deposit multiplier
        require(depositMultiplier >= MIN_DEPOSIT_MULTIPLIER, Aera__DepositMultiplierTooLow());
        require(depositMultiplier <= ONE_IN_BPS, Aera__DepositMultiplierTooHigh());
        uint256 redeemMultiplier = details.redeemMultiplier;
        // Requirements: redeem multiplier is greater than or equal to min redeem multiplier
        require(redeemMultiplier >= MIN_REDEEM_MULTIPLIER, Aera__RedeemMultiplierTooLow());
        // Requirements: redeem multiplier is less than or equal to one in BPS
        require(redeemMultiplier <= ONE_IN_BPS, Aera__RedeemMultiplierTooHigh());

        // Effects: set token details
        tokensDetails[token] = details;

        if (details.asyncRedeemEnabled || details.asyncDepositEnabled || details.syncDepositEnabled) {
            // Requirements: check that the token can be priced
            // convertUnitsToToken instead of convertTokensToUnits to avoid having to call token.decimals()
            require(
                PRICE_FEE_CALCULATOR.convertUnitsToToken(MULTI_DEPOSITOR_VAULT, token, ONE_UNIT) != 0,
                Aera__TokenCantBePriced()
            );
        }

        // Log emit token details set event
        emit TokenDetailsSet(token, details);
    }

    /// @inheritdoc IProvisioner
    function removeToken(IERC20 token) external requiresAuth {
        // Effects: remove tokensDetails
        delete tokensDetails[token];

        // Log emit token removed event
        emit TokenRemoved(token);
    }

    /// @inheritdoc IProvisioner
    function maxDeposit() external view returns (uint256) {
        // Interactions: get current total supply
        uint256 totalSupply = IERC20(MULTI_DEPOSITOR_VAULT).totalSupply();
        // Interactions: convert total supply to numeraire
        uint256 totalAssets = PRICE_FEE_CALCULATOR.convertUnitsToNumeraire(MULTI_DEPOSITOR_VAULT, totalSupply);

        // Return max of 0 or difference between deposit cap and total assets
        return totalAssets < depositCap ? depositCap - totalAssets : 0;
    }

    /// @inheritdoc IProvisioner
    function areUserUnitsLocked(address user) external view returns (bool) {
        return userUnitsRefundableUntil[user] >= block.timestamp;
    }

    /// @inheritdoc IProvisioner
    function getDepositHash(
        address user,
        IERC20 token,
        uint256 tokenAmount,
        uint256 unitsAmount,
        uint256 refundableUntil
    ) external pure returns (bytes32) {
        return _getDepositHash(user, token, tokenAmount, unitsAmount, refundableUntil);
    }

    /// @inheritdoc IProvisioner
    function getRequestHash(IERC20 token, Request calldata request) external pure returns (bytes32) {
        return _getRequestHash(token, request);
    }

    ////////////////////////////////////////////////////////////
    //              Internal / Private Functions              //
    ////////////////////////////////////////////////////////////

    /// @notice Handles a synchronous deposit, records the deposit hash, and enters the vault
    /// @dev Reverts if the deposit hash already exists. Sets the refundable period for the user
    /// @param token The ERC20 token to deposit
    /// @param tokenAmount The amount of tokens to deposit
    /// @param unitAmount The amount of vault units to mint for the user
    function _syncDeposit(IERC20 token, uint256 tokenAmount, uint256 unitAmount) internal {
        uint256 refundableUntil = block.timestamp + depositRefundTimeout;
        bytes32 depositHash = _getDepositHash(msg.sender, token, tokenAmount, unitAmount, refundableUntil);

        // Requirements: deposit hash is not set
        require(!syncDepositHashes[depositHash], Aera__HashCollision());
        // Effects: set hash as used
        syncDepositHashes[depositHash] = true;

        // Effects: set user refundable until
        userUnitsRefundableUntil[msg.sender] = refundableUntil;

        // Interactions: enter vault
        IMultiDepositorVault(MULTI_DEPOSITOR_VAULT).enter(msg.sender, token, tokenAmount, unitAmount, msg.sender);

        // Log emit deposit event
        emit Deposited(msg.sender, token, tokenAmount, unitAmount, depositHash);
    }

    /// @notice Solves an async deposit request for the vault, transfering tokens or refunding as needed
    /// @dev
    /// - Returns 0 if any of:
    ///   - price age is too high, emits PriceAgeExceeded
    ///   - request hash is not set, emits InvalidRequestHash
    ///   - units out is less than min required, emits AmountBoundExceeded
    ///   - deposit cap would be exceeded, emits DepositCapExceeded
    /// - If deadline not passed, processes deposit and emits DepositSolved
    /// - If deadline passed, refunds and emits DepositRefunded
    /// - Always unsets hash after processing
    /// @param token The ERC20 token being deposited
    /// @param depositMultiplier The multiplier (in BPS) applied to the deposit for premium calculation
    /// @param request The deposit request struct containing all user parameters
    /// @param priceAge The age of the price data used for conversion
    /// @param index The index of the request in the given solving batch
    /// @return solverTip The tip amount paid to the solver, or 0 if not processed
    function _solveDepositVaultAutoPrice(
        IERC20 token,
        uint256 depositMultiplier,
        Request calldata request,
        uint256 priceAge,
        uint256 index
    ) internal returns (uint256 solverTip) {
        // Requirements: price age is within user specified max price age
        if (_guardPriceAge(priceAge, request.maxPriceAge, index)) return 0;

        bytes32 depositHash = _getRequestHash(token, request);
        // Requirements: hash has been set
        if (_guardInvalidRequestHash(asyncDepositHashes[depositHash], depositHash)) return 0;

        if (request.deadline >= block.timestamp) {
            solverTip = request.solverTip;
            uint256 tokens = request.tokens;

            // Requirements: tokens are enough for tip
            if (_guardInsufficientTokensForTip(tokens, solverTip, index)) return 0;

            uint256 tokensAfterTip;
            unchecked {
                tokensAfterTip = tokens - solverTip;
            }

            // Interactions: apply premium and convert tokens in to units out
            uint256 unitsOut = _tokensToUnitsFloorIfActive(token, tokensAfterTip, depositMultiplier);
            // Requirements: units out meets min units out
            if (_guardAmountBound(unitsOut, request.units, index)) return 0;
            // Requirements + interactions: convert new total units to numeraire and check against deposit cap
            if (_guardDepositCapExceeded(unitsOut, index)) return 0;

            // Effects: unset hash as used
            asyncDepositHashes[depositHash] = false;
            // Interactions: enter vault
            IMultiDepositorVault(MULTI_DEPOSITOR_VAULT).enter(
                address(this), token, tokensAfterTip, unitsOut, request.user
            );

            // Log emit deposit solved event
            emit DepositSolved(depositHash);
        } else {
            // Effects: unset hash as used
            asyncDepositHashes[depositHash] = false;
            // Interactions: transfer tokens from provisioner to sender
            token.safeTransfer(request.user, request.tokens);
            // Log emit deposit refunded event
            emit DepositRefunded(depositHash);
        }
    }

    /// @notice Solves a fixed price deposit request for the vault, transfering tokens or refunding as needed
    /// @dev User gets exactly min units out, but may over‑fund, the difference is paid to the solver as a tip
    /// @dev
    /// - Returns 0 if any of:
    ///   - price age is too high, emits PriceAgeExceeded
    ///   - request hash is not set, emits InvalidRequestHash
    ///   - tokens needed exceed the maximum allowed, emits AmountBoundExceeded
    ///   - deposit cap would be exceeded, emits DepositCapExceeded
    /// - If deadline not passed, processes deposit and emits DepositSolved
    /// - If deadline passed, refunds and emits DepositRefunded
    /// - Always unsets hash after processing
    /// @param token The ERC20 token being deposited
    /// @param depositMultiplier The multiplier (in BPS) applied to the deposit for premium calculation
    /// @param request The deposit request struct containing all user parameters
    /// @param priceAge The age of the price data used for conversion
    /// @param index The index of the request in the given solving batch
    /// @return solverTip The tip amount paid to the solver, or 0 if not processed
    function _solveDepositVaultFixedPrice(
        IERC20 token,
        uint256 depositMultiplier,
        Request calldata request,
        uint256 priceAge,
        uint256 index
    ) internal returns (uint256 solverTip) {
        // Requirements: price age is within user specified max price age
        if (_guardPriceAge(priceAge, request.maxPriceAge, index)) return 0;

        bytes32 depositHash = _getRequestHash(token, request);
        // Requirements: hash has been set
        if (_guardInvalidRequestHash(asyncDepositHashes[depositHash], depositHash)) return 0;

        if (request.deadline >= block.timestamp) {
            // Interactions: convert units to tokens applying premium
            uint256 tokensNeeded = _unitsToTokensCeilIfActive(token, request.units, depositMultiplier);
            // Requirements: tokens needed is less than or equal to max tokens in
            if (_guardAmountBound(request.tokens, tokensNeeded, index)) return 0;
            // Requirements + interactions: convert new total units to numeraire and check against deposit cap
            if (_guardDepositCapExceeded(request.units, index)) return 0;

            // Effects: unset hash as used
            asyncDepositHashes[depositHash] = false;
            // Interactions: enter vault
            IMultiDepositorVault(MULTI_DEPOSITOR_VAULT).enter(
                address(this), token, tokensNeeded, request.units, request.user
            );

            unchecked {
                solverTip = request.tokens - tokensNeeded;
            }

            // Log emit deposit solved event
            emit DepositSolved(depositHash);
        } else {
            // Effects: unset hash as used
            asyncDepositHashes[depositHash] = false;
            // Interactions: transfer tokens from provisioner to sender
            token.safeTransfer(request.user, request.tokens);
            // Log emit deposit refunded event
            emit DepositRefunded(depositHash);
        }
    }

    /// @notice Solves an async redeem request for the vault, transfering tokens or refunding as needed
    /// @dev
    /// - Returns 0 if any of:
    ///   - price age is too high, emits PriceAgeExceeded
    ///   - request hash is not set, emits InvalidRequestHash
    ///   - token out after premium is less than min required, emits AmountBoundExceeded
    /// - If deadline not passed, processes redeem and emits RedeemSolved
    /// - If deadline passed, refunds and emits RedeemRefunded
    /// - Always unsets hash after processing
    /// @param token The ERC20 token being redeemed
    /// @param redeemMultiplier The multiplier (in BPS) applied to the redeem for premium calculation
    /// @param request The redeem request struct containing all user parameters
    /// @param priceAge The age of the price data used for conversion
    /// @param index The index of the request in the given solving batch
    /// @return solverTip The tip amount paid to the solver, or 0 if not processed
    function _solveRedeemVaultAutoPrice(
        IERC20 token,
        uint256 redeemMultiplier,
        Request calldata request,
        uint256 priceAge,
        uint256 index
    ) internal returns (uint256 solverTip) {
        // Requirements: price age is within user specified max price age
        if (_guardPriceAge(priceAge, request.maxPriceAge, index)) return 0;

        bytes32 redeemHash = _getRequestHash(token, request);
        // Requirements: hash has been set
        if (_guardInvalidRequestHash(asyncRedeemHashes[redeemHash], redeemHash)) return 0;

        if (request.deadline >= block.timestamp) {
            solverTip = request.solverTip;

            // Interactions: convert units to token amount
            uint256 tokenOut = _unitsToTokensFloorIfActive(token, request.units, redeemMultiplier);
            // Requirements: tokens are enough for tip
            if (_guardInsufficientTokensForTip(tokenOut, solverTip, index)) return 0;

            uint256 tokenOutAfterTip;
            unchecked {
                tokenOutAfterTip = tokenOut - solverTip;
            }

            // Requirements: token amount is greater than or equal to net token amount
            if (_guardAmountBound(tokenOutAfterTip, request.tokens, index)) return 0;

            // Effects: unset hash as used
            asyncRedeemHashes[redeemHash] = false;
            // Interactions: exit vault
            IMultiDepositorVault(MULTI_DEPOSITOR_VAULT).exit(
                address(this), token, tokenOut, request.units, address(this)
            );

            // Interactions: transfer tokens from provisioner to sender
            token.safeTransfer(request.user, tokenOutAfterTip);

            // Log emit redeem solved event
            emit RedeemSolved(redeemHash);
        } else {
            // Effects: unset hash as used
            asyncRedeemHashes[redeemHash] = false;
            // Interactions: transfer units from provisioner to sender
            IERC20(MULTI_DEPOSITOR_VAULT).safeTransfer(request.user, request.units);
            // Log emit redeem refunded event
            emit RedeemRefunded(redeemHash);
        }
    }

    /// @notice Solves a fixed price redeem request for the vault, transfering tokens or refunding as needed
    /// @dev User gets exactly min tokens out, but may under‑fund, the difference is paid to the solver as a tip
    /// @dev
    /// - Returns 0 if any of:
    ///   - price age is too high, emits PriceAgeExceeded
    ///   - request hash is not set, emits InvalidRequestHash
    /// - If deadline not passed, processes redeem and emits RedeemSolved
    /// - If deadline passed, refunds and emits RedeemRefunded
    /// - Always unsets hash after processing
    /// @param token The ERC20 token being redeemed
    /// @param redeemMultiplier The multiplier (in BPS) applied to the redeem for premium calculation
    /// @param request The redeem request struct containing all user parameters
    /// @param priceAge The age of the price data used for conversion
    /// @param index The index of the request in the given solving batch
    /// @return solverTip The tip amount paid to the solver, or 0 if not processed
    function _solveRedeemVaultFixedPrice(
        IERC20 token,
        uint256 redeemMultiplier,
        Request calldata request,
        uint256 priceAge,
        uint256 index
    ) internal returns (uint256 solverTip) {
        // Requirements: price age is within user specified max price age
        if (_guardPriceAge(priceAge, request.maxPriceAge, index)) return 0;

        bytes32 redeemHash = _getRequestHash(token, request);
        // Requirements: hash has been set
        if (_guardInvalidRequestHash(asyncRedeemHashes[redeemHash], redeemHash)) return 0;

        if (request.deadline >= block.timestamp) {
            // Interactions: convert units to token amount
            uint256 tokenOut = _unitsToTokensFloorIfActive(token, request.units, redeemMultiplier);
            // Requirements: token amount is greater than or equal to net token amount
            if (_guardAmountBound(tokenOut, request.tokens, index)) return 0;

            // Effects: unset hash as used
            asyncRedeemHashes[redeemHash] = false;
            // Interactions: exit vault
            IMultiDepositorVault(MULTI_DEPOSITOR_VAULT).exit(
                address(this), token, tokenOut, request.units, address(this)
            );
            // Interactions: transfer tokens from provisioner to sender
            token.safeTransfer(request.user, request.tokens);

            unchecked {
                solverTip = tokenOut - request.tokens;
            }

            // Log emit redeem solved event
            emit RedeemSolved(redeemHash);
        } else {
            // Effects: unset hash as used
            asyncRedeemHashes[redeemHash] = false;
            // Interactions: transfer units from provisioner to sender
            IERC20(MULTI_DEPOSITOR_VAULT).safeTransfer(request.user, request.units);
            // Log emit redeem refunded event
            emit RedeemRefunded(redeemHash);
        }
    }

    /// @notice Solves a direct deposit request, transfering tokens and units between users
    /// @dev
    /// - Returns early if any of:
    ///   - request hash is not set, emits InvalidRequestHash
    /// - If deadline not passed, transfers units and tokens, emits DepositSolved
    /// - If deadline passed, refunds tokens, emits DepositRefunded
    /// - Always unsets hash after processing
    /// @param token The ERC20 token being deposited
    /// @param request The deposit request struct containing all user parameters
    function _solveDepositDirect(IERC20 token, Request calldata request) internal {
        bytes32 depositHash = _getRequestHash(token, request);
        // Requirements: hash has been set
        if (!asyncDepositHashes[depositHash]) {
            // Log emit invalid async deposit hash event
            emit InvalidRequestHash(depositHash);
            return;
        }

        // Effects: unset hash as used
        asyncDepositHashes[depositHash] = false;

        if (request.deadline >= block.timestamp) {
            // Interactions: pull units from sender(solver) to user
            IERC20(MULTI_DEPOSITOR_VAULT).safeTransferFrom(msg.sender, request.user, request.units);

            // Interactions: transfer tokens from provisioner to sender
            token.safeTransfer(msg.sender, request.tokens);

            // Log emit deposit solved event
            emit DepositSolved(depositHash);
        } else {
            // Interactions: transfer tokens from provisioner to sender
            token.safeTransfer(request.user, request.tokens);

            // Log emit deposit refunded event
            emit DepositRefunded(depositHash);
        }
    }

    /// @notice Solves a direct redeem request, transfering tokens and units between users
    /// @dev
    /// - Returns early if:
    ///   - request hash is not set, emits InvalidRequestHash
    /// - If deadline not passed, transfers units and tokens, emits RedeemSolved
    /// - If deadline passed, refunds units, emits RedeemRefunded
    /// - Always unsets hash after processing
    /// @param token The ERC20 token being redeemed
    /// @param request The redeem request struct containing all user parameters
    function _solveRedeemDirect(IERC20 token, Request calldata request) internal {
        bytes32 redeemHash = _getRequestHash(token, request);
        // Requirements: hash has been set
        if (!asyncRedeemHashes[redeemHash]) {
            // Log emit invalid async redeem hash event
            emit InvalidRequestHash(redeemHash);
            return;
        }

        // Effects: unset hash as used
        asyncRedeemHashes[redeemHash] = false;

        if (request.deadline >= block.timestamp) {
            // Interactions: transfer units from provisioner to sender
            IERC20(MULTI_DEPOSITOR_VAULT).safeTransfer(msg.sender, request.units);

            // Interactions: pull tokens from sender(solver) to user
            token.safeTransferFrom(msg.sender, request.user, request.tokens);

            // Log emit redeem solved event
            emit RedeemSolved(redeemHash);
        } else {
            // Interactions: transfer units from provisioner to sender
            IERC20(MULTI_DEPOSITOR_VAULT).safeTransfer(request.user, request.units);

            // Log emit redeem refunded event
            emit RedeemRefunded(redeemHash);
        }
    }

    /// @notice Checks if the price age exceeds the maximum allowed and emits an event if so
    /// @param priceAge The difference between when price was measured and submitted onchain
    /// @param maxPriceAge The maximum allowed price age
    /// @param index The index of the request in the given solving batch
    /// @return True if price age is too high, false otherwise
    function _guardPriceAge(uint256 priceAge, uint256 maxPriceAge, uint256 index) internal returns (bool) {
        if (priceAge > maxPriceAge) {
            emit PriceAgeExceeded(index);
            return true;
        }
        return false;
    }

    /// @notice Checks if the request hash exists and emits an event if not
    /// @param hashExists Whether the hash exists
    /// @param requestHash The request hash
    /// @return True if hash does not exist, false otherwise
    function _guardInvalidRequestHash(bool hashExists, bytes32 requestHash) internal returns (bool) {
        if (!hashExists) {
            // Log emit invalid request hash event
            emit InvalidRequestHash(requestHash);
            return true;
        }
        return false;
    }

    /// @notice Checks if there are enough tokens for the solver tip and emits an event if not
    /// @param tokens The number of tokens
    /// @param solverTip The solver tip amount
    /// @param index The index of the request in the given solving batch
    /// @return True if not enough tokens for tip, false otherwise
    function _guardInsufficientTokensForTip(uint256 tokens, uint256 solverTip, uint256 index) internal returns (bool) {
        if (tokens < solverTip) {
            // Log emit insufficient tokens for tip event
            emit InsufficientTokensForTip(index);
            return true;
        }
        return false;
    }

    /// @notice Checks if the amount is less than the bound and emits an event if so
    /// @param amount The actual amount
    /// @param bound The minimum required amount
    /// @param index The index of the request in the given solving batch
    /// @return True if amount is less than bound, false otherwise
    function _guardAmountBound(uint256 amount, uint256 bound, uint256 index) internal returns (bool) {
        if (amount < bound) {
            // Log emit amount bound exceeded event
            emit AmountBoundExceeded(index, amount, bound);
            return true;
        }
        return false;
    }

    /// @notice Checks if the deposit cap would be exceeded and emits an event if so
    /// @param totalUnits The total units after deposit
    /// @param index The index of the request in the given solving batch
    /// @return True if deposit cap would be exceeded, false otherwise
    function _guardDepositCapExceeded(uint256 totalUnits, uint256 index) internal returns (bool) {
        // Interactions: check if deposit cap would be exceeded
        if (_isDepositCapExceeded(totalUnits)) {
            // Log emit deposit cap exceeded event
            emit DepositCapExceeded(index);
            return true;
        }
        return false;
    }

    /// @notice Reverts if sync deposits are not enabled for the token
    /// @param token The ERC20 token to check
    /// @return tokenDetails The token details storage reference
    function _requireSyncDepositsEnabled(IERC20 token) internal view returns (TokenDetails storage tokenDetails) {
        tokenDetails = tokensDetails[token];
        // Requirements: sync deposits are enabled
        require(tokenDetails.syncDepositEnabled, Aera__SyncDepositDisabled());
    }

    /// @notice Reverts if deposit cap would be exceeded by adding units
    /// @param units The number of units to add
    function _requireDepositCapNotExceeded(uint256 units) internal view {
        // Requirements + interactions: deposit cap not exceeded
        require(!_isDepositCapExceeded(units), Aera__DepositCapExceeded());
    }

    /// @notice Checks if deposit cap would be exceeded by adding units
    /// @param units The number of units to add
    /// @return True if deposit cap would be exceeded, false otherwise
    function _isDepositCapExceeded(uint256 units) internal view returns (bool) {
        // Interactions: get current total supply
        uint256 newTotal = IERC20(MULTI_DEPOSITOR_VAULT).totalSupply() + units;
        // Interactions: convert total supply to numeraire
        return PRICE_FEE_CALCULATOR.convertUnitsToNumeraire(MULTI_DEPOSITOR_VAULT, newTotal) > depositCap;
    }

    /// @notice Converts token amount to units, applying multiplier and flooring
    /// @param token The ERC20 token
    /// @param tokens The amount of tokens
    /// @param multiplier The multiplier to apply
    /// @return The resulting units (floored)
    function _tokensToUnitsFloorIfActive(IERC20 token, uint256 tokens, uint256 multiplier)
        internal
        view
        returns (uint256)
    {
        uint256 tokensAdjusted = tokens * multiplier / ONE_IN_BPS;
        // Interactions: convert tokens to units
        return PRICE_FEE_CALCULATOR.convertTokenToUnitsIfActive(
            MULTI_DEPOSITOR_VAULT, token, tokensAdjusted, Math.Rounding.Floor
        );
    }

    /// @notice Converts units to token amount, applying multiplier and flooring
    /// @param token The ERC20 token
    /// @param units The amount of units
    /// @param multiplier The multiplier to apply
    /// @return The resulting token amount (floored)
    function _unitsToTokensFloorIfActive(IERC20 token, uint256 units, uint256 multiplier)
        internal
        view
        returns (uint256)
    {
        // Interactions: convert units to tokens
        uint256 tokensAmount =
            PRICE_FEE_CALCULATOR.convertUnitsToTokenIfActive(MULTI_DEPOSITOR_VAULT, token, units, Math.Rounding.Floor);
        return tokensAmount * multiplier / ONE_IN_BPS;
    }

    /// @notice Converts units to token amount, applying multiplier and ceiling
    /// @param token The ERC20 token
    /// @param units The amount of units
    /// @param multiplier The multiplier to apply
    /// @return The resulting token amount (ceiled)
    function _unitsToTokensCeilIfActive(IERC20 token, uint256 units, uint256 multiplier)
        internal
        view
        returns (uint256)
    {
        // Interactions: convert units to tokens
        uint256 tokensAmount =
            PRICE_FEE_CALCULATOR.convertUnitsToTokenIfActive(MULTI_DEPOSITOR_VAULT, token, units, Math.Rounding.Ceil);
        return Math.mulDiv(tokensAmount, ONE_IN_BPS, multiplier, Math.Rounding.Ceil);
    }

    /// @notice Get the hash of a deposit
    /// @param user The user who made the deposit
    /// @param token The token that was deposited
    /// @param tokenAmount The amount of tokens deposited
    /// @param unitsAmount The amount of units received
    /// @param refundableUntil The timestamp at which the deposit can be refunded
    /// @dev Since refundableUntil is block.timestamp + depositRefundTimeout (which is subject to change), it's
    /// theoretically possible to have a hash collision, but the probability is negligible and we optimize for the
    /// common case
    function _getDepositHash(
        address user,
        IERC20 token,
        uint256 tokenAmount,
        uint256 unitsAmount,
        uint256 refundableUntil
    ) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(user, token, tokenAmount, unitsAmount, refundableUntil));
    }

    /// @notice Get the hash of a request from parameters
    /// @param token The token that was deposited or redeemed
    /// @param user The user who made the request
    /// @param requestType The type of request
    /// @param tokens The amount of tokens in the request
    /// @param units The amount of units in the request
    /// @param solverTip The tip paid to the solver
    /// @param deadline The deadline of the request
    /// @param maxPriceAge The maximum age of the price data
    /// @return The hash of the request
    function _getRequestHashParams(
        IERC20 token,
        address user,
        RequestType requestType,
        uint256 tokens,
        uint256 units,
        uint256 solverTip,
        uint256 deadline,
        uint256 maxPriceAge
    ) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(token, user, requestType, tokens, units, solverTip, deadline, maxPriceAge));
    }

    /// @notice Get the hash of a request
    /// @param token The token that was deposited or redeemed
    /// @param request The request to get the hash of
    function _getRequestHash(IERC20 token, Request calldata request) internal pure returns (bytes32) {
        return keccak256(
            abi.encodePacked(
                token,
                request.user,
                request.requestType,
                request.tokens,
                request.units,
                request.solverTip,
                request.deadline,
                request.maxPriceAge
            )
        );
    }

    /// @notice Returns true if the request type is a deposit
    /// @param requestType The request type
    /// @return True if deposit, false otherwise
    function _isRequestTypeDeposit(RequestType requestType) internal pure returns (bool) {
        return uint8(requestType) & DEPOSIT_REDEEM_FLAG == 0;
    }

    /// @notice Returns true if the request type is fixed price
    /// @param requestType The request type
    /// @return True if fixed price, false otherwise
    function _isRequestTypeAutoPrice(RequestType requestType) internal pure returns (bool) {
        return uint8(requestType) & AUTO_PRICE_FIXED_PRICE_FLAG == 0;
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

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

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

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

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

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

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

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;

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

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
    }
}

lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol

// SPDX-License-Identifier: MIT
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represent a slot holding a address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);
}

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

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

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

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

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

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

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

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

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

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

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

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

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

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 1);
        }
        return result;
    }

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

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/structs/BitMaps.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/BitMaps.sol)
pragma solidity ^0.8.20;

/**
 * @dev Library for managing uint256 to bool mapping in a compact and efficient way, provided the keys are sequential.
 * Largely inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
 *
 * BitMaps pack 256 booleans across each bit of a single 256-bit slot of `uint256` type.
 * Hence booleans corresponding to 256 _sequential_ indices would only consume a single slot,
 * unlike the regular `bool` which would consume an entire slot for a single value.
 *
 * This results in gas savings in two ways:
 *
 * - Setting a zero value to non-zero only once every 256 times
 * - Accessing the same warm slot for every 256 _sequential_ indices
 */
library BitMaps {
    struct BitMap {
        mapping(uint256 bucket => uint256) _data;
    }

    /**
     * @dev Returns whether the bit at `index` is set.
     */
    function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        return bitmap._data[bucket] & mask != 0;
    }

    /**
     * @dev Sets the bit at `index` to the boolean `value`.
     */
    function setTo(BitMap storage bitmap, uint256 index, bool value) internal {
        if (value) {
            set(bitmap, index);
        } else {
            unset(bitmap, index);
        }
    }

    /**
     * @dev Sets the bit at `index`.
     */
    function set(BitMap storage bitmap, uint256 index) internal {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        bitmap._data[bucket] |= mask;
    }

    /**
     * @dev Unsets the bit at `index`.
     */
    function unset(BitMap storage bitmap, uint256 index) internal {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        bitmap._data[bucket] &= ~mask;
    }
}

src/core/Auth2Step.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

import { Auth, Authority } from "@solmate/auth/Auth.sol";
import { IAuth2Step } from "src/core/interfaces/IAuth2Step.sol";

/// @title Auth2Step
/// @notice An extension of Auth.sol that supports two-step ownership transfer
contract Auth2Step is IAuth2Step, Auth {
    ////////////////////////////////////////////////////////////
    //                        Storage                         //
    ////////////////////////////////////////////////////////////

    /// @notice Address of the pending owner
    address public pendingOwner;

    ////////////////////////////////////////////////////////////
    //                       Modifiers                        //
    ////////////////////////////////////////////////////////////

    modifier onlyOwner() virtual {
        require(msg.sender == owner, Aera__Unauthorized());
        _;
    }

    constructor(address newOwner_, Authority authority_) Auth(newOwner_, authority_) { }

    ////////////////////////////////////////////////////////////
    //              Public / External Functions               //
    ////////////////////////////////////////////////////////////

    /// @inheritdoc IAuth2Step
    function acceptOwnership() external virtual override {
        address pendingOwner_ = pendingOwner;

        // Requirements: the caller must be the pending owner
        require(msg.sender == pendingOwner_, Aera__Unauthorized());

        // Effects: set the owner to the pending owner and delete the pending owner
        owner = pendingOwner_;
        delete pendingOwner;

        // Log the ownership transfer
        emit OwnershipTransferred(msg.sender, pendingOwner_);
    }

    /// @notice Start the ownership transfer of the contract to a new account
    /// @param newOwner Address to transfer ownership to
    /// @dev Replaces the pending transfer if there is one
    /// @dev Overrides the `Auth` contract's `transferOwnership` function
    /// @dev Zero check is not needed because pendingOwner can always be overwritten
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        // Effects: set the pending owner
        //slither-disable-next-line missing-zero-check
        pendingOwner = newOwner;

        // Log the ownership transfer start
        emit OwnershipTransferStarted(owner, newOwner);
    }
}

src/core/Constants.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

////////////////////////////////////////////////////////////
//                    Memory & Calldata                   //
////////////////////////////////////////////////////////////

// Size of a word in bytes
uint256 constant WORD_SIZE = 32;

// Size of a function selector in bytes
uint256 constant SELECTOR_SIZE = 4;

// Minimum valid calldata size (selector + one word = 36)
uint256 constant MINIMUM_CALLDATA_LENGTH = WORD_SIZE + SELECTOR_SIZE;

// Offset to skip selector and first word in calldata
uint256 constant CALLDATA_OFFSET = MINIMUM_CALLDATA_LENGTH;

// Offset for extracting spender address from approval calldata
uint256 constant ERC20_SPENDER_OFFSET = 36;

// Size of an address in bits
uint256 constant ADDRESS_SIZE_BITS = 160;

////////////////////////////////////////////////////////////
//                     Hooks Constants                    //
////////////////////////////////////////////////////////////

// Mask for a bit indicating whether a hooks has before submit call
uint256 constant BEFORE_HOOK_MASK = 1;

// Mask for a bit indicating whether a hooks has after submit call
uint256 constant AFTER_HOOK_MASK = 2;

// Mask for a bit indicating whether a hooks exists
uint256 constant HOOKS_FLAG_MASK = 0x80;

// Mask for 7 bits indicating the number of configurable hooks offsets
uint256 constant CONFIGURABLE_HOOKS_LENGTH_MASK = 0x7F;

////////////////////////////////////////////////////////////
//                     Bit Operations                     //
////////////////////////////////////////////////////////////

// Mask for extracting 8-bit values
uint256 constant MASK_8_BIT = 0xff;

// Mask for extracting 16-bit values
uint256 constant MASK_16_BIT = 0xffff;

////////////////////////////////////////////////////////////
//                    Pipeline Constants                  //
////////////////////////////////////////////////////////////

// Bit offset for results index in packed clipboard data
uint256 constant RESULTS_INDEX_OFFSET = 24;

// Bit offset for copy word position in packed clipboard data
uint256 constant COPY_WORD_OFFSET = 16;

////////////////////////////////////////////////////////////
//                   Extractor Constants                  //
////////////////////////////////////////////////////////////

// Number of bits per extraction offset
uint256 constant EXTRACT_OFFSET_SIZE_BITS = 16;

// Number of bits to shift to get the offset (256 - 16)
uint256 constant EXTRACTION_OFFSET_SHIFT_BITS = 240;

/// @dev Maximum number of extraction offsets(16) + 1
uint256 constant MAX_EXTRACT_OFFSETS_EXCLUSIVE = 17;

////////////////////////////////////////////////////////////
//                   Callback Constants                   //
////////////////////////////////////////////////////////////

// Maximum value for uint16, used to indicate no callback data
uint16 constant NO_CALLBACK_DATA = type(uint16).max;

// Offset for selector in callback data
uint256 constant SELECTOR_OFFSET = 48;

// Offset for callback data
uint256 constant CALLBACK_DATA_OFFSET = 160;

////////////////////////////////////////////////////////////
//                   Fee Constants                        //
////////////////////////////////////////////////////////////

// Basis points denominator (100%)
uint256 constant ONE_IN_BPS = 1e4;

// Maximum TVL fee
uint256 constant MAX_TVL_FEE = 2000; // 20%

// Maximum performance fee
uint256 constant MAX_PERFORMANCE_FEE = ONE_IN_BPS;

// Seconds in a year for fee calculations
uint256 constant SECONDS_PER_YEAR = 365 days;

// Maximum dispute period
uint256 constant MAX_DISPUTE_PERIOD = 30 days;

////////////////////////////////////////////////////////////
//                   Unit Price Constants                //
////////////////////////////////////////////////////////////

/// @dev Precision for unit price calculations (18 decimals)
uint256 constant UNIT_PRICE_PRECISION = 1e18;

/// @dev One minute in seconds
uint256 constant ONE_MINUTE = 1 minutes;

/// @dev One day in seconds
uint256 constant ONE_DAY = 1 days;

////////////////////////////////////////////////////////////
//                   Provisioner Constants                //
////////////////////////////////////////////////////////////

/// @dev Minimum deposit multiplier 50%
uint256 constant MIN_DEPOSIT_MULTIPLIER = 5000;

/// @dev Minimum redeem multiplier 50%
uint256 constant MIN_REDEEM_MULTIPLIER = 5000;

/// @dev Deposit/Redeem flag in RequestType enum
uint256 constant DEPOSIT_REDEEM_FLAG = 1;

/// @dev Auto/Fixed price flag in RequestType enum
uint256 constant AUTO_PRICE_FIXED_PRICE_FLAG = 2;

/// @dev One unit with 18 decimals
uint256 constant ONE_UNIT = 1e18;

/// @dev Maximum seconds between request deadline and current timestamp
uint256 constant MAX_SECONDS_TO_DEADLINE = 365 days;

/// @dev Upper bound for depositRefundTimeout to prevent indefinite user lockout
uint256 constant MAX_DEPOSIT_REFUND_TIMEOUT = 30 days;

////////////////////////////////////////////////////////////
//                   Whitelist Constants                  //
////////////////////////////////////////////////////////////

/// @dev Whitelist flag in AddressToUintMap
uint8 constant IS_WHITELISTED_FLAG = 1;

src/core/Types.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

import { IERC20 } from "@oz/interfaces/IERC20.sol";
import { Authority } from "@solmate/auth/Auth.sol";

import { IFeeCalculator } from "src/core/interfaces/IFeeCalculator.sol";
import { ISubmitHooks } from "src/core/interfaces/ISubmitHooks.sol";
import { IWhitelist } from "src/core/interfaces/IWhitelist.sol";
import { IOracle } from "src/dependencies/oracles/IOracle.sol";

/// @notice Type of request: deposit/redeem and auto/fixed price
/// @dev
/// - The order is chosen so each bit encodes a property:
///   - Bit 0: 0 = deposit, 1 = redeem
///   - Bit 1: 0 = auto price, 1 = fixed price
enum RequestType {
    DEPOSIT_AUTO_PRICE, // 00: deposit, auto price
    REDEEM_AUTO_PRICE, // 01: redeem, auto price
    DEPOSIT_FIXED_PRICE, // 10: deposit, fixed price
    REDEEM_FIXED_PRICE // 11: redeem, fixed price

}

/// @notice Type of return value: no return, static return, dynamic return
/// @dev
/// - 00: no return
/// - 01: static return - hardcoded return data
/// - 10: dynamic return - return data is extracted from the results array
enum ReturnValueType {
    NO_RETURN,
    STATIC_RETURN,
    DYNAMIC_RETURN
}

/// @notice Type of hook call: before, after, or none
enum HookCallType {
    NONE,
    BEFORE,
    AFTER
}

/// @notice Operation struct for vault operations
/// @dev This struct is not used directly in core logic, but included for reference and clarity
///      It illustrates the full structure of an operation without storage packing
struct Operation {
    /// @notice Target contract address to call
    address target;
    /// @notice Calldata for the target contract
    bytes data;
    /// @notice Array of clipboard operations for copying return data
    Clipboard[] clipboards;
    /// @notice Whether to perform a static call
    bool isStaticCall;
    /// @notice Callback data for post-operation processing
    CallbackData callbackData;
    /// @notice Address of the hooks contract
    address hooks;
    /// @notice Array of offsets for extracting calldata
    uint16[] configurableHooksOffsets;
    /// @notice Merkle proof for operation verification
    bytes32[] proof;
    /// @notice ETH value to send with the call
    uint256 value;
}

/// @notice Operation execution context data
/// @dev Used to avoid stack too deep in BaseVault._executeSubmit function
struct OperationContext {
    /// @notice Address of the target contract to call
    address target;
    /// @notice Function selector extracted from calldata
    bytes4 selector;
    /// @notice Callback data packed
    uint208 callbackData;
    /// @notice ETH value to send with the call
    uint256 value;
    /// @notice Address of the operation-specific hooks contract
    address operationHooks;
    /// @notice Offset of the calldata extraction offsets packed in uint256
    uint256 configurableOperationHooks;
}

/// @notice Struct for payable operations
struct OperationPayable {
    /// @notice Target contract address
    address target;
    /// @notice Calldata for the target contract
    bytes data;
    /// @notice ETH value to send with the call
    uint256 value;
}

/// @notice Struct for token approvals
struct Approval {
    /// @notice Token address to approve
    address token;
    /// @notice Address to approve spending for
    address spender;
}

/// @notice Struct for token amounts
struct TokenAmount {
    /// @notice ERC20 token address
    IERC20 token;
    /// @notice Amount of tokens
    uint256 amount;
}

/// @notice Struct for clipboard operations
struct Clipboard {
    /// @notice Index of the result to copy from
    uint8 resultIndex;
    /// @notice Which word to copy from the result
    uint8 copyWord;
    /// @notice Offset to paste the copied data
    uint16 pasteOffset;
}

/// @notice Struct for callback data
struct CallbackData {
    /// @notice Address allowed to execute the callback
    address caller;
    /// @notice Function selector for the callback
    bytes4 selector;
    /// @notice Offset in calldata for the callback
    uint16 calldataOffset;
}

/// @notice Vault parameters for vault deployment
struct BaseVaultParameters {
    /// @notice Initial owner address
    address owner;
    /// @notice Initial authority address
    Authority authority;
    /// @notice Submit hooks address
    ISubmitHooks submitHooks;
    /// @notice Whitelist contract address
    IWhitelist whitelist;
}

/// @notice Parameters for fee vault deployment
struct FeeVaultParameters {
    /// @notice The fee calculator address
    IFeeCalculator feeCalculator;
    /// @notice The fee token address
    IERC20 feeToken;
    /// @notice The fee recipient address
    address feeRecipient;
}

/// @notice Parameters for ERC20 deployment
struct ERC20Parameters {
    /// @notice ERC20 token name
    string name;
    /// @notice ERC20 token symbol
    string symbol;
}

/// @notice Fee structure for TVL and performance fees
/// @dev All fees are in basis points (1/10000)
struct Fee {
    /// @notice TVL fee in basis points
    uint16 tvl;
    /// @notice Performance fee in basis points
    uint16 performance;
}

/// @notice Tracks fee configuration and accrued fees for a vault
struct VaultAccruals {
    /// @notice Current fee rates for the vault
    Fee fees;
    /// @notice Accrued fees for the vault fee recipient
    uint112 accruedFees;
    /// @notice Total protocol fees accrued but not claimed
    uint112 accruedProtocolFees;
}

/// @notice Complete state of a vault's fee configuration and accruals
struct VaultSnapshot {
    /// @notice Timestamp of last fee accrual
    uint32 lastFeeAccrual;
    /// @notice Timestamp when snapshot was taken
    uint32 timestamp;
    /// @notice Timestamp when snapshot is finalized after dispute period
    uint32 finalizedAt;
    /// @notice Average value of vault assets during snapshot period
    uint160 averageValue;
    /// @notice Highest profit achieved during snapshot period
    uint128 highestProfit;
    /// @notice Highest profit achieved in previous periods
    uint128 lastHighestProfit;
}

/// @notice Struct for target and calldata
struct TargetCalldata {
    /// @notice Target contract address
    address target;
    /// @notice Calldata for the target contract
    bytes data;
}

/// @notice Vault price information and configuration
struct VaultPriceState {
    /// @notice Whether vault price updates are paused
    bool paused;
    /// @notice Maximum age of price data in seconds before it is considered stale
    uint8 maxPriceAge;
    /// @notice Minimum time between price updates in minutes
    uint16 minUpdateIntervalMinutes;
    /// @notice Maximum allowed price increase ratio in basis points
    uint16 maxPriceToleranceRatio;
    /// @notice Minimum allowed price decrease ratio in basis points
    uint16 minPriceToleranceRatio;
    /// @notice Maximum allowed delay in price updates in days
    uint8 maxUpdateDelayDays;
    /// @notice Timestamp of last price update
    uint32 timestamp;
    /// @notice Seconds between last fee accrual and last price update
    uint24 accrualLag;
    /// @notice Current unit price
    uint128 unitPrice;
    /// @notice Highest historical unit price
    uint128 highestPrice;
    /// @notice Total supply at last price update
    uint128 lastTotalSupply;
}

/// @notice Token configuration for deposits and redemptions
struct TokenDetails {
    /// @notice Whether async deposits are enabled
    bool asyncDepositEnabled;
    /// @notice Whether async redemptions are enabled
    bool asyncRedeemEnabled;
    /// @notice Whether sync deposits are enabled
    bool syncDepositEnabled;
    /// @notice Premium multiplier applied to deposits in basis points (9999 = 0.1% premium)
    uint16 depositMultiplier;
    /// @notice Premium multiplier applied to redemptions in basis points (9999 = 0.1% premium)
    uint16 redeemMultiplier;
}

/// @notice Request parameters for deposits and redemptions
/// @dev
/// - For deposits:
///   - units: minimum units the user wants to receive (minUnitsOut)
///   - tokens: amount of tokens the user is providing (tokensIn)
/// - For redemptions:
///   - units: amount of units the user is redeeming (unitsIn)
///   - tokens: minimum tokens the user wants to receive (minTokensOut)
struct Request {
    /// @notice Request type(deposit/redeem + auto/fixed price)
    RequestType requestType;
    /// @notice User address making the request
    address user;
    /// @notice Amount of vault units
    uint256 units;
    /// @notice Amount of underlying tokens
    uint256 tokens;
    /// @notice Tip paid to solver, always in tokens
    uint256 solverTip;
    /// @notice Timestamp after which request expires
    uint256 deadline;
    /// @notice Maximum age of price data allowed
    uint256 maxPriceAge;
}

/// @notice Oracle data for a base/quote pair, including current, pending, and status flags
struct OracleData {
    /// @notice True if an oracle update is scheduled
    bool isScheduledForUpdate;
    /// @notice True if the current oracle is disabled
    bool isDisabled;
    /// @notice The currently active oracle
    IOracle oracle;
    /// @notice The pending oracle to be activated after delay
    IOracle pendingOracle;
    /// @notice Timestamp at which the pending oracle can be committed
    uint32 commitTimestamp;
}

src/core/interfaces/IAuth2Step.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

/// @title IAuth2Step
/// @notice Interface for the Auth2Step contract
interface IAuth2Step {
    ////////////////////////////////////////////////////////////
    //                         Events                         //
    ////////////////////////////////////////////////////////////

    /// @notice Emitted when ownership transfer is initiated
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    ////////////////////////////////////////////////////////////
    //                         Errors                         //
    ////////////////////////////////////////////////////////////

    error Aera__ZeroAddressAuthority();
    error Aera__Unauthorized();

    ////////////////////////////////////////////////////////////
    //                       Functions                        //
    ////////////////////////////////////////////////////////////

    /// @notice Accept ownership transfer
    function acceptOwnership() external;
}

src/core/interfaces/IBeforeTransferHook.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

/// @title IBeforeTransferHook
/// @notice Interface for token transfer hooks used for vault units in multi-depositor vaults
interface IBeforeTransferHook {
    ////////////////////////////////////////////////////////////
    //                         Events                         //
    ////////////////////////////////////////////////////////////

    event VaultUnitTransferableSet(address indexed vault, bool isTransferable);

    ////////////////////////////////////////////////////////////
    //                         Errors                         //
    ////////////////////////////////////////////////////////////

    error Aera__NotVaultOwner();
    error Aera__VaultUnitsNotTransferable(address vault);

    ////////////////////////////////////////////////////////////
    //                       Functions                        //
    ////////////////////////////////////////////////////////////

    /// @notice Set whether vault units should be transferable
    /// @param vault The vault to update status for
    /// @param isTransferable Whether the vault units are transferable
    function setIsVaultUnitsTransferable(address vault, bool isTransferable) external;

    /// @notice Perform before transfer checks
    /// @param from Address that is sending the units
    /// @param to Address that is receiving the units
    /// @param transferAgent Address that is always allowed to transfer the units
    function beforeTransfer(address from, address to, address transferAgent) external view;
}

src/core/interfaces/IFeeCalculator.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

/// @title IFeeCalculator
/// @notice Interface for a contract that calculates fees for a vault and protocol
interface IFeeCalculator {
    ////////////////////////////////////////////////////////////
    //                         Events                         //
    ////////////////////////////////////////////////////////////

    /// @notice Emitted when a new vault is registered
    /// @param vault The address of the registered vault
    event VaultRegistered(address indexed vault);

    ////////////////////////////////////////////////////////////
    //                         Errors                         //
    ////////////////////////////////////////////////////////////

    /// @notice Thrown when attempting to register an already registered vault
    error Aera__VaultAlreadyRegistered();

    ////////////////////////////////////////////////////////////
    //                       Functions                        //
    ////////////////////////////////////////////////////////////

    /// @notice Register a new vault with the fee calculator
    function registerVault() external;

    /// @notice Process a fee claim for a specific vault
    /// @param feeTokenBalance Available fee token balance to distribute
    /// @return earnedFees The amount of fees to be claimed by the fee recipient
    /// @return protocolEarnedFees The amount of protocol fees to be claimed by the protocol
    /// @return protocolFeeRecipient The address of the protocol fee recipient
    /// @dev Expected to be called by the vault only when claiming fees
    /// Only accrues fees and updates stored values; does not transfer tokens
    /// Caller must perform the actual transfers to avoid permanent fee loss
    function claimFees(uint256 feeTokenBalance) external returns (uint256, uint256, address);

    /// @notice Process a protocol fee claim for a vault
    /// @param feeTokenBalance Available fee token balance to distribute
    /// @return accruedFees The amount of protocol fees claimed
    /// @return protocolFeeRecipient The address of the protocol fee recipient
    /// @dev Expected to be called by the vault only when claiming protocol fees
    /// Only accrues protocol fees and updates stored values; does not transfer tokens
    /// Caller must perform the actual transfers to avoid permanent protocol fee loss
    function claimProtocolFees(uint256 feeTokenBalance) external returns (uint256, address);

    /// @notice Returns the current claimable fees for the given vault, as if a claim was made now
    /// @param vault The address of the vault to preview fees for
    /// @param feeTokenBalance Available fee token balance to distribute
    /// If set to `type(uint256).max`, the function returns all accrued fees
    /// If set to an actual balance, the result is capped to that claimable amount
    /// @return vaultFees The amount of claimable fees for the vault
    /// @return protocolFees The amount of claimable protocol fees
    function previewFees(address vault, uint256 feeTokenBalance)
        external
        view
        returns (uint256 vaultFees, uint256 protocolFees);

    /// @notice Returns the address that receives protocol fees
    /// @return The address that receives the protocol fees
    function protocolFeeRecipient() external view returns (address);
}

src/core/interfaces/IMultiDepositorVault.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

import { IERC20 } from "@oz/interfaces/IERC20.sol";
import { IBeforeTransferHook } from "src/core/interfaces/IBeforeTransferHook.sol";

/// @title IMultiDepositorVault
/// @notice Interface for vaults that can accept deposits from multiple addresses
interface IMultiDepositorVault {
    ////////////////////////////////////////////////////////////
    //                         Events                         //
    ////////////////////////////////////////////////////////////

    event BeforeTransferHookSet(address indexed beforeTransferHook);
    event ProvisionerSet(address indexed provisioner);
    event Enter(
        address indexed sender,
        address indexed recipient,
        IERC20 indexed token,
        uint256 tokenAmount,
        uint256 unitsAmount
    );
    event Exit(
        address indexed sender,
        address indexed recipient,
        IERC20 indexed token,
        uint256 tokenAmount,
        uint256 unitsAmount
    );

    ////////////////////////////////////////////////////////////
    //                         Errors                         //
    ////////////////////////////////////////////////////////////

    error Aera__UnitsLocked();
    error Aera__ZeroAddressProvisioner();
    error Aera__CallerIsNotProvisioner();

    ////////////////////////////////////////////////////////////
    //                       Functions                        //
    ////////////////////////////////////////////////////////////

    /// @notice Set the before transfer hooks
    /// @param hooks The before transfer hooks address
    function setBeforeTransferHook(IBeforeTransferHook hooks) external;

    /// @notice Deposit tokens into the vault and mint units
    /// @param sender The sender of the tokens
    /// @param token The token to deposit
    /// @param tokenAmount The amount of token to deposit
    /// @param unitsAmount The amount of units to mint
    /// @param recipient The recipient of the units
    function enter(address sender, IERC20 token, uint256 tokenAmount, uint256 unitsAmount, address recipient)
        external;

    /// @notice Withdraw tokens from the vault and burn units
    /// @param sender The sender of the units
    /// @param token The token to withdraw
    /// @param tokenAmount The amount of token to withdraw
    /// @param unitsAmount The amount of units to burn
    /// @param recipient The recipient of the tokens
    function exit(address sender, IERC20 token, uint256 tokenAmount, uint256 unitsAmount, address recipient) external;
}

src/core/interfaces/IPriceAndFeeCalculator.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

import { IERC20 } from "@oz/token/ERC20/IERC20.sol";
import { Math } from "@oz/utils/math/Math.sol";
import { VaultAccruals, VaultPriceState } from "src/core/Types.sol";

/// @title IPriceAndFeeCalculator
/// @notice Interface for the unit price provider
interface IPriceAndFeeCalculator {
    ////////////////////////////////////////////////////////////
    //                         Events                         //
    ////////////////////////////////////////////////////////////

    /// @notice Emitted when thresholds are set for a vault
    /// @param vault The address of the vault
    /// @param minPriceToleranceRatio Minimum ratio (of a price decrease) in basis points
    /// @param maxPriceToleranceRatio Maximum ratio (of a price increase) in basis points
    /// @param minUpdateIntervalMinutes The minimum interval between updates in minutes
    /// @param maxPriceAge Max delay between when a vault was priced and when the price is acceptable
    event ThresholdsSet(
        address indexed vault,
        uint16 minPriceToleranceRatio,
        uint16 maxPriceToleranceRatio,
        uint16 minUpdateIntervalMinutes,
        uint8 maxPriceAge
    );

    /// @notice Emitted when a vault's unit price is updated
    /// @param vault The address of the vault
    /// @param price The new unit price
    /// @param timestamp The timestamp when the price was updated
    event UnitPriceUpdated(address indexed vault, uint128 price, uint32 timestamp);

    /// @notice Emitted when a vault's paused state is changed
    /// @param vault The address of the vault
    /// @param paused Whether the vault is paused
    event VaultPausedChanged(address indexed vault, bool paused);

    /// @notice Emitted when a vault's highest price is reset
    /// @param vault The address of the vault
    /// @param newHighestPrice The new highest price
    event HighestPriceReset(address indexed vault, uint128 newHighestPrice);

    ////////////////////////////////////////////////////////////
    //                         Errors                         //
    ////////////////////////////////////////////////////////////

    error Aera__StalePrice();
    error Aera__TimestampMustBeAfterLastUpdate();
    error Aera__TimestampCantBeInFuture();
    error Aera__ZeroAddressOracleRegistry();
    error Aera__InvalidMaxPriceToleranceRatio();
    error Aera__InvalidMinPriceToleranceRatio();
    error Aera__InvalidMaxPriceAge();
    error Aera__InvalidMaxUpdateDelayDays();
    error Aera__ThresholdNotSet();
    error Aera__VaultPaused();
    error Aera__VaultNotPaused();
    error Aera__UnitPriceMismatch();
    error Aera__TimestampMismatch();
    error Aera__VaultAlreadyInitialized();
    error Aera__VaultNotInitialized();
    error Aera__InvalidPrice();
    error Aera__CurrentPriceAboveHighestPrice();

    ////////////////////////////////////////////////////////////
    //                       Functions                        //
    ////////////////////////////////////////////////////////////

    /// @notice Set the initial price state for the vault
    /// @param vault Address of the vault
    /// @param price New unit price
    /// @param timestamp Timestamp when the price was measured
    function setInitialPrice(address vault, uint128 price, uint32 timestamp) external;

    /// @notice Set vault thresholds
    /// @param vault Address of the vault
    /// @param minPriceToleranceRatio Minimum ratio (of a price decrease) in basis points
    /// @param maxPriceToleranceRatio Maximum ratio (of a price increase) in basis points
    /// @param minUpdateIntervalMinutes The minimum interval between updates in minutes
    /// @param maxPriceAge Max delay between when a vault was priced and when the price is acceptable
    /// @param maxUpdateDelayDays Max delay between two price updates
    function setThresholds(
        address vault,
        uint16 minPriceToleranceRatio,
        uint16 maxPriceToleranceRatio,
        uint16 minUpdateIntervalMinutes,
        uint8 maxPriceAge,
        uint8 maxUpdateDelayDays
    ) external;

    /// @notice Set the unit price for the vault in numeraire terms
    /// @param vault Address of the vault
    /// @param price New unit price
    /// @param timestamp Timestamp when the price was measured
    function setUnitPrice(address vault, uint128 price, uint32 timestamp) external;

    /// @notice Pause the vault
    /// @param vault Address of the vault
    function pauseVault(address vault) external;

    /// @notice Unpause the vault
    /// @param vault Address of the vault
    /// @param price Expected price of the last update
    /// @param timestamp Expected timestamp of the last update
    /// @dev MUST revert if price or timestamp don't exactly match last update
    function unpauseVault(address vault, uint128 price, uint32 timestamp) external;

    /// @notice Resets the highest price for a vault to the current price
    /// @param vault Address of the vault
    function resetHighestPrice(address vault) external;

    /// @notice Convert units to token amount
    /// @param vault Address of the vault
    /// @param token Address of the token
    /// @param unitsAmount Amount of units
    /// @return tokenAmount Amount of tokens
    function convertUnitsToToken(address vault, IERC20 token, uint256 unitsAmount)
        external
        view
        returns (uint256 tokenAmount);

    /// @notice Convert units to token amount if vault is not paused
    /// @param vault Address of the vault
    /// @param token Address of the token
    /// @param unitsAmount Amount of units
    /// @param rounding The rounding mode
    /// @return tokenAmount Amount of tokens
    /// @dev MUST revert if vault is paused
    function convertUnitsToTokenIfActive(address vault, IERC20 token, uint256 unitsAmount, Math.Rounding rounding)
        external
        view
        returns (uint256 tokenAmount);

    /// @notice Convert token amount to units
    /// @param vault Address of the vault
    /// @param token Address of the token
    /// @param tokenAmount Amount of tokens
    /// @return unitsAmount Amount of units
    function convertTokenToUnits(address vault, IERC20 token, uint256 tokenAmount)
        external
        view
        returns (uint256 unitsAmount);

    /// @notice Convert token amount to units if vault is not paused
    /// @param vault Address of the vault
    /// @param token Address of the token
    /// @param tokenAmount Amount of tokens
    /// @param rounding The rounding mode
    /// @return unitsAmount Amount of units
    /// @dev MUST revert if vault is paused
    function convertTokenToUnitsIfActive(address vault, IERC20 token, uint256 tokenAmount, Math.Rounding rounding)
        external
        view
        returns (uint256 unitsAmount);

    /// @notice Convert units to numeraire token amount
    /// @param vault Address of the vault
    /// @param unitsAmount Amount of units
    /// @return numeraireAmount Amount of numeraire
    function convertUnitsToNumeraire(address vault, uint256 unitsAmount)
        external
        view
        returns (uint256 numeraireAmount);

    /// @notice Return the state of the vault
    /// @param vault Address of the vault
    /// @return vaultPriceState The price state of the vault
    /// @return vaultAccruals The accruals state of the vault
    function getVaultState(address vault) external view returns (VaultPriceState memory, VaultAccruals memory);

    /// @notice Returns the age of the last submitted price for a vault
    /// @param vault Address of the vault
    /// @return priceAge The difference between block.timestamp and vault's unit price timestamp
    function getVaultsPriceAge(address vault) external view returns (uint256);

    /// @notice Check if a vault is paused
    /// @param vault The address of the vault
    /// @return True if the vault is paused, false otherwise
    function isVaultPaused(address vault) external view returns (bool);
}

src/core/interfaces/IProvisioner.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

import { IERC20 } from "@oz/token/ERC20/IERC20.sol";
import { Request, TokenDetails } from "src/core/Types.sol";

/// @title IProvisioner
/// @notice Interface for the contract that can mint and burn vault units in exchange for tokens
interface IProvisioner {
    ////////////////////////////////////////////////////////////
    //                         Events                         //
    ////////////////////////////////////////////////////////////

    /// @notice Emitted when a user deposits tokens directly into the vault
    /// @param user The address of the depositor
    /// @param token The token being deposited
    /// @param tokensIn The amount of tokens deposited
    /// @param unitsOut The amount of units minted
    /// @param depositHash Unique identifier for this deposit
    event Deposited(
        address indexed user, IERC20 indexed token, uint256 tokensIn, uint256 unitsOut, bytes32 depositHash
    );

    /// @notice Emitted when a deposit is refunded
    /// @param depositHash The hash of the deposit being refunded
    event DepositRefunded(bytes32 indexed depositHash);

    /// @notice Emitted when a direct (sync) deposit is refunded
    /// @param depositHash The hash of the deposit being refunded
    event DirectDepositRefunded(bytes32 indexed depositHash);

    /// @notice Emitted when a user creates a deposit request
    /// @param user The address requesting the deposit
    /// @param token The token being deposited
    /// @param tokensIn The amount of tokens to deposit
    /// @param minUnitsOut The minimum amount of units expected
    /// @param solverTip The tip offered to the solver in deposit token terms
    /// @param deadline Timestamp until which the request is valid
    /// @param maxPriceAge Maximum age of price data that solver can use
    /// @param isFixedPrice Whether the request is a fixed price request
    /// @param depositRequestHash The hash of the deposit request
    event DepositRequested(
        address indexed user,
        IERC20 indexed token,
        uint256 tokensIn,
        uint256 minUnitsOut,
        uint256 solverTip,
        uint256 deadline,
        uint256 maxPriceAge,
        bool isFixedPrice,
        bytes32 depositRequestHash
    );

    /// @notice Emitted when a user creates a redeem request
    /// @param user The address requesting the redemption
    /// @param token The token requested in return for units
    /// @param minTokensOut The minimum amount of tokens the user expects to receive
    /// @param unitsIn The amount of units being redeemed
    /// @param solverTip The tip offered to the solver in redeem token terms
    /// @param deadline The timestamp until which this request is valid
    /// @param maxPriceAge Maximum age of price data that solver can use
    /// @param isFixedPrice Whether the request is a fixed price request
    /// @param redeemRequestHash The hash of the redeem request
    event RedeemRequested(
        address indexed user,
        IERC20 indexed token,
        uint256 minTokensOut,
        uint256 unitsIn,
        uint256 solverTip,
        uint256 deadline,
        uint256 maxPriceAge,
        bool isFixedPrice,
        bytes32 redeemRequestHash
    );

    /// @notice Emitted when a deposit request is solved successfully
    /// @param depositHash The unique identifier of the deposit request that was solved
    event DepositSolved(bytes32 indexed depositHash);

    /// @notice Emitted when a redeem request is solved successfully
    /// @param redeemHash The unique identifier of the redeem request that was solved
    event RedeemSolved(bytes32 indexed redeemHash);

    /// @notice Emitted when an unrecognized async deposit hash is used
    /// @param depositHash The deposit hash that was not found in async records
    event InvalidRequestHash(bytes32 indexed depositHash);

    /// @notice Emitted when async deposits are disabled and a deposit request cannot be processed
    /// @param index The index of the deposit request that was rejected
    event AsyncDepositDisabled(uint256 indexed index);

    /// @notice Emitted when async redeems are disabled and a redeem request cannot be processed
    /// @param index The index of the redeem request that was rejected
    event AsyncRedeemDisabled(uint256 indexed index);

    /// @notice Emitted when the price age exceeds the maximum allowed for a request
    /// @param index The index of the request that was rejected
    event PriceAgeExceeded(uint256 indexed index);

    /// @notice Emitted when a deposit exceeds the vault's configured deposit cap
    /// @param index The index of the request that was rejected
    event DepositCapExceeded(uint256 indexed index);

    /// @notice Emitted when there are not enough tokens to cover the required solver tip
    /// @param index The index of the request that was rejected
    event InsufficientTokensForTip(uint256 indexed index);

    /// @notice Emitted when the output units are less than the amount requested
    /// @param index The index of the request that was rejected
    /// @param amount The actual amount
    /// @param bound The minimum amount
    event AmountBoundExceeded(uint256 indexed index, uint256 amount, uint256 bound);

    /// @notice Emitted when a redeem request is refunded due to expiration or cancellation
    /// @param redeemHash The unique identifier of the redeem request that was refunded
    event RedeemRefunded(bytes32 indexed redeemHash);

    /// @notice Emitted when the vault's deposit limits are updated
    /// @param depositCap The new maximum total value that can be deposited into the vault
    /// @param depositRefundTimeout The new time window during which deposits can be refunded
    event DepositDetailsUpdated(uint256 depositCap, uint256 depositRefundTimeout);

    /// @notice Emitted when a token's deposit/withdrawal settings are updated
    /// @param token The token whose settings are being updated
    /// @param tokensDetails The new token details
    event TokenDetailsSet(IERC20 indexed token, TokenDetails tokensDetails);

    /// @notice Emitted when a token is removed from the provisioner
    /// @param token The token that was removed
    event TokenRemoved(IERC20 indexed token);

    ////////////////////////////////////////////////////////////
    //                         Errors                         //
    ////////////////////////////////////////////////////////////

    error Aera__SyncDepositDisabled();
    error Aera__AsyncDepositDisabled();
    error Aera__AsyncRedeemDisabled();
    error Aera__DepositCapExceeded();
    error Aera__MinUnitsOutNotMet();
    error Aera__TokensInZero();
    error Aera__UnitsInZero();
    error Aera__UnitsOutZero();
    error Aera__MinUnitsOutZero();
    error Aera__MaxTokensInZero();
    error Aera__MaxTokensInExceeded();
    error Aera__MaxDepositRefundTimeoutExceeded();
    error Aera__DepositHashNotFound();
    error Aera__HashNotFound();
    error Aera__RefundPeriodExpired();
    error Aera__DeadlineInPast();
    error Aera__DeadlineTooFarInFuture();
    error Aera__DeadlineInFutureAndUnauthorized();
    error Aera__MinTokenOutZero();
    error Aera__HashCollision();
    error Aera__ZeroAddressPriceAndFeeCalculator();
    error Aera__ZeroAddressMultiDepositorVault();
    error Aera__DepositMultiplierTooLow();
    error Aera__DepositMultiplierTooHigh();
    error Aera__RedeemMultiplierTooLow();
    error Aera__RedeemMultiplierTooHigh();
    error Aera__DepositCapZero();
    error Aera__PriceAndFeeCalculatorVaultPaused();
    error Aera__AutoPriceSolveNotAllowed();
    error Aera__FixedPriceSolverTipNotAllowed();
    error Aera__TokenCantBePriced();
    error Aera__CallerIsVault();
    error Aera__InvalidToken();

    ////////////////////////////////////////////////////////////
    //                         Functions                      //
    ////////////////////////////////////////////////////////////

    /// @notice Deposit tokens directly into the vault
    /// @param token The token to deposit
    /// @param tokensIn The amount of tokens to deposit
    /// @param minUnitsOut The minimum amount of units expected
    /// @dev MUST revert if tokensIn is 0, minUnitsOut is 0, or sync deposits are disabled
    /// @return unitsOut The amount of shares minted to the receiver
    function deposit(IERC20 token, uint256 tokensIn, uint256 minUnitsOut) external returns (uint256 unitsOut);

    /// @notice Mint exact amount of units by depositing required tokens
    /// @param token The token to deposit
    /// @param unitsOut The exact amount of units to mint
    /// @param maxTokensIn Maximum amount of tokens willing to deposit
    /// @return tokensIn The amount of tokens used to mint the requested shares
    function mint(IERC20 token, uint256 unitsOut, uint256 maxTokensIn) external returns (uint256 tokensIn);

    /// @notice Refund a deposit within the refund period
    /// @param sender The original depositor
    /// @param token The deposited token
    /// @param tokenAmount The amount of tokens deposited
    /// @param unitsAmount The amount of units minted
    /// @param refundableUntil Timestamp until which refund is possible
    /// @dev Only callable by authorized addresses
    function refundDeposit(
        address sender,
        IERC20 token,
        uint256 tokenAmount,
        uint256 unitsAmount,
        uint256 refundableUntil
    ) external;

    /// @notice Refund an expired deposit or redeem request
    /// @param token The token involved in the request
    /// @param request The request to refund
    /// @dev Can only be called after request deadline has passed
    function refundRequest(IERC20 token, Request calldata request) external;

    /// @notice Create a new deposit request to be solved by solvers
    /// @param token The token to deposit
    /// @param tokensIn The amount of tokens to deposit
    /// @param minUnitsOut The minimum amount of units expected
    /// @param solverTip The tip offered to the solver
    /// @param deadline Duration in seconds for which the request is valid
    /// @param maxPriceAge Maximum age of price data that solver can use
    /// @param isFixedPrice Whether the request is a fixed price request
    function requestDeposit(
        IERC20 token,
        uint256 tokensIn,
        uint256 minUnitsOut,
        uint256 solverTip,
        uint256 deadline,
        uint256 maxPriceAge,
        bool isFixedPrice
    ) external;

    /// @notice Create a new redeem request to be solved by solvers
    /// @param token The token to receive
    /// @param unitsIn The amount of units to redeem
    /// @param minTokensOut The minimum amount of tokens expected
    /// @param solverTip The tip offered to the solver
    /// @param deadline Duration in seconds for which the request is valid
    /// @param maxPriceAge Maximum age of price data that solver can use
    function requestRedeem(
        IERC20 token,
        uint256 unitsIn,
        uint256 minTokensOut,
        uint256 solverTip,
        uint256 deadline,
        uint256 maxPriceAge,
        bool isFixedPrice
    ) external;

    /// @notice Solve multiple requests using vault's liquidity
    /// @param token The token for which to solve requests
    /// @param requests Array of requests to solve
    /// @dev Only callable by authorized addresses
    function solveRequestsVault(IERC20 token, Request[] calldata requests) external;

    /// @notice Solve multiple requests using solver's own liquidity
    /// @param token The token for which to solve requests
    /// @param requests Array of requests to solve
    function solveRequestsDirect(IERC20 token, Request[] calldata requests) external;

    /// @notice Update token parameters
    /// @param token The token to update
    /// @param tokensDetails The new token details
    function setTokenDetails(IERC20 token, TokenDetails calldata tokensDetails) external;

    /// @notice Removes token from provisioner
    /// @param token The token to be removed
    function removeToken(IERC20 token) external;

    /// @notice Update deposit parameters
    /// @param depositCap_ New maximum total value that can be deposited
    /// @param depositRefundTimeout_ New time window for deposit refunds
    function setDepositDetails(uint256 depositCap_, uint256 depositRefundTimeout_) external;

    /// @notice Return maximum amount that can still be deposited
    /// @return Amount of deposit capacity remaining
    function maxDeposit() external view returns (uint256);

    /// @notice Check if a user's units are currently locked
    /// @param user The address to check
    /// @return True if user's units are locked, false otherwise
    function areUserUnitsLocked(address user) external view returns (bool);

    /// @notice Computes the hash for a sync deposit
    /// @param user The address making the deposit
    /// @param token The token being deposited
    /// @param tokenAmount The amount of tokens to deposit
    /// @param unitsAmount Minimum amount of units to receive
    /// @param refundableUntil The timestamp until which the deposit is refundable
    /// @return The hash of the deposit
    function getDepositHash(
        address user,
        IERC20 token,
        uint256 tokenAmount,
        uint256 unitsAmount,
        uint256 refundableUntil
    ) external pure returns (bytes32);

    /// @notice Computes the hash for a generic request
    /// @param token The token involved in the request
    /// @param request The request struct
    /// @return The hash of the request
    function getRequestHash(IERC20 token, Request calldata request) external pure returns (bytes32);
}

src/core/interfaces/ISubmitHooks.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

/// @title ISubmitHooks
/// @notice Interface for hooks that execute before and after submit calls
interface ISubmitHooks {
    ////////////////////////////////////////////////////////////
    //                       Functions                        //
    ////////////////////////////////////////////////////////////

    /// @notice Called before a submit
    /// @param data Encoded data of the submit
    /// @param guardian Address of the guardian that submitted
    function beforeSubmit(bytes memory data, address guardian) external;

    /// @notice Called after a submit
    /// @param data Encoded data of the submit
    /// @param guardian Address of the guardian that submitted
    function afterSubmit(bytes memory data, address guardian) external;
}

src/core/interfaces/IWhitelist.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

interface IWhitelist {
    ////////////////////////////////////////////////////////////
    //                        Events                          //
    ////////////////////////////////////////////////////////////

    event WhitelistSet(address indexed addr, bool isAddressWhitelisted);

    ////////////////////////////////////////////////////////////
    //                       Functions                        //
    ////////////////////////////////////////////////////////////

    /// @notice Set the address whitelisted status
    /// @param addr The address to add/remove from the whitelist
    /// @param isAddressWhitelisted Whether address should be whitelisted going forward
    function setWhitelisted(address addr, bool isAddressWhitelisted) external;

    /// @notice Checks if the address is whitelisted
    /// @param addr The address to check
    /// @return True if the addr is whitelisted, false otherwise
    function isWhitelisted(address addr) external view returns (bool);

    /// @notice Get all whitelisted addresses
    /// @return An array of all whitelisted addresses
    function getAllWhitelisted() external view returns (address[] memory);
}

src/dependencies/oracles/IOracle.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

/// @dev Implements the spec at https://eips.ethereum.org/EIPS/eip-7726
interface IOracle {
    ////////////////////////////////////////////////////////////
    //                       Functions                        //
    ////////////////////////////////////////////////////////////

    /// @notice Returns the value of `baseAmount` of `base` in `quote` terms
    /// @dev MUST round down towards 0
    /// MUST revert with `OracleUnsupportedPair` if not capable to provide data for the specified `base`
    /// and `quote` pair
    /// MUST revert with `OracleUntrustedData` if not capable to provide data within a degree of
    /// confidence publicly specified
    /// @param baseAmount The amount of `base` to convert
    /// @param base The asset that the user needs to know the value for
    /// @param quote The asset in which the user needs to value the base
    /// @return quoteAmount The value of `baseAmount` of `base` in `quote` terms
    function getQuote(uint256 baseAmount, address base, address quote) external view returns (uint256 quoteAmount);
}

src/dependencies/solmate/auth/Auth.sol

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.29;

/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
abstract contract Auth {
    event OwnershipTransferred(address indexed user, address indexed newOwner);

    event AuthorityUpdated(address indexed user, Authority indexed newAuthority);

    address public owner;

    Authority public authority;

    constructor(address _owner, Authority _authority) {
        owner = _owner;
        authority = _authority;

        emit OwnershipTransferred(msg.sender, _owner);
        emit AuthorityUpdated(msg.sender, _authority);
    }

    modifier requiresAuth() virtual {
        require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");

        _;
    }

    function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
        Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.

        // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
        // aware that this makes protected functions uncallable even to the owner if the authority is out of order.
        return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
    }

    function setAuthority(Authority newAuthority) public virtual {
        // We check if the caller is the owner first because we want to ensure they can
        // always swap out the authority even if it's reverting or using up a lot of gas.
        require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));

        authority = newAuthority;

        emit AuthorityUpdated(msg.sender, newAuthority);
    }

    function transferOwnership(address newOwner) public virtual requiresAuth {
        owner = newOwner;

        emit OwnershipTransferred(msg.sender, newOwner);
    }
}

/// @notice A generic interface for a contract which provides authorization data to an Auth instance.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
interface Authority {
    function canCall(address user, address target, bytes4 functionSig) external view returns (bool);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 100000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@oz/=lib/openzeppelin-contracts/contracts/",
    "@solmate/=src/dependencies/solmate/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.