Skip to content
Verified contractExactMIT

FastExchange

Address0x162ff8b2cd2cee7afd12dc907c0910da918b6028
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

2 more contracts

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,218,881
Creation transaction
0xaaf07c203b…d263dae0b4
Main copy (most transactions)
0x06fda5df…3e23b062

31 files

src/FastExchange.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Exchange} from "./Exchange.sol";
import {ExecutionOracle} from "./ExecutionOracle.sol";
import {IPricing} from "./interfaces/IPricing.sol";
import {ISessions} from "./interfaces/ISessions.sol";

/// @notice Tape execution without a fixed pricing wait. Wallet authorization, collateral,
///         pricing, queues, fees and permissionless exits follow the original Exchange.
/// @dev Each manual execution needs a price-signer attestation for that exact order digest.
///      This deliberately trusts the signer to quote promptly from a fresh source and to retain
///      the first quote per order. Ethereum inclusion still follows pricing. A generic historical
///      market print cannot execute a manual open or close.
contract FastExchange is Exchange {
    mapping(bytes32 id => uint64 observedAt) private _executionTime;
    event PositionPricingTime(bytes32 indexed id, uint64 observedAt);

    constructor(
        string memory name_,
        IERC20 usdc_,
        ExecutionOracle oracle_,
        IPricing pricing_,
        ISessions sessions_,
        address owner_,
        address devRecipient_,
        uint256 stakerCap_,
        uint96 minMargin_
    ) Exchange(name_, usdc_, oracle_, pricing_, sessions_, owner_, devRecipient_, stakerCap_, minMargin_) {}

    function EXEC_DELAY() public pure override returns (uint64) {
        return 0;
    }

    function _requireWalletAuth(address owner, bytes32 digest, bytes calldata signature)
        internal
        view
        override
    {
        if (!ExecutionOracle(address(oracle)).checkWalletSignature(owner, digest, signature)) revert BadSignature();
    }

    function _openPrice(OpenIntent calldata it, bytes32 id, bytes[] calldata update)
        internal
        override
        returns (uint64 price, uint64 conf, uint64 publishTime)
    {
        uint64 observedAt;
        (price, conf, publishTime, observedAt) = ExecutionOracle(address(oracle)).fill(
            _markets[it.market].feedId, id, update, it.timestamp, it.timestamp + PIN_WINDOW
        );
        _executionTime[id] = observedAt;
        emit PositionPricingTime(id, observedAt);
    }

    function _intentClosePrice(CloseIntent calldata it, Position memory p, bytes[] calldata update)
        internal
        view
        override
        returns (uint64 price)
    {
        Market storage m = _markets[p.market];
        if (m.retired) return m.frozenPrice;
        uint64 observedAt;
        (price,,, observedAt) = ExecutionOracle(address(oracle)).fill(
            m.feedId, _hashClose(it), update, it.timestamp, it.timestamp + PIN_WINDOW
        );
        // An order-bound quote can close after an open within the same second. Its provenance
        // comes from the signed order digest, rather than selecting a public print for that second.
        if (observedAt <= _executionTime[it.positionId]) revert CloseNotAfterOpen();
    }

    function _triggerPrice(Position memory, uint64 touchedPrice, uint64, bytes[] calldata)
        internal
        pure
        override
        returns (uint64)
    {
        // The trigger was authorized before this touch. Its actual crossing print fixes the fill;
        // there is no delayed print for the operator to select after seeing the crossing.
        return touchedPrice;
    }

    function _triggerTouch(TriggerIntent calldata it, Position memory p, bytes[] calldata touch)
        internal
        view
        override
        returns (uint64 price, uint64 touchedAt)
    {
        uint64 afterTime = _executionTime[it.positionId];
        // Trigger timestamps use whole seconds. Requiring a later second prevents a newly signed
        // trigger selecting an already-known tick from the same second. Existing triggers have no
        // extra wait when they cross, and can fire within the position's opening second.
        uint64 afterSignature = (it.timestamp + 1) * 1000 - 1;
        if (afterSignature > afterTime) afterTime = afterSignature;
        (price,, touchedAt,) = ExecutionOracle(address(oracle)).afterMs(
            _markets[p.market].feedId, touch, afterTime
        );
    }

    function _liquidationPrice(bytes32 id, Position memory p, bytes[] calldata update)
        internal
        view
        override
        returns (uint64 price, uint64 publishTime)
    {
        (price,, publishTime,) = ExecutionOracle(address(oracle)).afterMs(
            _markets[p.market].feedId, update, _executionTime[id]
        );
    }

    function _removePosition(bytes32 id, Position memory p) internal override {
        super._removePosition(id, p);
        delete _executionTime[id];
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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.1.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.1.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.1.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/Context.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

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

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

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

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

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/Strings.sol

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

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// 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/cryptography/ECDSA.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol

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

pragma solidity ^0.8.20;

import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";

/**
 * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
 * signatures from externally owned accounts (EOAs) as well as ERC-1271 signatures from smart contract wallets like
 * Argent and Safe Wallet (previously Gnosis Safe).
 */
library SignatureChecker {
    /**
     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
     * signature is validated against that smart contract using ERC-1271, otherwise it's validated using `ECDSA.recover`.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
        if (signer.code.length == 0) {
            (address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature);
            return err == ECDSA.RecoverError.NoError && recovered == signer;
        } else {
            return isValidERC1271SignatureNow(signer, hash, signature);
        }
    }

    /**
     * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
     * against the signer smart contract using ERC-1271.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidERC1271SignatureNow(
        address signer,
        bytes32 hash,
        bytes memory signature
    ) internal view returns (bool) {
        (bool success, bytes memory result) = signer.staticcall(
            abi.encodeCall(IERC1271.isValidSignature, (hash, signature))
        );
        return (success &&
            result.length >= 32 &&
            abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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.1.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.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @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, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

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

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

src/Exchange.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

import {Intents} from "./base/Intents.sol";
import {IOracle} from "./interfaces/IOracle.sol";
import {IPricing} from "./interfaces/IPricing.sol";
import {ISessions} from "./interfaces/ISessions.sol";
import {IStaking, ILossMining, IAttached} from "./interfaces/IHooks.sol";

/// @title Exchange
/// @notice Synthetic perpetuals up to 1000x against a house that starts from zero.
///
/// @dev HOW A TRADE WORKS
///      Every trade is a swap between one trader and the house. There is no order book and no other
///      counterparty. A position is a discrete slug: margin and leverage are fixed at open, and it
///      ends by being closed in full or by busting.
///
///      PRICE. A trader signs an intent stamped with the current second T. The intent executes at
///      the first Pyth price published at or after T + EXEC_DELAY. That price is unique and
///      verifiable, so the trader knows their fill two seconds after clicking even though the
///      transaction lands a block later, and the operator that submits it cannot choose it.
///
///      COST. No fee on notional, no spread, no funding. The house takes its cut from winning closes
///      only: a 0.2 bps deadband, an impact haircut that shrinks as the move grows, and a 2% fee on
///      what is left. A loss costs the loss and nothing more.
///
///      SIZE. A position fills and closes at the oracle's price whatever its size, so a trader
///      holding enough of one side could push the real market a few basis points, close, and be
///      paid for the push on all of it. Two things stand against that. Each side of a market is
///      capped. And size costs: every market has a `depth`, and a position opened on a side that
///      already holds more than that keeps less of a win, the more so the fuller the side and the
///      smaller the move (see `PerpMath.impactNotionalFor`). The terms follow the side, not the
///      position, so splitting a position or spreading it over accounts climbs the same stack
///      and buys only a few percent. They are fixed at open, so nothing done afterwards changes
///      them, and the order itself says the most it will accept (`impactLimit`). Up to `depth`,
///      and for a single position of up to twice that on an empty side, nothing changes at all.
///
///      THE HOUSE. It holds no seed capital. Losses fund it. A win it cannot pay in full goes into a
///      first-in-first-out queue and is paid as later losses arrive. Collateral is never queued:
///      only profit is.
///
///      WHY INTENTS CANNOT BE SWITCHED. Because the price is fixed by the signed timestamp while the
///      transaction lands seconds later, a trader able to cancel an intent in between, or to bring a
///      failing one to life, would hold a free option on those seconds. So nothing a trader can call
///      directly changes the fate of an intent they have already signed:
///        - a session key change only bites on later timestamps, and an ended key never comes back;
///        - a withdrawal request freezes new opens instead of moving money, and pays out only after
///          a delay far longer than any intent lives;
///        - a signed withdrawal has its own replay counter and goes through the operator;
///        - a direct close is a binding request: until every intent signed before it has had time
///          to land, only an operator can execute it, and a signed close priced after it is refused.
///
///      TRUST. Operators (the relayer keys) are trusted to submit intents promptly, in order, and
///      only when freshly signed. They cannot forge an intent, choose a price or move funds. If they
///      stop, traders still exit through `requestClose` and `requestWithdraw`. The contract is not
///      upgradeable and has no function that touches a trader's balance.
contract Exchange is Intents, Ownable2Step, ReentrancyGuardTransient {
    using SafeERC20 for IERC20;

    // ------------------------------------------------------------------------------------------
    // Types
    // ------------------------------------------------------------------------------------------

    struct Market {
        bytes32 feedId;
        uint16 maxLeverage;
        /// @dev The most of a raw gain a win keeps, in bps.
        uint16 maxKeepBps;
        /// @dev Opens are refused while Pyth's confidence interval is wider than this, in bps.
        uint16 maxConfBps;
        /// @dev The impact curve's two parameters (see `PerpMath.settle`). The second is in thousandths.
        uint32 rateMultiplier;
        uint32 positionMultiplier;
        /// @dev One price tick in 1e8 terms: the unit the deadband and the bust price round to.
        uint32 tick;
        /// @dev How far the bust trigger sits before zero equity, as a 1e18 fraction of that price.
        uint64 bustBuffer;
        bool retired;
        uint64 retiredAt;
        uint64 frozenPrice;
        uint80 maxNotional;
        /// @dev How much may be open on one side at the curve's own price, in whole dollars. A
        ///      position opened past it is charged for the size already there.
        uint32 depth;
        uint96 oiLong;
        uint96 oiShort;
        uint96 capLong;
        uint96 capShort;
        /// @dev Open positions per side in units of the asset, scaled by 1e18. With the open
        ///      interest (what was paid for them) this is all that is needed to mark the house's
        ///      exposure at any price.
        uint128 sizeLong;
        uint128 sizeShort;
    }

    /// @dev The pricing parameters of a market, as `listMarket` takes them.
    struct Curve {
        uint32 rateMultiplier;
        uint32 positionMultiplier;
        uint32 tick;
        uint64 bustBuffer;
        uint32 depth;
    }

    struct Position {
        address owner;
        uint16 market;
        uint16 leverage;
        bool isLong;
        /// @dev Slot in the owner's list of open positions.
        uint16 index;
        /// @dev Publish time of the entry price.
        uint40 openTime;
        uint80 margin;
        /// @dev The part of `margin` that was funded from the owner's queued payout, not cash.
        uint80 debtMargin;
        uint64 entryPrice;
        /// @dev The notional the impact of a win is charged on, in whole dollars. Set at open
        ///      from how full the side was, and never changed.
        uint32 impactNotional;
    }

    struct Claim {
        address user;
        uint96 amount;
    }

    struct WithdrawRequest {
        uint128 amount;
        uint64 requestedAt;
        /// @dev When the request was executed or cancelled. Zero while it is pending.
        uint64 closedAt;
    }

    enum CloseKind {
        Close,
        Liquidation
    }

    // ------------------------------------------------------------------------------------------
    // Constants
    // ------------------------------------------------------------------------------------------

    uint256 private constant BPS = 10_000;

    /// @notice Fee on a win's gain, and the house-side fee carved from a loss.
    uint256 public constant FEE_BPS = 200;
    /// @notice Share of every fee that goes to stakers. The rest goes to the dev recipient.
    uint256 public constant STAKER_SHARE_BPS = 5_000;
    uint16 internal constant MAX_LEVERAGE = 1_000;
    uint256 public constant MAX_OPEN_POSITIONS = 200;

    /// @notice An intent stamped T executes at the first price published at or after T + this.
    function EXEC_DELAY() public pure virtual returns (uint64) {
        return 2;
    }
    /// @notice ...and no later than this many seconds after that.
    uint64 public constant PIN_WINDOW = 10;
    /// @notice An intent must land within this many seconds of its timestamp.
    uint64 public constant INTENT_TTL = 60;
    /// @notice A direct close executes at the first price this long after the request. Two slots,
    ///         so the price cannot be known when the request is sent.
    uint64 public constant DIRECT_DELAY = 24;
    /// @notice A direct close request lapses if nobody executed it within this long. After that
    ///         it shields the position from nothing and a new one can be made.
    uint64 public constant REQUEST_EXPIRY = 10 minutes;
    /// @notice Delay on the direct withdrawal exit. Must exceed `INTENT_TTL`.
    uint64 public constant WITHDRAW_DELAY = 15 minutes;
    /// @dev Oldest price a guardian may freeze a retired market at.
    uint64 internal constant RETIRE_MAX_AGE = 60;

    /// @dev The widest a bust buffer may be: 1% of the zero-equity price.
    uint64 internal constant MAX_BUST_BUFFER = 1e16;
    uint16 internal constant MIN_KEEP_BPS = 5_000;
    uint16 internal constant MAX_CONF_BPS = 1_000;

    /// @dev Queue entries paid automatically whenever a loss lands.
    uint256 private constant AUTO_HARVEST = 4;
    /// @dev Gas handed to the loss-mining hook, and the floor required before calling it so that a
    ///      caller cannot starve the hook by under-supplying gas.
    uint256 private constant MINING_GAS = 150_000;
    uint256 private constant MINING_GAS_FLOOR = 165_000;

    // ------------------------------------------------------------------------------------------
    // Immutables
    // ------------------------------------------------------------------------------------------

    IERC20 public immutable usdc;
    IOracle public immutable oracle;
    /// @notice The arithmetic of a position. Stateless, and fixed for good.
    IPricing public immutable pricing;
    /// @notice House equity above this is distributable to stakers.
    uint256 public immutable stakerCap;

    // ------------------------------------------------------------------------------------------
    // Storage
    // ------------------------------------------------------------------------------------------

    Market[] internal _markets;
    mapping(bytes32 id => Position) private _positions;
    mapping(address owner => bytes32[]) private _openIds;
    /// @notice When a binding direct close was requested for a position, or zero.
    mapping(bytes32 id => uint64) public closeRequestedAt;
    mapping(bytes32 intentHash => bool) public usedIntent;

    /// @notice A trader's free collateral. Always fully backed and always theirs to withdraw.
    mapping(address user => uint256) public balances;
    mapping(address user => WithdrawRequest) public withdrawRequests;

    /// @notice All USDC the Exchange accounts for.
    uint256 public treasury;
    uint256 public totalBalances;
    /// @notice Cash margin locked in open positions.
    uint256 public totalCashMargin;
    /// @notice Queue-funded margin locked in open positions. A liability, not cash.
    uint256 public debtMarginOpen;
    uint256 public stakerFees;
    uint256 public devFees;

    /// @notice The payout queue. Live claims are `queueHead` up to, not including, `queueTail`.
    mapping(uint256 claimId => Claim) public claims;
    uint256 public queueHead;
    uint256 public queueTail;
    /// @notice Everything the house owes and has not paid.
    uint256 public totalQueued;
    /// @notice What the house owes one trader.
    mapping(address user => uint256) public queuedOf;
    /// @dev Queued payout a trader has already spent as margin, netted off their oldest claims when
    ///      the queue reaches them.
    mapping(address user => uint256) public queueSpent;

    mapping(address => bool) public isOperator;
    address public guardian;
    address public devRecipient;
    address public staking;
    address public lossMining;
    /// @notice The only contract that may send house cash above the cap to stakers.
    address public sweeper;
    bool public opensPaused;
    uint96 public minMargin;
    /// @notice The smallest position, margin times leverage, that can be opened.
    uint96 public minNotional;

    // ------------------------------------------------------------------------------------------
    // Events
    // ------------------------------------------------------------------------------------------

    event Deposited(address indexed user, address indexed from, uint256 amount);
    event Withdrawn(address indexed user, address indexed to, uint256 amount);
    event WithdrawRequested(address indexed user, uint256 amount, uint256 executableAt);
    event PositionOpened(
        bytes32 indexed id,
        address indexed owner,
        uint16 indexed market,
        bool isLong,
        uint16 leverage,
        uint96 margin,
        uint96 debtMargin,
        uint64 entryPrice,
        uint64 entryTime,
        uint32 impactNotional
    );
    /// @param pnl Profit after every deduction, or minus the loss.
    /// @param credited USDC credited to the owner's balance by this close.
    /// @param queued USDC added to the owner's queued payout by this close.
    /// @param fee Fee actually paid out to stakers and the dev recipient.
    event PositionClosed(
        bytes32 indexed id,
        address indexed owner,
        uint16 indexed market,
        CloseKind kind,
        uint64 exitPrice,
        int256 pnl,
        uint256 credited,
        uint256 queued,
        uint256 fee
    );
    event CloseRequested(bytes32 indexed id, address indexed owner, uint64 pinTime);
    event Queued(address indexed user, uint256 indexed claimId, uint256 amount);
    event QueuePaid(address indexed user, uint256 indexed claimId, uint256 amount);
    event QueueSpent(address indexed user, uint256 amount);
    event StakerFeesPushed(uint256 fees, uint256 excess);
    event DevFeesClaimed(address indexed to, uint256 amount);
    event Donated(address indexed from, uint256 amount);
    event MarketListed(uint16 indexed id, bytes32 feedId, string symbol);
    event MarketRetired(uint16 indexed id, uint64 frozenPrice);
    event CapsSet(uint16 indexed id, uint96 capLong, uint96 capShort);
    event DepthSet(uint16 indexed id, uint32 depth);
    event MinimumsSet(uint96 minMargin, uint96 minNotional);
    event OperatorSet(address indexed operator, bool allowed);
    event GuardianSet(address indexed guardian);
    event DevRecipientSet(address indexed recipient);
    event CoinAttached(address indexed staking, address indexed lossMining);
    event OpensPausedSet(bool paused);
    event MiningFailed(address indexed user, uint256 usd);

    // ------------------------------------------------------------------------------------------
    // Errors
    // ------------------------------------------------------------------------------------------

    error ZeroAddress();
    error ZeroAmount();
    error NotOperator();
    error NotGuardian();
    error BadMarket();
    error BadParams();
    error MarketIsRetired();
    error OpensPaused();
    error IntentUsed();
    error IntentExpired();
    error BadLeverage();
    error MarginTooSmall();
    error NotionalTooLarge();
    error NotionalTooSmall();
    error ConfidenceTooWide();
    error PriceLimitExceeded();
    error ImpactLimitExceeded();
    error OpenInterestCap();
    error InsufficientBalance();
    error TooManyPositions();
    error NoPosition();
    error NotPositionOwner();
    error CloseNotAfterOpen();
    error CloseAlreadyRequested();
    error NoRequest();
    error TooEarly();
    error Expired();
    error NotLiquidatable();
    error NotTriggered();
    error CloseHasPriority();
    error ExitPending();
    error LiquidationGrace();
    error AlreadyAttached();
    error NoStaking();
    error NothingToPush();
    error InsufficientGas();

    // ------------------------------------------------------------------------------------------
    // Construction
    // ------------------------------------------------------------------------------------------

    constructor(
        string memory name_,
        IERC20 usdc_,
        IOracle oracle_,
        IPricing pricing_,
        ISessions sessions_,
        address owner_,
        address devRecipient_,
        uint256 stakerCap_,
        uint96 minMargin_
    ) Intents(name_, sessions_) Ownable(owner_) {
        if (
            address(usdc_) == address(0) || address(oracle_) == address(0) || address(pricing_) == address(0)
                || address(sessions_) == address(0) || devRecipient_ == address(0)
        ) revert ZeroAddress();
        usdc = usdc_;
        oracle = oracle_;
        pricing = pricing_;
        devRecipient = devRecipient_;
        stakerCap = stakerCap_;
        minMargin = minMargin_;
    }

    modifier onlyOperator() {
        if (!isOperator[msg.sender]) revert NotOperator();
        _;
    }

    modifier onlyGuardian() {
        if (msg.sender != guardian && msg.sender != owner()) revert NotGuardian();
        _;
    }

    // ------------------------------------------------------------------------------------------
    // Collateral
    // ------------------------------------------------------------------------------------------

    /// @notice Deposits USDC into the caller's balance.
    function deposit(uint256 amount) external nonReentrant {
        _deposit(msg.sender, msg.sender, amount);
    }

    /// @notice Deposits the caller's USDC into `user`'s balance.
    function depositFor(address user, uint256 amount) external nonReentrant {
        _deposit(msg.sender, user, amount);
    }

    /// @notice Withdraws on the wallet's signature, submitted by an operator. Instant and gasless.
    /// @dev Operator-only so that a trader cannot race their own pending intents with it.
    function withdrawBySig(
        address owner_,
        address to,
        uint256 amount,
        uint64 deadline,
        bytes calldata signature
    ) external onlyOperator nonReentrant {
        if (block.timestamp > deadline) revert Expired();
        _requireWalletAuth(
            owner_, _hashWithdraw(owner_, to, amount, withdrawNonces[owner_]++, deadline), signature
        );
        _withdraw(owner_, to, amount);
    }

    /// @notice Starts the direct exit: after `WITHDRAW_DELAY` the caller can take up to `amount`.
    ///         Needs no operator. Requesting zero cancels a pending request.
    /// @dev A request moves no money. What it does is stop the account opening new positions (see
    ///      `open`) until it is executed or cancelled, so that the withdrawal, once it matures, has
    ///      no pending open to pull the margin out from under. One request at a time, and a new one
    ///      may not follow so closely that it would lift the freeze the last one still imposes.
    function requestWithdraw(uint128 amount) external {
        WithdrawRequest storage request = withdrawRequests[msg.sender];
        bool pending = request.requestedAt != 0 && request.closedAt == 0;
        if (amount == 0) {
            if (!pending) revert NoRequest();
            request.closedAt = uint64(block.timestamp);
        } else {
            if (pending || block.timestamp < uint256(request.closedAt) + GRACE + INTENT_TTL) {
                revert TooEarly();
            }
            withdrawRequests[msg.sender] = WithdrawRequest(amount, uint64(block.timestamp), 0);
        }
        emit WithdrawRequested(msg.sender, amount, block.timestamp + WITHDRAW_DELAY);
    }

    /// @notice Completes the direct exit. Pays the requested amount, or the whole balance if less.
    function executeWithdraw(address to) external nonReentrant {
        WithdrawRequest storage request = withdrawRequests[msg.sender];
        if (request.requestedAt == 0 || request.closedAt != 0) revert NoRequest();
        if (block.timestamp < uint256(request.requestedAt) + WITHDRAW_DELAY) revert TooEarly();
        request.closedAt = uint64(block.timestamp);
        _withdraw(msg.sender, to, Math.min(request.amount, balances[msg.sender]));
    }

    function _deposit(address from, address user, uint256 amount) private {
        if (user == address(0)) revert ZeroAddress();
        if (amount == 0) revert ZeroAmount();
        usdc.safeTransferFrom(from, address(this), amount);
        treasury += amount;
        _credit(user, amount);
        emit Deposited(user, from, amount);
    }

    function _withdraw(address user, address to, uint256 amount) private {
        if (to == address(0)) revert ZeroAddress();
        if (amount == 0) revert ZeroAmount();
        if (balances[user] < amount) revert InsufficientBalance();
        balances[user] -= amount;
        totalBalances -= amount;
        treasury -= amount;
        usdc.safeTransfer(to, amount);
        emit Withdrawn(user, to, amount);
    }

    // ------------------------------------------------------------------------------------------
    // Trading: operator path
    // ------------------------------------------------------------------------------------------

    /// @notice Opens the position described by a signed intent. The intent's hash is the position id.
    function open(OpenIntent calldata it, bytes calldata signature, bytes[] calldata update)
        external
        onlyOperator
        nonReentrant
        returns (bytes32 id)
    {
        id = _hashOpen(it);
        if (usedIntent[id]) revert IntentUsed();
        _requireTradeAuth(it.owner, id, signature, it.timestamp);
        if (block.timestamp > uint256(it.timestamp) + INTENT_TTL) revert IntentExpired();
        usedIntent[id] = true;

        // An account that has asked to leave does not open. Like every account-level switch, the
        // freeze starts and ends one slot after the block that changed it, on the intent's clock.
        WithdrawRequest memory exit = withdrawRequests[it.owner];
        if (
            exit.requestedAt != 0 && it.timestamp >= exit.requestedAt + GRACE
                && (exit.closedAt == 0 || it.timestamp < exit.closedAt + GRACE)
        ) revert ExitPending();

        if (opensPaused) revert OpensPaused();
        if (it.market >= _markets.length) revert BadMarket();
        Market storage m = _markets[it.market];
        if (m.retired) revert MarketIsRetired();
        if (it.leverage == 0 || it.leverage > m.maxLeverage) revert BadLeverage();
        if (it.margin < minMargin || it.margin == 0) revert MarginTooSmall();
        uint256 notional = uint256(it.margin) * it.leverage;
        if (notional > m.maxNotional) revert NotionalTooLarge();
        if (notional < minNotional) revert NotionalTooSmall();

        (uint64 price, uint64 conf, uint64 publishTime) =
            _openPrice(it, id, update);
        if (uint256(conf) * BPS > uint256(price) * m.maxConfBps) revert ConfidenceTooWide();
        if (it.priceLimit != 0 && (it.isLong ? price > it.priceLimit : price < it.priceLimit)) {
            revert PriceLimitExceeded();
        }

        // `notional` is bounded by `maxNotional`, a uint80, and a size by notional * 1e18.
        // forge-lint: disable-start(unsafe-typecast)
        uint128 size = uint128(Math.mulDiv(notional, 1e18, price));
        // What is already open on this side: the position is charged for it (see `Pricing`).
        uint256 ahead;
        if (it.isLong) {
            ahead = m.oiLong;
            if (ahead + notional > m.capLong) revert OpenInterestCap();
            m.oiLong = uint96(ahead + notional);
            m.sizeLong += size;
        } else {
            ahead = m.oiShort;
            if (ahead + notional > m.capShort) revert OpenInterestCap();
            m.oiShort = uint96(ahead + notional);
            m.sizeShort += size;
        }
        // forge-lint: disable-end(unsafe-typecast)
        uint32 impactNotional =
            pricing.open(price, it.leverage, m.tick, m.bustBuffer, ahead, notional, m.depth);
        if (impactNotional == 0) revert BadLeverage();
        // The side can fill up between the signing of an order and its landing. The trader says
        // how much of that they will take, as they do for the price.
        if (it.impactLimit != 0 && impactNotional > it.impactLimit) revert ImpactLimitExceeded();

        // Margin comes from the queued payout first when asked, then from cash. Drawing on the sum
        // means a harvest that pays the owner in between changes nothing.
        uint256 debtPart;
        if (it.useQueued) {
            debtPart = Math.min(queuedOf[it.owner], it.margin);
            if (debtPart != 0) _spendQueued(it.owner, debtPart);
        }
        uint256 cashPart = it.margin - debtPart;
        if (balances[it.owner] < cashPart) revert InsufficientBalance();
        balances[it.owner] -= cashPart;
        totalBalances -= cashPart;
        totalCashMargin += cashPart;
        debtMarginOpen += debtPart;

        bytes32[] storage ids = _openIds[it.owner];
        if (ids.length >= MAX_OPEN_POSITIONS) revert TooManyPositions();
        // `ids.length` is below 200, `publishTime` fits 40 bits until the year 36812, and
        // `debtPart` is at most `it.margin`, which is at most the notional: `maxNotional`, a uint80.
        // forge-lint: disable-start(unsafe-typecast)
        _positions[id] = Position({
            owner: it.owner,
            market: it.market,
            leverage: it.leverage,
            isLong: it.isLong,
            index: uint16(ids.length),
            openTime: uint40(publishTime),
            margin: uint80(it.margin),
            debtMargin: uint80(debtPart),
            entryPrice: price,
            impactNotional: impactNotional
        });
        ids.push(id);

        emit PositionOpened(
            id,
            it.owner,
            it.market,
            it.isLong,
            it.leverage,
            it.margin,
            uint96(debtPart),
            price,
            publishTime,
            impactNotional
        );
        // forge-lint: disable-end(unsafe-typecast)
    }

    /// @notice Closes a position on a signed intent, at the price fixed by the intent's timestamp.
    function close(CloseIntent calldata it, bytes calldata signature, bytes[] calldata update)
        external
        onlyOperator
        nonReentrant
    {
        Position memory p = _positions[it.positionId];
        if (p.owner == address(0)) revert NoPosition();
        if (p.owner != it.owner) revert NotPositionOwner();
        _requireTradeAuth(it.owner, _hashClose(it), signature, it.timestamp);
        if (block.timestamp > uint256(it.timestamp) + INTENT_TTL) revert IntentExpired();
        _beforeRequest(it.positionId, it.timestamp + EXEC_DELAY());
        _settle(it.positionId, p, _intentClosePrice(it, p, update), false);
    }

    /// @notice Closes a position on its take-profit or stop-loss: a signed trigger, a print that
    ///         touched it, and the price the close is then fixed at.
    /// @dev The trader signs the trigger once and the operator holds it. When a print at or beyond
    ///      the trigger's price appears after the trigger was signed, the close is priced exactly as
    ///      if the trader had clicked at that print: the first price `EXEC_DELAY` after it. Like any
    ///      order it has to land within `INTENT_TTL` of that moment, so a touch cannot be saved up
    ///      and used later. The operator still chooses whether to land it, as with every order.
    function closeOnTrigger(
        TriggerIntent calldata it,
        bytes calldata signature,
        bytes[] calldata touch,
        bytes[] calldata update
    ) external onlyOperator nonReentrant {
        Position memory p = _positions[it.positionId];
        if (p.owner == address(0)) revert NoPosition();
        // Checked against the position's own owner: only their keys can sign for it, whatever
        // owner the trigger names.
        _requireTradeAuth(p.owner, _hashTrigger(it), signature, it.timestamp);
        // A print after the trigger was signed, and after the position opened, at or past its price.
        (uint64 price, uint64 touchedAt) = _triggerTouch(it, p, touch);
        if (it.above ? price < it.price : price > it.price) revert NotTriggered();
        if (block.timestamp > uint256(touchedAt) + INTENT_TTL) revert IntentExpired();
        _beforeRequest(it.positionId, touchedAt + EXEC_DELAY());
        _settle(it.positionId, p, _triggerPrice(p, price, touchedAt, update), false);
    }

    // ------------------------------------------------------------------------------------------
    // Trading: direct path (no operator needed)
    // ------------------------------------------------------------------------------------------

    /// @notice Requests a close straight from the owner's wallet. Binding: it cannot be cancelled,
    ///         and it is priced at the first print `DIRECT_DELAY` after this block.
    /// @dev A request lapses after `REQUEST_EXPIRY`. That covers the rare case of Pyth publishing
    ///      nothing inside the pricing window, where the close could otherwise never execute and
    ///      the position could never be liquidated.
    function requestClose(bytes32 id) external {
        if (_positions[id].owner != msg.sender) revert NotPositionOwner();
        if (_liveRequest(id) != 0) revert CloseAlreadyRequested();
        uint64 nowTs = uint64(block.timestamp);
        closeRequestedAt[id] = nowTs;
        emit CloseRequested(id, msg.sender, nowTs + DIRECT_DELAY);
    }

    /// @notice Executes a requested close at the first price `DIRECT_DELAY` after the request.
    /// @dev Anyone can execute it, but a non-operator must first let every intent and every
    ///      liquidation that predates its price have its turn. Otherwise the owner could race a
    ///      signed close of their own with it and keep the better of two prices, or slip a touched
    ///      position out before the public is allowed to liquidate it.
    function executeClose(bytes32 id, bytes[] calldata update) external nonReentrant {
        Position memory p = _positions[id];
        if (p.owner == address(0)) revert NoPosition();
        uint64 requestedAt = _liveRequest(id);
        if (requestedAt == 0) revert NoRequest();
        if (!isOperator[msg.sender] && block.timestamp <= uint256(requestedAt) + DIRECT_DELAY + INTENT_TTL) {
            revert TooEarly();
        }
        _settle(id, p, _closePrice(p, requestedAt + DIRECT_DELAY, update), false);
    }

    /// @notice Busts a position by proving its trigger price was touched after it opened.
    /// @dev Anyone can liquidate, but a non-operator must wait until the proof is older than any
    ///      close intent that could still be in flight: a close signed before the touch has to be
    ///      allowed to land first.
    function liquidate(bytes32 id, bytes[] calldata update) external nonReentrant {
        Position memory p = _positions[id];
        if (p.owner == address(0)) revert NoPosition();
        Market storage m = _markets[p.market];

        uint64 price;
        if (m.retired) {
            price = m.frozenPrice;
        } else {
            uint64 publishTime;
            (price, publishTime) = _liquidationPrice(id, p, update);
            // A touch at or after the moment a binding close is priced comes too late.
            _beforeRequest(id, publishTime);
            if (!isOperator[msg.sender] && block.timestamp <= uint256(publishTime) + INTENT_TTL) {
                revert LiquidationGrace();
            }
        }

        _settle(id, p, price, true);
    }

    // ------------------------------------------------------------------------------------------
    // The house
    // ------------------------------------------------------------------------------------------

    /// @notice Pays queued winners from the front, as far as the house's cash goes.
    function harvest(uint256 maxEntries) external nonReentrant {
        _harvest(maxEntries);
    }

    /// @notice Gives USDC to the house. Nothing is received in return.
    function donate(uint256 amount) external nonReentrant {
        if (amount == 0) revert ZeroAmount();
        usdc.safeTransferFrom(msg.sender, address(this), amount);
        treasury += amount;
        emit Donated(msg.sender, amount);
        _harvest(AUTO_HARVEST);
    }

    /// @notice Sends accrued staker fees to staking, which streams them to stakers. Anyone can
    ///         call it. House cash above `stakerCap` goes the same way, through `sweepExcess`.
    function pushStakerFees() external nonReentrant returns (uint256 amount) {
        amount = stakerFees;
        if (amount == 0) revert NothingToPush();
        stakerFees = 0;
        _toStakers(amount);
        emit StakerFeesPushed(amount, 0);
    }

    /// @notice Sends `amount` of the house's cash above its cap to stakers. Only the sweeper may
    ///         call this: it first works out, at current prices, how much of that cash the house
    ///         would need if every open position closed now, and sweeps only the rest.
    function sweepExcess(uint256 amount) external nonReentrant {
        if (msg.sender != sweeper) revert NotOperator();
        if (amount == 0 || amount > lpExcess()) revert NothingToPush();
        _toStakers(amount);
        emit StakerFeesPushed(0, amount);
    }

    function _toStakers(uint256 amount) private {
        address staking_ = staking;
        if (staking_ == address(0)) revert NoStaking();
        treasury -= amount;
        usdc.safeTransfer(staking_, amount);
        IStaking(staking_).notify(amount);
    }

    /// @notice Sends accrued dev fees to the dev recipient.
    function claimDevFees() external nonReentrant returns (uint256 amount) {
        amount = devFees;
        if (amount == 0) revert ZeroAmount();
        devFees = 0;
        treasury -= amount;
        usdc.safeTransfer(devRecipient, amount);
        emit DevFeesClaimed(devRecipient, amount);
    }

    // ------------------------------------------------------------------------------------------
    // Administration
    // ------------------------------------------------------------------------------------------

    /// @notice Lists a market. Its pricing parameters are fixed for good: changing them means
    ///         retiring the market and listing a new one, never repricing open positions. The
    ///         one exception is the depth, which the owner can move for positions not yet open
    ///         (`setDepth`).
    function listMarket(
        bytes32 feedId,
        string calldata symbol,
        uint16 maxLeverage,
        Curve calldata curve,
        uint16 maxKeepBps,
        uint16 maxConfBps,
        uint80 maxNotional,
        uint96 capLong,
        uint96 capShort
    ) external onlyOwner returns (uint16 id) {
        if (
            feedId == bytes32(0) || maxLeverage == 0 || maxLeverage > MAX_LEVERAGE
                || curve.rateMultiplier == 0 || curve.positionMultiplier == 0 || curve.tick == 0
                || curve.depth == 0 || curve.bustBuffer > MAX_BUST_BUFFER || maxKeepBps < MIN_KEEP_BPS
                || maxKeepBps > BPS - FEE_BPS || maxConfBps == 0 || maxConfBps > MAX_CONF_BPS
                || maxNotional == 0 || _markets.length >= type(uint16).max
        ) revert BadParams();

        // Bounded by the length check above.
        // forge-lint: disable-next-line(unsafe-typecast)
        id = uint16(_markets.length);
        Market storage m = _markets.push();
        m.feedId = feedId;
        m.maxLeverage = maxLeverage;
        m.rateMultiplier = curve.rateMultiplier;
        m.positionMultiplier = curve.positionMultiplier;
        m.tick = curve.tick;
        m.bustBuffer = curve.bustBuffer;
        m.depth = curve.depth;
        m.maxKeepBps = maxKeepBps;
        m.maxConfBps = maxConfBps;
        m.maxNotional = maxNotional;
        m.capLong = capLong;
        m.capShort = capShort;
        emit MarketListed(id, feedId, symbol);
        emit CapsSet(id, capLong, capShort);
        emit DepthSet(id, curve.depth);
    }

    /// @notice Retires a market for good, freezing its price. Opens stop; closes and liquidations
    ///         settle at the frozen price from then on. A retired id never reopens.
    function retireMarket(uint16 id, bytes[] calldata update) external onlyGuardian nonReentrant {
        if (id >= _markets.length) revert BadMarket();
        Market storage m = _markets[id];
        if (m.retired) revert MarketIsRetired();
        (uint64 price,,) =
            oracle.within(m.feedId, update, uint64(block.timestamp) - RETIRE_MAX_AGE, type(uint64).max);
        m.retired = true;
        m.retiredAt = uint64(block.timestamp);
        m.frozenPrice = price;
        emit MarketRetired(id, price);
    }

    /// @notice Stops new opens everywhere. Closes, liquidations and withdrawals are unaffected.
    function pauseOpens() external onlyGuardian {
        opensPaused = true;
        emit OpensPausedSet(true);
    }

    function unpauseOpens() external onlyOwner {
        opensPaused = false;
        emit OpensPausedSet(false);
    }

    /// @notice Sets the most that may be open on each side of a market.
    /// @dev The caps and the depth are what stand between the house and a trader who moves the
    ///      market the oracle reads. A position is filled and closed at the oracle's price
    ///      whatever its size, so someone holding enough of one side can push the real price a
    ///      few basis points, close, and be paid on the whole position. The cap times the move is
    ///      the most that can ever earn, and it is the cap that bounds a large move. The depth is
    ///      what makes a small push on a full side earn a fraction of that. Both are sized under
    ///      what moving the real market costs, and only the owner sets them: an operator key must
    ///      not be able to lift them.
    function setCaps(uint16 id, uint96 capLong, uint96 capShort) external onlyOwner {
        if (id >= _markets.length) revert BadMarket();
        _markets[id].capLong = capLong;
        _markets[id].capShort = capShort;
        emit CapsSet(id, capLong, capShort);
    }

    /// @notice Sets how much may be open on one side of a market before size starts to cost, in
    ///         whole dollars.
    /// @dev It bites on positions opened from now on, orders already signed included: those are
    ///      covered by their own `impactLimit`. An open position keeps the terms it opened on, so
    ///      this never reprices anyone. In whole dollars, unlike the caps.
    function setDepth(uint16 id, uint32 depth) external onlyOwner {
        if (id >= _markets.length) revert BadMarket();
        if (depth == 0) revert BadParams();
        _markets[id].depth = depth;
        emit DepthSet(id, depth);
    }

    /// @notice Sets the smallest margin and the smallest position that can be opened. These decide
    ///         who can trade at all, so they are the owner's to set, not the operator's.
    function setMinimums(uint96 minMargin_, uint96 minNotional_) external onlyOwner {
        minMargin = minMargin_;
        minNotional = minNotional_;
        emit MinimumsSet(minMargin_, minNotional_);
    }

    function setOperator(address operator, bool allowed) external onlyOwner {
        if (operator == address(0)) revert ZeroAddress();
        isOperator[operator] = allowed;
        emit OperatorSet(operator, allowed);
    }

    function setGuardian(address guardian_) external onlyOwner {
        guardian = guardian_;
        emit GuardianSet(guardian_);
    }

    function setDevRecipient(address recipient) external onlyOwner {
        if (recipient == address(0)) revert ZeroAddress();
        devRecipient = recipient;
        emit DevRecipientSet(recipient);
    }

    /// @notice Attaches the coin: where staker fees go, and who pays losers. Once, forever.
    /// @dev The Exchange runs without a coin. Until one is attached, the staker share of fees
    ///      accrues here and is paid to stakers on the first push after attachment.
    function attachCoin(address staking_, address lossMining_, address sweeper_) external onlyOwner {
        if (staking != address(0)) revert AlreadyAttached();
        // Each has to be the right kind of contract, built for this Exchange. Each kind answers
        // under its own name, which catches arguments in the wrong order as well as contracts
        // deployed against another Exchange. Neither could be undone.
        if (
            IAttached(staking_).stakingFor() != address(this)
                || IAttached(lossMining_).lossMiningFor() != address(this)
                || IAttached(sweeper_).sweeperFor() != address(this)
        ) revert BadParams();
        staking = staking_;
        lossMining = lossMining_;
        sweeper = sweeper_;
        emit CoinAttached(staking_, lossMining_);
    }

    // ------------------------------------------------------------------------------------------
    // Views
    // ------------------------------------------------------------------------------------------

    /// @notice The house's cash: everything held that is not a trader's balance, locked cash margin
    ///         or an accrued fee. While anything is queued, all of it is owed to the queue.
    function lpCash() public view returns (uint256) {
        return treasury - totalBalances - totalCashMargin - stakerFees - devFees;
    }

    /// @notice House equity above `stakerCap`, distributable to stakers. Zero while anyone is queued.
    function lpExcess() public view returns (uint256) {
        if (totalQueued != 0) return 0;
        uint256 cash = lpCash();
        uint256 floor = debtMarginOpen + stakerCap;
        return cash > floor ? cash - floor : 0;
    }

    function marketCount() external view returns (uint256) {
        return _markets.length;
    }

    function getMarket(uint16 id) external view returns (Market memory) {
        if (id >= _markets.length) revert BadMarket();
        return _markets[id];
    }

    function getPosition(bytes32 id) external view returns (Position memory) {
        return _positions[id];
    }

    /// @notice Ids of every open position of `owner_`.
    function openIdsOf(address owner_) external view returns (bytes32[] memory) {
        return _openIds[owner_];
    }

    // ------------------------------------------------------------------------------------------
    // Settlement
    // ------------------------------------------------------------------------------------------

    /// @dev When the pending direct close for `id` was requested, or zero if there is none or it
    ///      has lapsed.
    function _liveRequest(bytes32 id) private view returns (uint64 requestedAt) {
        requestedAt = closeRequestedAt[id];
        if (requestedAt != 0 && block.timestamp >= uint256(requestedAt) + REQUEST_EXPIRY) requestedAt = 0;
    }

    /// @dev Once a binding direct close has been priced, that price stands: only a close or a
    ///      liquidation priced at an earlier moment than `pinTime` may still come first.
    function _beforeRequest(bytes32 id, uint64 pinTime) private view {
        uint64 requestedAt = _liveRequest(id);
        if (requestedAt != 0 && pinTime >= requestedAt + DIRECT_DELAY) revert CloseHasPriority();
    }

    function _openPrice(OpenIntent calldata it, bytes32, bytes[] calldata update)
        internal
        virtual
        returns (uint64 price, uint64 conf, uint64 publishTime)
    {
        uint64 minTime = it.timestamp + EXEC_DELAY();
        return oracle.pinned(_markets[it.market].feedId, update, minTime, minTime + PIN_WINDOW);
    }

    function _intentClosePrice(CloseIntent calldata it, Position memory p, bytes[] calldata update)
        internal
        virtual
        returns (uint64)
    {
        return _closePrice(p, it.timestamp + EXEC_DELAY(), update);
    }

    function _triggerPrice(Position memory p, uint64, uint64 touchedAt, bytes[] calldata update)
        internal
        virtual
        returns (uint64)
    {
        return _closePrice(p, touchedAt + EXEC_DELAY(), update);
    }

    function _triggerTouch(TriggerIntent calldata it, Position memory p, bytes[] calldata touch)
        internal
        virtual
        returns (uint64 price, uint64 touchedAt)
    {
        uint64 from = it.timestamp > p.openTime ? it.timestamp : uint64(p.openTime);
        (price,, touchedAt) = oracle.within(_markets[p.market].feedId, touch, from + 1, type(uint64).max);
    }

    function _liquidationPrice(bytes32, Position memory p, bytes[] calldata update)
        internal
        virtual
        returns (uint64 price, uint64 publishTime)
    {
        (price,, publishTime) =
            oracle.within(_markets[p.market].feedId, update, uint64(p.openTime) + 1, type(uint64).max);
    }

    function _closePrice(Position memory p, uint64 minTime, bytes[] calldata update)
        private
        returns (uint64 price)
    {
        Market storage m = _markets[p.market];
        if (m.retired) return m.frozenPrice;
        uint64 publishTime;
        (price,, publishTime) = oracle.pinned(m.feedId, update, minTime, minTime + PIN_WINDOW);
        if (publishTime <= p.openTime) revert CloseNotAfterOpen();
    }

    /// @param mustBust True for a liquidation: `exitPrice` has to be at or beyond the trigger.
    function _settle(bytes32 id, Position memory p, uint64 exitPrice, bool mustBust) private {
        Market storage m = _markets[p.market];
        uint256 notional = uint256(p.margin) * p.leverage;

        _removePosition(id, p);
        // The same amounts were added at open.
        // forge-lint: disable-start(unsafe-typecast)
        uint128 size = uint128(Math.mulDiv(notional, 1e18, p.entryPrice));
        if (p.isLong) {
            m.oiLong -= uint96(notional);
            m.sizeLong -= size;
        } else {
            m.oiShort -= uint96(notional);
            m.sizeShort -= size;
        }
        // forge-lint: disable-end(unsafe-typecast)

        uint256 cashMargin = p.margin - p.debtMargin;
        totalCashMargin -= cashMargin;
        debtMarginOpen -= p.debtMargin;

        // A close priced at or beyond the trigger is a bust like any other.
        (bool busted, bool win, uint256 amount) = pricing.close(
            p.entryPrice,
            exitPrice,
            notional,
            p.leverage,
            p.isLong,
            p.impactNotional,
            m.rateMultiplier,
            m.positionMultiplier,
            m.maxKeepBps,
            m.tick,
            m.bustBuffer
        );
        if (mustBust && !busted) revert NotLiquidatable();

        if (win) {
            _settleWin(id, p, exitPrice, cashMargin, amount);
        } else {
            _settleLoss(id, p, exitPrice, cashMargin, busted ? p.margin : Math.min(amount, p.margin), busted);
        }
    }

    /// @dev Cash margin goes straight back. The profit, and any queue-funded margin, is what the
    ///      house owes: paid now if it can be, queued if not.
    function _settleWin(bytes32 id, Position memory p, uint64 exitPrice, uint256 cashMargin, uint256 gain)
        private
    {
        uint256 fee = (gain * FEE_BPS) / BPS;
        uint256 profit = gain - fee;

        _credit(p.owner, cashMargin);
        (uint256 paid, uint256 queued, bool feePaid) = _payOrQueue(p.owner, p.debtMargin + profit, fee);

        emit PositionClosed(
            id,
            p.owner,
            p.market,
            CloseKind.Close,
            exitPrice,
            // A USDC amount, far below 2**255.
            // forge-lint: disable-next-line(unsafe-typecast)
            int256(profit),
            cashMargin + paid,
            queued,
            feePaid ? fee : 0
        );
    }

    /// @dev A loss is shared pro rata between the cash and queue-funded parts of the margin. Lost
    ///      cash becomes house cash; lost queue-funded margin is debt the house simply no longer
    ///      owes. A bust takes all of both.
    function _settleLoss(
        bytes32 id,
        Position memory p,
        uint64 exitPrice,
        uint256 cashMargin,
        uint256 loss,
        bool busted
    ) private {
        uint256 lossDebt = busted ? p.debtMargin : Math.mulDiv(loss, p.debtMargin, p.margin);
        uint256 lossCash = loss - lossDebt;
        uint256 surviving = p.debtMargin - lossDebt;

        _credit(p.owner, cashMargin - lossCash);

        // The house-side fee is carved from what the house gained, never added to the loss. It is
        // paid only while nobody is queued and the house can also cover what it still owes here.
        // A bust charges nothing on queue-funded margin.
        uint256 fee;
        if (totalQueued == 0) {
            fee = ((lossCash + (busted ? 0 : lossDebt)) * FEE_BPS) / BPS;
            // Queue-funded margin in other positions is money the house still owes its owners.
            if (fee != 0 && lpCash() >= surviving + fee + debtMarginOpen) _accrueFee(fee);
            else fee = 0;
        }

        (uint256 paid, uint256 queued,) = _payOrQueue(p.owner, surviving, 0);
        if (totalQueued != 0) _harvest(AUTO_HARVEST);

        emit PositionClosed(
            id,
            p.owner,
            p.market,
            busted ? CloseKind.Liquidation : CloseKind.Close,
            exitPrice,
            // A USDC amount, far below 2**255.
            // forge-lint: disable-next-line(unsafe-typecast)
            -int256(loss),
            cashMargin - lossCash + paid,
            queued,
            fee
        );

        _mine(p.owner, busted ? p.margin : loss - fee);
    }

    /// @dev Pays `owed` from house cash if nobody is queued, and queues whatever is left. `fee` is
    ///      paid out only if the house can cover it on top of `owed`; otherwise the house keeps it.
    function _payOrQueue(address user, uint256 owed, uint256 fee)
        private
        returns (uint256 paid, uint256 queued, bool feePaid)
    {
        if (totalQueued == 0) {
            uint256 available = lpCash();
            paid = Math.min(owed, available);
            if (fee != 0 && available >= owed + fee + debtMarginOpen) {
                _accrueFee(fee);
                feePaid = true;
            }
            if (paid != 0) _credit(user, paid);
        }
        queued = owed - paid;
        if (queued != 0) _enqueue(user, queued);
    }

    function _enqueue(address user, uint256 amount) private {
        uint256 tail = queueTail;
        uint256 claimId;
        // `amount` is a USDC amount; uint96 holds 7.9e22 dollars.
        // forge-lint: disable-start(unsafe-typecast)
        if (tail != queueHead && claims[tail - 1].user == user) {
            // The back of the queue is already this trader's: extend it.
            claimId = tail - 1;
            claims[claimId].amount += uint96(amount);
        } else {
            claimId = tail;
            claims[claimId] = Claim(user, uint96(amount));
            queueTail = tail + 1;
        }
        // forge-lint: disable-end(unsafe-typecast)
        totalQueued += amount;
        queuedOf[user] += amount;
        emit Queued(user, claimId, amount);
    }

    /// @dev Spends queued payout as margin. The claims themselves are left in place and netted off
    ///      when the queue reaches them, oldest first.
    function _spendQueued(address user, uint256 amount) private {
        queuedOf[user] -= amount;
        totalQueued -= amount;
        queueSpent[user] += amount;
        emit QueueSpent(user, amount);
    }

    function _harvest(uint256 maxEntries) private {
        uint256 head = queueHead;
        uint256 tail = queueTail;
        uint256 available = lpCash();

        for (uint256 n; n < maxEntries && head < tail; ++n) {
            Claim storage claim = claims[head];
            address user = claim.user;
            uint256 amount = claim.amount;

            // Net off what this trader already spent as margin.
            uint256 spent = queueSpent[user];
            if (spent != 0) {
                uint256 netted = Math.min(spent, amount);
                queueSpent[user] = spent - netted;
                amount -= netted;
            }

            uint256 pay = Math.min(amount, available);
            if (pay != 0) {
                available -= pay;
                amount -= pay;
                totalQueued -= pay;
                queuedOf[user] -= pay;
                _credit(user, pay);
                emit QueuePaid(user, head, pay);
            }

            if (amount != 0) {
                // Out of cash with this claim still owed. It stays at the front.
                // `amount` only ever shrinks from a uint96.
                // forge-lint: disable-next-line(unsafe-typecast)
                claim.amount = uint96(amount);
                break;
            }
            delete claims[head];
            ++head;
        }
        queueHead = head;
    }

    function _removePosition(bytes32 id, Position memory p) internal virtual {
        bytes32[] storage ids = _openIds[p.owner];
        uint256 last = ids.length - 1;
        if (p.index != last) {
            bytes32 moved = ids[last];
            ids[p.index] = moved;
            _positions[moved].index = p.index;
        }
        ids.pop();
        delete _positions[id];
        delete closeRequestedAt[id];
    }

    function _credit(address user, uint256 amount) private {
        balances[user] += amount;
        totalBalances += amount;
    }

    function _accrueFee(uint256 fee) private {
        uint256 toStakers = (fee * STAKER_SHARE_BPS) / BPS;
        stakerFees += toStakers;
        devFees += fee - toStakers;
    }

    /// @dev Tells the loss-mining hook about a realised loss. The hook can never block a close or a
    ///      liquidation: it is gas-capped and its failure is swallowed.
    function _mine(address user, uint256 usd) private {
        address hook = lossMining;
        if (hook == address(0) || usd == 0) return;
        if (gasleft() < MINING_GAS_FLOOR) revert InsufficientGas();
        // A plain call, not try/catch: try/catch reverts when its target has no code, and a hook
        // whose code has gone must not be able to stop a loss from settling. The return data is
        // not copied, so a hostile hook cannot make that expensive either.
        (bool ok,) = hook.call{gas: MINING_GAS}(abi.encodeCall(ILossMining.onLoss, (user, usd)));
        if (!ok) emit MiningFailed(user, usd);
    }
}

src/ExecutionOracle.sol

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

import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {SignedOracle} from "./SignedOracle.sol";

/// @notice Signed market prints plus execution prices bound to one exact trader-signed order.
/// @dev The signer remains trusted for price accuracy and prompt, single-price execution. It must
///      persist the first execution quote for an order before releasing it, and must never sign a
///      second price for that order. Binding a quote to its full EIP-712 order digest prevents a
///      trader or operator from substituting an ordinary historical print or another order's quote.
///      No fixed pricing delay is imposed. Public prints still support liquidations and direct exits.
contract ExecutionOracle is SignedOracle {
    bytes32 public constant FILL_TYPEHASH = keccak256(
        "Fill(bytes32 feedId,bytes32 orderId,uint64 price,uint64 conf,uint64 publishTime,uint64 observedAt)"
    );
    uint256 private constant FILL_LENGTH = 288;
    bytes32 public constant TICK_TYPEHASH = keccak256(
        "Tick(bytes32 feedId,uint64 price,uint64 conf,uint64 publishTime,uint64 prevPublishTime,uint64 observedAt,uint64 prevObservedAt)"
    );

    constructor(address exchange_, address signer_) SignedOracle(exchange_, signer_) {}

    /// @notice Fixed wallet-signature validation, including ERC-1271 wallets. Kept here so the
    ///         Exchange's runtime remains within Ethereum's code-size limit. No signer setting
    ///         participates in this check: only the owner's actual wallet can authorize it.
    function checkWalletSignature(address owner, bytes32 digest, bytes calldata signature)
        external
        view
        returns (bool)
    {
        return SignatureChecker.isValidSignatureNow(owner, digest, signature);
    }

    /// @notice An execution price signed for this feed and this complete order digest.
    /// @dev `observedAt` is the source observation in milliseconds; public position times remain
    ///      seconds. The operator cannot turn a normal signed market print into an execution quote.
    function fill(bytes32 feedId, bytes32 orderId, bytes[] calldata update, uint64 minTime, uint64 maxTime)
        external
        view
        returns (uint64 price, uint64 conf, uint64 publishTime, uint64 observedAt)
    {
        if (update.length != 1 || update[0].length != FILL_LENGTH) revert BadUpdate();
        bytes32 feed;
        bytes32 order;
        uint8 v;
        bytes32 r;
        bytes32 s;
        (feed, order, price, conf, publishTime, observedAt, v, r, s) =
            abi.decode(update[0], (bytes32, bytes32, uint64, uint64, uint64, uint64, uint8, bytes32, bytes32));
        if (feed != feedId || order != orderId || orderId == bytes32(0)) revert NoPriceInWindow();
        if (price == 0) revert NonPositivePrice();
        if (publishTime < minTime || publishTime > maxTime || observedAt / 1000 != publishTime) {
            revert NoPriceInWindow();
        }
        bytes32 digest = keccak256(
            abi.encodePacked(
                "\x19\x01",
                domainSeparator(),
                keccak256(abi.encode(FILL_TYPEHASH, feed, order, price, conf, publishTime, observedAt))
            )
        );
        (address recovered, ECDSA.RecoverError error,) = ECDSA.tryRecover(digest, v, r, s);
        if (error != ECDSA.RecoverError.NoError || recovered != signer) revert BadSignature();
    }

    /// @notice Public tick with millisecond ordering, for proving a post-entry bust or trigger.
    function afterMs(bytes32 feedId, bytes[] calldata update, uint64 afterTime)
        external
        view
        returns (uint64 price, uint64 conf, uint64 publishTime, uint64 observedAt)
    {
        (price, conf, publishTime,, observedAt) = _tick(feedId, update);
        if (observedAt <= afterTime) revert NoPriceInWindow();
    }

    function read(bytes32 feedId, bytes[] calldata update)
        public
        view
        override
        returns (uint64 price, uint64 conf, uint64 publishTime, uint64 prevPublishTime)
    {
        (price, conf, publishTime, prevPublishTime,) = _tick(feedId, update);
    }

    function _tick(bytes32 feedId, bytes[] calldata update)
        private
        view
        returns (uint64 price, uint64 conf, uint64 publishTime, uint64 prevPublishTime, uint64 observedAt)
    {
        if (update.length != 1 || update[0].length != 320) revert BadUpdate();
        bytes32 feed;
        uint64 prevObservedAt;
        uint8 v;
        bytes32 r;
        bytes32 s;
        (feed, price, conf, publishTime, prevPublishTime, observedAt, prevObservedAt, v, r, s) = abi.decode(
            update[0], (bytes32, uint64, uint64, uint64, uint64, uint64, uint64, uint8, bytes32, bytes32)
        );
        if (feed != feedId) revert NoPriceInWindow();
        if (price == 0) revert NonPositivePrice();
        if (
            observedAt / 1000 != publishTime || prevObservedAt / 1000 != prevPublishTime
                || prevObservedAt >= observedAt
        ) revert BadUpdate();
        bytes32 digest = keccak256(
            abi.encodePacked(
                "\x19\x01",
                domainSeparator(),
                keccak256(abi.encode(TICK_TYPEHASH, feed, price, conf, publishTime, prevPublishTime, observedAt, prevObservedAt))
            )
        );
        (address recovered, ECDSA.RecoverError error,) = ECDSA.tryRecover(digest, v, r, s);
        if (error != ECDSA.RecoverError.NoError || recovered != signer) revert BadSignature();
    }
}

src/SignedOracle.sol

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

import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

import {IOracle} from "./interfaces/IOracle.sol";

/// @dev As much of the Exchange as this oracle asks of it.
interface IOwned {
    function owner() external view returns (address);
}

/// @title SignedOracle
/// @notice A price source for the Exchange whose prices are signed by one key: the price signer.
/// @dev The signer reads a market's price off-chain (at launch, Hyperliquid's order book through
///      its public API) and signs it, one print after another. This contract checks the signature
///      and the Exchange's two questions, and nothing else.
///
///      What that means, plainly: THE SIGNER IS TRUSTED. Whoever holds its key decides every fill,
///      every close and every bust. Nothing on-chain can tell a true price from a false one. The
///      key is kept apart from the operator's (it never sends a transaction and needs no ETH) and
///      the Exchange's owner can replace it at once (`setSigner`), which is the only remedy if it
///      leaks.
///
///      What is still enforced on-chain:
///      1. A print is for one feed, on one chain, for this contract: it cannot be replayed for
///         another market, on a fork, or against another deployment (EIP-712).
///      2. Each print names the publish time of the print before it. `pinned` takes only the
///         FIRST print at or after a second, so a trade signed for second T has one price, and
///         the operator who submits it cannot pick among the signer's prints.
///
///      A print is `abi.encode(feedId, price, conf, publishTime, prevPublishTime, v, r, s)`: the
///      price and its uncertainty scaled to 1e8, both times in unix seconds.
///
///      The contract holds no funds and has no owner of its own: its one setting follows the
///      Exchange's owner, so handing the Exchange over hands this over with it.
contract SignedOracle is IOracle {
    bytes32 private constant DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 private constant NAME_HASH = keccak256("SignedOracle");
    bytes32 private constant VERSION_HASH = keccak256("1");
    /// @notice The EIP-712 type the signer signs.
    bytes32 public constant PRINT_TYPEHASH =
        keccak256("Print(bytes32 feedId,uint64 price,uint64 conf,uint64 publishTime,uint64 prevPublishTime)");
    /// @dev Eight words: the feed, four numbers and a signature.
    uint256 private constant PRINT_LENGTH = 256;

    /// @notice The Exchange this prices for. Its owner is the one who may change the signer.
    address public immutable exchange;
    /// @notice The key whose prints are prices.
    address public signer;

    event SignerSet(address indexed signer);

    error ZeroAddress();
    error NotOwner();
    error BadUpdate();
    error BadSignature();
    error NonPositivePrice();
    error NoPriceInWindow();

    constructor(address exchange_, address signer_) {
        if (exchange_ == address(0) || signer_ == address(0)) revert ZeroAddress();
        exchange = exchange_;
        signer = signer_;
        emit SignerSet(signer_);
    }

    /// @notice Replaces the price signer. Every print the old key signed stops counting at once.
    function setSigner(address signer_) external {
        if (msg.sender != IOwned(exchange).owner()) revert NotOwner();
        if (signer_ == address(0)) revert ZeroAddress();
        signer = signer_;
        emit SignerSet(signer_);
    }

    /// @inheritdoc IOracle
    function pinned(bytes32 feedId, bytes[] calldata update, uint64 minTime, uint64 maxTime)
        external
        view
        override
        returns (uint64 price, uint64 conf, uint64 publishTime)
    {
        uint64 prevPublishTime;
        (price, conf, publishTime, prevPublishTime) = read(feedId, update);
        // The first print at or after `minTime`: the one before it was published earlier.
        if (prevPublishTime >= minTime || publishTime < minTime || publishTime > maxTime) revert NoPriceInWindow();
    }

    /// @inheritdoc IOracle
    function within(bytes32 feedId, bytes[] calldata update, uint64 minTime, uint64 maxTime)
        external
        view
        override
        returns (uint64 price, uint64 conf, uint64 publishTime)
    {
        (price, conf, publishTime,) = read(feedId, update);
        if (publishTime < minTime || publishTime > maxTime) revert NoPriceInWindow();
    }

    /// @notice The print in `update`, if it is for `feedId` and the signer signed it. Reverts
    ///         otherwise.
    function read(bytes32 feedId, bytes[] calldata update)
        public
        view
        virtual
        returns (uint64 price, uint64 conf, uint64 publishTime, uint64 prevPublishTime)
    {
        if (update.length != 1 || update[0].length != PRINT_LENGTH) revert BadUpdate();
        bytes32 feed;
        uint8 v;
        bytes32 r;
        bytes32 s;
        (feed, price, conf, publishTime, prevPublishTime, v, r, s) =
            abi.decode(update[0], (bytes32, uint64, uint64, uint64, uint64, uint8, bytes32, bytes32));
        // A print for another market is no price for this one.
        if (feed != feedId) revert NoPriceInWindow();
        if (price == 0) revert NonPositivePrice();
        // A print cannot come before the one it follows.
        if (prevPublishTime > publishTime) revert BadUpdate();

        bytes32 digest = keccak256(
            abi.encodePacked(
                "\x19\x01",
                domainSeparator(),
                keccak256(abi.encode(PRINT_TYPEHASH, feedId, price, conf, publishTime, prevPublishTime))
            )
        );
        // Rejects a malformed signature and the second form of a valid one.
        (address recovered, ECDSA.RecoverError error,) = ECDSA.tryRecover(digest, v, r, s);
        if (error != ECDSA.RecoverError.NoError || recovered != signer) revert BadSignature();
    }

    /// @notice The EIP-712 domain prints are signed under: this contract, on this chain.
    function domainSeparator() public view returns (bytes32) {
        return keccak256(abi.encode(DOMAIN_TYPEHASH, NAME_HASH, VERSION_HASH, block.chainid, address(this)));
    }
}

src/base/Intents.sol

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

import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";

import {ISessions} from "../interfaces/ISessions.sol";

/// @title Intents
/// @notice The orders traders sign, and who may sign them.
/// @dev Opens and closes are signed by the owner's key or by one of their session keys (see
///      `Sessions`). Withdrawals are signed by the owner's wallet only.
///
///      The EIP-712 domain is the standard one: the name given at deployment, version "1", this
///      chain and this contract. It is worked out here rather than inherited: the usual base
///      contract also answers `eip712Domain()` with the name as a string, which nothing here
///      needs and which costs several hundred bytes that the Exchange does not have. The separator
///      is computed afresh on every call, so it is right on any chain the contract finds itself on.
abstract contract Intents {
    struct OpenIntent {
        address owner;
        uint16 market;
        bool isLong;
        /// @dev Fund the margin from the owner's queued payout first, then from their balance.
        bool useQueued;
        uint16 leverage;
        uint96 margin;
        /// @dev Worst acceptable entry (max for a long, min for a short). Zero means no limit.
        uint64 priceLimit;
        /// @dev The most the position may be charged on for its size, in whole dollars (see
        ///      `PerpMath.impactNotionalFor`). What it is charged on depends on what is open on
        ///      its side when the order lands, which other orders can change after this one is
        ///      signed. Zero means no limit.
        uint32 impactLimit;
        uint64 timestamp;
        uint64 salt;
    }

    struct CloseIntent {
        address owner;
        bytes32 positionId;
        uint64 timestamp;
    }

    /// @dev A take-profit or a stop-loss: close the position once a price at or beyond `price`
    ///      prints, from `timestamp` on. `above` says which way: at or above it, or at or below.
    struct TriggerIntent {
        address owner;
        bytes32 positionId;
        uint64 price;
        bool above;
        uint64 timestamp;
    }

    bytes32 private constant OPEN_TYPEHASH = keccak256(
        "Open(address owner,uint16 market,bool isLong,bool useQueued,uint16 leverage,uint96 margin,uint64 priceLimit,uint32 impactLimit,uint64 timestamp,uint64 salt)"
    );
    bytes32 private constant CLOSE_TYPEHASH =
        keccak256("Close(address owner,bytes32 positionId,uint64 timestamp)");
    bytes32 private constant TRIGGER_TYPEHASH =
        keccak256("Trigger(address owner,bytes32 positionId,uint64 price,bool above,uint64 timestamp)");
    bytes32 private constant WITHDRAW_TYPEHASH =
        keccak256("Withdraw(address owner,address to,uint256 amount,uint256 nonce,uint64 deadline)");
    bytes32 private constant DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 private constant VERSION_HASH = keccak256("1");

    /// @dev The hash of the name orders are signed under.
    bytes32 private immutable _nameHash;

    /// @notice One slot. Anything a trader does to their own account bites this long after the
    ///         block it lands in, so that it cannot reach an order already signed.
    uint64 public constant GRACE = 12;

    /// @notice The registry of session keys.
    ISessions public immutable sessions;

    /// @notice Replay counter for withdrawals signed by the wallet. Nothing else moves it, so no
    ///         other signature of the owner's can void a withdrawal already handed to an operator.
    mapping(address owner => uint256) public withdrawNonces;

    error BadSignature();

    constructor(string memory name_, ISessions sessions_) {
        _nameHash = keccak256(bytes(name_));
        sessions = sessions_;
    }

    /// @notice The EIP-712 domain separator orders are signed against.
    function domainSeparator() public view returns (bytes32) {
        return keccak256(abi.encode(DOMAIN_TYPEHASH, _nameHash, VERSION_HASH, block.chainid, address(this)));
    }

    /// @dev The digest a wallet signs for a struct with this hash, under this contract's domain.
    function _hashTypedDataV4(bytes32 structHash) private view returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(domainSeparator(), structHash);
    }

    function _hashOpen(OpenIntent calldata it) internal view returns (bytes32) {
        return _hashTypedDataV4(
            keccak256(
                abi.encode(
                    OPEN_TYPEHASH,
                    it.owner,
                    it.market,
                    it.isLong,
                    it.useQueued,
                    it.leverage,
                    it.margin,
                    it.priceLimit,
                    it.impactLimit,
                    it.timestamp,
                    it.salt
                )
            )
        );
    }

    function _hashClose(CloseIntent calldata it) internal view returns (bytes32) {
        return _hashTypedDataV4(keccak256(abi.encode(CLOSE_TYPEHASH, it.owner, it.positionId, it.timestamp)));
    }

    function _hashTrigger(TriggerIntent calldata it) internal view returns (bytes32) {
        return _hashTypedDataV4(
            keccak256(abi.encode(TRIGGER_TYPEHASH, it.owner, it.positionId, it.price, it.above, it.timestamp))
        );
    }

    function _hashWithdraw(address owner, address to, uint256 amount, uint256 nonce, uint64 deadline)
        internal
        view
        returns (bytes32)
    {
        return _hashTypedDataV4(keccak256(abi.encode(WITHDRAW_TYPEHASH, owner, to, amount, nonce, deadline)));
    }

    /// @dev An order is valid if signed by the owner's key, or by a session key whose validity
    ///      covers the order's own timestamp. A smart-contract wallet trades through a session key.
    function _requireTradeAuth(address owner, bytes32 digest, bytes calldata signature, uint64 timestamp)
        internal
        view
    {
        (address signer, ECDSA.RecoverError err,) = ECDSA.tryRecover(digest, signature);
        if (err != ECDSA.RecoverError.NoError) revert BadSignature();
        if (signer != owner && !sessions.isValid(owner, signer, timestamp)) revert BadSignature();
    }

    /// @dev Withdrawals take the wallet's own signature. A session key is never enough.
    function _requireWalletAuth(address owner, bytes32 digest, bytes calldata signature) internal view virtual {
        if (!SignatureChecker.isValidSignatureNow(owner, digest, signature)) revert BadSignature();
    }
}

src/interfaces/IHooks.sol

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

/// @notice Receives the staker share of fees. USDC is transferred in before `notify` is called.
interface IStaking {
    function notify(uint256 amount) external;
}

/// @notice Told about every realised loss so it can pay the loser in coin.
interface ILossMining {
    function onLoss(address user, uint256 usd) external;
}

/// @notice What the Exchange asks of a contract before it accepts it: which Exchange it was built
///         for, under a name only that kind of contract answers to.
/// @dev The three names differ on purpose. Attaching is for good, so handing the contracts over in
///      the wrong order has to fail rather than attach: a staking contract does not answer
///      `lossMiningFor`, and so on.
interface IAttached {
    function stakingFor() external view returns (address);
    function lossMiningFor() external view returns (address);
    function sweeperFor() external view returns (address);
}

src/interfaces/IOracle.sol

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

/// @notice Price source for the Exchange. Every price is scaled to 1e8.
interface IOracle {
    /// @notice The FIRST price published at or after `minTime` (and no later than `maxTime`).
    ///         Deterministic: for a given feed and `minTime` there is exactly one answer.
    function pinned(bytes32 feedId, bytes[] calldata update, uint64 minTime, uint64 maxTime)
        external
        returns (uint64 price, uint64 conf, uint64 publishTime);

    /// @notice Any price published inside `[minTime, maxTime]`. Used to prove a price was touched.
    function within(bytes32 feedId, bytes[] calldata update, uint64 minTime, uint64 maxTime)
        external
        returns (uint64 price, uint64 conf, uint64 publishTime);
}

src/interfaces/IPricing.sol

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

/// @notice The pricing rules of a position, as the Exchange asks for them. See `Pricing`.
interface IPricing {
    /// @notice The terms a position opens on. Reverts with OpenInterestCap if the resulting
    ///         side exceeds the immutable house-cash ceiling; the caller must expose lpCash().
    /// @return impactNotional The notional its impact will be charged on, in whole dollars. Zero
    ///         if `leverage` leaves no room for a bust trigger at `price`: such a position must
    ///         not be opened.
    function open(
        uint256 price,
        uint256 leverage,
        uint256 tick,
        uint256 bustBuffer,
        uint256 ahead,
        uint256 notional,
        uint256 depth
    ) external view returns (uint32 impactNotional);

    /// @notice What a position is worth at `exit`.
    /// @return busted True if `exit` is at or beyond the bust trigger: the whole margin is lost.
    /// @return win True if the exit is on the profitable side of entry.
    /// @return amount For a win, the gain before the win fee. For a loss, the raw loss, not capped
    ///         at the margin. Zero for a bust.
    function close(
        uint256 entry,
        uint256 exit,
        uint256 notional,
        uint256 leverage,
        bool isLong,
        uint256 impactNotional,
        uint256 rateMultiplier,
        uint256 positionMultiplier,
        uint256 maxKeepBps,
        uint256 tick,
        uint256 bustBuffer
    ) external pure returns (bool busted, bool win, uint256 amount);
}

src/interfaces/ISessions.sol

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

/// @notice The one question the Exchange asks about session keys.
interface ISessions {
    /// @notice Whether `key` may sign for `owner` an order timestamped `timestamp`.
    function isValid(address owner, address key, uint64 timestamp) external view returns (bool);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1,
    "details": {
      "yulDetails": {
        "optimizerSteps": "dhfoDgvulfnTUtnIf[xa[r]EscLMcCTUtTOntnfDIulLculVcul[j]Tpeulxa[rul]xa[r]cLgvifCTUca[r]LSsTFOtfDnca[r]Iulc]jmul[jul]VcTOculjmul:fDnTOcmu"
      }
    },
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "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.